simple版本nn模型 訓練手寫數字處理
MNIST_data數據 百度網盤鏈接:https://pan.baidu.com/s/19lhmrts-vz0-w5wv2A97gg
提取碼:cgnx
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #載入數據集 mnist=input_data.read_data_sets("MNIST_data", one_hot=True) #每個批次的大小 batch_size=100 #計算一共有多少批次 n_batch=mnist.train.num_examples // batch_size #定義兩個placeholder x=tf.placeholder(tf.float32,[None,784]) y=tf.placeholder(tf.float32,[None,10]) #創建一個簡單的神經網絡 W=tf.Variable(tf.zeros([784,10])) b=tf.Variable(tf.zeros([1,10])) prediction=tf.nn.softmax(tf.matmul(x,W)+b) #二次代價函數 loss=tf.reduce_mean(tf.square(y-prediction))
#使用剃度下降法 train_step=tf.train.GradientDescentOptimizer(0.2).minimize(loss) #初始化變量 init=tf.global_variables_initializer() #結果存放在一個布爾型列表中 correct_prediction=tf.equal(tf.argmax(y,1), tf.argmax(prediction,1)) #argmax返回一維張量中最大的值所在的位置 #求准確率 accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) with tf.Session() as sess: sess.run(init) for epoch in range(20): for batch in range(n_batch): batch_xs,batch_ys=mnist.train.next_batch(batch_size) sess.run(train_step,feed_dict={x:batch_xs, y:batch_ys}) acc=sess.run(accuracy,feed_dict={x:mnist.test.images, y:mnist.test.labels}) print("Iter"+str(epoch)+",Testing Accuracy "+str(acc))
如果我們把上邊代碼的二次代價函數換成下邊這行代碼,其余不變,得到的結果會更好一些,具體原因看下篇博客 對交叉墒和二次代價函數的介紹
loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))
目錄:
- tensorflow簡介、目錄
- tensorflow中的圖(02-1)
- tensorflow變量的使用(02-2)
- tensorflow中的Fetch、Feed(02-3)
- tensorflow版helloworld---擬合線性函數的k和b(02-4)
- tensorflow非線性回歸(03-1)
- MNIST手寫數字分類simple版(03-2)
- 二次代價函數、交叉熵(cross-entropy)、對數似然代價函數(log-likelihood cost)(04-1)
- 多層網絡通過防止過擬合,增加模型的准確率(04-2)
- 修改優化器進一步提升准確率(04-3)
- 手寫數字識別-卷積神經網絡cnn(06-2)
- 循環神經網絡rnn與長短時記憶神經網絡簡述(07-2)
- 循環神經網絡lstm代碼實現(07-3)
- tensorflow模型保存和使用08
- 下載inception v3 google訓練好的模型並解壓08-3
- 使用inception v3做各種圖像分類識別08-4
- word2vec模型訓練簡單案例
- word2vec+textcnn文本分類簡述及代碼