【发布时间】:2026-01-31 19:40:01
【问题描述】:
我有一个运行以下内容的模型:
import pandas as pd
import numpy as np
# initialize list of lists
data = [['tom', 10,1,'a'], ['tom', 15,5,'a'], ['tom', 14,1,'a'], ['tom', 15,4,'b'], ['tom', 18,1,'b'], ['tom', 15,6,'a'], ['tom', 17,3,'a']
, ['tom', 14,7,'b'], ['tom',16 ,6,'a'], ['tom', 22,2,'a'],['matt', 10,1,'c'], ['matt', 15,5,'b'], ['matt', 14,1,'b'], ['matt', 15,4,'a'], ['matt', 18,1,'a'], ['matt', 15,6,'a'], ['matt', 17,3,'a']
, ['matt', 14,7,'c'], ['matt',16 ,6,'b'], ['matt', 10,2,'b']]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Attempts','Score','Category'])
print(df.head(2))
Name Attempts Score Category
0 tom 10 1 a
1 tom 15 5 a
然后我使用以下代码创建了一个虚拟 df 以在模型中使用:
from sklearn.linear_model import LogisticRegression
df_dum = pd.get_dummies(df)
print(df_dum.head(2))
Attempts Score Name_matt Name_tom Category_a Category_b Category_c
0 10 1 0 1 1 0 0
1 15 5 0 1 1 0 0
然后我创建了以下模型:
#Model
X = df_dum.drop(('Score'),axis=1)
y = df_dum['Score'].values
#Training Size
train_size = int(X.shape[0]*.7)
X_train = X[:train_size]
X_test = X[train_size:]
y_train = y[:train_size]
y_test = y[train_size:]
#Fit Model
model = LogisticRegression(max_iter=1000)
model.fit(X_train,y_train)
#Send predictions back to dataframe
Z = model.predict(X_test)
zz = model.predict_proba(X_test)
df.loc[train_size:,'predictions']=Z
dfpredictions = df.dropna(subset=['predictions'])
print(dfpredictions)
Name Attempts Score Category predictions
14 matt 18 1 a 1.0
15 matt 15 6 a 1.0
16 matt 17 3 a 1.0
17 matt 14 7 c 1.0
18 matt 16 6 b 1.0
19 matt 10 2 b 1.0
现在我有了想要预测的新数据:
newdata = [['tom', 10,'a'], ['tom', 15,'a'], ['tom', 14,'a']]
newdf = pd.DataFrame(newdata, columns = ['Name', 'Attempts','Category'])
print(newdf)
Name Attempts Category
0 tom 10 a
1 tom 15 a
2 tom 14 a
然后创建假人并运行预测
newpredict = pd.get_dummies(newdf)
predict = model.predict(newpredict)
输出:
ValueError: X has 3 features per sample; expecting 6
这是有道理的,因为没有类别 b 和 c,也没有名为 matt 的名称。
我的问题是,鉴于我的新数据并不总是包含原始数据中使用的完整列集,如何设置此模型的最佳方式是什么。每天我都有新数据,所以我不太确定最有效和无错误的方法。
这是一个示例数据 - 我的数据集在运行 pd.get_dummies 时有 2000 列。非常感谢!
【问题讨论】:
-
我记得在这个网站上进行了长时间的讨论,其中人们得出的结论是,出于这个确切原因,最好使用
sklearnone-hot 编码器。 -
@NicolasGervais 明白了。如果你使用同一个 OneHotEncoder 对象,它会记住你第一次适应它时总共有多少列。
标签: python scikit-learn