1. 程式人生 > >人工智能 tensorflow框架-->Softmax回歸模型的訓練與評估 09

人工智能 tensorflow框架-->Softmax回歸模型的訓練與評估 09

min 初始化 dict ntop ict port true on() run

import tensorflow as tf
import numpy as np

#mnist數據輸入
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(‘MNIST_data‘, one_hot=True)

x = tf.placeholder("float", [None, 784]) #placeholder是一個占位符,None表示此張量的第一個維度可以是任何長度的

#
w = tf.Variable(tf.zeros([784,10])) #定義w維度是:[784,10],初始值是0
b = tf.Variable(tf.zeros([10])) # 定義b維度是:[10],初始值是0

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

# loss
y_ = tf.placeholder("float", [None, 10])
cross_entropy = -tf.reduce_sum(y_*tf.log(y)) #用 tf.log 計算 y 的每個元素的對數。接下來,我們把 y_ 的每一個元素和 tf.log(y_) 的對應元素相乘。最後,用 tf.reduce_sum 計算張量的所有元素的總和。

# 梯度下降
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

# 初始化
init=tf.global_variables_initializer()

# Session
sess = tf.Session()
sess.run(init)

# 叠代
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
if i % 50 == 0:
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print("Setp: ", i, "Accuracy: ",sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

=====================================================================================
# 評估模型
#correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
#accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
#print sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})

=====================================================================================

附圖:

技術分享

技術分享

技術分享

技術分享

技術分享

人工智能 tensorflow框架-->Softmax回歸模型的訓練與評估 09