tensorflow - 线性回归和估计器返回错误的损失。张量流
问题描述
我使用 Keras 实现了这个模型,结果符合预期。现在我正在尝试使用 Tensorflow,但我就是做错了。正如你在下面看到的那样,我的损失是不对的。
我在这里做错了什么?
ps:我更喜欢使用估计器而不是乘法张量等。
X = numpy.array([ 1.1, 1.3, 1.5, 2.0, 2.2, 2.9, 3.0, 3.2, 3.2, 3.7, 3.9, 4.0, 4.0, 4.1, 4.5, 4.9, 5.1, 5.3, 5.9, 6.0, 6.8, 7.1, 7.9, 8.2, 8.7, 9.0, 9.5, 9.6, 10.3, 10.5])
y = numpy.array([ 39.343, 46.205, 37.731, 43.525, 39.891, 56.642, 60.15, 54.445, 64.445, 57.189, 63.218, 55.794, 56.957, 57.081, 61.111, 67.938, 66.029, 83.088, 81.363, 93.94, 91.738, 98.273, 101.302, 113.812, 109.431, 105.582, 116.969, 112.635, 122.391, 121.872])
#reduce salaries to unit of thousands
#Split 70% training, 30% test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
#Create estimator
feat_cols = [ tf.feature_column.numeric_column('X', shape=[1]) ]
estimator = tf.estimator.LinearRegressor(feature_columns=feat_cols)
#input functions
train_input_func = tf.estimator.inputs.numpy_input_fn({'X': X_train}, y_train, shuffle=False)
test_input_func = tf.estimator.inputs.numpy_input_fn({'X': X_test}, y_test, shuffle=False)
#Train and test
estimator.train(input_fn=train_input_func)
train_metrics = estimator.evaluate(input_fn=train_input_func)
test_metrics = estimator.evaluate(input_fn=test_input_func)
#Predict salary for arbitrary years of experience
X_single_data = np.array([4.6])
pred_input_func = tf.estimator.inputs.numpy_input_fn({'X': X_single_data}, shuffle=False)
single_pred = estimator.predict(pred_input_func)
print('--Train metrics--')
print(train_metrics)
print(' ')
print('--Test metrics--')
print(test_metrics)
--训练指标--
{'average_loss': 5795.477, 'label/mean': 72.32367, 'loss': 121705.016, 'prediction/mean': 1.2057142, 'global_step': 1}
--测试指标--
{'average_loss': 7422.221, 'label/mean': 84.588104, 'loss': 66799.99, 'prediction/mean': 1.3955557, 'global_step': 1}
仅供参考:这就是我用 keras 得到的: 链接到图片
解决方案
您缺少要与批量大小一起训练的时期数。将这些参数添加到输入函数的定义中,例如,在用于线性回归的训练输入的情况下,它可能看起来像这样
train_input_func = \
tf.estimator.inputs.numpy_input_fn({'X': X_train},\
y_train,\
num_epochs=500,\
batch_size=1,\
shuffle=False)
之后它应该开始训练并且损失函数会下降。
推荐阅读
- php - php数组检查添加了什么,删除了什么改变了什么
- bootstrap-4 - Bootstrap - div内的行与对齐内容中心不是在每行之后垂直放置?
- c# - 在我的算术序列中查找异常号
- odoo - ODOO 14 - CRM - 将公司名称设置为机会标题
- ffmpeg - ffmpeg视频保留源的参考帧
- javascript - Cypress:点击粘流
- python - 根据 csv 文件发送批准者电子邮件的 Python 脚本
- arrays - 使用 Bash 通过分隔符将文件列表拆分为 2 个数组
- java - 多模块Maven项目在Eclipse中不断构建
- tensorflow - 如何减少验证损失并提高年龄预测的准确性?