? ? ? ? TensorFlow是一個(gè)深度學(xué)習(xí)的庫(kù),上層支持Python語言,底層用C++實(shí)現(xiàn)具體操作。
? ? ? ? 它以圖graph的方式來建立操作序列,圖中的節(jié)點(diǎn)表示數(shù)學(xué)操作,連線表示數(shù)據(jù)的流動(dòng)方向。
? ? ? ? 它以定義和執(zhí)行分離的方式來編程,用圖來定義操作序列,然后建立session來執(zhí)行,執(zhí)行時(shí)可以把每個(gè)操作分配到不同的CPU、GPU上進(jìn)行,所以速度很快。
具體編程流程:
建立計(jì)算圖
初始化變量
建立會(huì)話
在會(huì)話中執(zhí)行圖
關(guān)閉會(huì)話
? ? ? ? 注意:需要注意不同版本之間的兼容性不是很好,下面的例子在Python3.5、TensorFlow 1.2版本下編譯執(zhí)行通過。
簡(jiǎn)單舉例
? ? ? ? 以上面圖中a=(b+c)?(c+2)來舉例,先導(dǎo)入tensorflow庫(kù),然后定義常量,再定義變量。
importtensorflowastf
# first, create a TensorFlow constant
const=tf.constant(2.0,name="const")
# create TensorFlow variables
b=tf.Variable(2.0,name='b')
c=tf.Variable(1.0,name='c')
? ? ? ? 再建立操作:
# now create some operations
d=tf.add(b,c,name='d')
e=tf.add(c,const,name='e')
a=tf.multiply(d,e,name='a')
? ? ? ? 再初始化所有變量:
# setup the variable initialisation
init_op=tf.global_variables_initializer()
? ? ? ? 最后建立并執(zhí)行session:
# start the session
withtf.Session()assess:
# initialise the variables
sess.run(init_op)
# compute the output of the graph
a_out=sess.run(a)
print("Variable a is {}".format(a_out))
? ? ? ? 具體執(zhí)行過程如下圖:
? ? ? ? 最終的執(zhí)行結(jié)果:
Variable a is 9.0
Process finished with exit code 0
神經(jīng)網(wǎng)絡(luò)舉例
? ? ? ? 以常見的神經(jīng)網(wǎng)絡(luò)基準(zhǔn)測(cè)試MNIST(圖片中阿拉伯?dāng)?shù)字的識(shí)別)為例,祥見注釋:
importtensorflowastf
fromtensorflow.examples.tutorials.mnistimportinput_data
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)# 從官方例子導(dǎo)入訓(xùn)練數(shù)據(jù)和測(cè)試數(shù)據(jù),導(dǎo)入后數(shù)據(jù)保存在當(dāng)前目錄的\MNIST_data目錄下。
# Python optimisation variables
learning_rate=0.5
epochs=10# 執(zhí)行10批次訓(xùn)練
batch_size=100# 每批次100個(gè)數(shù)據(jù)
# declare the training data placeholders
# input x - for 28 x 28 pixels = 784
x=tf.placeholder(tf.float32,[None,784])# 預(yù)留訓(xùn)練數(shù)據(jù)的輸入值
# now declare the output data placeholder - 10 digits
y=tf.placeholder(tf.float32,[None,10])# 預(yù)留訓(xùn)練數(shù)據(jù)的輸入值對(duì)應(yīng)的輸出值
# now declare the weights connecting the input to the hidden layer
W1=tf.Variable(tf.random_normal([784,300],stddev=0.03),name='W1')#定義第一層輸入層需要優(yōu)化的參數(shù)變量,計(jì)算公式為:y = x * W + b
b1=tf.Variable(tf.random_normal([300]),name='b1')
# and the weights connecting the hidden layer to the output layer
W2=tf.Variable(tf.random_normal([300,10],stddev=0.03),name='W2')#定義第二層隱藏層的參數(shù)變量。
b2=tf.Variable(tf.random_normal([10]),name='b2')
# calculate the output of the hidden layer
hidden_out=tf.add(tf.matmul(x,W1),b1)
hidden_out=tf.nn.relu(hidden_out)
# now calculate the hidden layer output - in this case, let's use a softmax activated
# output layer
y_=tf.nn.softmax(tf.add(tf.matmul(hidden_out,W2),b2))# 計(jì)算隱藏層輸出
y_clipped=tf.clip_by_value(y_,1e-10,0.9999999)
cross_entropy=-tf.reduce_mean(tf.reduce_sum(y*tf.log(y_clipped)+(1-y)*tf.log(1-y_clipped),axis=1))#計(jì)算最終評(píng)估因子
# add an optimiser
optimiser=tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)# 定義一個(gè)對(duì)參數(shù)的BP優(yōu)化器
# finally setup the initialisation operator
init_op=tf.global_variables_initializer()# 初始化變量
# define an accuracy assessment operation
correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))# 定義精度
# start the session
withtf.Session()assess:#開始執(zhí)行
# initialise the variables
sess.run(init_op)
total_batch=int(len(mnist.train.labels)/batch_size)
forepochinrange(epochs):
avg_cost=0
foriinrange(total_batch):
batch_x,batch_y=mnist.train.next_batch(batch_size=batch_size)
_,c=sess.run([optimiser,cross_entropy],
feed_dict={x:batch_x,y:batch_y})
avg_cost+=c/total_batch
print("Epoch:",(epoch+1),"cost =","{:.3f}".format(avg_cost))
print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}))# 最終結(jié)果,精度
執(zhí)行結(jié)果,可以看到很不錯(cuò),精度有0.9742(1.0位為理想值):
Epoch:1 cost=0.768
Epoch:2 cost=0.245
Epoch:3 cost=0.183
Epoch:4 cost=0.152
Epoch:5 cost=0.125
Epoch:6 cost=0.108
Epoch:7 cost=0.090
Epoch:8 cost=0.078
Epoch:9 cost=0.068
Epoch:10 cost=0.060
0.9742
Process finished with exit code 0