機器學習簡易入門(一) - 線性回歸


摘要:本文簡單敘述了如何根據標准普爾500指數使用線性回歸來預測股票的走勢

聲明:(本文的內容非原創,但經過本人翻譯和總結而來,轉載請注明出處)

本文內容來源:https://www.dataquest.io/mission/58/regression-basics

標准普爾500(S&P 500)說明:http://www.investopedia.com/ask/answers/05/sp500calculation.asp

 

原始數據展現(使用了2005年至2015年的數據)

import pandas

sp500 = pandas.read_csv("sp500.csv")

Image 001

注意到上面的數據中有一些行(如第六行)的value值為點號(.),這是因為這個日期在美國是一個假日,所以沒有股票交易信息,現在要過濾掉這些行

sp500 = sp500[sp500['value'] != '.']

 

格式化數據

為了更容易地使用機器學習的算法,需要把用來預測的值和預測后的真實值放在同一行,在這個例子中,我們要根據每一天的股票指數來預測下一個交易日的股票指數,所以要在每一行上增加下一天指數的列,我們需要的是這樣格式的數據

clip_image002

next_day = sp500["value"].iloc[1:] 
sp500 = sp500.iloc[:-1,:] # 去掉最后一行
sp500["next_day"] = next_day.values

clip_image003

在導入文件的時候,Pandas會自動為每一列的數據推斷數據格式,但由於在導入原始的文件時有一些行(如第六行)的value值為點號(.),所以pandas把該列認為是字符類型,而不是float類型,需要將該列轉換數據格式

# 原始的數據格式

print(sp500.dtypes)

clip_image004

sp500['value'] = sp500['value'].astype(float)

sp500['next_day'] = sp500['next_day'].astype(float)

# 轉換后的數據格式

print(sp500.dtypes)

clip_image005

 

建立模型

使用sckit-learn包中的線性回歸(http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression)來預測下一個交易日的股票指數

#導入類

from sklearn.linear_model import LinearRegression

# 初始化

regressor = LinearRegression()

# predictors變量需要是一個dataframe,而不能是一個series

predictors = sp500[["value"]] # 這是一個dataframe

to_predict = sp500["next_day"] # 這是一個series

# 訓練這個線性回歸模型

regressor.fit(predictors, to_predict)

# 根據模型生成預測值

next_day_predictions = regressor.predict(predictors)

print(next_day_predictions)

clip_image007

 

評估模型

一個經常用於評估回歸模型的指標是均方差(mean squared error, MSE),計算公式:

clip_image009

mse = sum((to_predict - next_day_predictions) ** 2) / len(next_day_predictions)

clip_image011

另外兩個常用的指標是根均方差(root mean squared error, RMSE)和平均絕對誤差(mean absolute error, MAE)

clip_image012

clip_image013

import math

rmse = math.sqrt(sum((predictions - test["next_day"]) ** 2) / len(predictions))

mae = sum(abs(predictions - test["next_day"])) / len(predictions)

 

在上面的評估模型中存在一個巨大的錯誤,那就是過度擬合:使用了同樣的數據來訓練模型和進行預測。想象一下,你告訴他人 2 + 2 等於4,然后問他2 + 2的結果,他可以馬上回答你正確的答案,但是他未必明白加法運算的原理,假如你問他3 + 3的結果,他就可能回答不了。同樣地,你用一批數據來訓練這個回歸模型,然后再用同樣的數據來進行預測,會造成一個結果,那就是錯誤率非常低,因為這個模型早就知道了每個正確的值。

用來避免過度擬合的最好方法就是將訓練的數據和用來預測(測試)的數據分開

import numpy as np

import random

np.random.seed(1)

random.seed(1)

#將sp500進行隨機重排

sp500 = sp500.loc[np.random.permutation(sp500.index)]

clip_image014

# 選擇前70%的數據作為訓練數據

highest_train_row = int(sp500.shape[0] * .7)

train = sp500.loc[:highest_train_row,:]

#選擇后30%的數據作為測試數據

test = sp500.loc[highest_train_row:,:]

regressor = LinearRegression()

predictors = train[['value']]

to_predict = train['next_day']

regressor.fit(predictors, to_predict)

next_day_predictions = regressor.predict(test[['value']])

mse = sum((next_day_predictions - test['next_day']) ** 2) / len(next_day_predictions)

 

數據可視化

除了上面用來評估模型誤差的指標可以說明一個模型的正確性,也可以使用圖表來展現,下面做一個散點圖,很坐標為測試數據的value列,縱坐標為測試數據的next_day列。然后在上面再做一個折線圖,橫坐標同樣為測試數據的value列,縱坐標為使用模型預測后的結果

import matplotlib.pyplot as plt

plt.scatter(test['value'], test['next_day'])

plt.plot(test['value'], predictions)

plt.show()

clip_image015


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM