模型数据的保存和读取
生活随笔
收集整理的這篇文章主要介紹了
模型数据的保存和读取
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1,基本內容
目的是將模型數據以文件的形式保存到本地。
使用神經網絡模型進行大數據量和復雜模型訓練時,訓練時間可能會持續增加,此時為避免訓練過程出現不可逆的影響,并驗證訓練效果,可以考慮分段進行,將訓練數據模型保存,然后在繼續訓練時重新讀取; 此外,模型訓練完畢,獲取一個性能良好的模型后,可以保存以備重復利用。
2,參數保存和讀取代碼
import tensorflow as tf
#隨機初始化兩個變量
v1 = tf.Variable(tf.random_normal([1,2]), name="v1")#矩陣大小為[1,2]
v2 = tf.Variable(tf.random_normal([2,4]), name="v2")#矩陣大小為[2,4]
init_op = tf.global_variables_initializer()
saver = tf.train.Saver()#定義該類的一個對象
with tf.Session() as sess:sess.run(init_op)print ("V1:",sess.run(v1)) print ("V2:",sess.run(v2))saver_path = saver.save(sess, "Save/model.ckpt")#保存sess計算域中所有的參數值print ("Model saved")saver.restore(sess, "Save/model.ckpt")#讀取保存的文件print ("V1_1:",sess.run(v1)) print ("V2_1:",sess.run(v2))print ("Model restored")
運行結果:
2,網絡模型的保存與讀取代碼
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets('data/', one_hot=True)
trainimg = mnist.train.images
trainlabel = mnist.train.labels
testimg = mnist.test.images
testlabel = mnist.test.labels# 輸入和輸出
n_input = 784
n_output = 10#卷積神經網絡的參數初始化(w,b)
weights = {'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64], stddev=0.1)), #第一層卷積層權重參數[3, 3, 1, 64]卷積核的大小(3*3*1);卷積核的個數64(特征圖的個數)'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128], stddev=0.1)), #第二層卷積層權重參數[3, 3, 64, 128]卷積核的大小(3*3*64(與輸入圖像深度對應));卷積核的個數128(特征圖的個數)'wd1': tf.Variable(tf.random_normal([7*7*128, 1024], stddev=0.1)),#第一層全連接層權重參數(由于該模型中卷積并未改變輸入圖像的大小,經過兩次池化原始圖像大小(28*28)變為(7*7))'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1))#第二層全連接層權重參數(10分類)}
biases = {'bc1': tf.Variable(tf.random_normal([64], stddev=0.1)),'bc2': tf.Variable(tf.random_normal([128], stddev=0.1)),'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)),'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1))}
#卷積層定義
def conv_basic(_input, _w, _b, _keepratio):# 輸入預處理(轉換為TensorFlow支持的格式)的_input_r = tf.reshape(_input, shape=[-1, 28, 28, 1])#第一維:batchsize的大小(-1讓TensorFlow根據其余值推斷該值的大小);第二維:圖像的高度;第三維:圖像的寬度;第四維:圖像的深度# 第一層卷積_conv1 = tf.nn.conv2d(_input_r, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME')#print(help(tf.nn.conv2d))查看函數的幫助文檔#strides=[batchsize的stride大小, h的stride大小, w的stride大小, c的stride大小]#padding='SAME'/'VALID':自動填充0(推薦)/不進行填充#_mean, _var = tf.nn.moments(_conv1, [0, 1, 2])#_conv1 = tf.nn.batch_normalization(_conv1, _mean, _var, 0, 1, 0.0001)_conv1 = tf.nn.relu(tf.nn.bias_add(_conv1, _b['bc1']))#卷積之后進行激活_pool1 = tf.nn.max_pool(_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')#池化操作,ksize窗口大小(batchsize的大小;圖像的高度;圖像的寬度;圖像的深度),strides=[1, 2, 2, 1]:h和w方向步長均為2_pool_dr1 = tf.nn.dropout(_pool1, _keepratio)#dropout(隨機地減少部分節點)# 第二層卷積_conv2 = tf.nn.conv2d(_pool_dr1, _w['wc2'], strides=[1, 1, 1, 1], padding='SAME')#_mean, _var = tf.nn.moments(_conv2, [0, 1, 2])#_conv2 = tf.nn.batch_normalization(_conv2, _mean, _var, 0, 1, 0.0001)_conv2 = tf.nn.relu(tf.nn.bias_add(_conv2, _b['bc2']))_pool2 = tf.nn.max_pool(_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')_pool_dr2 = tf.nn.dropout(_pool2, _keepratio)# 全連接層_dense1 = tf.reshape(_pool_dr2, [-1, _w['wd1'].get_shape().as_list()[0]])#定義全連接的輸入# 第一層全連接層(神經網絡)_fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1']))_fc_dr1 = tf.nn.dropout(_fc1, _keepratio)# 第一、二層全連接層_out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2'])# 定義返回值out = { 'input_r': _input_r, 'conv1': _conv1, 'pool1': _pool1, 'pool1_dr1': _pool_dr1,'conv2': _conv2, 'pool2': _pool2, 'pool_dr2': _pool_dr2, 'dense1': _dense1,'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out}return outx = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_output])
keepratio = tf.placeholder(tf.float32)_pred = conv_basic(x, weights, biases, keepratio)['out']
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(y, _pred))
optm = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)
_corr = tf.equal(tf.argmax(_pred,1), tf.argmax(y,1))
accr = tf.reduce_mean(tf.cast(_corr, tf.float32))
init = tf.global_variables_initializer()#保存與讀取
do_train = 1 #利用該參數控制對模型的操作(是訓練保存模型還是讀取模型進行測試)
save_step = 1#每隔1個epoch進行對模型保存
saver = tf.train.Saver(max_to_keep=3)#max_to_keep=3:最多同時保存3個最近更新的模型sess = tf.Session()
sess.run(init)training_epochs = 10
batch_size = 16 #網絡結果比較復雜,這里取小一些,方便演示,正常情況下要稍大一些
display_step = 1if do_train ==1:for epoch in range(training_epochs):avg_cost = 0.#total_batch = int(mnist.train.num_examples/batch_size)total_batch = 10 #簡單示例,正常情況如上for i in range(total_batch):batch_xs, batch_ys = mnist.train.next_batch(batch_size)# Fit training using batch datasess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7})# Compute average lossavg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/total_batchif epoch % display_step == 0: print ("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})print (" Training accuracy: %.3f" % (train_acc)) #保存模型if epoch % save_step == 0:saver.save(sess,"Save/CNN/cnn_minst.ckpt-"+str(epoch))
if do_train ==0:epoch = training_epochs-1saver.restore(sess,"Save/CNN/cnn_minst.ckpt-"+str(epoch))
運行結果:
相應路徑下文件夾中的文件列表:
在上述訓練好的模型基礎上,將do_train改為0,restart kernel后,再次運行程序讀取剛剛保存的模型對測試集進行測試。
總結
以上是生活随笔為你收集整理的模型数据的保存和读取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信网名一个字
- 下一篇: 街角的咖啡店是哪首歌啊?