python - 使用 Scikit-Learn 使用分类数据制作回归模型

标签 python machine-learning scikit-learn

我有一个包含超过 10 列的 CSV 文件,其中一些列有分类数据,一些分类列只有 yesno 值,一些列有颜色(greenbluered...)并且某些列具有其他字符串值。

有没有办法制作所有列的回归模型?

我知道yesno值可以表示为1和0,但我读到用数字表示颜色名称或城市名称不好。 有更好/正确的方法来做到这一点吗?

这是带有虚拟数据的简单代码:

import pandas as pd
from sklearn.linear_model import LinearRegression

df = pd.DataFrame({'par1':[1,3,5,7,9, 11,13],
                   'par2':[0.2, 0.4, 0.5, 0.7, 1, 1.2, 1.45],
                   'par3':['yes', 'no', 'no', 'yes', 'no', 'yes', 'no'],
                   'par4':['blue', 'red', 'red', 'blue', 'green', 'green', 'blue'],
                   'output':[103, 310, 522, 711, 921, 1241, 1451]})

print(df)

features = df.iloc[:,:-1]
result = df.iloc[:,-1]

reg = LinearRegression()
model = reg.fit(features, result)

prediction = model.predict([[2, 0.33, 'no', 'red']])

reg_score = reg.score(features, result)

print(prediction, reg_score)

在我使用的真实数据集中,这些字符串值对于数据集非常重要,因此我不能只删除该列

最佳答案

您通常会“one-hot encode”对变量进行分类。这也称为“adding dummy variables”。

您还需要“standardize”数值变量。

Scikit-learn 让这一切变得简单:

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder

t = ColumnTransformer(transformers=[
    ('onehot', OneHotEncoder(), ['par3', 'par4']),
    ('scale', StandardScaler(), ['par1', 'par2'])
], remainder='passthrough') # Default is to drop untransformed columns

t.fit_transform(df)

最后,您需要以相同的方式转换输入,然后再通过模型运行它。

把它们放在一起你会得到:

import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler


df = pd.DataFrame({'par1':[1,3,5,7,9, 11,13],
                   'par2':[0.2, 0.4, 0.5, 0.7, 1, 1.2, 1.45],
                   'par3':['yes', 'no', 'no', 'yes', 'no', 'yes', 'no'],
                   'par4':['blue', 'red', 'red', 'blue', 'green', 'green', 'blue'],
                   'output':[103, 310, 522, 711, 921, 1241, 1451]})

t = ColumnTransformer(transformers=[
    ('onehot', OneHotEncoder(), ['par3', 'par4']),
    ('scale', StandardScaler(), ['par1', 'par2'])
], remainder='passthrough')

# Transform the features
features = t.fit_transform(df.iloc[:,:-1])
result = df.iloc[:,-1]

# Train the linear regression model
reg = LinearRegression()
model = reg.fit(features, result)

# Generate a prediction
example = t.transform(pd.DataFrame([{
    'par1': 2, 'par2': 0.33, 'par3': 'no', 'par4': 'red'
}]))
prediction = model.predict(example)
reg_score = reg.score(features, result)
print(prediction, reg_score)

关于python - 使用 Scikit-Learn 使用分类数据制作回归模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58163835/

相关文章:

Python Pandas 将初始列组融合为多个目标列

python - 是否可以用Python提取经过训练的机器学习模型的公式?

python - sklearn.linear_model RidgeCV normalize= 参数到底是做什么的

python - 安装 scikit-learn 时与 cblas 的链接错误

python - pyqt向导将字段注册为字符串而不是整数

python - Pandas 满足匹配条件的行的平均值

python - 逻辑回归无法拟合我的数据

python - 为什么 xgboost 的 Dmatrix 加载 svm 轻文本文件如此快

python - 从 Python 快速查询大型 MongoDB 集合

machine-learning - 这个神经网络可以进行分离吗?