【问题标题】:How to pickle dump tfidf vectorizer with custom method?如何使用自定义方法腌制转储 tfidf 矢量化器?
【发布时间】:2021-08-15 05:58:28
【问题描述】:

我有一个带有自定义分析器的 tfidf 分词器,

def ngrams(text, n=3):
    text = str(text)
    text = text.lower()

    text = ' '+ text +' '
    ngrams = zip(*[text[i:] for i in range(n)])
    return [''.join(ngram) for ngram in ngrams]

# fit and transform 
vectorizer = TfidfVectorizer(min_df=1, analyzer=ngrams)
input_matrix = vectorizer.fit_transform(data)

print(input_matrix.shape)

我想转储它并稍后加载它,但由于我在 tfidf 中用作分析器的名为 ngrams 的自定义方法,我无法这样做。

当我做 pickle.dump 然后加载时,这是我得到的错误,

pickle.dump(vectorizer, open("data", "wb))
vec = pickle.load(open("data", "wb"))

AttributeError: Can't get attribute 'ngrams' on ma​​in'>

有谁知道如何使用自定义方法腌制转储 tfidf。所以我可以使用 pickle.load 来加载。

【问题讨论】:

    标签: python python-3.x scikit-learn tf-idf


    【解决方案1】:

    我的建议是使用扩展 Python 的 pickle 模块的 dill 包:

    dill 非常灵活,允许序列化任意用户定义的类和函数。

    您所要做的就是在酸洗之前添加以下导入语句:

    import dill as pickle
    

    那么你可以照常进行:

    pickle.dump(vectorizer, open("data", "wb"))
    ...
    

    当我在不同的 Python 会话中将矢量化器加载到另一个模块中时,它对我来说效果很好:

    vec = pickle.load(open("data", "rb")) # <-- here it should be 'rb'
    print(vec)
    
    >>> TfidfVectorizer(analyzer=<function ngrams at 0x11f5f1440>)
    

    【讨论】:

    猜你喜欢
    • 2014-03-10
    • 2020-05-07
    • 2020-07-14
    • 2021-02-03
    • 2018-06-04
    • 2017-12-11
    • 2019-06-09
    • 2021-10-06
    • 2020-08-19
    相关资源
    最近更新 更多