數(shù)據(jù)
我存為.xlsx格式催跪,可以直接讀取投蝉。
一行是一個樣本裙士,前17個為特征(自變量),最后一個是目標變量(因變量)自阱。
我們進行回歸預測通常就是通過一個樣本的特征來預測目標變量嚎莉。
這個數(shù)據(jù)是我之前寫論文的時候用的,事先進行歸一化處理沛豌。得分是該樣本城市的人口增長趋箩。
代碼
——————————————————————————
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import xlrd
import xlwt
import random
###########1.讀取數(shù)據(jù)部分##########
#載入數(shù)據(jù)并且打亂數(shù)據(jù)集
def load_data(StartPo,EndPo,TestProportion,FeatureNum,Shuffle,FilePath):? ? ? ? #樣本起始行數(shù),結(jié)束行數(shù)加派,測試集占總樣本集比重,特征數(shù)叫确,是否打亂樣本集? ? #如果Testproportion為0或1就訓練集=測試集
? ? #打開excel文件
? ? workbook = xlrd.open_workbook(str(FilePath))? ? ? #excel路徑
? ? sheet = workbook.sheet_by_name('Sheet1')? ? ? ? ? ? #sheet表
? ? Sample = []#總樣本集
? ? train = []#訓練集
? ? test = []#測試集
? ? TestSetSphere = (EndPo-StartPo+1)*TestProportion? #測試集數(shù)目
? ? TestSetSphere = int(TestSetSphere)#測試集數(shù)目
? ? #獲取全部樣本集并打亂順序
? ? for loadi in range(StartPo-1,EndPo):
? ? ? ? RowSample = sheet.row_values(loadi)
? ? ? ? Sample.append(RowSample)
? ? if Shuffle == 1:? #是否打亂樣本集
? ? ? ? random.shuffle(Sample)? #如果shuffle=1,打亂樣本集
? ? #如果Testproportion為0就訓練集=測試集
? ? if TestProportion == 0 or TestProportion == 1:
? ? ? ? TrainSet = np.array(Sample)? ? ? ? ? #變換為array
? ? ? ? TestSet = np.array(Sample)
? ? else:
? ? ? ? #設置訓練集
? ? ? ? for loadtraina in Sample[:(EndPo-TestSetSphere)]:
? ? ? ? ? ? GetTrainValue = loadtraina
? ? ? ? ? ? train.append(GetTrainValue)
? ? ? ? #設置測試集
? ? ? ? for loadtesta in range(-TestSetSphere-1,-1):
? ? ? ? ? ? GetTestValue = Sample[loadtesta]
? ? ? ? ? ? test.append(GetTestValue)
? ? ? ? #變換樣本集
? ? ? ? TrainSet = np.array(train)? ? ? ? ? ? ? ? ? #變換為array
? ? ? ? TestSet = np.array(test)? ? ? ?
? #分割特征與目標變量
? ? x1 , y1 = TrainSet[:,:FeatureNum] , TrainSet[:,-1]
? ? x2 , y2 = TestSet[:,:FeatureNum] , TestSet[:,-1]
? ? return x1 , y1 , x2 , y2
###########2.回歸部分##########
def regression_method(model):
? ? model.fit(x_train,y_train)
? ? score = model.score(x_test, y_test)
? ? result = model.predict(x_test)
? ? ResidualSquare = (result - y_test)**2? ? #計算殘差平方
? ? RSS = sum(ResidualSquare)? #計算殘差平方和
? ? MSE = np.mean(ResidualSquare)? ? ? #計算均方差
? ? num_regress = len(result)? #回歸樣本個數(shù)
? ? print(f'n={num_regress}')
? ? print(f'R^2={score}')
? ? print(f'MSE={MSE}')
? ? print(f'RSS={RSS}')
############繪制折線圖##########
? ? plt.figure()
? ? plt.plot(np.arange(len(result)), y_test,'go-',label='true value')
? ? plt.plot(np.arange(len(result)),result,'ro-',label='predict value')
? ? plt.title('RandomForestRegression R^2: %f'%score)
? ? plt.legend()? ? ? ? # 將樣例顯示出來
? ? plt.show()
? ? return result
##########3.繪制驗證散點圖########
def scatter_plot(TureValues,PredictValues):
? ? #設置參考的1:1虛線參數(shù)
? ? xxx = [-0.5,1.5]
? ? yyy = [-0.5,1.5]
? ? #繪圖
? ? plt.figure()
? ? plt.plot(xxx , yyy , c='0' , linewidth=1 , linestyle=':' , marker='.' , alpha=0.3)#繪制虛線
? ? plt.scatter(TureValues , PredictValues , s=20 , c='r' , edgecolors='k' , marker='o' , alpha=0.8)#繪制散點圖芍锦,橫軸是真實值竹勉,豎軸是預測值
? ? plt.xlim((0,1))? #設置坐標軸范圍
? ? plt.ylim((0,1))
? ? plt.title('RandomForestRegressionScatterPlot')
? ? plt.show()
###########4.預設回歸方法##########
####隨機森林回歸####
from sklearn import ensemble
model_RandomForestRegressor = ensemble.RandomForestRegressor(n_estimators=800)? #esitimators決策樹數(shù)量
########5.設置參數(shù)與執(zhí)行部分#############
#設置數(shù)據(jù)參數(shù)部分
x_train , y_train , x_test , y_test = load_data(2,121,1,17,0,'C:\Code\MachineLearning\極差標準化數(shù)據(jù)集.xlsx')? #行數(shù)以excel里為準
#起始行數(shù)2,結(jié)束行數(shù)121娄琉,訓練集=測試集次乓,特征數(shù)量17,不打亂樣本集
y_pred = regression_method(model_RandomForestRegressor)? ? ? ? #括號內(nèi)填上方法,并獲取預測值
scatter_plot(y_test,y_pred)? #生成散點圖
——————————————————————————————
代碼很簡單孽水,不超過100行票腰。說明說得很清楚了,這里就不贅述了女气。
在使用時一般設置第五部分即可丧慈。
x_train , y_train , x_test , y_test = load_data(2,121,1,17,1,'C:\Code\MachineLearning\極差標準化數(shù)據(jù)集.xlsx') #起始行數(shù)1,結(jié)束行數(shù)121主卫,訓練集=測試集逃默,特征數(shù)量17,打亂樣本集
值得注意的是,這里的起始和結(jié)束行數(shù)我設置成了以excel表里為準簇搅。
效果
最后會出四個參數(shù)和兩個圖完域,一個是折線圖,另一個是散點圖瘩将。
折線圖展示的測試集樣本中的實測值與預測值吟税。
散點圖的橫軸是實測值,豎軸是隨機森林回歸后的預測值姿现。
輸出的四個指標分別是:
n:測試集的樣本數(shù)肠仪,體現(xiàn)在圖上就是折線圖的紅點或綠點數(shù),散點圖的紅點數(shù)备典;
R方:擬合優(yōu)度异旧,模型對數(shù)據(jù)的擬合程度,取值范圍在0~1提佣,越接近1效果越好吮蛹;
MSE:均方誤差荤崇,MSE越小模型效果越好;
RSS:殘差平方和潮针,RSS越小模型效果越好术荤;
一帶而過,不多贅述每篷,MSE還是RSS什么的不懂自己百度或者看代碼就知道是什么意思了瓣戚。
原文鏈接:https://blog.csdn.net/Leaze932822995/article/details/103951150