tensorflow LeNet例程

1.模型的训练

import tensorflow as tf  
from tensorflow.examples.tutorials.mnist import input_data  
import time  
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)  
sess = tf.InteractiveSession()  
  
  
def weight_variable(shape,namew='w'):  
    initial = tf.truncated_normal(shape, stddev=0.1)  
    return tf.Variable(initial,name=namew)  
  
  
def bias_variable(shape,nameb='b'):  
    initial = tf.constant(0.1, shape=shape)  
    return tf.Variable(initial,name=nameb)  
  
  
def conv2d(x, W,namec='c'):  
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME',name=namec)  
  
  
def max_pool_2x2(x,namep='p'):  
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME',name=namep)  
  
  
x = tf.placeholder(tf.float32, [None, 784],name='xinput')  
y_ = tf.placeholder(tf.float32, [None, 10])  
x_image = tf.reshape(x, [-1, 28, 28, 1])  
  
# Conv1 Layer  
W_conv1 = weight_variable([5, 5, 1, 32],'w1')  
b_conv1 = bias_variable([32],'b1')  
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1,'c1')  
h_pool1 = max_pool_2x2(h_conv1,'p1')  
  
# Conv2 Layer  
W_conv2 = weight_variable([5, 5, 32, 64],'w2')  
b_conv2 = bias_variable([64],'b2')  
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)  
h_pool2 = max_pool_2x2(h_conv2)  
  
W_fc1 = weight_variable([7 * 7 * 64, 1024],'wf1')  
b_fc1 = bias_variable([1024],'bf1')  
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)  
  
keep_prob = tf.placeholder(tf.float32,name="prob")  
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)  
  
W_fc2 = weight_variable([1024, 10],'wfull2')  
b_fc2 = bias_variable([10],'bf2')  
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)  
  
  
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))  
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, tf.float32))  
  
tf.global_variables_initializer().run()  
  
saver = tf.train.Saver();  
start = time.clock()  
for i in range(500):  
    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})  
  
print("test accuracy %g" % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))  
end = time.clock()  
print(end - start)  
saver.save(sess, "Model/model.ckpt")  

2.加载模型

import tensorflow as tf  
from skimage import io  
import numpy as np  
import cv2  
  
def conv2d(x, W):  
    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')  
  
sess = tf.Session()  
saver = tf.train.import_meta_graph("Model/model.ckpt.meta")  
saver.restore(sess,tf.train.latest_checkpoint('./Model'))  
  
  
im = cv2.imread('1.jpg', cv2.IMREAD_GRAYSCALE).astype(np.float32)  
  
# im = cv2.resize(im, (28, 28), interpolation=cv2.INTER_CUBIC)  
# 图片预处理  
# img_gray = cv2.cvtColor(im , cv2.COLOR_BGR2GRAY).astype(np.float32)  
# 数据从0~255转为-0.5~0.5  
img_gray = (im - (255 / 2.0)) / 255  
# img_gray = im / 255  
  
x_image = tf.reshape(im, [-1, 28, 28, 1])  
# x_img = np.reshape(img_gray, [-1, 784])  
  
W_conv1 = sess.run('w1:0')  
b_conv1 = sess.run('b1:0')  
cov1=tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)  
p1=max_pool_2x2(cov1)  
  
W_conv2 = sess.run('w2:0')  
b_conv2 = sess.run('b2:0')  
cov2=tf.nn.relu(conv2d(p1,W_conv2)+b_conv2)  
p2=max_pool_2x2(cov2)  
  
Wf1 = sess.run('wf1:0')  
bf1 = sess.run('bf1:0')  
h_pool2_flat = tf.reshape(p2, [-1, 7 * 7 * 64])  
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, Wf1) + bf1)  
  
# graph = tf.get_default_graph()  
# keep_prob = graph.get_tensor_by_name("prob:0")  
# init = tf.global_variables_initializer() #加载模型绝对不能添加变量初始化  这条语句之后的变量初始化  
# sess.run(init)  
# keep_prob = tf.placeholder(tf.float32)  
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob=1.0)  
  
W_fc2 = sess.run('wfull2:0')  
b_fc2 = sess.run('bf2:0')  
  
  
  
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)  
# print(b_fc2)  
result=sess.run(y_conv)  
print(sess.run(y_conv))  
print("the result of predict is:",np.argmax(result))  


TensorFlow MNIST例程是一个非常经典的入门示例,用于演示如何使用TensorFlow库来构建和训练一个简单的卷积神经网络,以识别手写数字图像。这个例程在CSDN上可以进行下载。 该例程主要包括以下步骤: 1. 导入相关的Python库和TensorFlow模块,包括数据集导入、模型定义、运行会话和模型评估所需的函数和类。 2. 导入MNIST手写数字数据集,该数据集包含60000个训练样本和10000个测试样本。 3. 定义卷积神经网络模型,包括卷积层、池化层和全连接层。通过调整网络的层数和每层的神经元数量,可以改变模型的性能。 4. 定义损失函数和优化器,用于最小化模型在训练数据上的预测误差。常用的损失函数包括交叉熵和平方差损失。 5. 创建会话,并使用训练数据迭代多次对模型进行训练。每次迭代中,通过向模型输入训练数据和期望的输出标签,并调用优化器来更新模型的参数。 6. 在训练结束后,使用测试数据对模型进行评估,并计算预测准确率。 7. 最后,可以将经过训练的模型应用于新的手写数字图像进行预测,以验证模型的泛化能力。 下载该例程后,可以通过在Python环境中运行该文件,逐步学习和理解各个部分的代码和功能。这个例程对于初学者来说是一个非常好的学习资源,可以帮助他们理解TensorFlow的基本使用方法和卷积神经网络的原理。同时,CSDN上还有许多相关的教程和博客,可以进一步扩展和深入了解这个例程的细节和应用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值