1. 程式人生 > >Tensorflow擼程式碼之2邏輯迴歸

Tensorflow擼程式碼之2邏輯迴歸

邏輯迴歸


詳細地址
# _*_ encoding=utf8 _*_

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("data/", one_hot=True)
# 設定學習率,
learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_step = 1

#圖片都是28*28 = 784的  預測為0-9 10個數字  10分類
x = tf.placeholder(tf.float32, [None, 784]) y = tf.placeholder(tf.float32, [None, 10]) # 初始化引數的值 W = tf.Variable(tf.zeros([28*28, 10]),name="W") b = tf.Variable(tf.zeros([10])) # 前向傳播 pred = tf.nn.softmax(tf.matmul(x, W) + b) # 使用交叉熵作為損失函式 cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=
1)) # 梯度下降求最佳的cost optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) print(W) #<tf.Variable 'W:0' shape=(784, 10) dtype=float32_ref> for epoch in range(training_epochs): # 得到資料總的batch
total_batch = int(mnist.train.num_examples / batch_size) # print(total_batch) #550 個batch 55000張訓練資料 # 每一訓練 都去求得平均的cost avg_cost = 0 #batch訓練 遍歷所以得batch for i in range(total_batch): batch_x,batch_y = mnist.train.next_batch(batch_size) # 訓練引數 _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,y: batch_y}) avg_cost += c / total_batch # 計算每一次迭代的cost if (epoch + 1) % display_step == 0: print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(avg_cost)) #評估模型 訓練出來的結果tf.argmax(pred, 1) 找10個數最大的那個 和真實值y對比 correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) # 計算準確率 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # 使用mnist的test資料進行評估 # 首先執行之前的所有必要的操作來產生這個計算這個tensor需要的輸入,然後通過這些輸入產生這個tensor。 print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))