使用 Estimators API 训练模型

Python 中的 TensorFlow 入门

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

什么是 Estimators API?

  • 高层子模块
  • 灵活性较低
  • 强制最佳实践
  • 更快部署
  • 预置模型丰富

此图展示了 Estimators API 的结构及其与更低层 API 的关系。

1 Image taken from https://www.tensorflow.org/guide/premade_estimators
Python 中的 TensorFlow 入门

模型设计与训练

  1. 定义特征列
  2. 加载并转换数据
  3. 定义估计器
  4. 训练模型
Python 中的 TensorFlow 入门

定义特征列

# Import tensorflow under its standard alias
import tensorflow as tf

# Define a numeric feature column
size = tf.feature_column.numeric_column("size")
# Define a categorical feature column
rooms = tf.feature_column.categorical_column_with_vocabulary_list("rooms",\
["1", "2", "3", "4", "5"])
Python 中的 TensorFlow 入门

定义特征列

# Create feature column list
features_list = [size, rooms]
# Define a matrix feature column
features_list = [tf.feature_column.numeric_column('image', shape=(784,))]
Python 中的 TensorFlow 入门

加载与转换数据

# Define input data function
def input_fn():
    # Define feature dictionary
    features = {"size": [1340, 1690, 2720], "rooms": [1, 3, 4]}
    # Define labels
    labels = [221900, 538000, 180000]
    return features, labels
Python 中的 TensorFlow 入门

定义并训练回归估计器

# Define a deep neural network regression
model0 = tf.estimator.DNNRegressor(feature_columns=feature_list,\
    hidden_units=[10, 6, 6, 3])

# Train the regression model
model0.train(input_fn, steps=20)
Python 中的 TensorFlow 入门

定义并训练深度神经网络

# Define a deep neural network classifier
model1 = tf.estimator.DNNClassifier(feature_columns=feature_list,\ 
   hidden_units=[32, 16, 8], n_classes=4)

# Train the classifier
model1.train(input_fn, steps=20)
Python 中的 TensorFlow 入门

Vamos praticar!

Python 中的 TensorFlow 入门

Preparing Video For Download...