在IDEA中实现Python随机森林模型预测人口
生活随笔
收集整理的這篇文章主要介紹了
在IDEA中实现Python随机森林模型预测人口
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
數據集鏈接在評論區噢。訓練數據中有22個自變量(valuexx是某種土地利用面積),因變量是最后的人口,每一行數據都是一個縣市的數據,根據訓練數據得到這22個自變量與因變量人口之間的函數關系式y=ax+by+z.....(a、b以及后面的省略號中都是常數,x、y等就是22個自變量的值,這個不一定時22,不同的模型可能會自動進行主成分分析,那時候自變量就沒有22個了),當新的數據(也就是要預測人口的數據,包含一樣的22個自變量字段以及相同的單位和先后排列順序)使用該模型進行預測時將會使用y=ax+by+z.....,并且將22個對應的自變量套進去,得到新的y,即預測人口數量。
# !/usr/bin/env python # -*- coding:utf-8-*- # 讀取數據 import pandas as pd import numpy as np import matplotlib.pyplot as plt from dataframe import dataframe import time pd.set_option('max_colwidth', 10) # 顯示5列 # 字段名為中文,編碼方式指定為gbk temp_data = pd.read_csv('D:\桌面\我的實驗\長沙市數據.csv', encoding='gbk') # temp_data = pd.read_csv('temp_data.csv') # print("輸出讀取的表格行數和列數:",temp_data.shape) # print("輸出前面6行數據:\n",temp_data.head()) # 查看基本信息 # print(temp_data.info())#none # print("輸出所有變量的特征值\n",temp_data.describe()) y = temp_data['人口'] # 表明這個列是作為目標數據(因變量)Y # 使用.drop(['列名'],axis=1)方法表示該列(自變量)不參與計算 X = temp_data.drop(['人口'], axis=1)#######訓練模型啦!!!!!!!!!!!! from sklearn.model_selection import train_test_split # 用來劃分訓練集和測試集 from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_absolute_error# 劃分訓練集和測試集 X是自變量,Y是因變量 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0) # print(X_train.shape) # print(y_train.shape) # print(X_test.shape) # print(y_test.shape) # 所有數據準備完畢 # 存儲一下目前的列名 features = list(X_train.columns) # print("輸出表頭:",features) # 我們先用默認參數訓練 rf0 = RandomForestRegressor(random_state=0) rf0.fit(X_train, y_train) #######訓練模型!!!!!!!!!!!!!!!###########開始預測模型精度!!!!!! y_predict0 = rf0.predict(X_test)# 開始預測之前就分好的訓練集 error0 = mean_absolute_error(y_test, y_predict0) print('當使用隨機森林默認參數時,平均絕對誤差為:', error0) # errors = [] # print(errors.append(error0)) # 看一下特征重要性 importances = list(rf0.feature_importances_) print("特征權重值:", importances) start_time=time.time() # 模型運行開始時間 # column和重要度組合起來 feature_importances = [(feature, round(importance, 3)) for feature, importance in zip(features, importances)] # print(feature_importances) # # 排序 # feature_importances = sorted(feature_importances, key=lambda x: x[1], reverse=True) print(feature_importances) # 開始調參 rf0.get_params # 因為數據量不大,所以我們直接選擇網格搜索來選擇最佳參數 from sklearn.model_selection import GridSearchCV from sklearn.model_selection import RandomizedSearchCV # 設置搜索參數 param_grid = {# 'bootstrap': [True], # 是否對樣本集進行有放回抽樣來構建樹# 'max_depth': [1], # 決策樹最大深度# 'max_features': ['auto'], # 構建決策樹最優模型時考慮的最大特征數。默認是”auto“,表示最大特征數是N的平方根# 'min_samples_leaf': [20], # 葉子節點最少樣本數# 'min_samples_split': [2, 11, 22], # 內部節點再劃分所需最小樣本數# 'n_estimators': [650, 670, 700],# 'min_weight_fraction_leaf':[0,0.5], } grid_search_rf = GridSearchCV(estimator=RandomForestRegressor(random_state=0),param_grid=param_grid, scoring='neg_mean_squared_error',cv=5) grid_search_rf.fit(X_train, y_train) # 模型存儲 print(grid_search_rf.best_params_) rf1 = RandomForestRegressor(bootstrap=True,max_depth=10,max_features='auto',min_samples_leaf=1,min_samples_split=2,n_estimators=20,) rf1.fit(X_train, y_train)# 對照著y_train作為目標數據訓練X_train數據 y_predict1 = rf1.predict(X_test)# 開始預測之前就分好的測試集 error1 = mean_absolute_error(y_test, y_predict1) print('調參后,平均絕對誤差為:', error1) # result = pd.DataFrame(y_test) # result['系統參數'] = y_predict0 # result['調參后'] = y_predict1 # print(round(result.head(10))) end_time=time.time() # 模型結束時間 print("模型運行時間:",end_time-start_time) # joblib.dump(rf1, 'D:\桌面\model1.pkl') # 對模型進行保存 # print("模型保存成功") # clf = joblib.load('D:\桌面\model1.pkl') #加載已經訓練好的模型 # print("模型加載成功") a=time.time() x=pd.read_csv('D:\桌面\我的實驗\研究區.csv',encoding='gbk')# 讀取要預測的數據 d=rf1.predict(x)# 重新調用訓練好的模型對進行測試集進行運算 # pd.set_option('display.max_columns',None)# 輸出所有的列數 pd.set_option('display.max_rows',None)# 輸出所有行數 result = pd.DataFrame() result['調參后'] = d print(round(result.head(960))) b=time.time() print("調用模型運行時間:",b-a)訓練模型使用的數據(由于22個自變量太多了,沒有截到最后面的其他自變量和人口因變量):?
?預測使用的數據(由于22個自變量太多了,截圖沒有全部顯示出來):?
?代碼運行結果:
總結
以上是生活随笔為你收集整理的在IDEA中实现Python随机森林模型预测人口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: dup和dup2的使用方法
- 下一篇: python爬虫笔记(七):实战(三)股