from__future__importprint_function#即使是在python2版本也要像在python3中使用print函式fromtensorflow.examples.tutorials.mnistimportinput_data
mnist = input_data.read_data_sets("/tmp/data/",one_hot=true)#onehot對標籤的標註,非onehot是1,2,3.onehot就是只有乙個1其餘全是0
importtensorflowastf
#超引數(學習率,batch的大小,訓練的輪數,多少輪展示一下loss)
learning_rate = 0.1
num_step = 500
batch_size = 128
display_step =100
#網路引數(有多少層網路,每層有多少個神經元,整個網路的輸入是多少維度的,輸出是多少維度的)
n_hidden_1 = 256
n_hidden_2 = 256
num_input = 784
#(28*28)
num_class = 10
#圖的輸入
x = tf.placeholder("float",[none,num_input])
y = tf.placeholder("float",[none,num_class])
#網路的權重和偏向,如果是兩個隱層的話需要定義三個權重,包括輸出層
weights=
biase =
#定義網路結構
defneural_net(x):
layer_1 = tf.add(tf.matmul(x,weights['h1']),biase['b1'])
layer_2 = tf.add(tf.matmul(layer_1,weights['h2']),biase['b2'])
out_layer = tf.add(tf.matmul(layer_2,weights['out']),biase['out'])
returnout_layer
#模型輸出處理
logits = neural_net(x)
prediction = tf.nn.softmax(logits)
#定義損失和優化器
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=y))
optimizer = tf.train.adamoptimizer(learning_rate = learning_rate)
train_op = optimizer.minimize(loss_op)
#評估模型準確率
correct_pred = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred,tf.float32))
#初始化變數
init = tf.global_variables_initializer()
#開始訓練
withtf.session()assess:
sess.run(init)
forstepinrange(1,num_step+1):
batch_x,batch_y = mnist.train.next_batch(batch_size)
ifstep % display_step == 0
orstep == 1:
loss,acc = sess.run([loss_op,accuracy],feed_dict=)
print("step:{},loss:{},acc:{}".format(step,loss,acc))
print("優化完成!")
#訓練完模型後,開始測試
print("testing accuracy:",sess.run(accuracy,feed_dict=))
tensorflow實現MNIST手寫數字識別
mnist資料集是由0 9,10個手寫數字組成。訓練影象有60000張,測試影象有10000張。from tensorflow.examples.tutorials.mnist import input data mnist input data.read data sets mnist data ...
tensorflow實踐 手寫MNIST數字識別
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input data 載入資料集,讀取的是壓縮包 mnist input data.read data sets mnist one hot true 每個...
Tensorflow實現DNN,手寫數字識別
from tensorflow.examples tutorials mnist import input data mnist input data.read data sets g tensorflow data one hot true import tensorflow as tf lear...