翻譯自https://www.tensorflow.org/get_started/tflearn
tf的高級(jí)API能夠更簡單的配置兵扬、訓(xùn)練和評(píng)估多種機(jī)器學(xué)習(xí)模型,本文將介紹如何構(gòu)建神經(jīng)網(wǎng)絡(luò)分類器峭咒,并在iris數(shù)據(jù)集上訓(xùn)練虫蝶,用花萼和花瓣的集合結(jié)構(gòu)來預(yù)測花的種類担神。有以下幾個(gè)步驟:
載入包含iris訓(xùn)練測試數(shù)據(jù)的 CSVs 到 tf 的Dataset
構(gòu)建神經(jīng)網(wǎng)絡(luò)分類器
用訓(xùn)練數(shù)據(jù) Fit 模型
評(píng)估模型精度
分類新樣本
iris數(shù)據(jù)被分為兩部分
A training set of 120 samples (iris_training.csv)
A test set of 30 samples (iris_test.csv).
- 導(dǎo)入所有的庫
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import urllib
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"
Then, if the training and test sets aren't already stored locally, download them.
if not os.path.exists(IRIS_TRAINING):
raw = urllib.urlopen(IRIS_TRAINING_URL).read()
with open(IRIS_TRAINING,'w') as f:
f.write(raw)
if not os.path.exists(IRIS_TEST):
raw = urllib.urlopen(IRIS_TEST_URL).read()
with open(IRIS_TEST,'w') as f:
f.write(raw)
- 載入訓(xùn)練數(shù)據(jù)和測試數(shù)據(jù)到 Dataset 怕磨,使用
load_csv_with_header()
穆刻。由于最后的分類是整形數(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)
training_set.data
and training_set.target
,test_set.data
andtest_set.target
包含訓(xùn)練和測試數(shù)據(jù)
- 構(gòu)建深度神經(jīng)網(wǎng)絡(luò)分類器
tf.contrib.learn
提供了多種預(yù)先定義好的模型,叫做Estimator氢伟,他們可以直接用在基于你自己數(shù)據(jù)的訓(xùn)練和評(píng)估操作榜轿。首先,我們來配置一個(gè)深度神經(jīng)網(wǎng)絡(luò)分類器來fit iris數(shù)據(jù)朵锣。你可以用以下幾行代碼來實(shí)例化一個(gè)分類器:
# Specify that all features have real-value data
feature_columns = [tf.contrib.layers.real_valued_column("", dimension=4)]
# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
hidden_units=[10, 20, 10],
n_classes=3,
model_dir="/tmp/iris_model")
以上代碼首先定義了模型的特征列谬盐,并且指定了數(shù)據(jù)類型。所有的特征feature數(shù)據(jù)都是連續(xù)型诚些,所以適合用tf.contrib.layers.real_valued_column
來構(gòu)建特征列飞傀,數(shù)據(jù)集里有4個(gè)特征維度sepal width, sepal height, petal width, and petal height,所以相應(yīng)的維度需要設(shè)置為4.
- 描述訓(xùn)練輸入流程
tf.contrib.learn 的API使用 為模型生成數(shù)據(jù)的TF 操作 作為輸入函數(shù)诬烹。本例中數(shù)據(jù)很小砸烦,可以直接儲(chǔ)存在tf.constant ,下面的代碼實(shí)現(xiàn)最簡單的輸入流程:
# Define the train inputs
def get_train_inputs():
x = tf.constant(training_set.data)
y = tf.constant(training_set.target)
return x, y
- Fit the DNNClassifier to the Iris Training Data
現(xiàn)在你已經(jīng)配置好了你的DNN分類模型绞吁,你可以用fit方法來 訓(xùn)練你的數(shù)據(jù)幢痘, 傳入get_train_inputs
作為input_fn
,還要傳入訓(xùn)練的步數(shù)家破。
# Fit model.
classifier.fit(input_fn=get_train_inputs, steps=2000)
模型的狀態(tài)被保存在classifier中颜说,這就意味著你可以迭代的訓(xùn)練购岗,例如,上面的代碼等價(jià)于下面的
classifier.fit(x=training_set.data, y=training_set.target, steps=1000)
classifier.fit(x=training_set.data, y=training_set.target, steps=1000)
然而你要追蹤模型的訓(xùn)練過程门粪,你需要使用TF的monitor來進(jìn)行記錄操作藕畔。See the tutorial “Logging and Monitoring Basics with tf.contrib.learn” for more on this topic.
- 評(píng)估模型精度
你已經(jīng)在iris數(shù)據(jù)集上訓(xùn)練過了DNNClassifier 模型,現(xiàn)在你可以使用evaluate方法檢查他在測試集上的精度了庄拇。和fit方法一樣,evaluate方法也要一個(gè)輸入函數(shù)作為他的輸入流程韭邓。evaluate方法返回一個(gè)包含評(píng)估結(jié)果的字典措近。下面的代碼傳入iris測試集test_set.data and test_set.target給evaluate,然后打印出來精度:
# Define the test inputs
def get_test_inputs():
x = tf.constant(test_set.data)
y = tf.constant(test_set.target)
return x, y
# Evaluate accuracy.
accuracy_score = classifier.evaluate(input_fn=get_test_inputs,
steps=1)["accuracy"]
print("\nTest Accuracy: {0:f}\n".format(accuracy_score))
- 分類新的樣本
使用estimator的predict()
方法來分類新樣本女淑,返回一個(gè)生成器瞭郑,可以很容易的轉(zhuǎn)化為列表。下面代碼做檢索和打印預(yù)測結(jié)果:
# Classify two new flower samples.
def new_samples():
return np.array(
[[6.4, 3.2, 4.5, 1.5],
[5.8, 3.1, 5.0, 1.7]], dtype=np.float32)
predictions = list(classifier.predict(input_fn=new_samples))
print("New Samples, Class Predictions: {}\n"
.format(predictions))