我尝试使用一个数组作为tensorflow模型的输入。训练输入是xs,训练输出是ys,测试输入是zs。当我训练模型时,一切正常,但当我使用预测功能时,出现了以下错误:
ValueError Traceback (most recent call last)<ipython-input-1-08c8b5d5ab9e> in <module>() 26 model.fit(xs,ys, epochs=500) 27 ---> 28 print(model.predict(zs)) 29 #print(str(model.get_weights())) 30 #np.array([np.array(x) for x in xs])10 frames/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) 971 except Exception as e: # pylint:disable=broad-except 972 if hasattr(e, "ag_error_metadata"):--> 973 raise e.ag_error_metadata.to_exception(e) 974 else: 975 raiseValueError: in user code: /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1462 predict_function * return step_function(self, iterator) /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1452 step_function ** outputs = model.distribute_strategy.run(run_step, args=(data,)) /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:1211 run return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs) /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2585 call_for_each_replica return self._call_for_each_replica(fn, args, kwargs) /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2945 _call_for_each_replica return fn(*args, **kwargs) /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1445 run_step ** outputs = model.predict_step(data) /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1418 predict_step return self(x, training=False) /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py:976 __call__ self.name) /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/input_spec.py:216 assert_input_compatibility ' but received input with shape ' + str(shape)) ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input with shape [None, 1]
这是我的代码:
import numpy as npfrom tensorflow import kerasmodel = tf.keras.Sequential([keras.layers.Dense(units=3, input_shape=[3])])model.add(keras.layers.Dense(units=20))model.add(keras.layers.Dense(units=40))model.add(keras.layers.Dense(units=100))model.add(keras.layers.Dense(units=20))model.add(keras.layers.Dense(units=1))#model.set_weights()model.compile(optimizer='sgd', loss='mean_squared_error')xs = tf.constant([[15,0,0], [17,0,0], [19,1,0], [21,1,20], [23,1,20], [1,1,0], [3,1,0], [5,1,0]])ys = tf.constant([0,0,0,0,0,1,1,1])zs = tf.constant([15,0,0])print(model.output_shape)model.fit(xs,ys, epochs=500)print(model.predict(zs))
我该如何正确使用我的模型?我听说过evaluate函数,但它只返回损失值。
回答:
Keras的输入期望有一个批次维度。你的zs
变量没有这个维度。
你可以使用zs = tf.expand_dims(zs,axis=0)
来添加批次维度,或者在创建zs
时使用嵌套列表。
zs = tf.constant([[15,0,0]])
你可以通过查看模型的输入来检查模型期望的形状:
>>> model.input.shapeTensorShape([None, 3])
这里的None
表示第一个维度可以是任何大于0的数字。
如果你检查你的变量zs
,你会发现形状不匹配。
>>> zs = tf.constant([15,0,0])>>> zs.shapeTensorShape([3])
但是如果我们使用tf.expand_dims
,或者在构建zs
时使用嵌套列表,形状将是兼容的。
>>> zs_exp = tf.expand_dims(zs,axis=0)>>> zs_exp.shapeTensorShape([1, 3])>>> zs_nested_list = tf.constant([[15,0,0]])>>> zs_nested_list.shapeTensorShape([1, 3])