以下是根據莫煩Python的程序
https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/5-01-classifier/
還有一個作者寫的挺好的
http://blog.csdn.net/wuyzhen_csdn/article/details/64920773
初步構建出基于tensorflow的一個簡單的神經網絡
運用的數據是mnist手寫字符庫
構建了三層的網絡 輸入層,隱藏層,輸出層
代碼如下
import tensorflow as tf
#下載或者加載mnist手寫庫
from tensorflow.examples.tutorials.mnist import input_data
# number 1 to 10 data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
def add_layer(inputs, in_size, out_size, activation_function=None,):
# add one more layer and return the output of this layer
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1,)
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b,)
return outputs
#計算識別的準確度
def compute_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs})
correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
return result
# define placeholder for inputs to network
xs = tf.placeholder(tf.float32,[None,784]) #28*28
ys = tf.placeholder(tf.float32,[None,10]) #10輸出
#add output layer
prediction = add_layer(xs,784,10,activation_function=tf.nn.softmax)
#the error between prediction and real data
#loss函數(即最優化目標函數)選用交叉熵函數
#交叉熵用來衡量預測值和真實值的相似程度,如果完全相同,它們的交叉熵等于零。
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
reduction_indices=[1]))
##tf.log計算y中元素的對數,tf.reduce_sum計算y中第2維元素的相加
##(y為tensor with shape[None, 10]),因為參數reduction_indices=[1]
##最后tf.reduce_mean計算平均值,在源代碼中我們不使用該方程,
##因為它數字上不是穩定的對于非規范化的邏輯,
##使用tf.nn.softmax_cross_entropy_with_logits
## cross_entropy = tf.reduce_mean(
## tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
##sess = tf.Session()
###現在可以運行模型,通過InteractiveSession
sess = tf.InteractiveSession();
# important step
# tf.initialize_all_variables() no long valid from
# 2017-03-02 if using tensorflow >= 0.12
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
else:
init = tf.global_variables_initializer()
sess.run(init)
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})
if i % 50 == 0:
print(compute_accuracy(
mnist.test.images, mnist.test.labels))