【深度學習筆記】(二)Hello, Tensorflow!
一、安裝
官方安裝的方式很多種,本文采用Docker方式。Docker的深入使用文案很長很多,但我們都不需要,我們的主要目的還是Tensorflow,所以只需要基本的使用即可。PS:打開Tensorflow官網是需要翻牆的,所以上面的一些鏈接不能翻牆的情況下是打不開的,然鵝!Docker不需要翻牆就能打開,所以用Docker來安裝Tensorflow就是爲了繞牆而走。
1、Docker安裝
既然不用翻牆,首先就是點我下載安裝包,打開頁面看到很多開發平臺的版本,選擇匹配自己開發平臺的包下載安裝即可,安裝的過程就是一直點“下一步”。。。over。
安裝成功後,會有兩個入口:
第一個既然看不清名稱就不用官他,也可以看得清也不要管他,因爲我們只需要用第二個:Kitmatic,我們僅用用Kitmatic來操作Docker來提供Tensorfow的,不需要要學習第一個命令行的操作方式。
2、Kitmatic安裝Tensorflow環境
點擊第1步中的第二個圖標啓動Kitmatic;點擊左上角的”NEW”按鈕:
進入下圖,在輸入框中輸入Tensorflow搜索,在Docker Hub搜索中選擇一個,一般是第一個,點擊“CREATE”按鈕下載安裝。
其他Jupyter Notebook、Tensorboard都可以在這裏找到下載安裝。
二、Hello, Tensorflow
1、編程步驟:
- 定義數據
- 定義計算圖與變量
- 定義會話
- 進行計算
2、基於MNIST數據集的手寫數字識別
這是很多教科書上的入門例子,但是沒有說明其中代碼依賴導致運行不起來。所以首先作爲Tensorflow的入門例子,應該是包括在Tensorflow代碼裏的,先要把它clone下來:
git clone https://github.com/tensorflow/tensorflow
這時候可能因爲權限問題無法拉下來,先去fork一份到自己名下就行了,或者直接打包下載。
接下來就能把代碼跑起來了,寫一遍感受一下:
# 1、load data set
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# 2、see data set:
# train - test - validation
# train data set
# print(mnist.train.images.shape,mnist.train.labels.shape)
# test data set
# print(mnist.test.images.shape,mnist.test.labels.shape)
# validation data set
# print(mnist.validation.images.shape,mnist.validation.labels.shape)
# 3、開啓tensorflow session
import tensorflow as tf
sess = tf.InteractiveSession()
# 4、define softmax regression
# x
x = tf.placeholder(tf.float32,[None,784])
# W
W = tf.Variable(tf.zeros([784,10]))
# b
b = tf.Variable(tf.zeros(10))
# y
y = tf.nn.softmax(tf.matmul(x,W) + b)
# y_
y_ = tf.placeholder(tf.float32,[None,10])
# loss
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))
# SGD
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# init
tf.global_variables_initializer().run()
# 5、trainning starts
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
train_step.run({x:batch_xs, y_:batch_ys})
# trainning ends
# correct predictiong
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
# accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
# evalue
print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels}))