我是一個(gè)很懶的人,我想試試
希望我能堅(jiān)持到最后,把tensorflow的官方教程全部翻譯出來
提高自己,也幫助他人
我的博客:終身學(xué)習(xí)者
tf.estimator Quickstart
TensorFlow 的高層次機(jī)器學(xué)習(xí) API(tf.estimator) 使得配置,訓(xùn)練,和評估各種各樣的機(jī)器學(xué)習(xí)模型變得更加的容易。在本教程中,你將使用 tf.estimator 構(gòu)造一個(gè)神經(jīng)網(wǎng)絡(luò)分類器,在 Iris 數(shù)據(jù)集 上訓(xùn)練,并通過花的萼片和花瓣的幾何形狀預(yù)測花的品種。你將編寫代碼來實(shí)現(xiàn)以下五個(gè)步驟:
- 讀取包含 Iris 訓(xùn)練/測試數(shù)據(jù)的 CSVs 數(shù)據(jù)格式,到TensorFlow
Dataset
- 構(gòu)造一個(gè) 神經(jīng)網(wǎng)絡(luò)分類器
- 使用訓(xùn)練數(shù)據(jù)訓(xùn)練模型
- 評估模型的準(zhǔn)確性
- 分類新的樣本
注意:請?jiān)陂_始本教程前, 安裝 TensorFlow 到你的機(jī)器上
Complete Neural Network Source Code
以下是神經(jīng)網(wǎng)絡(luò)分類器的完整代碼:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from six.moves.urllib.request import urlopen
import numpy as np
import tensorflow as tf
# Data sets
IRIS_TRAINING = "iris_training.csv"
IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_training.csv"
IRIS_TEST = "iris_test.csv"
IRIS_TEST_URL = "http://download.tensorflow.org/data/iris_test.csv"
def main():
# If the training and test sets aren't stored locally, download them.
if not os.path.exists(IRIS_TRAINING):
raw = urlopen(IRIS_TRAINING_URL).read()
with open(IRIS_TRAINING, "wb") as f:
f.write(raw)
if not os.path.exists(IRIS_TEST):
raw = urlopen(IRIS_TEST_URL).read()
with open(IRIS_TEST, "wb") as f:
f.write(raw)
# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv_with_header(
filename=IRIS_TRAINING,
target_dtype=np.int,
features_dtype=np.float32)
test_set = tf.contrib.learn.datasets.base.load_csv_with_header(
filename=IRIS_TEST,
target_dtype=np.int,
features_dtype=np.float32)
# Specify that all features have real-value data
feature_columns = [tf.feature_column.numeric_column("x", shape=[4])]
# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns,
hidden_units=[10, 20, 10],
n_classes=3,
model_dir="/tmp/iris_model")
# Define the training inputs
train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(training_set.data)},
y=np.array(training_set.target),
num_epochs=None,
shuffle=True)
# Train model.
classifier.train(input_fn=train_input_fn, steps=2000)
# Define the test inputs
test_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(test_set.data)},
y=np.array(test_set.target),
num_epochs=1,
shuffle=False)
# Evaluate accuracy.
accuracy_score = classifier.evaluate(input_fn=test_input_fn)["accuracy"]
print("\nTest Accuracy: {0:f}\n".format(accuracy_score))
# Classify two new flower samples.
new_samples = np.array(
[[6.4, 3.2, 4.5, 1.5],
[5.8, 3.1, 5.0, 1.7]], dtype=np.float32)
predict_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": new_samples},
num_epochs=1,
shuffle=False)
predictions = list(classifier.predict(input_fn=predict_input_fn))
predicted_classes = [p["classes"] for p in predictions]
print(
"New Samples, Class Predictions: {}\n"
.format(predicted_classes))
if __name__ == "__main__":
main()
以下部分將詳細(xì)介紹代碼細(xì)節(jié)。
Load the Iris CSV data to TensorFlow
Iris 數(shù)據(jù)集 包含了 150 行數(shù)據(jù),三種相關(guān)的 Iris 品種,每種 Iris 品種有 50 個(gè)樣本: Iris setosa,Iris virginica,和Iris versicolor 。
對于每個(gè)花朵樣本,每一行都包含了以下數(shù)據(jù):萼片長度,萼片寬度, 花瓣長度,花瓣寬度和花的品種。花的品種用整數(shù)型數(shù)字表示,0表示Iris setosa,1表示Iris versicolor 。
Sepal Length | Sepal Width | Petal Length | Petal Width | Species |
---|---|---|---|---|
5.1 | 3.5 | 1.4 | 0.2 | 0 |
4.9 | 3.0 | 1.4 | 0.2 | 0 |
4.7 | 3.2 | 1.3 | 0.2 | 0 |
… | … | … | … | … |
7.0 | 3.2 | 4.7 | 1.4 | 1 |
6.4 | 3.2 | 4.5 | 1.5 | 1 |
6.9 | 3.1 | 4.9 | 1.5 | 1 |
… | … | … | … | … |
6.5 | 3.0 | 5.2 | 2.0 | 2 |
6.2 | 3.4 | 5.4 | 2.3 | 2 |
5.9 | 3.0 | 5.1 | 1.8 | 2 |
本教程中,Iris 數(shù)據(jù)隨機(jī)打亂并劃分成兩個(gè)獨(dú)立的 CSV 數(shù)據(jù)集:
- 包含 120 個(gè)樣本的訓(xùn)練集 (iris_training.csv)
- 包含 30 個(gè)樣本的測試集 (iris_test.csv)
開始前,首先 import 進(jìn)所有的需要的模塊,并定義哪里下載數(shù)據(jù)和存儲(chǔ)數(shù)據(jù)集:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from six.moves.urllib.request import urlopen
import tensorflow as tf
import numpy as np
IRIS_TRAINING = "iris_training.csv"
IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_training.csv"
IRIS_TEST = "iris_test.csv"
IRIS_TEST_URL = "http://download.tensorflow.org/data/iris_test.csv"
然后,如果訓(xùn)練和測試數(shù)據(jù)集不總是存在于本地,那么下載它們。
if not os.path.exists(IRIS_TRAINING):
raw = urlopen(IRIS_TRAINING_URL).read()
with open(IRIS_TRAINING,'wb') as f:
f.write(raw)
if not os.path.exists(IRIS_TEST):
raw = urlopen(IRIS_TEST_URL).read()
with open(IRIS_TEST,'wb') as f:
f.write(raw)
下一步,使用 learn.datasets.base
中的load_csv_with_header()
方法讀取訓(xùn)練和測試數(shù)據(jù)集,加載到 Dataset
中。load_csv_with_header()
方法帶有三個(gè)必要的參數(shù):
-
filename
, 它從 CSV 文件得到文件路徑 -
target_dtype
, 它采用數(shù)據(jù)集目標(biāo)值的numpy
數(shù)據(jù)類型 -
features_dtype
, 它采用數(shù)據(jù)集特征值的numpy
數(shù)據(jù)類型
在這里,目標(biāo)(值是你訓(xùn)練的模型的預(yù)測)是花的品種,它是一個(gè)從 0 到 2 的整數(shù),所以合適的numpy
數(shù)據(jù)類型是np.int
:
# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv_with_header(
filename=IRIS_TRAINING,
target_dtype=np.int,
features_dtype=np.float32)
test_set = tf.contrib.learn.datasets.base.load_csv_with_header(
filename=IRIS_TEST,
target_dtype=np.int,
features_dtype=np.float32)
Dataset
在 tf.contrib.learn 中名為元組;你可以通過 data
和target
字段訪問特征數(shù)據(jù)和目標(biāo)值。這里, training_set.data
和 training_set.target
分別包含了訓(xùn)練集的特征數(shù)據(jù)和特征值,而 test_set.data
和test_set.target
分別包含了測試集的特征數(shù)據(jù)和目標(biāo)值。
稍后,在 "Fit the DNNClassifier to the Iris Training Data," 你將使用training_set.data
和 training_set.target
訓(xùn)練你的模型,在"Evaluate Model Accuracy," 你將使用 test_set.data
和 test_set.target
。但首先,你將在下一節(jié)中構(gòu)造你的模型。
Construct a Deep Neural Network Classifier
tf.estimator 提供了各種預(yù)定義的模型,稱為Estimator
,你可以使用"開箱即用"對你的數(shù)據(jù)運(yùn)行訓(xùn)練和評估操作。在這里,你將配置一個(gè)深度神經(jīng)網(wǎng)絡(luò)分類器模型來適應(yīng) Iris 數(shù)據(jù)。使用 tf.estimator,你可以通過兩行代碼來實(shí)例化你的 tf.estimator.DNNClassifier
:
# Specify that all features have real-value data
feature_columns = [tf.feature_column.numeric_column("x", shape=[4])]
# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns,
hidden_units=[10, 20, 10],
n_classes=3,
model_dir="/tmp/iris_model")
上面的代碼首先定義了模型的特征列,指定了數(shù)據(jù)集中的特征的數(shù)據(jù)類型。所有的特征數(shù)據(jù)都是連續(xù)的,所以tf.feature_column.numeric_column
是用于構(gòu)造特征列的適當(dāng)函數(shù)。這里有四個(gè)特征在數(shù)據(jù)集中(萼片寬度,萼片長度,花瓣寬度和花瓣長度),于是shape
必須設(shè)置為[4]
以適應(yīng)所有的數(shù)據(jù)。
然后,代碼使用以下參數(shù)創(chuàng)建了一個(gè) DNNClassifier
模型:
-
feature_columns=feature_columns
。上面定義的一組特征列。 -
hidden_units=[10, 20, 10]
。三個(gè) 隱藏層,分別包含 10,20 和 10 神經(jīng)元。 -
n_classes=3
。三個(gè)目標(biāo)分類,代表三種 Iris 品種。 -
model_dir=/tmp/iris_model
。TensorFlow 將在模型訓(xùn)練期間保存檢測數(shù)據(jù)和 TensorBoard 摘要的目錄。
Describe the training input pipeline
tf.estimator
API 使用輸入函數(shù),創(chuàng)建了為了模型生成數(shù)據(jù)的 TensorFlow 操作。我們可以使用tf.estimator.inputs.numpy_input_fn
來產(chǎn)生輸入管道:
# Define the training inputs
train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(training_set.data)},
y=np.array(training_set.target),
num_epochs=None,
shuffle=True)
Fit the DNNClassifier to the Iris Training Data
現(xiàn)在,你已經(jīng)配置了你的 DNN classifier
模型,你可以使用 train
方法將模型擬合 Iris 訓(xùn)練數(shù)據(jù)。將 train_input_fn
傳遞給input_fn
,并設(shè)置訓(xùn)練的次數(shù)(這里是 2000):
# Train model.
classifier.train(input_fn=train_input_fn, steps=2000)
模型的狀態(tài)是保存在classifier
,這意味著如果你喜歡你可以迭代訓(xùn)練模型。例如,以上代碼等同于以下代碼:
classifier.train(input_fn=train_input_fn, steps=1000)
classifier.train(input_fn=train_input_fn, steps=1000)
然而,如果你希望在訓(xùn)練的過程中跟蹤模型,則你可能更需要使用TensorFlow 的 SessionRunHook
來執(zhí)行日志操作記錄。
Evaluate Model Accuracy
你已經(jīng)在 Iris 訓(xùn)練數(shù)據(jù)上訓(xùn)練了你的DNNClassifier
模型?,F(xiàn)在你可以在 Iris 測試數(shù)據(jù)上使用 evaluate
方法來檢測模型的準(zhǔn)確性。像train
那樣,evaluate
使用輸入函數(shù)構(gòu)建它的輸入管道。evaluate
返回一個(gè)包含評估結(jié)果的dict
。以下代碼傳遞 Iris 測試數(shù)據(jù)——test_set.data
和 test_set.target
到evaluate
并從結(jié)果中打印 accuracy
:
# Define the test inputs
test_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(test_set.data)},
y=np.array(test_set.target),
num_epochs=1,
shuffle=False)
# Evaluate accuracy.
accuracy_score = classifier.evaluate(input_fn=test_input_fn)["accuracy"]
print("\nTest Accuracy: {0:f}\n".format(accuracy_score))
注意:在這里 numpy_input_fn
中參數(shù)num_epochs=1
是很重要的。test_input_fn
將迭代數(shù)據(jù)一次,然后觸發(fā)OutOfRangeError
。這個(gè)錯(cuò)誤表示分類器停止評估,所以它將對輸入只評估一次。
當(dāng)你運(yùn)行整個(gè)腳本,它將打印類似下面的數(shù)字:
Test Accuracy: 0.966667
你的準(zhǔn)確性結(jié)果可能會(huì)有一點(diǎn)不同,但是應(yīng)該高于 90%。對于一個(gè)相對較小的數(shù)據(jù)集來說這并不算太差!
Classify New Samples
使用 estimator 的 predict()
方法來分類新的樣本。例如,假如你有這兩個(gè)新的花的樣本:
Sepal Length | Sepal Width | Petal Length | Petal Width |
---|---|---|---|
6.4 | 3.2 | 4.5 | 1.5 |
5.8 | 3.1 | 5.0 | 1.7 |
你可以使用predict()
方法預(yù)測它們的品種。 predict
返回一個(gè)dict,你可以簡單的將其轉(zhuǎn)為 list 。以下代碼檢索并打印預(yù)測的類:
# Classify two new flower samples.
new_samples = np.array(
[[6.4, 3.2, 4.5, 1.5],
[5.8, 3.1, 5.0, 1.7]], dtype=np.float32)
predict_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": new_samples},
num_epochs=1,
shuffle=False)
predictions = list(classifier.predict(input_fn=predict_input_fn))
predicted_classes = [p["classes"] for p in predictions]
print(
"New Samples, Class Predictions: {}\n"
.format(predicted_classes))
你的結(jié)果看起來如下:
New Samples, Class Predictions: [1 2]
因此你的模型預(yù)測了第一個(gè)樣本是Iris versicolor,而第二個(gè)樣本是 Iris virginica。
Additional Resources
- 欲了解更多有關(guān)使用 tf.estimator 創(chuàng)建線性模型,請查閱 Large-scale Linear Models with TensorFlow。
- 要使用 tf.estimator APIs 構(gòu)建你子集的 Estimator,請查閱Creating Estimators in tf.estimator 。
- 為了在瀏覽器中實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)建模并可視化,請查閱Deep Playground。
- 有關(guān)神經(jīng)網(wǎng)絡(luò)更高級的教程,請查閱 Convolutional Neural Networks 和Recurrent Neural Networks。