簡體   English   中英

在Google AI平台上使用Scikit學習獲取預測時出現問題:“ numpy.ndarray”對象沒有屬性“ lower”

[英]Problem getting predictions with Scikit-learn on Google AI Platform: 'numpy.ndarray' object has no attribute 'lower'"

我一般來說對機器學習還很陌生,並且想將我的模型存儲在雲中以便進行在線預測。

我在本地使用Jupyter Notebook在Scikit-learn上使用TfIdf vecotrizer(用於情感分析)成功訓練了Logistic回歸模型,並在Google AI平台上使用了他們的Training Job功能在其上進行了訓練。

我必須提到,在我的培訓包setup.py文件中包括bs4,nltk,lxml作為必需的PyPI包。

我的訓練算法如下:

  1. 將輸入字符串及其標簽(輸出)的CSV文件作為pandas數據框導入(模型具有1個輸入變量,即字符串)。

  2. 使用bs4和nltk預處理輸入字符串,以刪除不必要的字符,停用詞,並將所有字符都轉換為小寫(要重現此內容,只需使用僅使用小寫字母的字符串)。

  3. 創建管道

     from sklearn.feature_extraction.text import TfidfVectorizer tvec=TfidfVectorizer() lclf = LogisticRegression(fit_intercept = False, random_state = 255, max_iter = 1000) from sklearn.pipeline import Pipeline model_1= Pipeline([('vect',tvec),('clf',lclf)]) 
  4. 使用GridSearchCV進行交叉驗證

     from sklearn.model_selection import GridSearchCV param_grid = [{'vect__ngram_range' : [(1, 1)], 'clf__penalty' : ['l1', 'l2'], 'clf__C' : [1.0, 10.0, 100.0]}, {'vect__ngram_range' : [(1, 1)], 'clf__penalty' : ['l1', 'l2'], 'clf__C' : [1.0, 10.0, 100.0], 'vect__use_idf' : [False], 'vect__norm' : [False]}] gs_lr_tfidf = GridSearchCV(model_1, param_grid, scoring='accuracy', cv=5, verbose=1, n_jobs=-1) gs_lr_tfidf.fit(X_train, y_train) 
  5. 用最佳估計獲得我想要的模型。 這是保存在Google model.joblib文件中的模型。

     clf = gs_lr_tfidf.best_estimator_ 

我可以使用以下命令在Jupyter Notebook文件上輸出一個簡單的預測

predicted = clf.predict(["INPUT STRING"])
print(predicted)

它為我的輸入字符串打印預測的標簽。 例如['好']或['壞']

但是,盡管模型已成功訓練並提交給AI平台,但是當我嘗試請求諸如(以所需JSON格式)的預測時:

["the quick brown fox jumps over the lazy dog"]
["hi what is up"]

外殼程序返回此錯誤:

{
  "error": "Prediction failed: Exception during sklearn prediction: 
  'numpy.ndarray' object has no attribute 'lower'"
}

這里可能出了什么問題?

這可能是依賴關系的問題,我也必須在我的Google托管模型中安裝bs4,lxml和nltk的軟件包嗎?

還是我的輸入JSON格式錯誤?

謝謝你的幫助。

好吧,我發現確實JSON格式的格式錯誤。 (在https://stackoverflow.com/a/51693619/10570541上回答)

如官方文檔所述,JSON格式具有換行符和方括號以分隔實例,例如:

[6.8,  2.8,  4.8,  1.4]
[6.0,  3.4,  4.5,  1.6]

如果您有多個輸入變量,則適用。

僅對於一個輸入變量,只需使用換行符即可。

"the quick brown fox jumps over the lazy dog"
"alright it works"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM