Python中基于天气数据集XGBoost的示例分析

发布时间:2022-03-04 10:57:39 作者:小新
来源:亿速云 阅读:324

这篇文章将为大家详细讲解有关Python中基于天气数据集XGBoost的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

一、XGBoost

XGBoost并不是一种模型,而是一个可供用户轻松解决分类、回归或排序问题的软件包。

1 XGBoost的优点

2 XGBoost的缺点

二、实现过程

1 数据集

天气数据集 提取码:1234

2 实现

#%%导入基本库
import numpy as np 
import pandas as pd

## 绘图函数库
import matplotlib.pyplot as plt
import seaborn as sns
#读取数据
data=pd.read_csv('D:\Python\ML\data\XGBtrain.csv')

通过variable explorer查看样本数据

Python中基于天气数据集XGBoost的示例分析

也可以使用head()或tail()函数,查看样本前几行和后几行。不难看出,数据集中含有NAN,代表数据中存在缺失值,可能是在数据采集或者处理过程中产生的一种错误,此处采用-1将缺失值进行填充,还有其他的填充方法:

注:在数据的前期处理中,一定要注意对缺失值的处理。前期数据处理的结果将会严重影响后面是否可能得到合理的结果

data=data.fillna(-1)
#利用value_counts()函数查看训练集标签的数量(Raintomorrow=no)
print(pd.Series(data['RainTomorrow']).value_counts())
data_des=data.describe()

填充后:

Python中基于天气数据集XGBoost的示例分析

#%%#可视化数据(特征值包括数字特征和非数字特征)
numerical_features = [x for x in data.columns if data[x].dtype == np.float]
category_features = [x for x in data.columns if data[x].dtype != np.float and x != 'RainTomorrow']
#%% 选取三个特征与标签组合的散点可视化
sns.pairplot(data=data[['Rainfall','Evaporation','Sunshine'] + ['RainTomorrow']], diag_kind='hist', hue= 'RainTomorrow')
plt.show()

Python中基于天气数据集XGBoost的示例分析

#%%每个特征的箱图
i=0
for col in data[numerical_features].columns:
    if col != 'RainTomorrow':
        plt.subplot(2,8,i+1)
        sns.boxplot(x='RainTomorrow', y=col, saturation=0.5, palette='pastel', data=data)
        plt.title(col)
        i=i+1
plt.show()

Python中基于天气数据集XGBoost的示例分析

#%%非数字特征
tlog = {}
for i in category_features:
    tlog[i] = data[data['RainTomorrow'] == 'Yes'][i].value_counts()
flog = {}
for i in category_features:
    flog[i] = data[data['RainTomorrow'] == 'No'][i].value_counts()
#%%不同地区下雨情况
plt.figure(figsize=(20,10))
plt.subplot(1,2,1)
plt.title('RainTomorrow')
sns.barplot(x = pd.DataFrame(tlog['Location']).sort_index()['Location'], y = pd.DataFrame(tlog['Location']).sort_index().index, color = "red")
plt.subplot(1,2,2)
plt.title('Not RainTomorrow')
sns.barplot(x = pd.DataFrame(flog['Location']).sort_index()['Location'], y = pd.DataFrame(flog['Location']).sort_index().index, color = "blue")
plt.show()

Python中基于天气数据集XGBoost的示例分析

#%%
plt.figure(figsize=(20,5))
plt.subplot(1,2,1)
plt.title('RainTomorrow')
sns.barplot(x = pd.DataFrame(tlog['RainToday'][:2]).sort_index()['RainToday'], y = pd.DataFrame(tlog['RainToday'][:2]).sort_index().index, color = "red")
plt.subplot(1,2,2)
plt.title('Not RainTomorrow')
sns.barplot(x = pd.DataFrame(flog['RainToday'][:2]).sort_index()['RainToday'], y = pd.DataFrame(flog['RainToday'][:2]).sort_index().index, color = "blue")
plt.show()

Python中基于天气数据集XGBoost的示例分析

XGBoost无法处理字符串类型的数据,需要将字符串数据转化成数值

#%%对离散变量进行编码
## 把所有的相同类别的特征编码为同一个值
def get_mapfunction(x):
    mapp = dict(zip(x.unique().tolist(),
         range(len(x.unique().tolist()))))
    def mapfunction(y):
        if y in mapp:
            return mapp[y]
        else:
            return -1
    return mapfunction
#将非数字特征离散化
for i in category_features:
    data[i] = data[i].apply(get_mapfunction(data[i]))
#%%利用XGBoost进行训练与预测
## 为了正确评估模型性能,将数据划分为训练集和测试集,并在训练集上训练模型,在测试集上验证模型性能。
from sklearn.model_selection import train_test_split

## 选择其类别为0和1的样本 (不包括类别为2的样本)
data_target_part = data['RainTomorrow']
data_features_part = data[[x for x in data.columns if x != 'RainTomorrow']]

## 测试集大小为20%, 80%/20%分
x_train, x_test, y_train, y_test = train_test_split(data_features_part, data_target_part, test_size = 0.2, random_state = 2020)

#%%导入XGBoost模型
from xgboost.sklearn import XGBClassifier
## 定义 XGBoost模型 
clf = XGBClassifier()
# 在训练集上训练XGBoost模型
clf.fit(x_train, y_train)
#%% 在训练集和测试集上分布利用训练好的模型进行预测
train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)
from sklearn import metrics

## 利用accuracy(准确度)【预测正确的样本数目占总预测样本数目的比例】评估模型效果
print('The accuracy of the XGBoost is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the XGBoost is:',metrics.accuracy_score(y_test,test_predict))

## 查看混淆矩阵 (预测值和真实值的各类情况统计矩阵)
confusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)
print('The confusion matrix result:\n',confusion_matrix_result)

# 利用热力图对于结果进行可视化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.show()

Python中基于天气数据集XGBoost的示例分析

#%%利用XGBoost进行特征选择:
#XGboost中可以用属性feature_importances_去查看特征的重要度。
sns.barplot(y=data_features_part.columns,x=clf.feature_importances_)

Python中基于天气数据集XGBoost的示例分析

初次之外,我们还可以使用XGBoost中的下列重要属性来评估特征的重要性:

#利用XGBoost的其他重要参数评估特征的重要性
from sklearn.metrics import accuracy_score
from xgboost import plot_importance

def estimate(model,data):
    #sns.barplot(data.columns,model.feature_importances_)
    ax1=plot_importance(model,importance_type="gain")
    ax1.set_title('gain')
    ax2=plot_importance(model, importance_type="weight")
    ax2.set_title('weight')
    ax3 = plot_importance(model, importance_type="cover")
    ax3.set_title('cover')
    plt.show()
def classes(data,label,test):
    model=XGBClassifier()
    model.fit(data,label)
    ans=model.predict(test)
    estimate(model, data)
    return ans
 
ans=classes(x_train,y_train,x_test)
pre=accuracy_score(y_test, ans)
print('acc=',accuracy_score(y_test,ans))

Python中基于天气数据集XGBoost的示例分析

Python中基于天气数据集XGBoost的示例分析

Python中基于天气数据集XGBoost的示例分析

Python中基于天气数据集XGBoost的示例分析

XGBoost中包括但不限于下列对模型影响较大的参数:

调节模型参数的方法有贪心算法、网格调参、贝叶斯调参等。这里我们采用网格调参,它的基本思想是穷举搜索:在所有候选的参数选择中,通过循环遍历,尝试每一种可能性,表现最好的参数就是最终的结果

#%%通过调参获得更好的效果
## 从sklearn库中导入网格调参函数
from sklearn.model_selection import GridSearchCV

## 定义参数取值范围
learning_rate = [0.1, 0.3, 0.6]
subsample = [0.8, 0.9]
colsample_bytree = [0.6, 0.8]
max_depth = [3,5,8]

parameters = { 'learning_rate': learning_rate,
              'subsample': subsample,
              'colsample_bytree':colsample_bytree,
              'max_depth': max_depth}
model = XGBClassifier(n_estimators = 50)

## 进行网格搜索
clf = GridSearchCV(model, parameters, cv=3, scoring='accuracy',verbose=1,n_jobs=-1)
clf = clf.fit(x_train, y_train)
#%%网格搜索后的参数
print(clf.best_params_)

Python中基于天气数据集XGBoost的示例分析

#%% 在训练集和测试集上分别利用最好的模型参数进行预测
## 定义带参数的 XGBoost模型 
clf = XGBClassifier(colsample_bytree = 0.6, learning_rate = 0.3, max_depth= 8, subsample = 0.9)
# 在训练集上训练XGBoost模型
clf.fit(x_train, y_train)

train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)

## 利用accuracy(准确度)【预测正确的样本数目占总预测样本数目的比例】评估模型效果
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))

## 查看混淆矩阵 (预测值和真实值的各类情况统计矩阵)
confusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)
print('The confusion matrix result:\n',confusion_matrix_result)

# 利用热力图对于结果进行可视化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.show()

Python中基于天气数据集XGBoost的示例分析

Python中基于天气数据集XGBoost的示例分析

三、Keys

XGBoost的重要参数

关于“Python中基于天气数据集XGBoost的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. Python 分析天气,告诉你中秋应该去哪里
  2. SQLserver中cube多维数据集的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python xgboost

上一篇:Python中LightGBM的示例分析

下一篇:DIV CSS HACK和浏览器兼容的方法有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》