我想在Tensorflow2中设计一个神经网络,将2D值映射到其他2D值。我无法弄清楚如何初始化我的模型来完成这个任务,而不产生维度错误。
import numpyimport tensorflow as tfdef euclidean_distance_loss(y_true, y_pred): return numpy.sqrt(sum((y_true - y_pred)**2.0))#===Make Data====#x_train = numpy.asarray([ [1, 2], [3, 1], [2, 2] ])x_test = numpy.asarray([ [10, 1], [2, 0], [5, 1] ])y_train = numpy.asarray([ [3, 8], [2, 7], [3, 3] ])y_test = numpy.asarray([ [1, 0], [0, 1], [4, 9] ])#===Make Model===#model = tf.keras.models.Sequential([ tf.keras.layers.Dense(128,input_shape=(1, x_train_points.shape[1]), activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(5, activation='relu')]) #===Run Model===#model.compile(optimizer='adam', loss=euclidean_distance_loss, metrics=['accuracy'])model.fit(x_train, y_train, epochs=5)
当我尝试运行这个代码时,我得到了以下错误:
ValueError: Dimensions must be equal, but are 2 and 5 for '{{node euclidean_distance_lowss/sub}} = Sub[T=DT_Float](IteratorGetNext:1, sequential/dense_1/Relu)' with input schapes: [?,2], [?,5].
我应该如何设置这个神经网络,以便它能够处理这种类型的2D数据?抱歉提出这个基础问题——我刚开始使用Tensorflow2!
编辑:给定一个2D向量作为输入,我希望模型输出另一个2D向量。
回答:
模型的最后一层定义了每个示例的形状为[5]
的输出张量:
tf.keras.layers.Dense(5, activation='relu')
然而,标签(y_train
和y_test
)每个示例的形状是[2]
:
y_train = numpy.asarray([ [3, 8], [2, 7], [3, 3] ])y_test = numpy.asarray([ [1, 0], [0, 1], [4, 9] ])
尝试将最后一层更改为2个单元。