按列(对象)分层拆分

2024-09-30 04:36:59 发布

您现在位置:Python中文网/ 问答频道 /正文

当尝试按列(分类)进行strified拆分时,它返回错误。你知道吗

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'

Tags: testdfab错误分类traincountrylabel
2条回答

在重新生成代码时,我发现错误来自于试图在一组包含字符串的特性上拟合线性回归模型。This answer为您提供了一些选择。我建议使用 X_train, X_test = pd.get_dummies(X_train.Country), pd.get_dummies(X_test.Country) 在进行train\u test\u split()之后,对国家/地区进行热编码,以保持您所寻找的类平衡。你知道吗

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列数据drop labely)和字符串country列时

方法2

如果您要对其进行预测的测试数据稍后会出现,那么在进行预测之前,您将需要一种机制将它们的country转换为code。在这种情况下,推荐的方法是使用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'])]))

相关问题 更多 >

    热门问题