from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
mnist = input_data.read_data_sets("mnist_data/", one_hot=true)
sess = tf.interactivesession()
def weight_variable(shape):
#從截斷的正態分佈輸出隨機值
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.variable(initial)
def bias_variable(shape):
#建立乙個常量張良,傳入list或者數值來填充
initial = tf.constant(0.1, shape=shape)
return tf.variable(initial)
def conv2d(x, w):
#二維卷積函式,x是輸入,w卷積的引數;[5,5,1,32]前面兩個數字代表卷積核的尺寸。
#第三個數字代表channel,最後乙個代表卷積核的數量;strides代表卷積模板移動的步長;
#padding代表邊界的處理方式
return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='same')
def max_pool_2x2(x):
#最大池化函式
#使用2x2的最大池化,即將乙個2x2的畫素塊降為1x1的畫素
#最大池化會保留原始畫素塊中灰度值最高的那乙個畫素,即保留最顯著的特徵
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='same')
#x是特徵,y_是真是的label
x = tf.placeholder(tf.float32, [none, 784])
y_ = tf.placeholder(tf.float32, [none, 10])
x_image = tf.reshape(x, [-1,28,28,1])
w_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
w_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
#經過兩次池化操作,尺寸為7x7
w_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
#對第二個卷積層的輸出tensor進行變形,將其轉成1d的向量
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)
#dropout層
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
w_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2) + b_fc2)
#定義損失函式
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))
#優化器使用adam,並給予乙個比較小的學習速率1e-4
train_step = tf.train.adamoptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.global_variables_initializer().run()
for i in range(20000):
batch = mnist.train.next_batch(50)
#每一百次輸出一次準確率
if i%100 == 0:
train_accuracy = accuracy.eval(feed_dict=)
print("step %d, training accuracy %g"%(i, train_accuracy))
train_step.run(feed_dict=)
print("test accuracy %g"%accuracy.eval(feed_dict=))
Tensorflow實戰 張量
import tensorflow as tf tf.constant 是乙個計算,這個計算的結果為乙個張量,儲存在變數a中。a tf.constant 1.0,2.0 name a b tf.constant 2.0,3.0 name b result tf.add a,b,name add pr...
tensorflow實戰 反向傳播
windows10 anaconda3 64位 batch size 8 每次訓練的資料量 seed 23455 隨機種子 rng np.random.randomstate seed x rng.rand 32,2 產生32行2列的隨機矩陣 y int x0 x1 1 for x0,x1 in x...
《tensorflow實戰》之實現多層感知器(二)
理論研究表明,神經網路隱含層,層數越多,所需要的隱含節點可以越少。有一種方法叫dropout,在使用複雜的卷積神經網路訓練影象資料時尤其有效,簡單說,就是將神經網路某一層的輸出節點資料隨機丟棄一部分。實質上等於創造出了很多新的隨機樣本,通過增大樣本量 減少特徵數量來防止過擬合。拿sgd來舉例,不同的...