google机器学习框架tensorflow学习笔记(七)

使用Tensorflow的基本步骤

第五步: 训练模型
现在,我们可以在 linear_regressor 上调用 train() 来训练模型。我们会将 my_input_fn 封装在 lambda 中,以便可以将 my_feature  target 作为参数传入,首先,我们会训练 100 步。
_ = linear_regressor.train(
    input_fn = lambda:my_input_fn(my_feature, targets),
    steps=100
)
第六步: 评估模型

我们基于该训练数据做一次预测,看看我们的模型在训练期间与这些数据的拟合情况。

注意:训练误差可以衡量您的模型与训练数据的拟合情况,但并 不能衡量模型 泛化到新数据的效果。在后面的练习中,您将探索如何拆分数据以评估模型的泛化能力。
# Create an input function for predictions.
# Note: Since we're making just one prediction for each example, we don't 
# need to repeat or shuffle the data here.
prediction_input_fn =lambda: my_input_fn(my_feature, targets, num_epochs=1, shuffle=False)

# Call predict() on the linear_regressor to make predictions.
predictions = linear_regressor.predict(input_fn=prediction_input_fn)

# Format predictions as a NumPy array, so we can calculate error metrics.
predictions = np.array([item['predictions'][0] for item in predictions])

# Print Mean Squared Error and Root Mean Squared Error.
mean_squared_error = metrics.mean_squared_error(predictions, targets)
root_mean_squared_error = math.sqrt(mean_squared_error)
print "Mean Squared Error (on training data): %0.3f" % mean_squared_error
print "Root Mean Squared Error (on training data): %0.3f" % root_mean_squared_error

运行以上程序可以得到:
Mean Squared Error (on training data): 56367.025
Root Mean Squared Error (on training data): 237.417

这是出色的模型吗?您如何判断误差有多大?

由于均方误差 (MSE) 很难解读,因此我们经常查看的是均方根误差 (RMSE)。RMSE 的一个很好的特性是,它可以在与原目标相同的规模下解读。

我们来比较一下 RMSE 与目标最大值和最小值的差值:

min_house_value = california_housing_dataframe["median_house_value"].min()
max_house_value = california_housing_dataframe["median_house_value"].max()
min_max_difference = max_house_value - min_house_value

print "Min. Median House Value: %0.3f" % min_house_value
print "Max. Median House Value: %0.3f" % max_house_value
print "Difference between Min. and Max.: %0.3f" % min_max_difference
print "Root Mean Squared Error: %0.3f" % root_mean_squared_error

运行以上程序可以得到:
Min. Median House Value: 14.999
Max. Median House Value: 500.001
Difference between Min. and Max.: 485.002
Root Mean Squared Error: 237.417

我们的误差跨越目标值的近一半范围,可以进一步缩小误差吗?

这是每个模型开发者都会烦恼的问题。我们来制定一些基本策略,以降低模型误差。

首先,我们可以了解一下根据总体摘要统计信息,预测和目标的符合情况。

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

好的,此信息也许有帮助。平均值与模型的 RMSE 相比情况如何?各种分位数呢?

我们还可以将数据和学到的线可视化。我们已经知道,单个特征的线性回归可绘制成一条将输入 x 映射到输出 y 的线。

首先,我们将获得均匀分布的随机数据样本,以便绘制可辨的散点图。


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()


这条初始线看起来与目标相差很大。看看您能否回想起摘要统计信息,并看到其中蕴含的相同信息。

综上所述,这些初始健全性检查提示我们也许可以找到更好的线。

猜你喜欢

转载自blog.csdn.net/qq_41196472/article/details/79836514