# 创建保存对象
saver = tf.train.Saver()
# 最优结果
best_acc = 0
# 创建保存训练模型的路径
model_path = 'save_models/'
if not os.path.exists(model_path):
os.makedirs(model_path)
save_path = os.path.join(path,'best')
# 添加节点用于初始化全部变量
init = tf.global_variables_initializer()
# 创建会话
sess = tf.Session()
sess.run(init)
# 创建FileWriter实例,并传入当前会话加载的数据流图
writer = tf.summary.FileWriter('./summary/linear-regression-1', sess.graph)
for i in range(2000):
# 随机选取64个样本的索引
sel_index = random.sample(
list(range(len(train_y))), k=batch_size)
# 批量选择训练样本
batch_X = train_X[sel_index]
batch_Y = train_Y[sel_index]
# 运行训练模型
sess.run(train, feed_dict={
X_holder:batch_X, Y_holder:batch_Y})
# 抽取样本观察训练效果
i += 1
if i % 100 == 0:
# 随机选择200个样本进行训练
sel_index = random.sample(
list(range(len(train_y))), k=200)
batch_X = train_X[sel_index]
batch_Y = train_Y[sel_index]
# 获取损失值loss_val和准确度accuracy_val
loss_val,accuracy_val = sess.run(
[loss,accuracy], feed_dict={
X_holder:batch_X, Y_holder:batch_Y})
# 将最优的模型保存下来
if accuracy_val > best_acc:
best_acc = accuracy_val
saver.save(sess=sess, save_path=save_path)
# 打印损失值和准确度
print('第{}轮训练,loss值:{:.4f},accuracy值:{:.4f}'.format(
i,loss_val,accuracy_val))
# 导入相关工具包
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix
# 定义批量预测函数,将结果转化为ndarray类型
def predictAll(test_X, batch_size=100):
pred_val_list = []
for i in range(0,len(test_X),batch_size):
select_X = test_X[i:i+batch_size]
pred_val = sess.run(pred_Y, {X_holder:select_X})
pred_val_list.extend(pred_val)
return np.array(pred_val_list)
# 运行模型进行预测
Y = predictAll(test_X)
# 获取局部最大可能预测值的位置矩阵
y = np.argmax(Y, axis=1)
# 格式化预测标签列表
pred_label_list = labelEncoder.inverse_transform(y)
# 获取混淆矩阵
content_matrix = confusion_matrix(test_label_list,pred_label_list)
pd.DataFrame(content_matrix,columns=labelEncoder.classes_,
index=labelEncoder.classes_)
from sklearn.metrics import precision_recall_fscore_support as prf
# 定义模型评估函数
def eval_model(true_y,pred_y,labels):
# 计算每个类别的测准率,召回率,f1得分
pred,recall,f1,s = prf(true_y, pred_y)
# 计算上面各参数的总体值
tt_pred = np.average(pred, weights=s)
tt_recall = np.average(recall, weights=s)
tt_f1 = np.average(f1, weights=s)
tt_s = np.sum(s)
res1 = pd.DataFrame({
'Label':labels,
'Prediction':pred,
'Recall':recall,
'F1':f1,
'Support':s
})
res2 = pd.DataFrame({
'Label':['总体'],
'Prediction':tt_pred,
'Recall':tt_recall,
'F1':tt_f1,
'Support':tt_s
})
res2.index = [999]
res = pd.concat([res1, res2])[['Label','Prediction','Recall','F1','Support']]
return res,res1,res2
res,res1,res2 = eval_model(test_label_list, pred_label_list, labelEncoder.classes_)
print(res)
github源码地址:https://github.com/Willsgao
参考网址:https://blog.csdn.net/sadfassd/article/details/80568321
https://blog.csdn.net/q383700092/article/details/79159776
https://blog.csdn.net/u011439796/article/details/77692621
https://blog.csdn.net/heyc861221/article/details/80128748