栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

随机森林算法

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

随机森林算法

import numpy
import pandas as pd

df = pd.read_csv("data/temps.csv")
# print(df.info())

# 构建时间 : 年 月 日 组合为 : 年 月 日
dates = pd.PeriodIndex(year=df["year"],month=df["month"],day=df["day"],freq="D")

dates = dates.to_timestamp()

import matplotlib.pyplot as plt

# 绘制时间与实际值关系
fg,ax = plt.subplots(2,2,figsize=(15,10))
ax[0,0].plot(dates,df["actual"])

# 绘制时间与昨天气温
ax[0,1].plot(dates,df["temp_1"])

ax[1,0].plot(dates,df["temp_2"])

ax[1,1].plot(dates,df["friend"])

plt.show()

df_2 = pd.get_dummies(df)
print(df_2.info())

# 标签
labels = df_2["actual"]

# 特征
df_features = df_2.drop("actual",axis=1)    # drop 去空值

# 数据分割
from sklearn.model_selection import train_test_split

train_feature,test_feature,train_y,test_y = train_test_split(df_features,labels,test_size=0.25,random_state=42)


# 建立随机森林模型
# 导入随机森林api
from sklearn.ensemble import RandomForestRegressor

# 实例化随机森林
rf = RandomForestRegressor(
    n_estimators=1000,
    random_state=42
)

# 训练模型
rf.fit(train_feature,train_y)

# 预测结果
prediction = rf.predict(test_feature)

# 错误 : 测试集预测值 - 测试集真实值
errors = abs(prediction-test_y)
print(numpy.mean(errors))

from sklearn import tree
import graphviz

# 拿到随机森林中的一棵树
tree_5 = rf.estimators_[5]


dot_data = tree.export_graphviz(tree_5,
                                filled = True,
                                rounded = True,
                                special_characters = True)

graph = graphviz.Source(dot_data)
graph.render('temperature')

print(f"该树的最大深度为:{tree_5.tree_.max_depth}")
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1005413.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号