NumPy 数组的形状不一致和Embedding层不识别input_length参数。

问题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层应该能够正常工作。

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值