线性回归-实践篇

 

 转至:云不知深处的博客: https://blog.csdn.net/pakko/article/details/37527799

总结了线性回归的理论部分,下面我们以浦东塘桥的二手房数据来实践线性回归。

数据及代码连接下载,工具使用Octave

1,数据获取

从网站爬到数据,并整理成我们需要的。爬取方式不便多讲,本人是用的jsoup。

2,数据过滤

爬到数据后,过滤了房间面积小于30平米,大于150平米的数据,总价格大于800w的也过滤了。(这些数据太小或者太大)

3,一元线性回归

x表示房子面积,y表示房价,使用正规方程组的方法计算。

拿到代码后执行one即可。

执行结果如下:

 

4,多元线性回归

 

x表示房子面积、房间数、楼层,y表示房价,使用正规方程组的方法计算。

 

拿到代码后执行multi即可。

执行结果如下:

 

 

% Load the data from our text file
data = load('house.txt');

% Define x and y
x = data(:,1:3);
y = data(:,4);

% Create a function to plot the data
function plotData(x,y)
plot(x,y,'rx','MarkerSize',8); % Plot the data
end
% Plot the data
plotData(x,y);
xlabel('Square Feet'); % Set the x-axis label
ylabel('Price'); % Set the y-axis label
fprintf('Program paused. Press enter to continue.\n');
pause;

% Count how many data points we have
m = length(x);
% Add a column of all ones (intercept term) to x
X = [ones(m, 1) x];

% Calculate theta
theta = (pinv(X'*X))*X'*y

% Plot the fitted equation we got from the regression
hold on; % this keeps our previous plot of the training data visible
plot(X(:,2), X*theta, '-')
legend('Training data', 'Linear regression')
hold off % Don't put any more plots on this figure

price = [1, 80, 2, 0.5] * theta;

fprintf(['Predicted price of a 80 sq-ft, 2 rooms, middle floor' ...
'(using normal equations):\n %f\n'], price);

 

posted @ 2018-05-09 10:31  jude_python  阅读(184)  评论(0编辑  收藏  举报