使用数组作为tensorflow的输入

我尝试使用一个数组作为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])

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注