TensorFlow MNIST 求助

2017-07-05 16:45:56 +08:00
 zbl430
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import time
import input_data
import tensorflow as tf


def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)


def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)


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')


# 计算开始时间
start = time.clock()
# MNIST 数据输入
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

x = tf.placeholder(tf.float32, [None, 784])  # 图像输入向量
W = tf.Variable(tf.zeros([784, 10]))  # 权重,初始化值为全零
b = tf.Variable(tf.zeros([10]))  # 偏置,初始化值为全零

# 第一层卷积,由一个卷积接一个 maxpooling 完成,卷积在每个
# 5x5 的 patch 中算出 32 个特征。
# 卷积的权重张量形状是[5, 5, 1, 32],前两个维度是 patch 的大小,
# 接着是输入的通道数目,最后是输出的通道数目。
# 而对于每一个输出通道都有一个对应的偏置量。
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])

x_image = tf.reshape(x, [-1, 28, 28, 1])  # 最后一维代表通道数目,如果是 rgb 则为 3
# x_image 权重向量卷积,加上偏置项,之后应用 ReLU 函数,之后进行 max_polling
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

# 实现第二层卷积

# 每个 5x5 的 patch 会得到 64 个特征
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)
h_pool2 = max_pool_2x2(h_conv2)

# 密集连接层
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, 用来防止过拟合 #加在输出层之前,训练过程中开启 dropout,测试过程中关闭
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

# 输出层, 添加 softmax 层
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)

# 训练和评估模型
y_ = tf.placeholder("float", [None, 10])
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))  # 计算交叉熵
# 使用 adam 优化器来以 0.0001 的学习率来进行微调
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"))

# 启动创建的模型,并初始化变量
saver = tf.train.Saver()  # 声明 tf.train.Saver 类用于保存模型 write_version=tf.train.SaverDef.V1
sess = tf.Session()
sess.run(tf.initialize_all_variables())

# 开始训练模型,循环训练 20000 次
for i in range(20000):
    batch = mnist.train.next_batch(100)  # batch 大小设置为 50
    if i % 1000 == 0:
        train_accuracy = accuracy.eval(session=sess, feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
        print("step %d, train_accuracy %g" % (i, train_accuracy))
    # 神经元输出保持不变的概率 keep_prob 为 0.5
    train_step.run(session=sess, feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

# 神经元输出保持不变的概率 keep_prob 为 1,即不变,永远保持输出
print("test accuracy %g" % accuracy.eval(session=sess, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

# 计算程序结束时间
end = time.clock()
saver_path = saver.save(sess, "save/model.ckpt")  # 将模型保存到 save/model.ckpt 文件
print("Model saved in file:", saver_path)
print("running time is %g s" % (end - start))

上面的代码将训练的结果进行保存

下面的代码使用训练结果进行识别

#! /usr/bin/env python
# -*- coding: utf-8 -*-

""""""
from PIL import Image
from numpy import *
import tensorflow as tf
import sys

if len(sys.argv) < 2:
    print('argv must at least 2. you give '+str(len(sys.argv)))
    sys.exit()
filename = sys.argv[1]
im = Image.open(filename)
img = array(im.resize((28, 28), Image.ANTIALIAS).convert("L"))
data = img.reshape([1, 784])

x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x, W) + b)

saver = tf.train.Saver()
init_op = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init_op)
    save_path = "./save/model.ckpt"
    saver.restore(sess, save_path)
    predictions = sess.run(y, feed_dict={x: data})
    print(predictions[0])

使用的图片是张黑白的 数字 4

结果是:[ 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1]

这结果不对啊,起码也应该是:[ 0.1 0.1 0.1 0.1 1.0 0.1 0.1 0.1 0.1 0.1]

求大神帮忙!!!!!

1898 次点击
所在节点    TensorFlow
2 条回复
ivechan
2017-07-05 21:47:46 +08:00
你 train 的 model 结构和做 predict 的 model 结构完全不一样, 怎么可能得到正确结果。
你 train 的时候 model 是各种 cnn + pool +fc,predict 的 model 却是 只有一个简单的 fc layer。
或许你可以看看他怎么写
https://github.com/niektemme/tensorflow-mnist-predict
zbl430
2017-07-06 09:43:03 +08:00
@ivechan 真的非常感谢,我找了好久找的就是这个!!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/373262

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX