gpt4 book ai didi

python - 预测和拟合之间的keras形状不匹配

转载 作者:行者123 更新时间:2023-12-01 06:46:55 26 4
gpt4 key购买 nike

我有一个简单的模型,可以展平序列嵌入,然后对它们求和。当我运行预测时,我没有得到任何错误和我期望的输出形状,但是当我尝试训练时,我得到了形状不匹配错误

这是模型:

import numpy as np
from keras import backend as K
from keras.models import Model
from keras.layers.embeddings import Embedding
from keras.layers import Reshape, Lambda

inputs = Input(shape=(20,), name="inputs")
embedding = Embedding(69, 100, name="embeddings")(inputs)
out = Reshape((2000,), name='reshape_embeddings')(embedding)
out = Lambda(lambda x: K.sum(x, axis=1), name='sum_embeddings')(out)
model = Model(inputs, out)
model.compile('adam', 'mean_squared_error')
print(model.summary())

_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
inputs (InputLayer) (None, 20) 0
_________________________________________________________________
embeddings (Embedding) (None, 20, 100) 6900
_________________________________________________________________
reshape_embeddings (Reshape) (None, 2000) 0
_________________________________________________________________
sum_embeddings (Lambda) (None,) 0
=================================================================
Total params: 6,900
Trainable params: 6,900
Non-trainable params: 0
_________________________________________________________________

这里我构建了一个随机 x,y 样本:

x = np.random.randint(69, size=(500,20))
y = np.random.uniform(0, 1, size=(500,))

当我预测 x 时,我得到正确的输出形状

preds = model.predict(x)
print(preds.shape == y.shape)

当我拟合模型时,出现以下错误:

model.fit(x, y, batch_size=50, verbose=1)

ValueError: Error when checking target: expected sum_embeddings to have 1 dimensions, but got array with shape (500, 1)

感觉我错过了一些非常简单的东西。任何建议将不胜感激

最佳答案

是的,这只是您的代码的一些简单问题。模型的输出至少需要具有 2 级(在本例中为 (None,1))(我的 2 美分是优化器在不是时会提示)。这是使用 keepdims=True 完成的。然后您还必须向 y 添加一维。

inputs = Input(shape=(20,), name="inputs")
embedding = Embedding(69, 100, name="embeddings")(inputs)
out = Reshape((2000,), name='reshape_embeddings')(embedding)
out = Lambda(lambda x: K.sum(x, axis=1, keepdims=True), name='sum_embeddings')(out)
model = Model(inputs, out)
model.compile('adam', 'mean_squared_error')
print(model.summary())

x = np.random.randint(69, size=(500,20))
y = np.random.uniform(0, 1, size=(500,1))

preds = model.predict(x)
print(preds.shape == y.shape)

model.fit(x, y, batch_size=50, verbose=1)

关于python - 预测和拟合之间的keras形状不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59184311/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com