python-3.x 尝试将分类数据转换为数值并运行RandomForestClassifier

sg3maiej  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(107)

我正在测试这段代码:

df1 = df[['Group', 'Sector', 'Cat2', 'Cat3', 'Cat4', 'Cat5', 'Cat6', 'Industry', 'Market', 'Price']].copy()
df1 = df1[:100000]
df1.shape

df1 = df1.fillna(0)

df1 = pd.get_dummies(df1)

X = df1.drop(['Price'], axis=1)
y = df1['Price']

from sklearn.model_selection import train_test_split
# Split dataset into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) # 70% training and 30% test

#Import Random Forest Model
from sklearn.ensemble import RandomForestClassifier

# Create the model with 100 trees
model = RandomForestClassifier(n_estimators=100, 
                               bootstrap = True,
                               max_features = 'sqrt')
# Fit on training data
model.fit(X_train, y_train)

我在这一行得到一个错误:model.fit(X_train, y_train)
这是我的错误:ValueError: Unknown label type: 'continuous'
我的设置是这样的:我有很多领域在'df',我复制了一些'df 1'。这些都是绝对的:'Group', 'Sector', 'Cat2', 'Cat3', 'Cat4', 'Cat5', 'Cat6', 'Industry', 'Market'
这是一个数字:'Price'
我使用one-hot编码将分类项目转换为数字项目,数字(价格)保持不变。这个设置有什么问题吗,还是它很好?

a0zr77ik

a0zr77ik1#

你正在使用一个分类器来预测连续价格。当它引用 * 标签 * 时,sklearn意味着目标,所以问题不是你的X,而是y。你需要的是sklearn.ensemble.RandomForestRegressor。有了这个,你就可以预测连续的值,比如price
使用这个代替:

from sklearn.ensemble import RandomForestRegressor

model = RandomForestRegressor(n_estimators=100, 
                               bootstrap = True,
                               max_features = 'sqrt')
# model.fit(X, y...

相关问题