接下來開始接觸深度學習的內容----卷積神經網路(cnn)
通過加入卷積網路來改善單一softmax回歸、隨機梯度下降**的結果
import tensorflow as tf
from tensorflow_core.examples.tutorials.mnist import input_data
defweight_variable
(shape)
:#標準差為0.1的隨機正態分佈
inital = tf.truncated_normal(shape,stddev=
0.1)
return tf.variable(inital)
defbias_weight
(shape)
:#建立乙個常量tensor,按照給出value=0.1來賦值,可以用shape來指定其形狀
inital = tf.constant(
0.1,shape=shape)
return tf.variable(inital)
defconv2d
(x,w)
:return tf.nn.conv2d(x,w,strides=[1
,1,1
,1],padding=
'same'
)def
max_pool_2x2
(x):
return tf.nn.max_pool(x,ksize=[1
,2,2
,1],strides=[1
,2,2
,1],padding=
'same'
)mnist = input_data.read_data_sets(
'mnist_dataset/'
, one_hot=
true
)#靈活構件**,能夠在執行圖時,插入計算圖
sess = tf.interactivesession(
)#佔位符
x = tf.placeholder(
'float',[
none
,784])
y_ = tf.placeholder(
'float',[
none,10
])#變數w = tf.variable(tf.zeros(
[784,10
]))b = tf.variable(tf.zeros([10
]))#第一層卷積、池化
w_conv1 = weight_variable([5
,5,1
,32])
b_conv1 = bias_weight([32
])#將原來改為中間兩維表示對應的寬高,最後一維代表顏色通道數
x_image = tf.reshape(x,[-
1,28,
28,1]
)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_weight([64
])h_conv2 = tf.nn.relu(conv2d(h_pool1,w_conv2)
+b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
#全連線層
#經過[1,2,2,1]兩個池化,變為28*28*1->14*14*32->7*7*64
w_fc1 = weight_variable([7
*7*64
,1024])
b_fc1 = bias_weight(
[1024])
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(
'float'
)h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
#輸出層
w_fc2 = weight_variable(
[1024,10
])b_fc2 = bias_weight([10
])#softmax
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop,w_fc2)
+b_fc2)
#交叉熵
cross_entropy =
-tf.reduce_sum(y_*tf.log(y_conv)
)#adam梯度下降
train_step = tf.train.adamoptimizer(1e-
4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1)
, tf.argmax(y_,1)
)# tf.cast 將correct_prediction轉化為「float」型別
accuracy = tf.reduce_mean(tf.cast(correct_prediction,
"float"))
#變數初始化
sess.run(tf.initialize_all_variables())
#訓練for i in
range
(20000):
batch = mnist.train.next_batch(50)
if i%
100==0:
train_accuray = accuracy.
eval
(feed_dict=
)print
('step %d, training accuracy %g'
%(i,train_accuray)
) train_step.run(feed_dict=
)print
('test accuray %g'
%accuracy.
eval
(feed_dict=
))
Caffe學習 2 Mnist的測試
mnist,乙個經典的手寫數字的影象數字庫,由紐約大學的yann lecun教授整理,包含60000個訓練樣本和10000個測試樣本,大小為28 28,在caffe上配置的第乙個案例。用的網路模型是lenet,它是公認在數字分類任務上效果很好的網路。實驗中在原始 lenet基礎上做了一點改動,對於神...
人工智慧學習(1)MNIST入門
好久沒有用到tensorflow了,把機器學習和深度學習扔了有一年了,今天撿起來發現自己還是如此有興趣,決定從頭開始學習的過程中來重新撿起快遺忘的知識。首先開始 從mnist手寫識別開始,我是通過tensorflow中文社群的教程學習的,總結一下這個過程中遇到的問題。tensorflow已經出到2....
人工智慧 2 智慧型體
理性智慧型體 任務環境 智慧型體的結構 智慧型體的類別 亞符號ai 反邏輯 聯結主義ai 機器智慧型體 機械人 軟體智慧型體 軟體機械人 抽象智慧型體 各種定義 正確的行為 理性的動作 理性的 探索 學習 自主 理性的動作,對給定的感知序列,能使期待的效能指標最大化 理性的概念 example pe...