使用 TensorFlow 的基本步骤

使用基本步骤 学习目标:数据基于 1990 年加州人口普查数据。 1.设置

首先我们需要对应的库,并做一些准备工作。

import math
from IPython import display
from matplotlib import cm
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import Dataset
#设置 tf 训练过程中输出报错信息
#如果要设置 tf训练过程中输出loss信息,可以把ERROR改为INFO,复制粘贴一下。
tf.logging.set_verbosity(tf.logging.ERROR)
#设置 pandas 的显示大小、格式
pd.options.display.max_rows = 10  
pd.options.display.float_format = '{:.1f}'.format

接下来我们将添加数据集。使用 的函数。

california_housing_dataframe = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_train.csv", sep=",")

我们将对数据进行随机化,以确保没有乱序的结果(这可能会影响随机梯度下降的性能)。此外,我们将调整为以千为单位,以便模型能够以通常范围内的学习率相对轻松地学习这些数据。

california_housing_dataframe = california_housing_dataframe.reindex(
    np.random.permutation(california_housing_dataframe.index))
california_housing_dataframe["median_house_value"] /= 1000.0
california_housing_dataframe

2.查看数据

建议使用前观察数据,在上一步的最后一句应该输出数据的首尾数字,大概可以理解数据的字段名。但是有一个更实用的函数(),可以快速输出数据统计的总结:样本量、均值、标准差、最大值、最小值和各种分位数。

california_housing_dataframe.describe()

[]

显示数据的统计摘要[/]

p>

3.构建第一个模型

我们将尝试预测,这将是我们的标签(有时称为目标)。我们将用作输入特征。

第 1 步:定义特征并配置特征列

为了将我们的训练数据导入 ,我们需要指定每个特征包含的数据类型。我们将使用两种主要类型的数据:

在 中,我们使用一种称为“特征列”的结构来表示特征的数据类型。特征列只存储特征数据的描述;它们本身不包含特征数据。

一开始,我们只使用了一个数字输入特征。以下代码从中提取数据并使用定义特征列,该列将其数据分配为数值:

# Define the input feature: total_rooms.
my_feature = california_housing_dataframe[["total_rooms"]]
# Configure a numeric feature column for total_rooms.
feature_columns = [tf.feature_column.numeric_column("total_rooms")]

第 2 步:定义目标

接下来,我们将定义目标,即。同样,我们可以从以下位置提取它:

# Define the label.
targets = california_housing_dataframe["median_house_value"]

第 3 步:配置

接下来,我们将使用配置线性回归模型,并使用 izer(实现小批量随机梯度下降 (SGD))来训练模型。该参数控制梯度步长的大小。

# Use gradient descent as the optimizer for training the model.
my_optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.0000001)
my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)
# Configure the linear regression model with our feature columns and optimizer.
# Set a learning rate of 0.0000001 for Gradient Descent.
linear_regressor = tf.estimator.LinearRegressor(
    feature_columns=feature_columns,
    optimizer=my_optimizer
)

第四步:定义输入函数

模型配置好后,选择目标和特征,导入数据,我们需要定义一个输入函数,告诉如何预处理数据,以及在模型训练过程中如何对数据进行批处理、洗牌和重复。

首先,我们将特征数据转换为 NumPy 数组的字典。然后,我们可以使用 API 从我们的数据中构建一个对象,并将数据分成大小不同的批次,以重复指定数量的周期 ( )。

注意:如果将默认值=None传递给(),输入数据会无限重复。

然后,如果设置为 True,我们将数据打乱,以便在训练期间以随机方式将数据传递给模型。该参数指定要从中随机采样的数据集的大小。

最后,输入函数在数据集上构建一个迭代器,并返回下一批数据。

def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):
    """用一个特征值训练一个线性回归模型
    Args:
      features: 特征值
      targets: 目标值
      batch_size: 传递给模型的batch的大小
      shuffle: True or False. 决定是否要将数据打乱顺序
      num_epochs: 可以重复的元组数, None 表示无重复
    Returns:
      包含下一个数据批的特征、标签的元组(tuple)
    """
    # Convert pandas data into a dict of np arrays.
    features = {key:np.array(value) for key,value in dict(features).items()}                                           
    # Construct a dataset, and configure batching/repeating
    ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit
    ds = ds.batch(batch_size).repeat(num_epochs)
    # Shuffle the data, if specified
    if shuffle:
      ds = ds.shuffle(buffer_size=10000)
    # Return the next batch of data
    features, labels = ds.make_one_shot_iterator().get_next()
    return features, labels

第 5 步:训练模型

我们现在可以调用 train() 来训练模型。我们将封装进去,以便我们可以传入和作为参数,我们可以先训练100步。

linear_regressor.train(
    input_fn = lambda:my_input_fn(my_feature, targets),
    steps=1000
)

第 6 步:评估模型

我们根据这些训练数据进行预测,并查看我们的模型在训练拟合这些数据期间的比较情况。

注意:训练误差衡量模型与训练数据的拟合程度,而不是模型对新数据的泛化程度。

然后我们看一下预测和目标函数的统计总结:

calibration_data = pd.DataFrame()
calibration_data["predictions"] = pd.Series(predictions)
calibration_data["targets"] = pd.Series(targets)
calibration_data.describe()

我们也可以根据模型绘制散点图:

sample = california_housing_dataframe.sample(n=300)
# Get the min and max total_rooms values.
x_0 = sample["total_rooms"].min()
x_1 = sample["total_rooms"].max()
# Retrieve the final weight and bias generated during training.
weight = linear_regressor.get_variable_value('linear/linear_model/total_rooms/weights')[0]
bias = linear_regressor.get_variable_value('linear/linear_model/bias_weights')
# Get the predicted median_house_values for the min and max total_rooms values.
y_0 = weight * x_0 + bias 
y_1 = weight * x_1 + bias
# Plot our regression line from (x_0, y_0) to (x_1, y_1).
plt.plot([x_0, x_1], [y_0, y_1], c='r')
# Label the graph axes.
plt.ylabel("median_house_value")
plt.xlabel("total_rooms")
# Plot a scatter plot from our data sample.
plt.scatter(sample["total_rooms"], sample["median_house_value"])
# Display graph.
plt.show()

这个初始行看起来和目标有很大的不同。看看你是否能回忆起汇总统计数据并看到其中隐含的相同信息。

总而言之,这些初步的健全性检查表明我们或许能够找到更好的线路。

© 版权声明
THE END
喜欢就支持一下吧
点赞12赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容