#!/usr/bin/env python # coding: utf-8 # In[6]: # 用于数据分析的库 import pandas as pd # python 2D 绘图库,对数据进行可视化分析 import matplotlib.pyplot as plt data = 'population_data.csv' # read_csv函数用于读取数据 df = pd.read_csv(data) # 将第一列 列名改为year # inplace=True:不创建新的对象,直接对原始对象进行修改 # inplace=False:对数据进行修改,创建并返回新的对象承载其修改结果 df.rename(columns={'year index': 'year'}, inplace=True) # df.columns:返回列标签,并打印出来 print(df.columns) target_var = 'life_expectancy' # 选取特征列 # .drop函数表示删除,因为年份year的影响已包含在其他特征中,所以删除year这一列,删除要预测的预期寿命列,留下的其余指标为选取的特征列 features = df.columns.drop(target_var) features = features.drop('year') # 随机森林 # sklearn.ensemble 模块中的 RandomForestRegressor 类是一个用于回归问题的随机森林模型。随机森林是一种集成学习方法,它通过组合多个决策树来预测结果。通过对每个决策树进行随机采样和特征选择,它可以减少过拟合,并提高预测准确性。 from sklearn.ensemble import RandomForestRegressor # sklearn.model_selection 这个模块主要是对数据的分割,以及与数据划分相关的功能。 # 可以使用 train_test_split 函数,将数据集随机划分为训练集和测试集,以便在训练模型时进行测试并评估其性能。 from sklearn.model_selection import train_test_split # sklearn.metrics 这个模块中主要是机器学习的一些评价指标,即检验机器学习模型效果的定量指标,都是一个不可避免且十分重要的问题。 # mean_squared_error 是 Scikit-Learn 中一个常用的函数,用于计算真实标签值和预测标签值之间的均方误差(mean squared error,MSE)。MSE 是衡量预测值与实际值之间差异的度量,用于评估机器学习模型的性能。 from sklearn.metrics import mean_squared_error # numpy 是用 Python 进行科学计算的基本库。它可以用于处理各种数据类型,包括矩阵、数组和张量。numpy 提供了许多方法和函数,可以执行诸如线性代数、数值优化、随机数生成、信号处理、图像处理和机器学习等各种计算任务。 import numpy as np # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(df[features], df[target_var], test_size=0.5, random_state=42) # 训练模型 # n_estimators:森林中树木的数量。决定随机森林中决策树的数量。通常情况下,树的数量越多,模型的性能越好。但是,过多的树会增加计算时间和内存占用,同时可能会导致过拟合。 ## 过拟合:是指机器学习算法在训练集上表现良好,但在测试集或实际应用中表现不佳的现象。 # random_state:控制每次运行模型时得到的随机数,以便每次运行相等。 # max_depth:决定树的最大深度。增加最大深度会增加模型的复杂度,从而可能导致过拟合。因此,需要通过交叉验证等方法来确定最佳的最大深度。 ## 交叉验证:交叉验证是一种常用的评估机器学习算法性能的技术。在这种技术下,我们将数据集划分为几个部分,并多次使用这些部分的子集进行训练和测试。这样可以评估模型在不同子集上的性能,并有助于避免过度拟合。 # min_samples_leaf:最小叶子节点数。决定每个叶子节点的最小样本数。增加最小叶子节点数会增加模型的泛化能力,从而可能降低过拟合的风险。但是,如果将最小叶子节点数设置得太高,可能会导致欠拟合。因此,需要通过交叉验证等方法来确定最佳的最小叶子节点数。 ## 泛化能力:指的是机器学习算法在未见过的数据上的表现能力。泛化能力是衡量一个机器学习算法优劣的重要指标之一,因为一个具有良好泛化能力的算法能够更好地适应现实场景、提高模型效果、避免过拟合等问题。 ## 欠拟合:指模型无法容纳训练数据中的关系,导致模型在训练集上表现不佳。 # max_features:为特征采样数。决定每个决策树在节点上分裂时使用的特征数量。较少的特征数会降低模型的复杂度,从而可能降低过拟合的风险。但是,如果将特征数设置得太少,可能会导致欠拟合。因此,需要通过交叉验证等方法来确定最佳的特征采样数。 # rf = RandomForestRegressor(n_estimators=10,random_state=42, max_depth=3, min_samples_leaf=5,max_features=0.5)(第一次随机设置) rf = RandomForestRegressor(n_estimators=30,random_state=42, max_depth=3, min_samples_leaf=1,max_features=0.8) #(调优后最优的参数值) # rf.fit的主要作用是触发随机森林回归类对数据进行训练,以建立模型,以便可以通过模型对未知数据进行预测。 rf.fit(X_train, y_train) # 预测 y_pred = rf.predict(X_test) # 计算y_test与y_pred之间的均方误差,均方误差越小,预测值与实际结果越接近 mse = mean_squared_error(y_test, y_pred) print('mse:', mse) ###################################################### # # n_estimators调优 # n_estimators = [10, 20, 30, 40, 50, 60, 70, 80, 90] # mse_list = [] # for n in n_estimators: # rf = RandomForestRegressor(n_estimators=n, random_state=42, max_depth=3, min_samples_leaf=5) # rf.fit(X_train, y_train) # y_pred = rf.predict(X_test) # mse = mean_squared_error(y_test, y_pred) # mse_list.append(mse) # plt.plot(n_estimators, mse_list) # plt.xlabel('n_estimators') # plt.ylabel('mse') # plt.savefig('n_estimators.png') # plt.show() # # max_depth交叉验证 # from sklearn.model_selection import cross_val_score # max_depth = [3, 4, 5, 6, 7, 8, 9, 10] # mse_list = [] # for d in max_depth: # rf = RandomForestRegressor(n_estimators=30, random_state=42, max_depth=d, min_samples_leaf=5) # mse = cross_val_score(rf, X_train, y_train, cv=5, scoring='neg_mean_squared_error').mean() # mse_list.append(-mse) # plt.plot(max_depth, mse_list) # plt.xlabel('max_depth') # plt.ylabel('mse') # plt.savefig('max_depth.png') # plt.show() # # min_samples_leaf交叉验证 # min_samples_leaf = [1, 2, 3, 4, 5, 6, 7, 8, 9] # mse_list = [] # for m in min_samples_leaf: # rf = RandomForestRegressor(n_estimators=30, random_state=42, max_depth=3, min_samples_leaf=m) # mse = cross_val_score(rf, X_train, y_train, cv=5, scoring='neg_mean_squared_error').mean() # mse_list.append(-mse) # plt.plot(min_samples_leaf, mse_list) # plt.xlabel('min_samples_leaf') # plt.ylabel('mse') # plt.savefig('min_samples_leaf.png') # plt.show() # # max_features交叉验证 # max_features = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6,0.7,0.8,0.9] # mse_list = [] # for f in max_features: # rf = RandomForestRegressor(n_estimators=30, random_state=42, max_depth=3, min_samples_leaf=1,max_features=f) # mse = cross_val_score(rf, X_train, y_train, cv=5, scoring='neg_mean_squared_error').mean() # mse_list.append(-mse) # plt.plot(max_features, mse_list) # plt.xlabel('max_features') # plt.ylabel('mse') # plt.savefig('max_features.png') # plt.show() ####################################################### # 打印特征重要性和特征名称 # 特征重要性是随机森林回归模型的一个重要指标,它可以帮助我们识别哪些特征在模型中具有最大影响力。这些特征对于正确预测目标变量非常重要,因此可以作为特征选择和建模过程中的重要参考。使用 feature_importances_ 属性可以非常方便地提取随机森林回归模型中每个特征的重要性得分。 importances = rf.feature_importances_ print('importances:', importances) print('features:', features) # 画出预测值和真实值的散点图 plt.scatter(y_test, y_pred) plt.xlabel('y_test') plt.ylabel('y_pred') plt.savefig('y_test_y_pred.png') # savefig 函数将当前 matplotlib 图形保存为指定的文件名。 plt.show() # 保存模型 # pickle 模块将训练好的 rf 随机森林回归模型对象保存到一个文件中。 # 我们使用 with 语句打开一个文件句柄并将其命名为 f。我们使用 pickle.dump() 函数将随机森林回归模型对象 rf 保存到该文件中。'wb' 参数表示以二进制模式打开文件。 import pickle with open('rf.pkl', 'wb') as f: pickle.dump(rf, f) # 加载保存的模型数据,读取模型 with open('rf.pkl', 'rb') as f: rf = pickle.load(f) # 预测 y_pred = rf.predict(X_test) # In[7]: import pandas as pd import matplotlib.pyplot as plt import seaborn as sns data = 'population_data.csv' df = pd.read_csv(data) # 将第一列 列名改为year df.rename(columns={'year index': 'year'}, inplace=True) print(df.columns) target_var = 'life_expectancy' # 选取特征列 features = df.columns.drop(target_var) # 在一张图上画出所有特征列与目标列的关系 fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(10, 10)) for i, feature in enumerate(features): df.plot(feature, target_var, subplots=True, kind='scatter', ax=axes[i // 3, i % 3]) # 保存图片 plt.savefig('feature.png') plt.show() # 计算相关系数 corr = df.corr() # 画出相关系数热力图 sns.heatmap(corr, annot=True) #保存图片 plt.savefig('corr.png') plt.show() # In[9]: import pickle import pandas as pd def rf_predict(GDP,Unemployment,Medical_resources,Past_years_life_expectancy_growth_rate): # 读取模型 with open('rf.pkl', 'rb') as f: rf = pickle.load(f) # 预测 X_test = [GDP,Unemployment,Medical_resources,Past_years_life_expectancy_growth_rate] X_test = pd.DataFrame(X_test).T X_test.columns = ['GDP_per_capita','Unemployment_rate','Medical_resources_per_capita','Past_years_life_expectancy_growth_rate'] y_pred = rf.predict(X_test) return y_pred # 读取模型 print(rf_predict(85698,5.5,2120,0.1)) # In[ ]: