1. 程式人生 > >聽說TensorFlow框架是人工智慧的必學框架!給你五分鐘能學會嗎?

聽說TensorFlow框架是人工智慧的必學框架!給你五分鐘能學會嗎?

聽說TensorFlow框架是人工智慧的必學框架!給你五分鐘能學會嗎?

 

聽說TensorFlow框架是人工智慧的必學框架!給你五分鐘能學會嗎?

 

virtualenv1.sh hosted with ❤ by GitHub

 

聽說TensorFlow框架是人工智慧的必學框架!給你五分鐘能學會嗎?

 

進群:548377875  等即可獲取大量的學習資料以及PDF哦!

sudo pip install --upgrade virtualenv

view raw

virtualenv2.sh hosted with ❤ by GitHub

 

聽說TensorFlow框架是人工智慧的必學框架!給你五分鐘能學會嗎?

 

 

virtualenv --system-site-packages tensorflow

view raw

virtualenv3.sh hosted with ❤ by GitHub

 

聽說TensorFlow框架是人工智慧的必學框架!給你五分鐘能學會嗎?

 

 

由於我的Python是2.7.10版本,並且沒有支援GPU,因此執行:

pip install --upgrade tensorflow

view raw

virtualenv4.sh hosted with ❤ by GitHub

如果是其他情況的請參照官方教程

 

聽說TensorFlow框架是人工智慧的必學框架!給你五分鐘能學會嗎?

 

 

驗證安裝

官方地址: https://www.tensorflow.org/install/install_mac#ValidateYourInstallation

 

聽說TensorFlow框架是人工智慧的必學框架!給你五分鐘能學會嗎?

 

 

II. 訓練模型案例

該案例來自官方的入門案例

 

import numpy as npimport tensorflow as tf

# 定義可訓練模型變數W = tf.Variable([.3], tf.float32) #型別為tf.float32初始值為0.3的可訓練模型變數Wb = tf.Variable([-.3], tf.float32) #型別為tf.float32初始值為-0.3的可訓練模型變數b

# 定義模型的輸入輸出x = tf.placeholder(tf.float32) #定義型別為tf.float32的模型輸入變數xlinear_model = W * x + b # 定義模型函式,已經模型輸出值linear_model

# 定義輸出目標變數y = tf.placeholder(tf.float32)

# 定義距離目標變數的距離loss = tf.reduce_sum(tf.square(linear_model - y)) # 每個輸出值與對應目標值差平方的和

# 定義優化器optimizer = tf.train.GradientDescentOptimizer(0.01) # 通過以精度0.01的梯度下降train = optimizer.minimize(loss) # 通過優化器,讓其距離目標值逐漸減小

# 準備訓練用的資料x_train = [1,2,3,4] # 輸入變數x的值序列y_train = [0,-1,-2,-3] # 需要能夠對應輸出的目標值序列

# 開始訓練init = tf.global_variables_initializer() # 初始化可訓練變數sess = tf.Session() # 建立一個sessionsess.run(init) # 復位訓練模型for i in range(1000): # 喂訓練資料 sess.run(train, {x:x_train, y:y_train})

# 輸出訓練結果curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x:x_train, y:y_train})print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))

# 最終結果當 W為-0.9999969、b為0.99999082,距離目標值(每個輸出值與目標值差的平方和)為5.69997e-11# 輸出: W: [-0.9999969] b: [0.99999082] loss: 5.69997e-11

view raw

tensorflow-low-level-sample1.py hosted with ❤ by GitHub

 

聽說TensorFlow框架是人工智慧的必學框架!給你五分鐘能學會嗎?

 

 

該次模型訓練的效能決定因素是: 優化器選擇、精度選擇、訓練資料

通過高階的介面快速的實現上面的模型訓練

import tensorflow as tf# Numpy通常用於載入,維護與預處理資料import numpy as np# 需求佇列(還有很多其他型別的column)features = [tf.contrib.layers.real_valued_column("x", dimension=1)]# estimator是一個前端呼叫用於訓練與評估的介面,這裡有非常多預定義的型別,如Linear Regression, Logistic Regression, Linear Classification, Logistic Classification 以及各種各樣的Neural Network Classifiers 與 Regressors. 這裡我們用的是Linear Regressionestimator = tf.contrib.learn.LinearRegressor(feature_columns=features)# TensorFlow有提供了許多工具方法來讀寫資料集,這裡我們使用`numpy_input_fn`,我們不得不告訴方法一共有多少組(num_epochs),並且每組有多大(batch_size)x = np.array([1., 2., 3., 4.])y = np.array([0., -1., -2., -3.])input_fn = tf.contrib.learn.io.numpy_input_fn({"x":x}, y, batch_size=4, num_epochs=1000)# 我們可以通過傳入訓練所用的資料集呼叫1000次`fit`方法來一步步訓練estimator.fit(input_fn=input_fn, steps=1000)# 評估目前模型訓練的怎麼樣。實際運用中,我們需要一個獨立的驗證與測試資料集避免訓練過渡(overfitting)estimator.evaluate(input_fn=input_fn)

view raw

tensorflow-high-level-sample1.py hosted with ❤ by GitHub

當然我們也可以通過tf.contrib.learn.Estimator這個高階介面,再使用低階介面來定製Linear Regressor演算法模型(實際上內建的tf.contrib.learn.LinearRegressor也是繼承自tf.contrib.learn.Estimator的)。當然我們不是通過繼承,是通過提供model_fn來告訴他訓練的步驟、如果評估等:

import numpy as npimport tensorflow as tf# 定義需求佇列(這裡我們只需要一個featurex)def model(features, labels, mode): # 構建線性模型 W = tf.get_variable("W", [1], dtype=tf.float64) b = tf.get_variable("b", [1], dtype=tf.float64) y = W*features['x'] + b # 定義距離目標變數的距離 loss = tf.reduce_sum(tf.square(y - labels)) # 訓練子圖 global_step = tf.train.get_global_step() optimizer = tf.train.GradientDescentOptimizer(0.01) train = tf.group(optimizer.minimize(loss), tf.assign_add(global_step, 1)) # ModelFnOps用於將各引數串起來 return tf.contrib.learn.ModelFnOps( mode=mode, predictions=y, loss=loss, train_op=train)

estimator = tf.contrib.learn.Estimator(model_fn=model)# 定義我們的訓練用的資料集x = np.array([1., 2., 3., 4.])y = np.array([0., -1., -2., -3.])input_fn = tf.contrib.learn.io.numpy_input_fn({"x": x}, y, 4, num_epochs=1000)

# 訓練estimator.fit(input_fn=input_fn, steps=1000)# 評估訓練模型print(estimator.evaluate(input_fn=input_fn, steps=10))

view raw

tensorflow-high-level-sample2.py hosted with ❤ by GitHub

III. 常見的API

具體API可以參看官網文件

 

聽說TensorFlow框架是人工智慧的必學框架!給你五分鐘能學會嗎?

 

 

  • 定義常量: tf.constant(value, type),如tf.constant(3.0, tf.float32),當type沒有給定的時候,會根據所給value定義
  • 定義變數: tf.placeholder(type), 如tf.placeholder(tf.float32)
  • 定義訓練模型: tf.Variable([value], type], 如tf.Variable([.3], tf.float32)
  • 計算結果: 通過tf.Session()的run去計算
  • 初始化訓練模型: tf.global_variables_initializer(),對其進行復位執行起物件即可,如Session物件是sees,初始化模型物件是init時: sess.run(init)
  • 對模型重新賦值: 如對W模型重新賦值: fixW = tf.assign(W, [-1.])
  • 求平方: tf.square(value)
  • 求和: tf.reduce_sum(value)