TensorFlow——acc/loss 可视化

import tensorflow as tf
import os
#导入numpy模块
import numpy as np

from matplotlib import pyplot as plt

np.set_printoptions(threshold=np.inf)

mnist = tf.keras.datasets.mnist
(x_train,y_train),(x_test,y_test) = mnist.load_data()
x_trian,x_test = x_train / 255.0,x_test / 255.0

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128,activation='relu'),
    tf.keras.layers.Dense(10,activation='softmax')
    ])
model.compile(
    optimizer = 'adam',
    loss = tf.keras.losses.CategoricalCrossentropy(from_logits=False),
    metrics = ['sparse_categorical_accuracy']
    )
checkpoint_save_path = "./checkpoint/mnist.ckpt" #存放模型的路径和文件名
#在生成ckpt文件的同时,也会生成索引表,所以通过判断有没有生成索引表,来判断是不是保存模型参数了
if os.path.exists(checkpoint_save_path + '.index'):
    print('-------------load the model-------------------')
    model.load_weights(checkpoint_save_path)
    #用load_weights函数,来读取文件
#保存模型参数用callbacks函数,
cp_callback = tf.keras.callbacks.ModelCheckpoint(
    filepath = checkpoint_save_path,
    save_weights_only = True,#是否只保留模型参数
    save_best_only = True#是否只保留最优结果
    )    
#在执行训练时,加入callbacks回调选项,返回给history
history = model.fit(
    x_train,y_train,batch_size=32,epochs=5,validation_data=(x_test,y_test),
    validation_freq=1,callbacks=[cp_callback]
    )
model.summary()

#将参数写入weights.txt文本文件
print(model.trainable_variables)
file = open('./weights.txt','w')
for v in model.trainable_variables:
    file.write(str(v.name) + '\n')
    file.write(str(v.shape) + '\n')
    file.write(str(v.numpy()) + '\n')
file.close()
########show##############
acc = history.history['sparse_categorical_accuracy']#训练集准确率
val_acc = history.history['val_sparse_categorical_accuracy']#测试集准确率
loss = history.history['loss']#训练集损失函数数值
val_loss = history.history['val_loss']#测试集损失函数数值

plt.subplot(1,2,1)#将图像分为1行2列,这段代码,画出第1列
plt.plot(acc,label='Training Accuracy')#画出acc数据
plt.plot(val_acc,label ='Validation Accuracy')#画出val_acc数据
plt.title('Training and Validation Accuracy')#设置标题
plt.legend()#画出图例

plt.subplot(1,2,2)#画出第二列
plt.plot(loss,label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.title('Training and Validation Loss')
plt.legend()
plt.show()
"""
Total params: 101,770
Trainable params: 101,770
Non-trainable params: 0
"""     

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值