tensorflow ValueError:形状不兼容

时间:2021-02-08 16:21:18

标签: python numpy tensorflow

我的模型的 x 是一个浮点数组数组(每个样本是一个包含 40 个元素的数组)。我的模型的 y 也是一个浮点数组数组(每个样本是一个包含 80 个元素的数组)。这是重现我的问题的代码:

import tensorflow as tf
from tensorflow.keras import models, layers
import numpy as np

x = []
for i in range(100):
  array_of_random_floats = np.random.random_sample((40))
  x.append(array_of_random_floats)
x = np.asarray(x)

y = []
for i in range(100):
  array_of_random_floats = np.random.random_sample((80))
  y.append(array_of_random_floats)
y = np.asarray(y)

print(f"x has {len(x)} elements. Each element has {len(x[0])} elements")
# x has 100 elements. Each element has 40 elements

print(f"y has {len(y)} elements. Each element has {len(y[0])} elements")
# y has 100 elements. Each element has 80 elements


model = models.Sequential([
  layers.Input(shape=(40,)),
  layers.Dense(units=40),
])

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())

history = model.fit(x=x,
                    y=y,
                    epochs=100)

这是产生的错误。

ValueError: Shapes (None, 80) and (None, 40) are incompatible

出了什么问题?

1 个答案:

答案 0 :(得分:1)

为了测量损失,维度需要匹配。您正在尝试将 (100, 40) 的输出与 (100, 80) 的目标数组进行比较。