【问题标题】:Don't understand this TypeError: 'NoneType' object is not subscriptable error不明白这个 TypeError: 'NoneType' object is not subscriptable 错误
【发布时间】:2018-10-15 20:36:09
【问题描述】:

我有以下课程:

class TfidfEmbeddingVectorizer(object):
    def __init__(self, word2vec):
        self.word2vec = word2vec
        self.word2weight = None
        self.dim = len(word2vec[next(iter(w2v))])

    def fit(self, X, y):
        tfidf = TfidfVectorizer(analyzer=lambda x: x)
        tfidf.fit(X)
        # if a word was never seen - it must be at least as infrequent
        # as any of the known words - so the default idf is the max of
        # known idf's
        max_idf = max(tfidf.idf_)
        self.word2weight = defaultdict(
            lambda: max_idf,
            [(w, tfidf.idf_[i]) for w, i in tfidf.vocabulary_.items()])

        return self

    def transform(self, X):
        return np.array([
                np.mean([self.word2vec[w] * self.word2weight[w]
                         for w in words if w in self.word2vec] or
                        [np.zeros(self.dim)], axis=0)
                for words in X
            ])

但是当我实例化它时,我得到以下错误:

File "<ipython-input-70-dcde03597dd3>", line 23, in <listcomp>
for w in words if w in self.word2vec] or
TypeError: 'NoneType' object is not subscriptable

【问题讨论】:

  • 看起来 self.word2vec 设置为 None。当你创建 TfidfEmbeddingVectorizer 类的实例时,你传递了什么作为参数?

标签: python numpy nonetype


【解决方案1】:

好吧,当您收到TypeError: 'NoneType' object is not subscriptable 错误时,您正在尝试执行None[0] 之类的操作。

你的问题就在这里:

self.word2weight = None

然后你试图在这里访问它:

np.mean([self.word2vec[w] * self.word2weight[w]

也许你需要先调用函数fit,它写入word2weight

【讨论】:

  • 谢谢@Fer Nando!你是对的,它在首先调用 fit 函数后起作用
猜你喜欢
  • 2018-01-23
  • 1970-01-01
  • 2015-05-26
  • 2021-11-17
  • 1970-01-01
  • 2018-02-05
  • 2022-07-06
  • 2022-01-15
  • 2020-07-04
相关资源
最近更新 更多