keras Embedding层报InvalidArgumentError: indices[23,18] = -1 is not in [0, 480)类似错误解决办法

对于码农来说,最害怕的就是各种bug。关于InvalidArgumentError: indices[23,18] = -1 is not in [0, 480)这个类型的错误,我之前也遇到了,然后在网上找了半天也没有解决,最后想了想这个报错: -1 is not in [0, 480)。是不是和负值有关呢?看了看数据,词向量里面有负值(<0的值),然后就把数据标准化了一下把负值变成了正值,运行竟然可以了,好神奇啊~(咳咳),想想也是,词向量里面有负值参与运算好像是不太那个哈(如果还有问题或疑问,欢迎打扰qq:1718066603)。。。
近期有几个同志(头发比较少的那种)都加我问我这个问题,鉴于这样我特写这篇博客来说一下我怎样解决的(这你都…,哎~,在这装大佬)。希望能帮到更多的同志。。。

检查以下代码:import numpy as np import tensorflow as tf # 读取数据 with open('data.txt', 'r', encoding='utf-8') as f: corpus = [line.strip() for line in f] sentences = [sentence.split() for sentence in corpus] # 构建词表和标记表 word_set = set([word for sentence in sentences for word in sentence]) tag_set = set([tag for sentence in sentences for _, tag in [tagged_word.split('/') for tagged_word in sentence]]) word_to_index = dict([(word, i+2) for i, word in enumerate(sorted(list(word_set)))]) tag_to_index = dict([(tag, i+1) for i, tag in enumerate(sorted(list(tag_set)))]) # 准备训练数据和标签 word_indices = [[word_to_index.get(word, 0) for word in sentence] for sentence in sentences] tag_indices = [[tag_to_index[tag] for _, tag in [tagged_word.split('/') for tagged_word in sentence]] for sentence in sentences] num_timesteps = max(len(x) for x in word_indices) num_samples = len(word_indices) word_indices_array = np.zeros((num_samples, num_timesteps), dtype=np.int32) for i, x in enumerate(word_indices): for j, val in enumerate(x): word_indices_array[i, j] = val # 构建模型 model = tf.keras.models.Sequential([ tf.keras.layers.Input(shape=(num_timesteps,)), tf.keras.layers.Embedding(input_dim=len(word_to_index)+2, output_dim=32, mask_zero=True), tf.keras.layers.SimpleRNN(128, return_sequences=True), tf.keras.layers.Dense(len(tag_to_index)+1, activation=tf.nn.softmax) ]) # 编译模型 model.compile(loss='sparse_categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(), metrics=['accuracy']) # 训练模型 model.fit(word_indices_array, np.array(tag_indices), epochs=10, batch_size=64) # 保存模型 model.save('rnn_model.h5') # 保存词汇表和标记表 with open('word_set.txt', 'w', encoding='utf-8') as f: f.write('\n'.join(word_set)) with open('tag_set.txt', 'w', encoding='utf-8') as f: f.write('\n'.join(tag_set))
06-09
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值