1.代码
import pandas as pd
import os
import numpy as np
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
inputfile = r"....\sales_data.xls"
data = pd.read_excel(inputfile, index_col='序号')
data[data == '好'] = 1
data[data == '是'] = 1
data[data == '高'] = 1
data[data != 1] = 0
data = pd.DataFrame(data)
x = data.iloc[:, :3].values.astype(int)
y = data.iloc[:, 3].values.astype(int)
from keras.models import Sequential
from tensorflow.python.keras.layers.core import Dense, Activation
model = Sequential() # 建立模型
model.add(Dense(input_dim=3, units=10))
model.add(Activation('relu')) # 用relu函数作为激活函数,能够大幅提高准确度
model.add(Dense(input_dim=10, units=1))
model.add(Activation('sigmoid')) # 由于是0-1输出,用sigmoid函数作为激活函数
model.compile(loss='binary_crossentropy', optimizer='adam')
# 编译模型。由于是二元分类,所以我们指定损失函数为binary_crossentropy,以及模式为binary
# 另外常见的损失函数还有mean_squared_error、categorical_crossentropy等,请阅读
# 对于求解方法,我们指定用adam,此外还有sgd、rmsprop等可选
model.fit(x, y, epochs=1000, batch_size=10) # 训练模型,学习一千次
yp = model.predict(x)
yp = np.round(yp).astype(int) # 分类预测
def cm_plot(y, yp):
from sklearn.metrics import confusion_matrix # 导入混淆矩阵函数
import matplotlib.pyplot as plt # 导入作图库
plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文黑体,不加这句会显示中文方格
cm = confusion_matrix(y, yp) # 混淆矩阵
plt.matshow(cm, cmap=plt.cm.Blues) # 画混淆矩阵图,配色风格使用cm.Blues
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("实际") # 坐标轴标签
plt.xlabel('预测') # 坐标轴标签
plt.title("LM神经网络模型的混淆矩阵")
plt.savefig("LM神经网络模型的混淆矩阵.jpg", dpi=300)
return plt
cm_plot(y, yp).show()
2.错误分析
错误:AttributeError: 'Sequential' object has no attribute 'predict_classes'. Did you mean: 'predict_step'?
yp = model.predict_classes(x).reshape(len(y))
predict_classes已弃,改为
yp = model.predict(x)
yp = np.round(yp).astype(int) # 分类预测
特别说明:astype()括号里面的len(y)要改成int,不然会报错
TypeError: Cannot interpret '34' as a data type
错误:ValueError: Classification metrics can't handle a mix of binary and continuous targets
而且报错不在这一行
yp = model.predict(x).reshape(len(y))
改为:
yp = model.predict(x)
yp = np.round(yp).astype(int) # 分类预测
错误:生成的图会显示中文方格,加上:
plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文黑体,不加这句会显示中文方格
最后,我是个小萌新,如果有错误欢迎指出