基于tensorflow使用全连接层函数实现多层神经网络并保存和读取模型
原标题:基于tensorflow使用全连接层函数实现多层神经网络并保存和读取模型
原文来自:博客园 原文链接:https://www.cnblogs.com/imae/p/10634234.html
使用之前那个格式写法到后面层数多的话会很乱,所以编写了一个函数创建层,这样看起来可读性高点也更方便整理后期修改维护
#全连接层函数def fcn_layer( inputs, #输入数据 input_dim, #输入层神经元数量 output_dim,#输出层神经元数量 activation =None): #激活函数 W = tf.Variable(tf.truncated_normal([input_dim,output_dim],stddev = 0.1)) #以截断正态分布的随机初始化W b = tf.Variable(tf.zeros([output_dim])) #以0初始化b XWb = tf.matmul(inputs,W)+b # Y=WX+B if(activation==None): #默认不使用激活函数 outputs =XWb else: outputs = activation(XWb) #代入参数选择的激活函数 return outputs #返回
#各层神经元数量设置 H1_NN = 256 H2_NN = 64 H3_NN = 32 #构建输入层 x = tf.placeholder(tf.float32,[None,784],name='X') y = tf.placeholder(tf.float32,[None,10],name='Y') #构建隐藏层 h1 = fcn_layer(x,784,H1_NN,tf.nn.relu) h2 = fcn_layer(h1,H1_NN,H2_NN,tf.nn.relu) h3 = fcn_layer(h2,H2_NN,H3_NN,tf.nn.relu) #构建输出层 forward = fcn_layer(h3,H3_NN,10,None) pred = tf.nn.softmax(forward)#输出层分类应用使用softmax当作激活函数
这样写方便后期维护 不必对着一群 W1 W2..... Wn
接下来记录一下保存模型的方法
1 2 3 4 5 6 | #保存模型 save_step = 5 #储存模型力度 import os ckpt_dir = '.ckpt_dir/' if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) |
5轮训练保存一次,以后大模型可以调高点,接下来需要在模型整合处修改一下
1 2 3 | saver = tf.train.Saver() #声明完所有变量以后,调用tf.train.Saver开始记录 和 if (epochs + 1 ) % save_step = = 0 :<br> saver.save(sess, os.path.join(ckpt_dir, "mnist_h256_model_{:06d}.ckpt" . format (epochs + 1 ))) #储存模型<br> print("mnist_h256_model_{:06d}.ckpt saved".format(epochs+1))#输出情况 |
至此储存模型结束
接下来是还原模型,要注意还原的模型层数和神经元数量大小需要和之前储存模型的大小一致。
第一步设置保存模型文件的路径
#必须指定存储位置ckpt_dir = "/ckpt_dir/"
存盘只会保存最近的5次,恢复会恢复最新那一份
1 2 3 4 5 6 7 8 9 10 11 12 | #恢复模型,创建会话 saver = tf.train.Saver() sess = tf.Session() init = tf.global_variables_initializer() sess.run(init) ckpt = tf.train.get_checkpoint_state(ckpt_dir) #选择模型保存路径 if ckpt and ckpt.model_checkpoint_path: saver.restore(sess ,ckpt.model_checkpoint_path) #从已保存模型中读取参数 print ( "Restore model from" + ckpt.model_checkpoint_path) |
至此模型恢复完成 下面可以选择继续训练或者评估使用
最后附上完整代码
import tensorflow as tf import tensorflow.examples.tutorials.mnist.input_data as input_data import numpy as np import matplotlib.pyplot as plt from time import time mnist = input_data.read_data_sets("data/",one_hot = True) #导入Tensorflwo和mnist数据集等 常用库 #全连接层函数 def fcn_layer( inputs, #输入数据 input_dim, #输入层神经元数量 output_dim,#输出层神经元数量 activation =None): #激活函数 W = tf.Variable(tf.truncated_normal([input_dim,output_dim],stddev = 0.1)) #以截断正态分布的随机初始化W b = tf.Variable(tf.zeros([output_dim])) #以0初始化b XWb = tf.matmul(inputs,W)+b # Y=WX+B if(activation==None): #默认不使用激活函数 outputs =XWb else: outputs = activation(XWb) #代入参数选择的激活函数 return outputs #返回 #各层神经元数量设置 H1_NN = 256 H2_NN = 64 H3_NN = 32 #构建输入层 x = tf.placeholder(tf.float32,[None,784],name='X') y = tf.placeholder(tf.float32,[None,10],name='Y') #构建隐藏层 h1 = fcn_layer(x,784,H1_NN,tf.nn.relu) h2 = fcn_layer(h1,H1_NN,H2_NN,tf.nn.relu) h3 = fcn_layer(h2,H2_NN,H3_NN,tf.nn.relu) #构建输出层 forward = fcn_layer(h3,H3_NN,10,None) pred = tf.nn.softmax(forward)#输出层分类应用使用softmax当作激活函数 #损失函数使用交叉熵 loss_function = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = forward,labels = y)) #设置训练参数 train_epochs = 50 batch_size = 50 total_batch = int(mnist.train.num_examples/batch_size) #随机抽取样本 learning_rate = 0.01 display_step = 1 #优化器 opimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss_function) #定义准确率 correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(pred,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) #保存模型 save_step = 5 #储存模型力度 import os ckpt_dir = '.ckpt_dir/' if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) #开始训练 sess = tf.Session() init = tf.global_variables_initializer() saver = tf.train.Saver() #声明完所有变量以后,调用tf.train.Saver开始记录 startTime = time() sess.run(init) for epochs in range(train_epochs): for batch in range(total_batch): xs,ys = mnist.train.next_batch(batch_size)#读取批次数据 sess.run(opimizer,feed_dict={x:xs,y:ys})#执行批次数据训练 #total_batch个批次训练完成后,使用验证数据计算误差与准确率 loss,acc = sess.run([loss_function,accuracy], feed_dict={ x:mnist.validation.images, y:mnist.validation.labels}) #输出训练情况 if(epochs+1) % display_step == 0: epochs += 1 print("Train Epoch:",epochs, "Loss=",loss,"Accuracy=",acc) if(epochs+1) % save_step == 0: saver.save(sess, os.path.join(ckpt_dir,"mnist_h256_model_{:06d}.ckpt".format(epochs+1))) print("mnist_h256_model_{:06d}.ckpt saved".format(epochs+1)) duration = time()-startTime print("Trian Finshed takes:","{:.2f}".format(duration))#显示预测耗时 #评估模型 accu_test = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}) print("model accuracy:",accu_test) #恢复模型,创建会话 saver = tf.train.Saver() sess = tf.Session() init = tf.global_variables_initializer() sess.run(init) ckpt = tf.train.get_checkpoint_state(ckpt_dir)#选择模型保存路径 if ckpt and ckpt.model_checkpoint_path: saver.restore(sess ,ckpt.model_checkpoint_path)#从已保存模型中读取参数 print("Restore model from"+ckpt.model_checkpoint_path) 完整代码
完整代码
免责声明:本文来自互联网新闻客户端自媒体,不代表本网的观点和立场。
合作及投稿邮箱:E-mail:editor@tusaishared.com
热门资源
Python 爬虫(二)...
所谓爬虫就是模拟客户端发送网络请求,获取网络响...
TensorFlow从1到2...
原文第四篇中,我们介绍了官方的入门案例MNIST,功...
TensorFlow从1到2...
“回归”这个词,既是Regression算法的名称,也代表...
机器学习中的熵、...
熵 (entropy) 这一词最初来源于热力学。1948年,克...
TensorFlow2.0(10...
前面的博客中我们说过,在加载数据和预处理数据时...
智能在线
400-630-6780
聆听.建议反馈
E-mail: support@tusaishared.com