本文共 5866 字,大约阅读时间需要 19 分钟。
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 npimport tensorflow as tfimport matplotlib.pyplot as pltfrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets('data/', one_hot=True)trainimg = mnist.train.imagestrainlabel = mnist.train.labelstestimg = mnist.test.imagestestlabel = 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 = 10batch_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 data sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7}) # Compute average loss avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/total_batch if 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-1 saver.restore(sess,"Save/CNN/cnn_minst.ckpt-"+str(epoch))
运行结果:
相应路径下文件夹中的文件列表: 在上述训练好的模型基础上,将do_train改为0,restart kernel后,再次运行程序读取刚刚保存的模型对测试集进行测试。转载地址:http://nohwi.baihongyu.com/