python - In[0] 不是矩阵。相反,它具有形状 [100] [Op :MatMul]

标签 python tensorflow neural-network nlp artificial-intelligence

我是 tensorflow 新手,我正在尝试为 NLP 实现一个简单的神经网络,但遇到一个错误,我不知道如何修复。我的网络的代码在这里:

model = tf.keras.Sequential()
model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))
model.add(layers.BatchNormalization())
model.add(layers.ReLU())

model.add(layers.Dense(7*7*256, use_bias=False))
model.add(layers.BatchNormalization())
model.add(layers.ReLU())

model.add(layers.Dense(7*7*128, use_bias=False))
model.add(layers.BatchNormalization())
model.add(layers.ReLU())

model.add(layers.Dense(7*7*64, use_bias=False))
model.add(layers.BatchNormalization())
model.add(layers.ReLU())

model.add(layers.Dense(7*7*64, use_bias=False))
model.add(layers.BatchNormalization())
model.add(layers.ReLU())

model.add(layers.Dense(100, use_bias = False, activation="relu"))

输入形状为(100,)。我正在尝试输入 100 个 float 的张量(在 0 和 1 之间标准化的 ASCII 字符),如以下代码所示:

generator = make_generator_model()

human_array = tf.convert_to_tensor([human[0]])
print("human shape: " + str(tf.shape(human[0])))
noise = tf.random.normal([1, 100])
print("noise shape: " + str(tf.shape(noise)))
generated_response_test = generator(human[0], training=False)

print("m: " + chr(109))
print(generated_response_test)
print(get_message(np.round(generated_response_test[0] * 95 + 32)))

其中 human[0] 是我正在讨论的张量

我收到以下错误以及此警告:

WARNING:tensorflow:Model was constructed with shape (None, 100) for input
Tensor("dense_input:0", shape=(None, 100), dtype=float32), but it was
called on an input with incompatible shape (100,).

In[0] is not a matrix. Instead it has shape [100] [Op:MatMul]

有趣的是,当我从具有相同形状的正态分布中传递随机噪声时,代码不会出现任何警告或错误。 tf.shape(noise) 和 tf.shape( human[0]) 的输出是:

human shape: tf.Tensor([  1 100], shape=(2,), dtype=int32)
noise shape: tf.Tensor([  1 100], shape=(2,), dtype=int32)

所以我很困惑

我相当确定这是我定义张量变量的方式的问题,并且 matmul() 需要一个矩阵作为输入,但我一生都无法弄清楚如何将我的列表转换为正确的格式,但我在互联网上找不到任何可以解决我的问题的内容

有人可以提供帮助吗? 谢谢!

最佳答案

我能够通过在 tf.variable 中指定 shape = [1,100] 而不是 shape = (100,) 来解决这个问题,并将 [] 移动到输入内部,因此我的工作代码是

generator = make_generator_model()

human_input = tf.Variable([np.array(human[0])], dtype = tf.float32, shape = [1,100])
human_input = tf.random.normal([1, 100])
generated_response = generator(human_input, training=False)

print("m: " + chr(109))
print(generated_response)
print(print_message(np.round(generated_response[0] * 95 + 32)))

请注意我对 human_input 的定义的差异。希望这对同样遇到此问题的人有所帮助,如果您需要更多信息,请对此答案发表评论!

关于python - In[0] 不是矩阵。相反,它具有形状 [100] [Op :MatMul],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61993883/

相关文章:

python - scipy.io.loadmat 不起作用

python - Keras 使用顺序层添加数据

neural-network - 为什么在神经网络类定义中使用多个 ReLU 对象?

python - 如何在 Mechanical Turk 之前将数据 POST 到网络服务器

python - 导入错误 : No module named _____

python - 为什么Python标准库中没有读写文件的函数

debugging - 如何在 TensorFlow 和 Keras 的损失函数中打印中间变量?

python - 时间序列数据的自定义损失函数

tensorflow - 使用 Huggingface Transformers 的聊天机器人

java - RNTN在java中的实现