tensorflow學習1

安裝好Tensorflow之後開始學習如何使用

使用ubuntu+python+vim學習Tensorflow

source ./venv/bin/activate
sudo vi a.py
a:py:

import tensorflow as tf
a = tf.constant([1,2])
print a

保存後,python a.py執行
Tensor(“Const:0”, shape=(2,), dtype=int32)
輸出結果:

tensor 張量
Const:0張量名
shape = (2,) 第一行兩個元素,即爲一行兩列的張量.
dtype = int32 數據類型爲32位整型1

以上代碼還可以改爲

tf.constant(1)
tf.constant([1])
tf.constant([1,2],[2,3])
tf.constant([1.0,2.0],[2.0,3.0])

下面介紹幾個概念

神經網絡的意義是當你給出足夠多的樣本,可以使算法中的權重值足夠準確,使得最後通過算法計算出的預測值非常接近真實值
從以上這句話,我們看得出神經網絡的構成需要以下幾樣東西
1.樣本:也就是輸入,比如人臉圖片
2.足夠多的樣本:比如人臉數據庫
3.算法:比如人臉識別算法,可能通過臉部的特徵判斷男女
4.權重值:這個目前階段咱還是靠想象,小白還沒接觸過算法。
5.預測值:輸出
6.真實值:比如得到這張人臉是男的
那麼我們寫代碼大概就是這麼個框架

一段例子

這段例子來源於MOOC網課,人工智能實踐:Tensorflow筆記中
實現的是:將(重量,體積)
輸入到神經網絡中,通過權重w1,w2計算得到了
預測值y_
最後與真實值Y比較

  1 import tensorflow as tf
  2 import numpy as np
  3 BATCH_SIZE = 8
  4 seed = 23455
  5 
  6 rng = np.random.RandomState(seed)
  7 X = rng.rand(32,2) //足夠多的樣本(32)
  8 Y = [[int(x0+x1<1)] for (x0,x1) in X] //根據樣本中體積+質量<1 則爲合格樣本Y賦值1
  9 print "X is", X
 10 print "Y is ", Y
 11 
 12 x = tf.compat.v1.placeholder(tf.float32,shape=(None,2))
 13 y_ = tf.compat.v1.placeholder(tf.float32,shape=(None,1))//預測值
 14 
 15 w1 = tf.compat.v1.Variable(tf.random.normal([2,3],stddev=1,seed=1))//權重變量(需要通過樣本訓練優化的值)
 16 w2 = tf.compat.v1.Variable(tf.random.normal([3,1],stddev=1,seed=1))//權重(需要通過樣本訓練優化的值)
 17 
 18 a = tf.matmul(x,w1)
 19 y = tf.matmul(a,w2)
 20 
 21 loss = tf.reduce_mean(tf.square(y-y_))
 22 train_step = tf.compat.v1.train.GradientDescentOptimizer(0.001).minimize(loss)
 23 with tf.compat.v1.Session() as sess:
 24     init_op = tf.global_variables_initializer()
 25     sess.run(init_op)
 26     print "w1 = \n" ,sess.run(w1)
 27     print "w2 = \n", sess.run(w2)
 28 
 29     STEPS = 3000
 30     for i in range(STEPS):
 31         start = (i*BATCH_SIZE)%32
 32         end = start + BATCH_SIZE
 33         sess.run(train_step,feed_dict={x:X[start:end],y_:Y[start:end]})
 34         if i%500 == 0:
 35             total_loss = sess.run(loss,feed_dict={x:X,y_:Y})
 36             print("After %d training steps, loss on all data is %g" %(i,total_loss))
 37     print "\nw1:\n",sess.run(w1)
 38     print "w2:\n", sess.run(w2)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章