matlab波士顿房价预测代码
时间: 2023-09-20 13:06:26 浏览: 93
以下是使用MATLAB进行波士顿房价预测的示例代码:
```
% 导入数据
data = load('boston_house_prices.csv');
X = data(:, 1:13);
y = data(:, 14);
% 数据标准化
[X, mu, sigma] = zscore(X);
% 添加常数项
X = [ones(length(X), 1) X];
% 划分训练集和测试集
m = length(y);
train_ratio = 0.7;
train_size = floor(train_ratio * m);
train_idx = randperm(m, train_size);
test_idx = setdiff(1:m, train_idx);
X_train = X(train_idx, :);
y_train = y(train_idx, :);
X_test = X(test_idx, :);
y_test = y(test_idx, :);
% 初始化参数
theta = zeros(size(X_train, 2), 1);
alpha = 0.01;
num_iters = 1000;
% 梯度下降
[theta, J_history] = gradientDescent(X_train, y_train, theta, alpha, num_iters);
% 预测
y_pred = X_test * theta;
% 计算均方误差
mse = mean((y_pred - y_test).^2);
% 打印结果
fprintf('均方误差: %f\n', mse);
% 绘制学习曲线
figure;
plot(1:num_iters, J_history, '-b', 'LineWidth', 2);
xlabel('迭代次数');
ylabel('代价函数值');
title('学习曲线');
% 梯度下降函数
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
h = X * theta;
theta = theta - alpha * (1 / m) * X' * (h - y);
J_history(iter) = computeCost(X, y, theta);
end
end
% 代价函数
function J = computeCost(X, y, theta)
m = length(y);
J = (1 / (2 * m)) * sum((X * theta - y).^2);
end
```
这段代码中,我们首先导入了波士顿房价数据集,并进行了数据标准化和训练集/测试集的划分。然后,我们使用梯度下降算法来拟合线性回归模型,并进行房价预测和均方误差的计算。最后,我们绘制了模型的学习曲线,以便进行模型性能的评估。