用matlab完成一个用线性回归算法预测数值型输出
时间: 2024-05-21 18:11:11 浏览: 11
以下是一个用线性回归算法预测数值型输出的matlab代码示例:
% 导入数据
data = csvread('data.csv');
X = data(:,1); % 输入变量
y = data(:,2); % 输出变量
% 将输入变量转换为矩阵形式
X = [ones(length(X),1), X];
% 初始化参数
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
theta = theta - alpha/m * X' * (X*theta - y);
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);
% 绘制代价函数随迭代次数变化的图像
plot(J_history);
xlabel('迭代次数');
ylabel('代价函数值');
% 预测新的输出值
x_new = [1, 5]; % 新输入变量
y_new = x_new * theta; % 预测输出值
disp(['预测输出值为:', num2str(y_new)]);
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)