use*_*496 5 python pandas scikit-learn
假设我们有一个 Pandas 数据框和一个 scikit-learn 模型,并使用该数据框进行训练(拟合)。有没有办法进行逐行预测?用例是使用 sklearn 模型使用预测函数填充数据框中的空值。
我预计这可以使用 pandas apply 函数(轴=1)实现,但我不断收到维度错误。
使用 Pandas 版本“0.22.0”和 sklearn 版本“0.19.1”。
简单的例子:
import pandas as pd
from sklearn.cluster import kmeans
data = [[x,y,x*y] for x in range(1,10) for y in range(10,15)]
df = pd.DataFrame(data,columns=['input1','input2','output'])
model = kmeans()
model.fit(df[['input1','input2']],df['output'])
df['predictions'] = df[['input1','input2']].apply(model.predict,axis=1)
Run Code Online (Sandbox Code Playgroud)
由此产生的维数误差:
ValueError: ('Expected 2D array, got 1D array instead:\narray=[ 1.
10.].\nReshape your data either using array.reshape(-1, 1) if your data has
a single feature or array.reshape(1, -1) if it contains a single sample.',
'occurred at index 0')
Run Code Online (Sandbox Code Playgroud)
对整个列运行预测效果很好:
df['predictions'] = model.predict(df[['input1','input2']])
Run Code Online (Sandbox Code Playgroud)
但是,我希望能够灵活地按行使用它。
我首先尝试了各种方法来重塑数据,例如:
def reshape_predict(df):
return model.predict(np.reshape(df.values,(1,-1)))
df[['input1','input2']].apply(reshape_predict,axis=1)
Run Code Online (Sandbox Code Playgroud)
它只返回输入,没有错误,而我希望它返回单列输出值(作为数组)。
解决方案:
感谢 Yakym 提供了可行的解决方案!根据他的建议尝试了一些变体,最简单的解决方案是简单地将行值括在方括号中(我之前尝试过这个,但没有用于预测的 0 索引,没有运气)。
df['predictions'] = df[['input1','input2']].apply(lambda x: model.predict([x])[0],axis=1)
Run Code Online (Sandbox Code Playgroud)
稍微详细一点,您可以通过向值添加新的新轴将每一行转换为二维数组。然后,您必须使用0索引访问预测:
df["predictions"] = df[["input1", "input2"]].apply(
lambda s: model.predict(s.values[None])[0], axis=1
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6002 次 |
| 最近记录: |