python - 按列(对象)分割分层

标签 python machine-learning split scikit-learn linear-regression

当尝试按列(分类)进行平移分割时,它返回错误。

Country     ColumnA    ColumnB   ColumnC   Label
AB            0.2        0.5       0.1       14  
CD            0.9        0.2       0.6       60
EF            0.4        0.3       0.8       5
FG            0.6        0.9       0.2       15  

这是我的代码:

X = df.loc[:, df.columns != 'Label']
y = df['Label']

# Train/test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=df.Country)

from sklearn.linear_model import LinearRegression
lm = LinearRegression()
lm.fit(X_train,y_train)
lm_predictions = lm.predict(X_test)

所以我得到如下错误:

ValueError: could not convert string to float: 'AB'

最佳答案

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

df = pd.DataFrame({
        'Country': ['AB', 'CD', 'EF', 'FG']*20,
        'ColumnA' : [1]*20*4,'ColumnB' : [10]*20*4, 'Label': [1,0,1,0]*20
    })

df['Country_Code'] = df['Country'].astype('category').cat.codes

X = df.loc[:, df.columns.drop(['Label','Country'])]
y = df['Label']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=df.Country_Code)
lm = LinearRegression()
lm.fit(X_train,y_train)
lm_predictions = lm.predict(X_test)
  • country中的字符串值转换为数字并将其保存为新列
  • 创建 x 列车数据时,放置 label (y) 以及字符串 country

方法2

如果您要进行预测的测试数据稍后出现,您将需要一种机制在进行预测之前将其国家/地区转换为代码。在这种情况下,推荐的方法是使用 LabelEncoder ,您可以使用 fit 方法将字符串编码为标签,然后使用 transform 进行编码测试数据所在国家/地区。

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import preprocessing

df = pd.DataFrame({
        'Country': ['AB', 'CD', 'EF', 'FG']*20,
        'ColumnA' : [1]*20*4,'ColumnB' : [10]*20*4, 'Label': [1,0,1,0]*20
    })

# Train-Validation 
le = preprocessing.LabelEncoder()
df['Country_Code'] = le.fit_transform(df['Country'])
X = df.loc[:, df.columns.drop(['Label','Country'])]
y = df['Label']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=df.Country_Code)
lm = LinearRegression()
lm.fit(X_train,y_train)

# Test
test_df = pd.DataFrame({'Country': ['AB'], 'ColumnA' : [1],'ColumnB' : [10] })
test_df['Country_Code'] = le.transform(test_df['Country'])
print (lm.predict(test_df.loc[:, test_df.columns.drop(['Country'])]))

关于python - 按列(对象)分割分层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54874639/

相关文章:

python - sklearn 随机森林分类器可以处理分类变量吗?

machine-learning - Kaggle - 猫与狗(用户警告 : Found 20000 invalid image filename(s) in x_col ="filename". 这些文件名将被忽略。)

python - 如何将 4d RGB 图像数据转换为 LogisticRegression 的 2d 数组

c# - NAudio 拆分 mp3 文件

python - 有没有一种很好的方法来拆分(可能)长的字符串而不用 Python 中的单词拆分?

python - 从 Flask-SQLAlchemy 获取 UTC 格式的日期时间字段

python - 由其他数据框行填充

python - Django 正在使用哪个服务器?

python - 根据列的多个条件将数据帧拆分为 block

python - 如何在Python中为Tensorflow创建CNN交叉过滤器?