MATLAB实现波士顿房价预测,使用BP神经网络

时间:2024-03-14 15:47:49

代码如下(包括下载数据和训练网络):

%%Download Housing Prices
filename = 'housing.txt';
%下载
urlwrite('http://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data',filename);
%指定名字
inputNames = {'CRIM','ZN','INDUS','CHAS','NOX','RM','AGE','DIS','RAD','TAX','PTRATIO','B','LSTAT'};
outputNames = {'MEDV'};
housingAttributes = [inputNames,outputNames];

%%Import Data 
%格式规范
formatSpec = '%8f%7f%8f%3f%8f%8f%7f%8f%4f%7f%7f%7f%7f%f%[^\n\r]'; 
fileID = fopen(filename,'r'); 
%读取大文件,比起testread方便
dataArray = textscan(fileID, formatSpec, 'Delimiter', '', 'WhiteSpace', '', 'ReturnOnError', false); 
fclose(fileID); 
%写进表格
housing = table(dataArray{1:end-1}, 'VariableNames', {'VarName1','VarName2','VarName3','VarName4','VarName5','VarName6','VarName7','VarName8','VarName9',... 
'VarName10','VarName11','VarName12','VarName13','VarName14'}); 
%Delete the file and clear temporary variables 
clearvars filename formatSpec fileID dataArray ans; 
%%delete housing.txt  
%%Read into a Table 
%重新定义变量名字
housing.Properties.VariableNames = housingAttributes; 
%X特征向量 Y房价
X = housing{:,inputNames}; 
Y = housing{:,outputNames};
%数据处理好了,开始训练
features=X;prices=Y;len = length(prices);
index = randperm(len);%生成1~len 的随机数

%%产生训练集和数据集
%训练集——前70%
p_train = features(index(1:round(len*0.7)),:);%训练样本输入
t_train = prices(index(1:round(len*0.7)),:);%训练样本输出
%测试集——后30%
p_test = features(index(round(len*0.7)+1:end),:);%测试样本输入
t_test = prices(index(round(len*0.7)+1:end),:);%测试样本输出

%%数据归一化
%输入样本归一化
[pn_train,ps1] = mapminmax(p_train');
pn_test = mapminmax('apply',p_test',ps1);
%输出样本归一化
[tn_train,ps2] = mapminmax(t_train');
%tn_test = mapminmax('apply',t_test',ps2);

%%神经网络
%创建和训练
net = feedforwardnet(5,'trainlm');%创建网络
net.trainParam.epochs = 5000;%设置训练次数
net.trainParam.goal=0.0000001;%设置收敛误差
[net,tr]=train(net,pn_train,tn_train);%训练网络
%网络仿真,测试数据
b=sim(net,pn_test);%放入到网络输出数据

%%结果反归一化,预测的价格
predict_prices = mapminmax('reverse',b,ps2);

%%结果分析
t_test = t_test';
err_prices = t_test-predict_prices;%误差
[mean(err_prices) std(err_prices)]%求平均,标准差
figure(1);
plot(t_test);
hold on;
plot(predict_prices,'r');
xlim([1 length(t_test)]);
hold off;
legend({'Actual','Predicted'})
xlabel('Training Data point');
ylabel('Median house price');

结果:

MATLAB实现波士顿房价预测,使用BP神经网络