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}")