1. 程式人生 > >tensorflow 學習 softmax Regression 識別手寫數字

tensorflow 學習 softmax Regression 識別手寫數字

下面程式碼是來自 tensorflow 實戰一書,

主要包括三個部分:
1.構建模型 y=w*x+b
2.構建損失函式模型-交叉熵
3.構建查詢最優值方法–梯度下降

#!/user/bin/env python
import tensorflow as tf

sess = tf.InteractiveSession()

 # x is feature value
x = tf.placeholder(tf.float32, [None, 784])

 # w is weight for feature
w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable
(tf.zeros([10])) #構建模型 y = tf.nn.softmax(tf.matmul(x,w) + b) # y_ is true value y_ = tf.placeholder(tf.float32, [None, 10]) #通過交叉熵計算損失函式 cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1])) learn_rate = 0.5 train_step = tf.train.GradientDescentOptimizer(learn_rate).minimize
(cross_entropy) tf.global_variables_initializer().run() #開始訓練 for _ in range(10000): #select 100 data as training set batch_xs, batch_ys = mnist_data.train.next_batch(100) train_step.run({x: batch_xs, y_: batch_ys}) #計算準確率 correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(y_, 1)) accuracy = tf.reduce
_mean(tf.cast(correct_prediction, tf.float32)) print(accuracy.eval({x: mnist_data.test.images,y_: mnist_data.test.labels}))