您的位置:首页 > 其它

使用自己的图片测试MNIST训练效果(TensorFlow1.5+CNN)

2018-02-09 15:02 726 查看
作为初学者研究了两周的TensorFlow基础的东西。首先是MNIST数据集在CNN的训练。中间经历了很多问题。
现在TensorFlow的版本已经更新到1.5,出了很多高级API,所以很多博客都不再合适了。
基于TensorFlow+anaconda在CNN训练MNIST之后,关于保存模型以及重新载入先关模型参数又折腾了一阵。原来老版本的方法,就是中文社区的MNIST训练之后使用保存数据,预测结果很差。这次做出来比较靠谱的结果。
我使用的是已经训练好的模型。所以程序里没有训练和评估。这些相关的代码在官方给的例子里已经有了。所以我直接用已经得到的数据进行预测了。



 这是我的训练结果,其实1W次我感觉就够了。我不小心弄到了4w.
注意使用的图片,28*28像素。(直接在画图工具里设定好分辨率,比用CV PIL快多了。。。。)。MNIST数据集里是黑底白字。我用画图做的是白底黑字,需要取反。
另外,如果训练的精度够了,不需要进行额外的图像处理(什么滤波啦,倾斜啦)


---我的


---MNIST的
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from PIL import Image
import numpy as np
import tensorflow as tf
def loaddata(filename):
#转换成灰度图也就是单通道。
img=Image.open(filename).convert('L')
#取出数据
array=np.asarray(img,dtype="float32")
#取反。
array=abs(255-array) #如果图像和MNIST里的一样,这里要注释
return array
'''下面这部分和教程中的model一样'''
def cnn_model_fn(features, labels, mode):
"""Model function for CNN."""
# Input Layer
# Reshape X to 4-D tensor: [batch_size, width, height, channels]
# batch_size:Size of the subset of examples to use when performing gradient descent during training
# MNIST images are 28x28 pixels, and have one color channel
# x----输入图像,我们希望能用任意张。所以batch_size用-1。如果我们feed batch=5.shape=[5,28,28,1]
# features["x"]=5*28*28.这样我们就构建好了输入层
input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])

# Convolutional Layer #1
# Computes 32 features using a 5x5 filter with ReLU activation.
# Padding is added to preserve width and height.
# Input Tensor Shape: [batch_size, 28, 28, 1]
# Output Tensor Shape: [batch_size, 28, 28, 32]
conv1 = tf.layers.conv2d(
inputs=input_layer,
filters=32, # 每张图卷积要取出的特征数。
kernel_size=[5, 5], # 卷积大小。kernel_size=5(if w=h)
padding="same", # 使用same表示输出张量和输入张量大小相同。用0去填补张量边缘
activation=tf.nn.relu # 指定使用什么激活函数来激活卷积。这里我们用ReLU神经元。
)

# Pooling Layer #1
# First max pooling layer with a 2x2 filter and stride of 2
# Input Tensor Shape: [batch_size, 28, 28, 32]
# Output Tensor Shape: [batch_size, 14, 14, 32]
pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

# Convolutional Layer #2
# Computes 64 features using a 5x5 filter.
# Padding is added to preserve width and height.
# Input Tensor Shape: [batch_size, 14, 14, 32]
# Output Tensor Shape: [batch_size, 14, 14, 64]
conv2 = tf.layers.conv2d(
inputs=pool1,
filters=64,
kernel_size=[5, 5],
padding="same",
activation=tf.nn.relu)

# Pooling Layer #2
# Second max pooling layer with a 2x2 filter and stride of 2
# Input Tensor Shape: [batch_size, 14, 14, 64]
# Output Tensor Shape: [batch_size, 7, 7, 64]
pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

# Flatten tensor into a batch of vectors
# Input Tensor Shape: [batch_size, 7, 7, 64]
# Output Tensor Shape: [batch_size, 7 * 7 * 64]
pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])

# Dense Layer
# Densely connected layer with 1024 neurons!!!
# Input Tensor Shape: [batch_size, 7 * 7 * 64]
# Output Tensor Shape: [batch_size, 1024]
dense = tf.layers.dense(
inputs=pool2_flat, units=1024, activation=tf.nn.relu)

# Add dropout operation; 0.6 (1-0,4)probability that element will be kept
dropout =
4000
tf.layers.dropout(
inputs=dense, rate=0.4,
# dropout will only be performed if training is True
training=mode == tf.estimator.ModeKeys.TRAIN
)

# Logits layer
# Input Tensor Shape: [batch_size, 1024]
# Output Tensor Shape: [batch_size, 10]
logits = tf.layers.dense(inputs=dropout, units=10)

predictions = {
# Generate predictions (for PREDICT and EVAL mode)
"预测值": tf.argmax(input=logits, axis=1), # 选择logits中最大的
# Add `softmax_tensor` to the graph. It is used for PREDICT and by the
# `logging_hook`.
"概率": tf.nn.softmax(logits, name="softmax_tensor")
}
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

# Calculate Loss (for both TRAIN and EVAL modes)
loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

# Configure the Training Op (for TRAIN mode)
if mode == tf.estimator.ModeKeys.TRAIN:
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
# 这是我们需要训练的op
train_op = optimizer.minimize(
loss=loss,
global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

# Add evaluation metrics (for EVAL mode) 准确性度量
eval_metric_ops = {
"accuracy": tf.metrics.accuracy(
labels=labels, # 这是我们给定的labels。
# tf.argmax(input=logits, axis=1)。这是logit层得到的。
predictions=predictions["classes"]
)}
return tf.estimator.EstimatorSpec(
mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)

def main():

#创建一个Estimator。
classifier=tf.estimator.Estimator(
model_fn=cnn_model_fn, #模型使用CNN
model_dir="./mnist_convnet_model" #checkpoints所在位置
)

#读入数据
predict_data=loaddata("./photo/77.png")#根据自己的图像位置修改
predict_input_fn=tf.estimator.inputs.numpy_input_fn(
x={"x":predict_data},#自己的数据
shuffle=False #一定要为false
)
#进行预测
predict_results=classifier.predict(input_fn=predict_input_fn)
#预测值
print((list(predict_results)))

main()

结果。我CPU版本的。运行时间比较久。正确率很高,但是也有认不出的,甚至用MNIST数据集的图像都会错,不过出错概率更低一些。
另外如果图像不一样,它的结果一直都是“8”



使用文件夹的所有图像,还是比较准的

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  深度学习 TensorFlow