如何利用Python建立随机森林分类模型?

时间:2026-02-15 09:46:44

1、 利用pandas准备数据框数据。

import pandas as pddf=pd.DataFrame({'name':['Lily','Lucy','Jim','Tom','Anna','Jack','Sam'],'weight':[42,38,78,67,52,80,92],'height':[162,158,169,170,166,175,178],'is_fat':[0,0,1,0,1,0,1]})

如何利用Python建立随机森林分类模型?

2、导入sklearn工具包。

from sklearn.ensemble import RandomForestClassifier

如何利用Python建立随机森林分类模型?

3、模型数据准备。

X=df.loc[:,['weight','height']]

y=df['is_fat']

如何利用Python建立随机森林分类模型?

4、建立模型,并进行模型训练。

clf=RandomForestClassifier()

clf.fit(X,y)

如何利用Python建立随机森林分类模型?

5、获得变量权重。

X_importance=clf.feature_importances_

print(X_importance)

可以看到第一个变量'weight'的权重最高。

如何利用Python建立随机森林分类模型?

6、模型预测。

y_pred=clf.predict(X)

print(y_pred)

如何利用Python建立随机森林分类模型?

7、绘制预测结果图。

import matplotlib.pyplot as plt

plt.figure()

df['is_fat_pred']=y_pred

df_0=df[df['is_fat_pred']==0]

df_1=df[df['is_fat_pred']==1]

plt.scatter(df_0['weight'],df_0['height'],c='y',s=50,label='normal')

plt.scatter(df_1['weight'],df_1['height'],c='lightblue',s=100,label='fat')

for k in range(len(X)):

 plt.text(X['weight'][k],X['height'][k],df['name'][k])

plt.legend()

如何利用Python建立随机森林分类模型?

© 2026 五度知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com