首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用于LSTM模型的KeyError '-f‘Python

用于LSTM模型的KeyError '-f‘Python
EN

Stack Overflow用户
提问于 2019-10-13 02:13:59
回答 1查看 285关注 0票数 0

从embedding_matrix调用的函数。有没有人能解释一下为什么我会收到这个错误,以及我如何解决它。

代码语言:javascript
运行
复制
def getEmbeddingMatrix (word_index, vectorSource):
        wordVecSources = {'fasttext' : './vectors/crawl-300d-2M-subword.vec', 'custom-fasttext' : 
           './vectors/' + '20news-fasttext.json' }
        f = open (wordVecSources[vectorSource])
        allWv = {}
        if (vectorSource == 'custom-fasttext'):
            allWv = json.loads(f.read())
        elif (vectorSource == 'fasttext'):
            errorCount = 0
            for line in f:
                values = line.split()
                word = values[0].strip()
                try:
                    wv = np.asarray(values[1:], dtype='float32')
                    if (len(wv) != wvLength):
                        errorCount = errorCount + 1
                        continue
                except:
                    errorCount = errorCount + 1
                    continue
                allWv[word] = wv
            print ("# Bad Word Vectors:", errorCount)
        f.close()
        embedding_matrix = np.zeros((len(word_index)+1, wvLength))  # +1 for the masked 0
        for word, i in word_index.items():
            if word in allWv:
                embedding_matrix[i] = allWv[word]
        return embedding_matrix

early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=2, mode='auto', restore_best_weights=False)
model = keras.models.Sequential()
if (vectorSource != 'none'):
    embedding_matrix = getEmbeddingMatrix (kTokenizer.word_index, vectorSource)
    embedding = keras.layers.embeddings.Embedding(input_dim=len(kTokenizer.word_index)+1, output_dim=wvLength, weights=[embedding_matrix], input_length=sequenceLength, trainable=False, mask_zero=True)
else:
    embedding = keras.layers.embeddings.Embedding(input_dim=len(kTokenizer.word_index)+1, output_dim=wvLength, input_length=sequenceLength, trainable=True, mask_zero=True)
model.add(embedding)
model.add(keras.layers.LSTM(units=150, dropout=0.2, recurrent_dropout=0.2, return_sequences=False))
model.add(keras.layers.Dense(numClasses, activation='softmax'))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
print(model.summary())

当调用getEmbeddingMatrix时,它会给出一个KeyError '-f',即使这两个文件存在于相同的位置

代码语言:javascript
运行
复制
KeyError                                  Traceback (most recent call last)
<ipython-input-45-ca6718845b1d> in <module>
      2 model = keras.models.Sequential()
      3 if (vectorSource != 'none'):
----> 4     embedding_matrix = getEmbeddingMatrix (kTokenizer.word_index, vectorSource)
      5     embedding = keras.layers.embeddings.Embedding(input_dim=len(kTokenizer.word_index)+1, output_dim=wvLength, weights=[embedding_matrix], input_length=sequenceLength, trainable=False, mask_zero=True)
      6 else:

<ipython-input-40-b29c56e927a3> in getEmbeddingMatrix(word_index, vectorSource)
      1 def getEmbeddingMatrix (word_index, vectorSource):
      2     wordVecSources = {'fasttext' : './vectors/crawl-300d-2M-subword.vec', 'custom-fasttext' : './vectors/' + '20news-fasttext.json' }
----> 3     f = open (wordVecSources[vectorSource])
      4     allWv = {}
      5     if (vectorSource == 'custom-fasttext'):

KeyError: '-f'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-13 03:34:59

字典wordVecSources的键可以是'fasttext''custom-fasttext',但它接收的键是'-f'

这意味着您以某种方式将'-f'赋值给vectorSource,而它应该是'none''fasttext''custom-fasttext',而不是为了防止KeyError

检查代码中与vectorSource相关的外壳命令行参数。例如,在your_file.py中假设您有vectorSource = str(sys.argv[1]),那么您应该运行类似$python your_file.py fasttext的代码,而不是运行$python your_file.py -f,因为这里的第一个命令行参数(sys.argv1)在运行时将其值赋给vectorSource

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58357089

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档