解决mnist各种错误,优化提升
2017-10-16 23:21
453 查看
上次写的mnist神经网络cnn预测只能输出训练数据,测试数据没有,百度发现是资源耗尽问题,就是这么多资源在训练的时候是batch拆分的,后面测试没有拆分导致不够用了,只要把test数据也分10份,跑10次结果取平均即可解决后的代码
保存模型的方法:
将模型保存好以后,载入也比较方便,如下所示:
上面一定要注意代码顺序
载入模型完整代码,包括显示tensorboard的代码
待续
# -*- coding:gbk -*- import input_data import tensorflow as tf import numpy mnist=input_data.read_data_sets("MNIST_data/", one_hot=True) #添加x作为占位符 x=tf.placeholder("float", [None, 784])#28*28 #正确结果占位符 y_=tf.placeholder("float", [None,10]) #生成权重函数 def weight_variable(shape): #tf.truncated_normal(shape, mean, stddev) :shape表示生成张量的维度,mean是均值,stddev是标准差。这个函数产生正态分布,均值和标准差自己设定 #权重在初始化时应该加入少量的噪声来打破对称性以及避免0梯度 initial=tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial,dtype=tf.float32) #生成偏置函数 #由于我们使用的是ReLU神经元,因此比较好的做法是用一个较小的正数来初始化偏置项,以避免神经元节点输出恒为0的问题(dead neurons) def bias_variable(shape): initial=tf.constant(0.1, shape=shape) return tf.Variable(initial,dtype=tf.float32) #卷积函数 #卷积使用1步长,0边距的模板,池化用2x2的模板 def conv2d(x, W): #x:待卷积的矩阵具有[batch, in_height, in_width, in_channels]这样的shape #w:卷积核具有[filter_height, filter_width, in_channels, out_channels]这样的shape #strides:卷积时在图像每一维的步长,这是一个一维的向量,长度4 return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') #池化函数 #和卷积基本相同 def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME') #卷积在每个5x5的patch中算出32个特征。 #卷积的权重张量形状是[5, 5, 1, 32],前两个维度是patch的大小, #接着是输出几个单位,和输出的几个维度 W_conv1=weight_variable([5, 5, 1, 32]) b_conv1=bias_variable([32]) #shape:[batch, in_height, in_width, in_channels] x_image=tf.reshape(x, [-1,28,28,1]) #卷积+偏置,然后给relu激活函数,最后激活函数返回值池化 h_conv1=tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) #output size 28*28*32 h_pool1=max_pool_2x2(h_conv1) #output size 14*14*32 #第二层卷积,池化 W_conv2=weight_variable([5, 5, 32, 64]) b_conv2=bias_variable([64]) h_conv2=tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) #output size 14*14*64 h_pool2=max_pool_2x2(h_conv2) #output size 7*7*64 #全连接层1 W_fc1=weight_variable([7*7*64,1024]) b_fc1=bias_variable([1024]) h_pool2_flat=tf.reshape(h_pool2, [-1,7*7*64]) h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1) + b_fc1) #dropout方法减轻过拟合问题 keep_prob=tf.placeholder("float") h_fc1_drop=tf.nn.dropout(h_fc1, keep_prob) #全连接层2 W_fc2=weight_variable([1024, 10]) b_fc2=bias_variable([10]) y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) #训练和评估模型 cross_entropy=-tf.reduce_sum(y_*tf.log(y_conv)) train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction=tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) accuracy=tf.reduce_mean(tf.cast(correct_prediction, "float")) sess = tf.InteractiveSession() sess.run(tf.initialize_all_variables()) saver=tf.train.Saver() for i in range(20001): batch = mnist.train.next_batch(50) if i%200 == 0: train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0}) print("step %d, training accuracy %g"%(i, train_accuracy)) train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) accuracyResult = list(range(10)) for i in range(10): batch = mnist.test.next_batch(1000) accuracyResult[i] = accuracy.eval(feed_dict={x:batch[0],y_:batch[1],keep_prob:1.0}) print("Test accuracy:", numpy.mean(accuracyResult))
保存模型的方法:
#之前是各种构建模型graph的操作(矩阵相乘,sigmoid等等....) saver = tf.train.Saver() # 生成saver with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # 先对模型初始化 # 然后将数据丢入模型进行训练blablabla # 训练完以后,使用saver.save 来保存 saver.save(sess, "save_path/file_name") #file_name如果不存在的话,会自动创建
将模型保存好以后,载入也比较方便,如下所示:
saver = tf.train.Saver() with tf.Session() as sess: #参数可以进行初始化,也可不进行初始化。即使初始化了,初始化的值也会被restore的值给覆盖 sess.run(tf.global_variables_initializer()) saver.restore(sess, "save_path/file_name") #会将已经保存的变量值resotre到 变量中
上面一定要注意代码顺序
载入模型完整代码,包括显示tensorboard的代码
# -*- coding:gbk -*- import input_data import tensorflow as tf import numpy mnist=input_data.read_data_sets("MNIST_data/", one_hot=True) #添加x作为占位符 x=tf.placeholder("float", [None, 784])#28*28 #正确结果占位符 y_=tf.placeholder("float", [None,10]) #生成权重函数 def weight_variable(shape): #tf.truncated_normal(shape, mean, stddev) :shape表示生成张量的维度,mean是均值,stddev是标准差。这个函数产生正态分布,均值和标准差自己设定 #权重在初始化时应该加入少量的噪声来打破对称性以及避免0梯度 initial=tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial,dtype=tf.float32) #生成偏置函数 #由于我们使用的是ReLU神经元,因此比较好的做法是用一个较小的正数来初始化偏置项,以避免神经元节点输出恒为0的问题(dead neurons) def bias_variable(shape): initial=tf.constant(0.1, shape=shape) return tf.Variable(initial,dtype=tf.float32) #卷积函数 #卷积使用1步长,0边距的模板,池化用2x2的模板 def conv2d(x, W): #x:待卷积的矩阵具有[batch, in_height, in_width, in_channels]这样的shape #w:卷积核具有[filter_height, filter_width, in_channels, out_channels]这样的shape #strides:卷积时在图像每一维的步长,这是一个一维的向量,长度4 return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') #池化函数 #和卷积基本相同 def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME') #卷积在每个5x5的patch中算出32个特征。 #卷积的权重张量形状是[5, 5, 1, 32],前两个维度是patch的大小, #接着是输出几个单位,和输出的几个维度 W_conv1=weight_variable([5, 5, 1, 32]) b_conv1=bias_variable([32]) #shape:[batch, in_height, in_width, in_channels] x_image=tf.reshape(x, [-1,28,28,1]) #卷积+偏置,然后给relu激活函数,最后激活函数返回值池化 h_conv1=tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) #output size 28*28*32 h_pool1=max_pool_2x2(h_conv1) #output size 14*14*32 #第二层卷积,池化 W_conv2=weight_variable([5, 5, 32, 64]) b_conv2=bias_variable([64]) h_conv2=tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) #output size 14*14*64 h_pool2=max_pool_2x2(h_conv2) #output size 7*7*64 #全连接层1 W_fc1=weight_variable([7*7*64,1024]) b_fc1=bias_variable([1024]) h_pool2_flat=tf.reshape(h_pool2, [-1,7*7*64]) h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1) + b_fc1) #dropout方法减轻过拟合问题 keep_prob=tf.placeholder("float") h_fc1_drop=tf.nn.dropout(h_fc1, keep_prob) #全连接层2 W_fc2=weight_variable([1024, 10]) b_fc2=bias_variable([10]) y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) #训练 评估 保存模型 cross_entropy=-tf.reduce_sum(y_*tf.log(y_conv)) tf.summary.scalar('cross_entropy',cross_entropy) train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction=tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) accuracy=tf.reduce_mean(tf.cast(correct_prediction, "float")) tf.summary.scalar('accuracy',accuracy) sess = tf.InteractiveSession() saver=tf.train.Saver() merged=tf.summary.merge_all() writer=tf.summary.FileWriter("D://logs",sess.graph) sess.run(tf.global_variables_initializer()) for i in range(10001): batch = mnist.train.next_batch(50) if i%100 == 0: train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0}) print("step %d, training accuracy %g"%(i, train_accuracy)) train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) summary_str = sess.run(merged,feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) writer.add_summary(summary_str,i) save_path=saver.save(sess,'my_net/save_net.ckpt') print("save to path:",save_path) accuracyResult = list(range(10)) for i in range(10): batch = mnist.test.next_batch(1000) accuracyResult[i] = accuracy.eval(feed_dict={x:batch[0],y_:batch[1],keep_prob:1.0}) print("Test accuracy:", numpy.mean(accuracyResult))
待续
相关文章推荐
- Spark优化-troubleshooting-解决各种序列化导致的错误
- QNX Momentics启动时各种内存错误解决方法
- Mysqldb安装的各种错误解决办法
- ionic报各种诡异错误的解决办法
- tensorflow_mnist数据集一直加载错误的解决办法
- Sqlserver 2016 R Service环境安装的各种错误(坑)解决办法
- 完美解决双核运行游戏不稳定问题,并提升XP运行效率正文分析错误
- C/C++ For循环语句的效率测试优化及运行时错误:Stack Overflow的解决办法
- myEclipse 8.5 各种错误解决办法
- 从 A/Looper: Could not create epoll instance. errno=24 错误浅谈解决各种 bug 的思路
- 今天在我导入一些安卓项目的源码的时候会出现style.xml 和MAIN.xml 等错误, 网上的方法试了各种clean各种fix等方法都是不能解决。最后去国外论坛得到解决
- Choose the best route HDU 各种优化加错误解析
- mac 系统下anaconda安装第三方包出现各种错误如何解决
- 解决用mysql front 或者navicat导入sql脚本时候各种错误问题
- ES各种错误解决
- 数据错误(循环冗余检查) 各种解决方法
- CGAL配置的一点心得(各种错误的解决办法)
- AndroidStudio 安装各种错误解决-安装教程
- 如果使用Excel oledb 导数据出现各种错误的解决方法
- vs------各种错误解决方法