python机器学习系列:预测房价并且可视化

这篇文章不是给纯粹的小白看的,需要一定的基础,需要小白补充一定的基础知识,在我的博客有相关的资源介绍。

在这里记录下这篇文章时因为很实用,并且也希望以此帮助需要的人。

这是我在YouTube上学习到的。

对应的网页课程地址在此:https://pythonprogramming.net/forecasting-predicting-machine-learning-tutorial/

在作者的基础上进行了一点点的改动。说明一下:相关的库自行安装,就不一一废话了。

项目开始

项目过程:从开放的数据接口拿到数据,并且做简单的数据处理,自行做好数据标签用于算法训练,之后在利用相关的模块做好预测得到的数值与相应的时间值的对接,得出数据的图表(包括预测部分),项目完成。

获取数据以及简单数据处理

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import quandl,math
import numpy as np
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
#获取公共数据接口
df = quandl.get("WIKI/GOOGL")
#简单的数据特征处理、整理,目的是得出“标签”特征列(因为仅仅是做到实践的效果,所以就不多说了,看代码便知)。
df = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']] #取用时需要用大括号
df['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100.0
df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) /df['Adj. Open'] * 100.0
df = df[['Adj. Close', 'Adj. Volume','HL_PCT','PCT_change']]
forecast_col = 'Adj. Close'
df.fillna(value=-99999, inplace=True)
forecast_out = int(math.ceil(0.01 * len(df)))
#得出标签特征列,以便直接用于训练
df['label'] = df[forecast_col].shift(-forecast_out)

关于quandl,是个公开的数据网站,有免费的,也有收费的,它有很好的支持python的数据接口。可用pip install quandl下载相关的支持模块。如果有时获取数据出错了,重新运行直到没错误出现为止。

算法预测

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
X = np.array(df.drop(['label'], 1))
X = preprocessing.scale(X)
#这里是取数据的后面一小部分用于预测得出的数值使用
X_lately = X[-forecast_out:]
X = X[:-forecast_out]
df.dropna(inplace=True)
y = np.array(df['label'])
#数据分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
clf = LinearRegression(n_jobs=-1)
clf.fit(X_train, y_train)
#预测准确性
confidence = clf.score(X_test, y_test)
#最后预测的数值部分
forecast_set = clf.predict(X_lately)

这里是简单的预测部分了,其中有一些简单的数据处理部分。

时间与预测值的对应以及图表的描绘

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import datetime
import matplotlib.pyplot as plt
#matplotlib的美化图表风格
plt.style.use('ggplot')
#预测标签
df['Forecast'] = np.nan
#获取源数据最后一天日期
last_date = df.iloc[-1].name
last_unix = last_date.timestamp()
one_day = 86400 #一天的时间戳
next_unix = last_unix + one_day
for i in forecast_set:
next_date = datetime.datetime.fromtimestamp(next_unix)
next_unix += 86400
#将此日期对应的前面五列不相干的均设为nan,而仅仅加上预测的数值,即仅仅有相应的时间对应相应的预测数值
df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)]+[i] #如果这里不理解的话,可以查看df的head和tail部分试试,就能一目了然了
#图表描绘
df['Adj. Close'].plot()
df['Forecast'].plot()
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()

这里有些难理解,但是其实很好理解,只是一些代码根本没见到过,所以导致阅读障碍。

估计有人不理解这段df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)]+[i]代码,我来简单说明一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
for i in forecast_set:
next_date = datetime.datetime.fromtimestamp(next_unix)
next_unix += 86400
df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)]+[i]
print(df.head())
输出:
Adj. Close Adj. Volume HL_PCT PCT_change label Forecast
Date
2004-08-19 50.322842 44659000.0 3.712563 0.324968 69.078238 NaN
2004-08-20 54.322689 22834300.0 0.710922 7.227007 67.839414 NaN
2004-08-23 54.869377 18256100.0 3.729433 -1.227880 68.912727 NaN
2004-08-24 52.597363 15247300.0 6.417469 -5.726357 70.668146 NaN
2004-08-25 53.164113 9188600.0 1.886792 1.183658 71.219849 NaN
print(df.tail())
输出:
Adj. Close Adj. Volume HL_PCT PCT_change label \
Date
2018-03-08 08:00:00 NaN NaN NaN NaN NaN
2018-03-09 08:00:00 NaN NaN NaN NaN NaN
2018-03-10 08:00:00 NaN NaN NaN NaN NaN
2018-03-11 08:00:00 NaN NaN NaN NaN NaN
2018-03-12 08:00:00 NaN NaN NaN NaN NaN
Forecast
Date
2018-03-08 08:00:00 1113.922012
2018-03-09 08:00:00 1071.104993
2018-03-10 08:00:00 1043.810593
2018-03-11 08:00:00 1073.778780
2018-03-12 08:00:00 1022.639186

就是这样,已经很明了了,就是仅仅为了让预测的时间对应预测的房价数值而已。

什么是时间戳?

简单说说:时间戳是自1970年1月1日(00:00:00 UTC/GMT)以来的秒数。它也被称为Unix时间戳(Unix Timestam、Unix epoch、POSIX time、Unix timestamp)是从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒。

UNIX时间戳的0按照ISO 8601规范为:1970-01-01T00:00:00Z

一个小时表示为UNIX时间戳格式为:3600秒;一天表示为UNIX时间戳为86400秒,闰秒不计算。

来自:http://www.htmer.com/article/420.htm

完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import quandl,math,datetime
import numpy as np
from sklearn import preprocessing,svm
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
plt.style.use('ggplot')
df = quandl.get("WIKI/GOOGL")
df = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']] #取用时需要用大括号
df['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100.0
df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) /df['Adj. Open'] * 100.0
df = df[['Adj. Close', 'Adj. Volume','HL_PCT','PCT_change']]
forecast_col = 'Adj. Close'
df.fillna(value=-99999, inplace=True)
forecast_out = int(math.ceil(0.01 * len(df)))
df['label'] = df[forecast_col].shift(-forecast_out)
X = np.array(df.drop(['label'], 1))
X = preprocessing.scale(X)
X_lately = X[-forecast_out:]
X = X[:-forecast_out]
df.dropna(inplace=True)
y = np.array(df['label'])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
clf = LinearRegression(n_jobs=-1)
clf.fit(X_train, y_train)
confidence = clf.score(X_test, y_test)
forecast_set = clf.predict(X_lately)
df['Forecast'] = np.nan
last_date = df.iloc[-1].name
last_unix = last_date.timestamp()
one_day = 86400
next_unix = last_unix + one_day
for i in forecast_set:
next_date = datetime.datetime.fromtimestamp(next_unix)
next_unix += 86400
df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)]+[i]
df['Adj. Close'].plot()
df['Forecast'].plot()
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()

最终效果展示

可以查看到预测的部分展示。

补助链接

这里是帮助理解的链接。

值得说明一下Legend 图例的一些知识:

使用plt.legend(loc=n)n的选择代表什么:

1
2
3
4
5
6
7
8
9
10
11
'best' : 0,
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5,
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10

补充添加序列化保存预测模型

添加了如何将预测代码序列化的过程加相关的代码。

序列化可简单理解为:先保存了这个预测的模型(序列化的过程),然后我们可以拿出这个模型直接进行以后的预测(反序列化的过程)。

加上代码:

1
2
3
4
5
6
7
8
import pickle
with open('houseforecastmodel.pickle','wb') as f:
#下载模型
pickle.dump(clf,f)
pickle_in = open('houseforecastmodel.pickle','rb')
clf = pickle.load(pickle_in) #加载模型

完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import quandl,math,datetime
import numpy as np
from sklearn import preprocessing,svm
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import pickle
plt.style.use('ggplot')
df = quandl.get("WIKI/GOOGL")
df = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']] #取用时需要用大括号
df['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100.0
df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) /df['Adj. Open'] * 100.0
df = df[['Adj. Close', 'Adj. Volume','HL_PCT','PCT_change']]
forecast_col = 'Adj. Close'
df.fillna(value=-99999, inplace=True)
forecast_out = int(math.ceil(0.01 * len(df)))
df['label'] = df[forecast_col].shift(-forecast_out)
X = np.array(df.drop(['label'], 1))
X = preprocessing.scale(X)
X_lately = X[-forecast_out:]
X = X[:-forecast_out]
df.dropna(inplace=True)
y = np.array(df['label'])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
clf = LinearRegression(n_jobs=-1)
clf.fit(X_train, y_train)
with open('houseforecastmodel.pickle','wb') as f:
#下载模型
pickle.dump(clf,f)
pickle_in = open('houseforecastmodel.pickle','rb')
clf = pickle.load(pickle_in) #加载模型
confidence = clf.score(X_test, y_test)
forecast_set = clf.predict(X_lately)
df['Forecast'] = np.nan
last_date = df.iloc[-1].name
last_unix = last_date.timestamp()
one_day = 86400
next_unix = last_unix + one_day
for i in forecast_set:
next_date = datetime.datetime.fromtimestamp(next_unix)
next_unix += 86400
df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)]+[i]
df['Adj. Close'].plot()
df['Forecast'].plot()
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()

在运行一遍以上的代码之后,就可以直接从保存的文件来加载模型来预测数据啦,如下可测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import quandl,math,datetime
import numpy as np
from sklearn import preprocessing,svm
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import pickle
plt.style.use('ggplot')
df = quandl.get("WIKI/GOOGL")
df = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']] #取用时需要用大括号
df['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100.0
df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) /df['Adj. Open'] * 100.0
df = df[['Adj. Close', 'Adj. Volume','HL_PCT','PCT_change']]
forecast_col = 'Adj. Close'
df.fillna(value=-99999, inplace=True)
forecast_out = int(math.ceil(0.01 * len(df)))
df['label'] = df[forecast_col].shift(-forecast_out)
X = np.array(df.drop(['label'], 1))
X = preprocessing.scale(X)
X_lately = X[-forecast_out:]
X = X[:-forecast_out]
df.dropna(inplace=True)
y = np.array(df['label'])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
#clf = LinearRegression(n_jobs=-1)
#clf.fit(X_train, y_train)
#with open('houseforecastmodel.pickle','wb') as f:
#下载模型
#pickle.dump(clf,f)
pickle_in = open('houseforecastmodel.pickle','rb')
clf = pickle.load(pickle_in) #加载模型
confidence = clf.score(X_test, y_test)
forecast_set = clf.predict(X_lately)
df['Forecast'] = np.nan
last_date = df.iloc[-1].name
last_unix = last_date.timestamp()
one_day = 86400
next_unix = last_unix + one_day
for i in forecast_set:
next_date = datetime.datetime.fromtimestamp(next_unix)
next_unix += 86400
df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)]+[i]
df['Adj. Close'].plot()
df['Forecast'].plot()
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()

得出的结果与上方展示的一致。

了解pickle

---------------本文终---------------

文章作者:刘俊

最后更新:2019年01月02日 - 14:01

许可协议: 转载请保留原文链接及作者。