Tensorflow逻辑回归处理MNIST数据集
生活随笔
收集整理的這篇文章主要介紹了
Tensorflow逻辑回归处理MNIST数据集
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#1:導入所需的軟件
import tensorflow as tf
'''
獲取mnist數據放在當前文件夾下,利用input_data函數解析該數據集
train_img和train——label構成訓練集,包含60000個手寫體數字圖片和對應的標簽
test_img和test_label表示測試集,包含10000個樣本和10000個標簽
'''
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data/',one_hot=True)train_img = mnist.train.images
train_label = mnist.train.labels
test_img = mnist.test.images
test_label = mnist.test.labels#3:在Tensorflow圖中為訓練數據集的輸入x和標簽y創建占位符x = tf.compat.v1.placeholder(tf.float32,[None,784],name='X')
y = tf.compat.v1.placeholder(tf.float32,[None,10],name='Y')#4:創建學習變量,權重和偏置W = tf.compat.v1.Variable(tf.zeros([784,10]),name='W')
b = tf.compat.v1.Variable(tf.zeros([10]),name='b')#5:創建邏輯回歸模型。y_hat = tf.nn.softmax(tf.matmul(x,W)+b)#6: 損失(loss)函數loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=y_hat))#7:采用Tensorflow GradientDescentOptimizer,學習率為0.01optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)#預測結果
pred = tf.equal(tf.argmax(y_hat,1),tf.argmax(y,1))#計算準確率
accuracy = tf.reduce_mean(tf.cast(pred,'float'))#8:為變量進行初始化:
init = tf.global_variables_initializer()
training_epochs = 50
batch_size = 100
display_step = 5with tf.compat.v1.Session() as sess:sess.run(init)summary_writer = tf.summary.FileWriter('graphs3',sess.graph)for epoch in range(training_epochs):loss_avg = 0num_of_batch = int(mnist.train.num_examples/batch_size)for i in range(num_of_batch):batch_xs,batch_ys = mnist.train.next_batch(batch_size)feeds_train = {x:batch_xs,y:batch_ys}sess.run([optimizer,loss],feed_dict=feeds_train)loss_avg+=sess.run(loss,feed_dict=feeds_train)/num_of_batch#訓練過程輸出if epoch % display_step ==0:feeds_test = {x:mnist.test.images,y:mnist.test.labels}train_acc = sess.run(accuracy,feed_dict=feeds_train)test_acc = sess.run(accuracy,feed_dict=feeds_test)print()print('Epoch {0}:Loss {1}:train_acc:{2}:test_acc:{3}'.format(epoch,loss_avg,train_acc,test_acc))print("Done")
結果輸入
總結
以上是生活随笔為你收集整理的Tensorflow逻辑回归处理MNIST数据集的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: omnigraffle 的一些总结
- 下一篇: KRPano JS 场景编辑器源码