《Pyhton数据分析与挖掘实战》第5章--使用BP神经网络预测销量代码纠错

1.先放代码吧,需要看错误分析的往下滑

# -*- coding: utf-8 -*-
# 使用神经网络算法预测销量高低
import numpy as np
import pandas as pd

# 参数初始化
inputfile = './sales_data.xls'
data = pd.read_excel(inputfile, index_col=u'序号')  # 导入数据
# 数据是类别标签,要将它转换为数据
# 用1来表示“好”、“是”、“高”这三个属性,用0来表示“坏”、“否”、“低”
data[data == u'好'] = 1
data[data == u'是'] = 1
data[data == u'高'] = 1
data[data != 1] = 0
x = data.iloc[:, :3].values.astype(int)
y = data.iloc[:, 3].values.astype(int)


from keras.models import Sequential
from 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=100, batch_size=10)  # 训练模型,学习一千次
# yp = model.predict_classes(x).reshape(len(y))  # 分类预测
yp = model.predict(x)
yp = np.round(yp).astype(int)


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)  # 画混淆矩阵图,配色风格使用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


cm_plot(y, yp).show()  # 显示混淆矩阵可视化结果

2.错误分析与总结

版本问题:

报错:AttributeError: 'Sequential' object has no attribute 'predict_classes'

yp = model.predict_classes(x).reshape(len(y))

tensorflow版本太高,predict_classes(x)方法已弃用,2.5版本以下才有这个。

替换方案在上面的代码里。

报错:TypeError: __init__() missing 1 required positional argument: 'units'

原:model.add(Dense(input_dim=3, output_dim=10))

改:model.add(Dense(input_dim=3, units=10))

output_dim -->  units

混淆矩阵是自行编写,这里也是抄别人的。

3.参考:

【1】《Python数据分析与挖掘实战》第五章案例代码总结与修改分析 - BabyGo000 - 博客园 (cnblogs.com)

【2】(12条消息) 记录李宏毅机器学习的FiZZ BUZZ程序代码问题——TypeError: __init__() missing 1 required positional argument: ‘units‘_weixin_42943494的博客-CSDN博客

Guess you like

Origin blog.csdn.net/m0_57362214/article/details/131195223