keras神经网络算法预测销量高低实践
基于样本数据周末,促销,天气,销量,进行深度学习。最终得出销量与周末、促销、天气的关系模型。并展示了神经网络算法对分类的预测。
以下为代码:
import pandas as pd
In [2]:
filename = ‘/Users/frontc/book/ppdam/sales_data.xls’
In [3]:
data = pd.read_excel(filename,index_col=u’序号’)
In [4]:
# 数据规整
data[data == u’好’] = 1
data[data == u’是’] = 1
data[data == u’高’] = 1
data[data !=1 ] = 0
In [5]:
x = data.iloc[:,:3].as_matrix().astype(int) # 自变量
y = data.iloc[:,3].as_matrix().astype(int) # 因变量
In [6]:
from keras.models import Sequential # 导入神经网络库
Using Theano backend.
In [7]:
from keras.layers.core import Dense,Activation # 导入层构建包
In [8]:
model = Sequential() # 初始化神经网络模型:线性叠加模型
In [9]:
model.add(Dense(input_dim=3,output_dim=10)) # 添加3个输入层节点,10个隐藏层节点
In [10]:
model.add(Activation(‘relu’)) # 设置激活函数为relu:Rectified Linear Units
In [11]:
model.add(Dense(output_dim=1)) # 设置输出层为1个节点
In [12]:
model.add(Activation(‘sigmoid’)) # 设置激活函数为sigmoid
In [14]:
model.compile(loss=’binary_crossentropy’,optimizer=’adam’) # 根据设置信息进行变异
In [15]:
model.fit(x,y,nb_epoch=1000,batch_size=10) # 迭代1000次,块大小10
Epoch 1/1000
34/34 [==============================] - 0s - loss: 0.6522
Epoch 2/1000
34/34 [==============================] - 0s - loss: 0.6502
…….
Epoch 999/1000
34/34 [==============================] - 0s - loss: 0.4472
Epoch 1000/1000
34/34 [==============================] - 0s - loss: 0.4474
Out[15]:
<keras.callbacks.History at 0x115f11150>
In [16]:
yp = model.predict_classes(x).reshape(len(y)) # predict_classes对x进行分类预测
32/34 [===========================>..] - ETA: 0s
In [19]:
#-*- coding: utf-8 --*
def cm_plot(y, yp):
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y, yp)
import matplotlib.pyplot as plt
plt.matshow(cm, cmap=plt.cm.Greens)
plt.colorbar()
for x in range(len(cm)):
for y in range(len(cm)):
plt.annotate(cm[x,y], xy=(x, y), horizontalalignment=’center’, verticalalignment=’center’)
plt.ylabel(‘True label’)
plt.xlabel(‘Predicted label’)
return plt
In [20]:
cm_plot(y,yp).show() # 可以从混淆矩阵图中看出样本数为34个,其中预测正确的项目为26个