python - 如何以正确的方式缩放和预测单个样本

标签 python machine-learning scikit-learn classification

根据乳腺癌数据集(5 个特征 + 1 个诊断列),我在标准化数据 (StandardScaler()) 上训练并测试了逻辑模型。我使用 Pickle 导入模型:

log = pickle.load(open('./log.pkl', 'rb'))

并且想要预测新样本属于 0 类(良性)还是 1 类(恶性)。

下面的测试数据属于1类(我尝试了1类的多个样本,所有结果都属于0分类):

radius = 11.41
texture = 10.82
perimeter = 73.34
area = 403.3
smoothness = 0.09373

为了创建样本并获得预测,我尝试了以下操作:

temp = [radius, texture, perimeter, area, smoothness]
temp = np.array(temp).reshape((len(temp), 1))
scaler = StandardScaler()
temp = scaler.fit_transform(temp)

# print(log.predict(temp))   # results in: ValueError: X has 1 features per sample; expecting 5
print(log.predict(temp.T)) # results in: [0] which is wrong

# print(log.predict_proba(temp)) # results in: ValueError: X has 1 features per sample; expecting 5
print(log.predict_proba(temp.T)) # results in: [[9.99999972e-01 2.78352951e-08]] which does not seem right

我也尝试过:

new_sample = np.array([radius, texture, perimeter, area, smoothness])
# scaled_sample = scaler.fit_transform(new_sample.reshape(1, -1)) # resulting array: array([[0., 0., 0., 0., 0.]])
# scaled_sample = scaler.fit_transform(new_sample.reshape(1, -1).T) # same as below
scaled_sample = scaler.fit_transform(new_sample[:, np.newaxis])
print(log.predict(scaled_sample.T))  # results in [0] which is wrong 
print(log.predict_proba(scaled_sample.T)) # results in: [[9.99999972e-01 2.78352951e-08]] which differs from the predict_proba above, and seems off

如何进行这种预测的正确方法?

谢谢

祝你好运,比 git

最佳答案

根据 predict 上的 scikit-learn 文档,您的代码可能看起来更简单功能:

temp = np.array([[radius, texture, perimeter, area, smoothness]]) # use double brackets
scaler = StandardScaler()
print(log.predict(scaler.fit_transform(temp)))

这是正确的使用方法。但这个函数不能说明回归器拟合的质量。

关于python - 如何以正确的方式缩放和预测单个样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59266368/

相关文章:

python - Keras 自定义损失函数 : Accessing current input pattern

python - Scikit-learn Column Transformer 不返回特征名称

python - 减小自动sklearn模型大小

python - 部署模型时在azure ml入口脚本中导入数据和python脚本

machine-learning - 是否可以仅使用阈值激活来学习 XOR?

pandas - 在 scikit-learn 中使用 Featureunion 为 tfidf 组合两个 Pandas 列

python - 如何为 python 安装 pjsua2 包?

python - 获取当年第一天/最后一天的日期对象

python - 如何使用每行中的特定列从矩阵创建向量,而无需在 Python 中循环?

python - 如何使用 CommentedMap 对 YAML 进行递归排序?