帮我用matlab写一个波士顿房价预测的代码
时间: 2024-05-22 09:17:17 浏览: 123
好的,以下是一个简单的基于线性回归模型的波士顿房价预测的代码实现,你可以参考一下:
%% 加载数据
data = load('bostonhousing.txt');
X = data(:, 1:end-1);
y = data(:, end);
m = length(y);
%% 特征标准化
mu = mean(X);
sigma = std(X);
X = (X - mu) ./ sigma;
%% 添加偏置项
X = [ones(m, 1), X];
%% 初始化 theta
theta = zeros(size(X, 2), 1);
%% 定义代价函数
function J = costFunction(X, y, theta)
m = length(y);
J = sum((X * theta - y) .^ 2) / (2 * m);
end
%% 定义梯度下降函数
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y);
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
delta = (((X * theta - y)' * X) / m)' ;
theta = theta - alpha * delta;
J_history(iter) = costFunction(X, y, theta);
end
end
%% 运行梯度下降算法
alpha = 0.01;
num_iters = 1000;
[theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters);
%% 绘制学习曲线
figure;
plot(1:num_iters, J_history, '-b', 'LineWidth', 2);
xlabel('Number of iterations');
ylabel('Cost J');
%% 预测房价
X_test = [0.03113, 0.0, 5.19, 0, 0.4040, 6.2110, 52.8, 5.0185, 5, 224, 20.2, 396.9, 14.76];
X_test = ([1, X_test] - mu) ./ sigma;
price = X_test * theta;
fprintf('Predicted price of the house is $%0.2f\n', price);
请注意,这只是一个简单的实现,你可能需要在实际应用中进行更多的优化和调整。希望这能帮助到你!
阅读全文