1. 程式人生 > >tensorflow 卷積神經網絡預測手寫 數字

tensorflow 卷積神經網絡預測手寫 數字

擬合 圖片地址 prepare nis 定義 imp ons put inpu

# coding=utf8

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from PIL import Image

def imageprepare(file_name):
"""
This function returns the pixel values.
The imput is a png file location.
"""
#file_name=‘d:/ddd.png‘#導入自己的圖片地址
#in terminal ‘mogrify -format png *.jpg‘ convert jpg to png
im = Image.open(file_name).convert(‘L‘)
im.show()
im = im.resize((28, 28))
print(im)


im.save("d:/log/sample.png")
#plt.imshow(im)
# plt.show()
tv = list(im.getdata()) #get pixel values

print(type(tv))

#normalize pixels to 0 and 1. 0 is pure white, 1 is pure black.
tva = [ ((255-x)*1.0)/255.0 for x in tv]
print(type(tva))
return tva

# 產生隨機變量,符合 normal 分布
# 傳遞 shape 就可以返回weight和bias的變量
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)


# 定義2維的 convolutional 圖層
def conv2d(x, W):
# stride [1, x_movement, y_movement, 1]
# Must have strides[0] = strides[3] = 1
# strides 就是跨多大步抽取信息
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=‘SAME‘)


# 定義 pooling
def max_pool_2x2(x):
# stride [1, x_movement, y_movement, 1]
# 用pooling對付跨步大丟失信息問題
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=‘SAME‘)


# 讀取數據
mnist = input_data.read_data_sets("D:/MNIST_data", one_hot=True)

# 為輸入圖像和目標輸出類別創建節點,來開始構建計算圖。x和y是占位符
x = tf.placeholder("float", shape=[None, 784]) # 784=28x28
y_ = tf.placeholder("float", shape=[None, 10])

‘‘‘1. conv1 layer‘‘‘
# 把x_image的厚度1加厚變成了32
W_conv1 = weight_variable([5, 5, 1, 32]) # patch 5x5, in size 1, out size 32
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1, 28, 28, 1]) # 最後一個1表示數據是黑白的

#conv1 第一層卷積
conv1 = conv2d(x_image, W_conv1)

# 構建第一個convolutional層,然後加一個非線性化的處理relu 計算激活函數relu,即max(features, 0)。即將矩陣中每行的非最大值置0。
h_conv1 = tf.nn.relu(conv1 + b_conv1) # output size 28x28x32

# 經過pooling後,長寬縮小為14x14
h_pool1 = max_pool_2x2(h_conv1) # output size 14x14x32

‘‘‘2. conv2 layer‘‘‘
# 把厚度32加厚變成了64
W_conv2 = weight_variable([5, 5, 32, 64]) # patch 5x5, in size 32, out size 64
b_conv2 = bias_variable([64])
# 構建第二個convolutional層
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # output size 14x14x64
# 經過pooling後,長寬縮小為7x7
h_pool2 = max_pool_2x2(h_conv2) # output size 7x7x64

‘‘‘3. func1 layer‘‘‘
# 變成1024
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
# [n_samples, 7, 7, 64] ->> [n_samples, 7*7*64]
# 把pooling後的結果變平
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("float")


#Dropout就是在不同的訓練過程中隨機扔掉一部分神經元,防止過擬合
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

‘‘‘4. func2 layer‘‘‘
# 最後一層,輸入1024,輸出size 10,用 softmax 計算概率進行分類的處理
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
# 向量化後的圖片x和權重矩陣W相乘,加上偏置b,然後計算每個分類的softmax概率值。
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

# 損失函數定義為交叉熵
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
# 最梯度下降法讓交叉熵下降,步長為0.01
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # 3333333333 test accuracy 0.9922
# train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy)
# 計算分類的準確率,tf.equal 來檢測我們的預測是否真實標簽匹配
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
# 計算出匹配結果correct_prediction的平均值為,如[1,0,1,1]為0.75 tf.cast 數據格式轉換
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

# 創建一個Saver對象,選擇性保存變量或者模型。
#訓練
saver = tf.train.Saver()

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(20000):
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}))

# 保存模型到model.ckpt
save_path = saver.save(sess, "model/model.ckpt")
print("Model saved in file: ", save_path)

prediction=tf.argmax(y_conv,1)

predint=prediction.eval(feed_dict={x: [result],keep_prob: 1.0}, session=sess)

print("result =", predint)

"""

#測試
result = imageprepare(‘d:/ddd.png‘)


saver = tf.train.Saver()
with tf.Session() as sess:
# 讀取模型
saver.restore(sess, "model/model.ckpt")
print("Model restored.")
print("test accuracy %g" % accuracy.eval(feed_dict={
x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
prediction=tf.argmax(y_conv,1)

predint=prediction.eval(feed_dict={x: [result],keep_prob: 1.0}, session=sess)

print("result =", predint)

"""

tensorflow 卷積神經網絡預測手寫 數字