-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlModelTrain.py
98 lines (76 loc) · 3.29 KB
/
AlModelTrain.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# -*- coding: utf-8 -*-
import networkx as nx
import matplotlib.pyplot as plt
import NetworkModel
import RandomGraph
import LatencyCount
import MigrationPathStatus
from scipy.optimize import linear_sum_assignment
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import pickle
import NetworkModel
def AI_model_learning(G, aim, bvnf_sorted, bvnf_mig_loc):
"""
利用Kuhn_Munkres_improvement和RandomAlgorithm生成数据进行训练并保存模型
:param G:
:param aim:
:param bvnf_sorted:
:param bvnf_mig_loc:
:return:
"""
x_train = []
y_train = []
# 此处的训练集应该更大,到时候改
s1 = MigrationPathStatus.Kuhn_Munkres_improvement(G, aim, bvnf_sorted, bvnf_mig_loc)
for i in s1:
x_train.append([i.MigTime_pre, i.MigTime_after, i.priority])
y_train.append(1)
s0 = MigrationPathStatus.RandomAlgorithm(G, aim, bvnf_sorted, bvnf_mig_loc)
for i in s0:
x_train.append([i.MigTime_pre, i.MigTime_after, i.priority])
y_train.append(0)
# 构建随机森林模型,训练并预测
clf = RandomForestClassifier(n_estimators=10)
clf.fit(x_train, y_train)
# 假设模型对象为clf
with open('model.pkl', 'wb') as f:
pickle.dump(clf, f)
print("保存完成")
if __name__ == '__main__':
# for i in ``` 利用循环随机生成足够的训练数据(暂时只写一组,没写循环)
G = RandomGraph.NewRandomGraph(70)
# 将图中任意两点之间的最小值求出
G = NetworkModel.dijkstra(G)
# NetworkModel.ShowGraph(G)
# print(G.get_edge_data("4", "1")['weight'])
# 实例化一个用户请求r
r = NetworkModel.UserRequests([0, 1, 2], 2, 1)
# 已知主VNF部署在vnf_loc,备份部署位置保存在列表 bvnf_loc中
vnf_loc = r.F[0]
bvnf_loc = r.F[1:]
# 已知用户从u移动到v,主VNF即将跟着从u移动到v(FM-MEC)
# 用户从0到4 (数据生成时此次可以随机生成)
aim = 4
# 求迁移后的平均故障时延afl
afl = LatencyCount.get_average_failure_latency(G, r, aim)
print("迁移后的afl:", afl)
# 如果迁移后的平均故障时延afl比用户所能容忍的高,则需要迁移
if afl > r.T_err:
print("需要进行迁移,用数据进行模型训练")
# 确定出状态$s_i=(u_i,v_i)$
# s = MigrationPathStatus.migration_status(G, r, aim)
# vnf_loc = r.F[0]
# 将bvnf按离主实例迁移后位置的权值从小到大排序
bvnf_sorted = MigrationPathStatus.bvnf_sort(G, aim, r.F[1:])
# 获取离aim最远的bvnf的边的权值
max_range = G.get_edge_data(aim, bvnf_sorted[-1])["weight"]
# print("max_range:", max_range)
# 选择出到点aim的边的权值小于max_range的点(不包括已经部署了bvnf的点)
adjacent_nodes = MigrationPathStatus.get_adjacent_points(G, aim, max_range)
# print("离目标点距离小于max的点:", adjacent_nodes)
not_migration_loc = r.F[1:]
not_migration_loc.append(aim)
bvnf_mig_loc = [x for x in adjacent_nodes if x not in not_migration_loc] # bvnf可以迁移的位置
AI_model_learning(G, aim, bvnf_sorted, bvnf_mig_loc)