问题1
Traceback (most recent call last): File "D:\work\python\lesson11\lesson11.py", line 23, in <module> x_train_index = shopping_data.word2Index(x_train, word_index) File "D:\work\python\lesson11\shopping_data.py", line 108, in word2Index return np.array(vecs) ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (26552,) + inhomogeneous part.
这个错误是由于尝试将一个包含不同长度的序列的列表(vecs
)转换为 NumPy 数组时引起的。这导致了 NumPy 数组的形状不一致。
为了解决这个问题,你可以对 vecs
中的序列进行填充或截断,以使它们的长度一致。在你的 word2Index
函数中,你可以使用 pad_sequences
函数来做到这一点。这将确保所有的序列都具有相同的长度。
在 shopping_data.py
文件中的 word2Index
函数中做如下修改:
from keras.preprocessing.sequence import pad_sequences
def word2Index(words, word_index, maxlen=25):
vecs = []
for sentence in words:
# 去掉标点
sentence = re.sub("[\s+\.\!\/_,$%^*(+\"\']+|[+——!,。?、~@#¥%……&*()]+", "", sentence)
# 结巴分词
cut = jieba.cut(sentence)
index = []
for word in cut:
if word in word_index:
index.append(float(word_index[word]))
vecs.append(index)
# 使用pad_sequences进行填充或截断
padded_vecs = pad_sequences(vecs, maxlen=maxlen, padding='post', truncating='post', dtype='float32')
return padded_vecs
在这个修改中,添加了 pad_sequences
函数来确保所有的序列都具有相同的长度。可以通过调整 maxlen
参数来控制序列的长度。
问题2
Unrecognized keyword arguments passed to Embedding: {'input_length': 25}
在Keras中,Embedding层的input_length
参数用于指定输入序列的长度。然而,根据你的错误信息,似乎你遇到了一个问题,即Embedding层不识别input_length
参数。
在Keras的最新版本(例如TensorFlow 2.x版本中的Keras)中,Embedding
层已经不再接受input_length
参数。相反,你可以在Flatten层之前使用GlobalAveragePooling1D
层或Flatten
层时不使用input_length
参数。
# 修改前
model.add(
Embedding(
trainable=True,
input_dim=vocalen,
output_dim=300,
input_length=maxlen # 这里的参数需要删除
)
)
# 修改后
model.add(
Embedding(
input_dim=vocalen,
output_dim=300,
trainable=True # 注意参数顺序
)
)
这样修改后,Embedding层应该能够正常工作。