【问题标题】:Load a pickle model to predict another dataset加载 pickle 模型以预测另一个数据集
【发布时间】:2021-06-01 04:35:18
【问题描述】:

我有两个数据集。第一个是 train ,另一个是 test 。首先,我使用 LogisticRegression 来训练我的模型并保存为 ;

df = pd.read_csv('train.csv')

X = df[['Age', 'Gender']]
y = df['Race']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 42)


ohe = OneHotEncoder(handle_unknown='ignore')
ohe.fit(X_train)
X_train_ohe = ohe.transform(X_train).toarray()
ohe_df = pd.DataFrame(X_train_ohe, columns=ohe.get_feature_names(X_train.columns))
clf= LogisticRegression(solver='liblinear')
clf.fit(X_train_ohe, y_train.values.ravel())
X_test_ohe = ohe.transform(X_test)
y_preds = clf.predict(X_test_ohe)


print(" Logistic Regression ")
print ("Logistic Regression : ",accuracy_score(y_test, y_preds))
print(classification_report(y_test, y_preds)) 



model = LogisticRegression(solver='liblinear')
model.fit(X_train, y_train)


pickle.dump(model,open('model.pkl','wb'))

在这一步,我想创建一个新的 python 文件并读取 test.csv 文件。但是,test.csv 在“Race”标头中有 NaN 值。我可以在 test.csv 中用 0 填充 NaN 值,但是在这一步之后我必须做什么?我必须使用加载的模型来预测 Race 值。我试过这样的代码块:

df = pd.read_csv('test.csv')
df['Race']=df['Race'].replace(['NaN'], '0')
X = df[['Age', 'Gender']]


model=pickle.load(open('model.pkl','rb'))

【问题讨论】:

  • 您好,您的模型负载是否需要预测?还是您的模型尚未加载?
  • 嗨@HarshParekh,我的模型已加载。只是我必须预测 test.csv 'Race' header ,它们是 NaN。
  • 嗨,那么就使用该模型并像这些 model.predict(X) 一样传递您的 X(数据帧),不要在其中传递您的 Y col。
  • 您好,您关闭文件了吗?
  • @VibhavSurve 还没有先生。

标签: python machine-learning pickle logistic-regression


【解决方案1】:
model=pickle.load(open('model.pkl','rb'))
df = pd.read_csv('test.csv')
predictions=model.predict(df.drop('Race',axis=1))
print(predictions)

【讨论】:

  • 感谢您的回复。但是,存在一些问题。所以,我的 'Race' 变量在 data.csv 中有值 1 、 2 、 3 、 4 ,5 但在预测中只出现值 0 和 1 。
猜你喜欢
  • 2022-01-12
  • 2021-01-31
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 2022-08-06
  • 2020-01-08
相关资源
最近更新 更多