# 使用neurolab预测波士顿房价

import neurolab as nl
from sklearn import preprocessing
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
x=boston.data
y=boston.target
train_x, test_x, train_y, test_y = train_test_split(x, y,train_size=0.5, random_state=33)#训练集和测试集的分隔
#数据标准化
ss_x = preprocessing.StandardScaler()
train_x = ss_x.fit_transform(train_x)
test_x = ss_x.transform(test_x)
train_y = ss_x.fit_transform(train_y.reshape(-1, 1))
test_y=ss_x.transform(test_y.reshape(-1, 1))
#因为输入格式要求，需要求每一列特征的最大最小值
x_minmax=pd.DataFrame(train_x)
max_x=x_minmax.max()
min_x=x_minmax.min()
maxmin=[[max_x[i],min_x[i]] for i in range(13)]
#newff的格式([每一列特征的最大值最小值],[隐藏层节点数，输出层节点数])
net=nl.net.newff(maxmin,[10,1])
err=net.train(train_x,train_y,epochs=500, show=1, goal=0.02)#误差为sse
err=np.array(err)/250#误差转为mse
out=net.sim(test_x)#对测试数据进行预测
fig = plt.figure(figsize=(10, 3))#画布的尺寸
axes = fig.add_subplot(1, 1, 1)#添加子图
line1,=axes.plot(range(len(err)), err, 'b',linewidth=2)#迭代误差的曲线图
#添加图表网格线，设置网格线颜色，线形，宽度和透明度
axes.grid()
fig.tight_layout()# 紧凑显示图片，居中显示
plt.xlabel('epoch')
plt.ylabel('err')
plt.title('cost')
plt.show()