赞
踩
参考博文:深度学习——入门经典案例《波士顿房价预测》深度解析_什么是梯度下降-CSDN博客
tensorflow BP神经网络 波士顿房价预测_bp神经网络波士顿房价预测-CSDN博客
网络训练部分:
- import numpy as np
- import matplotlib.pyplot as plt
-
- ##使用了随机梯度下降法提高效率
- def load_data():
- # 读取以空格分开的文件,变成一个连续的数组
- firstdata = np.fromfile('F:/boston-house-price-forecast-master/boston-house-price-forecast-master/housing.data', sep=' ')
- # 添加属性
- feature_names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT',
- 'MEDV']
- # 列的长度
- feature_num = len(feature_names)
- # print(firstdata.shape) 输出结果:(7084, )
- # print(firstdata.shape[0] // feature_nums) 输出结果:506
- # 构造506*14的二维数组
- data = firstdata.reshape([firstdata.shape[0] // feature_num, feature_num])
-
- # 训练集设置为总数据的80%
- ratio = 0.8
- offset = int(data.shape[0] * ratio)
- training_data = data[:offset]
- # print(training_data.shape)
-
- # axis=0表示列
- # axis=1表示行
- maximums, minimums, avgs = training_data.max(axis=0), training_data.min(axis=0), training_data.sum(axis=0) / \
- training_data.shape[0]
- # 查看训练集每列的最大值、最小值、平均值
- # print(maximums, minimums, avgs)
-
- # 对所有数据进行归一化处理
- for i in range(feature_num):
- # print(maximums[i], minimums[i], avgs[i])
- # 归一化,减去平均值是为了移除共同部分,凸显个体差异
- data[:, i] = (data[:, i] - avgs[i]) / (maximums[i] - minimums[i])
-
- # 覆盖上面的训练集
- training_data = data[:offset]
- # 剩下的20%为测试集
- test_data = data[offset:]
- return training_data, test_data
-
-
- class Network(object):
- def __init__(self, num_of_weights):
- np.random.seed(0)
- self.w = np.random.randn(num_of_weights, 1)
- # self.w[5] = -100.
- # self.w[9] = -100.
- self.b = 0.
-
- def forward(self, x):
- z = np.dot(x, self.w) + self.b
- return z
-
- #添加损失函数
- def loss(self, z, y):
- # 根据下面y的取值可以确定y的结构
- error = z - y
- # num_samples为总行数404
- num_samples = error.shape[0]
- # cost为均方误差,用来评价模型的好坏
- cost = error * error
- # 计算损失时需要把每个样本的损失都考虑到
- # 对单个样本的损失函数进行求和,并除以样本总数
- cost = np.sum(cost) / num_samples
- return cost
-
- #训练过程,计算梯度的另一种方法,可以不修改
- def gradient(self, x, y):
- z = self.forward(x)
- # 取数据的行数
- N = x.shape[0]
- # 计算w的梯度,总数相加再除以N
- gradient_w = 1. / N * np.sum((z - y) * x, axis=0)
- # 增加维度
- gradient_w = gradient_w[:, np.newaxis]
- # 计算b的梯度,同上
- gradient_b = 1. / N * np.sum(z - y)
- return gradient_w, gradient_b
-
- #确定损失函数更小的点封装在train和update函数中,并在Network中添加
- def update(self, gradient_w, gradient_b, eta=0.01):
- self.w = self.w - eta * gradient_w
- self.b = self.b - eta * gradient_b
-
- #训练数据导入后,越接近模型训练结束,最后几个批次数据对模型参数的影响越大。为了避免模型记忆影响训练效果,需要进行样本乱序操作。
- # num_epoches为训练的轮数,eta为步长
- def train(self, training_data, num_epoches, batch_size=10, eta=0.01):
- n = len(training_data)
- losses = []
- for epoch_id in range(num_epoches):
- # 打乱样本顺序
- np.random.shuffle(training_data)
- # 将train_data分成多个mini_batch
- # 循环取值,每次取出batch_size条数据
- mini_batches = [training_data[k:k + batch_size] for k in range(0, n, batch_size)]
- for iter_id, mini_batche in enumerate(mini_batches):
- # 取mini_batch的前13列
- x = mini_batche[:, :-1]
- # 取mini_batch的最后1列
- y = mini_batche[:, -1:]
- # 前向计算
- a = self.forward(x)
- # 计算损失
- loss = self.loss(a, y)
- # 计算梯度
- gradient_w, gradient_b = self.gradient(x, y)
- # 更新参数
- self.update(gradient_w, gradient_b, eta)
- losses.append(loss)
- print('Epoch {:3d} / iter {:3d}, loss = {:.4f}'.format(epoch_id, iter_id, loss))
- return losses
- def saveModel(self, fileName):
- np.savez(fileName, self.w, self.b)
-
-
- #开始训练以及作图
- # 获取数据
- training_data, test_data = load_data()
- # 创建网络
- net = Network(13)
- # 启动训练,训练10000轮,每轮样本数目为100,步长为0.1
- losses = net.train(training_data, num_epoches=10000, batch_size=100, eta=0.1)
-
- # 画出损失函数的变化趋势
- plot_x = np.arange(len(losses))
- plot_y = np.array(losses)
- plt.plot(plot_x, plot_y)
- plt.show()
-
-
- net.saveModel("model2")
- # 打印输出查看模型
- print(np.load('model2.npz')["arr_0"], np.load('model2.npz')["arr_1"])
预测部分:这部分是自己写的,有点小白了
- import numpy as np
-
- # 加载训练文件
- datafile1 = 'F:/boston-house-price-forecast-master/boston-house-price-forecast-master/housing.data' # 原始文件,506行14列
- data4 = np.fromfile(datafile1, sep=' ') # 7084 = 14 * 506,一行数据显示
- # 每条包含14列
- feature_names1 = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS','RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT',
- 'MEDV']
- feature_num1 = len(feature_names1) # 14列
- # print(data.shape[0] // feature_num) # 7084//14 向下取整保留整数
- data4 = data4.reshape([data4.shape[0] // feature_num1, feature_num1]) # 506行,14列
- Y=data4[:,-1]
- # 最大值,最小值,平均值
- maximums =data4.max(axis=0)
- minimums = data4.min(axis=0)
- avgs = data4.sum(axis=0) / data4.shape[0]
-
- datafile = 'F:/boston-house-price-forecast-master/boston-house-price-forecast-master/yuce.data'
- feature_names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT']
- data = np.fromfile(datafile, sep=' ')
- feature_num = len(feature_names)
- d = data.reshape([data.shape[0] // feature_num, feature_num])
-
-
- # 按照训练集归一化的规律对所有的预测数据进行归一化处理
- for i in range(feature_num): # 从0到13列
- d[:, i] = (d[:, i] - avgs[i]) / (maximums[i] - minimums[i]) # 逐列的归一化
-
-
- d[np.isnan(d)]=0
-
- #数组转矩阵,不然之后的矩阵乘法会出错
- data=np.matrix(d)
- Y=np.matrix(Y)
- Y=np.transpose(Y)
-
-
- #数组
- d1=np.load('model2.npz')["arr_0"]
- #数组转矩阵
- data1=np.matrix(d1)
- data2=np.load('model2.npz')["arr_1"]
- data3=data*data1+data2
-
- #去标准化
- firstdata2 = np.fromfile('F:/boston-house-price-forecast-master/boston-house-price-forecast-master/housing.data', sep=' ')
- feature_names2 = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT',
- 'MEDV']
-
-
- feature_num2 = len(feature_names2)
- # print(firstdata.shape) 输出结果:(7084, )
- # print(firstdata.shape[0] // feature_nums) 输出结果:506
- # 构造506*14的二维数组
- data4 = firstdata2.reshape([firstdata2.shape[0] // feature_num2, feature_num2])
- p=data4[:,-1]
- max = np.max(p)
- min = np.min(p)
- avg =np.mean(p)
- #输出预测结果
- w=data3*(max-min)+avg
-
-
- np.savetxt('test.txt',w,fmt='%s')
-
-
- import matplotlib.pyplot as plt
- plt.title(f"BP network")
- plt.plot(np.arange(200), Y[:200], "go-", label="True value")
- plt.plot(np.arange(200), w[:200], "ro-", label="Predict value")
- plt.legend(loc="best")
- plt.show()
- plt.figure(figsize=(10, 6))
- plt.title("importance of feature in dateset", fontsize=18)
- plt.ylabel("import level", fontsize=15, rotation=90)
运行结果:
训练loss图:
预测结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。