2014-09-11 18 views
4

我使用JOBLIB救了我的分級管道:帶來一個分類,以生產

vec = TfidfVectorizer(sublinear_tf=True, max_df=0.5, ngram_range=(1, 3)) 
pac_clf = PassiveAggressiveClassifier(C=1) 
vec_clf = Pipeline([('vectorizer', vec), ('pac', pac_clf)]) 
vec_clf.fit(X_train,y_train) 
joblib.dump(vec_clf, 'class.pkl', compress=9) 

現在我想要在生產ENV使用它:

def classify(title): 

    #load classifier and predict 
    classifier = joblib.load('class.pkl') 

    #vectorize/transform the new title then predict 
    vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, ngram_range=(1, 3)) 
    X_test = vectorizer.transform(title) 
    predict = classifier.predict(X_test) 
    return predict 

我是錯誤得到是:ValueError:詞彙不適合或是空的! 我想我應該從德joblid加載的詞彙,但我不能讓它的工作

+0

存儲/加載矢量器時會出現什麼錯誤? – 2014-09-11 17:06:50

+0

加載時我沒有收到錯誤,現在問題已解決。比你的幫助 – Ruben 2014-09-11 19:40:48

回答

5

只需更換:

#load classifier and predict 
    classifier = joblib.load('class.pkl') 

    #vectorize/transform the new title then predict 
    vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, ngram_range=(1, 3)) 
    X_test = vectorizer.transform(title) 
    predict = classifier.predict(X_test) 
    return predict 

由:

# load the saved pipeline that includes both the vectorizer 
    # and the classifier and predict 
    classifier = joblib.load('class.pkl') 
    predict = classifier.predict(X_test) 
    return predict 

class.pkl包含了完整的管道,有不需要創建一個新的矢量化器實例。由於錯誤消息表明您需要重用首先訓練過的矢量化器,因爲從標記(字符串ngrams)到列索引的功能映射已保存在矢量化器本身中。這個映射被命名爲「詞彙」。

+0

謝謝@ogrisel工程很好...此外,剛剛發現這個有用的博客優化我的分類器[鏈接](http://blog.scrapinghub.com/2014/03/26/optimizing-memory-使用-的-scikit學習的模型 - 利用 - 簡潔,嘗試/) – Ruben 2014-09-11 19:37:48