我使用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上得到的: Link to image
答案 0 :(得分:0)
您缺少与批次大小一起训练的时期数。将这些参数添加到输入函数的定义中,例如,在用于线性回归的火车输入的情况下,可能看起来像这样
train_input_func = \
tf.estimator.inputs.numpy_input_fn({'X': X_train},\
y_train,\
num_epochs=500,\
batch_size=1,\
shuffle=False)
此后,它应该开始训练,并且丢失功能会下降。