TensorFlow学习笔记

保存训练参数,并再下一次训练时直接使用

1、保存模型:
下面展示一些 内联代码片

cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
                                                 save_weights_only=True,
                                                 save_best_only=True)   # 加入回调函数,返回给callback
history = model.fit(x_train,y_train,batch_size=32,epochs=5,validation_data=(x_test,y_test),validation_freq=1,
                    callbacks=[cp_callback])    # 训练时加入callbacks参数,将callback赋值给history

2、读取模型(load.weight(路径文件名))

checkpoint_save_path = './checkpoint/mnist.ckpt' 	 # 确定文件存储路径

if os.path.exists(checkpoint_save_path + '.index'):		#  若查询到和参数文件同步生成的index文件则直接读取
    print('_______________load the model________________')
    model.load_weights(checkpoint_save_path)

提取可训练参数

两种方式,第一种,通过修改print的打印方式直接打印。第二种,通过将参数存入txt文本文档
1、直接打印

np.set_printoptions(threshold=np.inf)
print(model.trainable_variables)

2、存入文本

file = open('./weights.txt','w')    # 存入txt文本文件
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()

可视化acc/loss,查看训练效果

其实,在model.fit过程种已经同步记录了,训练集/测试集loss,训练集/测试集准确率。

# 若存在history = model.fit()
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列,第一列
plt.plot(acc,label = 'Training Accuracy')
plt.plot(val_acc,label = 'Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.legend() 	 # 画出图例


plt.subplot(1,2,2)  # 将图像分为1行2列,第二列
plt.plot(loss,label = 'Training Loss')
plt.plot(val_loss,label = 'Validation Loss')
plt.title('Training and Validation Loss')
plt.legend()	 #  画出图例
plt.show()

给图实物(练习)

前向传播执行应用

predict(输入特征,batch_size = 整数)

1、复现模型(前向传播)

model = tf,keras.model.Sequential([
	tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128,activation='relu'),
    tf.keras.layers.Dense(10,activation='softmax')
	])

2、加载参数

model.load_weights(model_save_path)

3、预测结果
result = model.perdict(x_predict)

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在神经网络训练完成后,我们可以使用模型对新的输入数据进行预测。以下是使用 TensorFlow 进行简单神经网络训练和测试的示例代码: ```python import tensorflow as tf # 定义输入数据 x = tf.placeholder(tf.float32, [None, input_size]) # 定义模型参数 W = tf.Variable(tf.zeros([input_size, num_classes])) b = tf.Variable(tf.zeros([num_classes])) # 定义模型 y = tf.nn.softmax(tf.matmul(x, W) + b) # 定义损失函数 y_ = tf.placeholder(tf.float32, [None, num_classes]) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) # 定义优化器 train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) # 训练模型 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(num_iterations): batch_xs, batch_ys = get_next_batch(train_data, train_labels, batch_size) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # 测试模型 correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print("Accuracy: ", sess.run(accuracy, feed_dict={x: test_data, y_: test_labels})) ``` 在训练完成后,我们可以使用 `sess.run()` 函数来获取模型的输出。例如,如果我们想要对一个新的数据样本进行预测,我们可以将其传递给 `sess.run()` 函数的 `feed_dict` 参数,并获取模型的输出 `y`。下面是一个简单的示例: ```python # 定义要预测的数据 new_data = [[5.1, 3.5, 1.4, 0.2]] # 获取预测结果 prediction = sess.run(y, feed_dict={x: new_data}) # 打印预测结果 print(prediction) ``` 在上面的代码中,我们将 `new_data` 作为输入数据传递给模型,并使用 `sess.run()` 函数获取模型的输出 `y`。然后,我们打印预测结果即可。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值