首页 > 解决方案 > TensorFlow 不学习

问题描述

编码:

import numpy as np
import tensorflow as tf
import pandas as pd
from sklearn.model_selection import train_test_split

x_data = np.linspace(0, 1000, 100000)
y_true = np.square(x_data)
y_true += np.random.randn(len(x_data))


feature_columns = [tf.feature_column.numeric_column('x', shape=[1])]
estimator = tf.estimator.DNNRegressor(feature_columns=feature_columns,         hidden_units=[2, 2], optimizer=lambda:
                                  tf.train.AdamOptimizer(
                                      learning_rate=0.001
                                  ))


X_train, X_test, y_train, y_test = train_test_split(x_data, y_true, test_size=0.3)

input_function = tf.estimator.inputs.numpy_input_fn({'x': X_train},y_train,
                                                batch_size=20, num_epochs=10000,
                                                shuffle=True)

train_input_function = tf.estimator.inputs.numpy_input_fn({'x': X_train},y_train,
                                                      batch_size=8, num_epochs=10000,
                                                      shuffle=False)
test_input_function = tf.estimator.inputs.numpy_input_fn({'x': X_test},y_test,
                                                     batch_size=8, num_epochs=10000,
                                                     shuffle=False)


estimator.train(input_fn=input_function, steps=1000)

train_metrics = estimator.evaluate(input_fn=train_input_function, steps=1000)
test_metrics = estimator.evaluate(input_fn=test_input_function, steps=1000)


print('TRAINING DATA METRICS')
print(train_metrics)
print()

print('TEST DATA METRICS')
print(test_metrics)
print()
###
new_data = np.linspace(0, 1000, 10)
input_function_predict = tf.estimator.inputs.numpy_input_fn({'x':new_data},     shuffle=False)
print(list(estimator.predict(input_fn=input_function_predict)))

给出以下输出:

TRAINING DATA METRICS
{'average_loss': 200498430000.0, 'label/mean': 332774.78, 'loss': 1603987400000.0, 'prediction/mean': 0.97833574, 'global_step': 1000}

TEST DATA METRICS
{'average_loss': 197508330000.0, 'label/mean': 332257.22, 'loss': 1580066700000.0, 'prediction/mean': 0.97833574, 'global_step': 1000}

[{'predictions': array([0.9783435], dtype=float32)}, {'predictions': array([0.9783435], dtype=float32)}, {'predictions': array([0.9783435], dtype=float32)}, {'predictions': array([0.9783435], dtype=float32)}, 
{'predictions': array([0.9783435],....

总而言之,损失是巨大的,因为 TF 预测所有 X 的 Y 值相同。代码有什么问题?

标签: pythontensorflowneural-networkdeep-learningloss

解决方案


对于那种大小的输入、响应变量的比例和给定的模型,损失总是很大的。

你所做的实际上工作正常,但需要很长时间才能收敛,无需进一步微调。特别是,如果我

  • 删除lambda:(参见上面的评论),
  • 更改learning_rate0.1,
  • 更改batch_size20000,
  • 更改num_epochs100,

那么你的 10 个预测变成

[-2.036557, 82379.797, 165955.28, 249530.75, 333106.22, 416681.72, 500257.19, 583832.63, 667408.13, 750983.63]

乍一看,它似乎接近给定模型的最佳值(这似乎不是一个特别好的模型):

在此处输入图像描述

这样,您就可以自由地使用模型了。例如,我们知道更好的模型(如果不是非常神经网络)将是通过

estimator = tf.estimator.DNNRegressor(feature_columns=feature_columns,
                                      hidden_units=[1],
                                      activation_fn=np.square,
                                      optimizer=tf.train.AdamOptimizer(learning_rate=1))

最终损失为 7.20825e+09,这提供了完美的预测:

在此处输入图像描述

在下面评论中的讨论之后,在您希望在模型中包含二次变换的现实生活中,您通常会将这些作为特征包含在内;例如,您可以DNNRegressor通过

feature_columns = [tf.feature_column.numeric_column('x'),
                   tf.feature_column.numeric_column('x_squared')]

estimator = tf.estimator.DNNRegressor(feature_columns=feature_columns,
                                      hidden_units=[1],
                                      activation_fn=tf.identity,
                                      optimizer= tf.train.AdamOptimizer(learning_rate=1))

input_function = tf.estimator.inputs.numpy_input_fn({'x': X_train, 'x_squared': X_train**2}, y_train, 
                                                    batch_size=1000, num_epochs=500,
                                                    shuffle=True)

和以前一样,这会给你一个完美的契合

在此处输入图像描述


推荐阅读