线性回归梯度下降代码MATLAB,单变量的线性回归(用梯度下降法实现,Python语言,MATLAB语言)...

单变量的线性回归(用梯度下降法实现,Python语言,MATLAB语言)

单变量的线性回归(用梯度下降法实现,Python语言,MATLAB语言)

单变量的线性回归实现:

7a2ed059bb81db2f8cbc47ae63fc1723.png

dc5fd2456814819aac2e9788fc7794fb.png

Python版:

import numpy as np

import matplotlib.pyplot as plt

a = np.loadtxt('ex1data1.txt')

m=a.shape[0]

print(m)

print(type(a))

x=a[:,0]

y=a[:,1]

plt.scatter(x,y,marker='*',color='r',s=20)

theta0=0

theta1=0

iterations = 1500

alpha = 0.01

def gradientdescent(x,y,theta0,theta1,iterations,alpha):

J_h=np.zeros( (iterations,1) )

for i in range(0,iterations):

y_hat=theta0+theta1*x

temp0=theta0-alpha*((1/m)*sum(y_hat-y))

temp1=theta1-alpha*(1/m)*sum((y_hat-y)*x)

theta0=temp0

theta1=temp1

y_hat2=theta0+theta1*x

aa=sum((y_hat2-y)**2)

J=aa*(1/(2*m))

J_h[i,:]=J

return theta0,theta1,J_h

(theta0,theta1,J_h) = gradientdescent(x,y,theta0,theta1,iterations,alpha)

print(theta1)

print(theta0)

plt.plot(x,theta0+theta1*x)

plt.title("fittingcurve")

plt.show()

x2=np.arange(iterations)

plt.plot(x2,J_h)

plt.title("costfunction")

plt.show()

ad6f95b6834e2c2912dc2860fe9df50e.png

Matlab版:

data = load('ex1data1.txt');

X = data(:, 1);

y = data(:, 2);

m = length(y); % number of training examples

hold on

plot(X,y, 'r*', 'MarkerSize', 10)

iterations = 1500;

alpha = 0.01;

theta0=0;

theta1=0;

computeCost1(X, y, theta0,theta1)

[theta0,theta1,J_history] = gradientDescent1(X, y, theta0,theta1, alpha, iterations);

y_hat=theta0+theta1*X;

plot(X,y_hat)

hold off

figure,plot(1:iterations,J_history)

function J = computeCost1(X, y, theta0,theta1)

m = length(y); % number of training examples

y_hat1=theta0+theta1*X;

J = sum((y_hat1 - y).^2) / (2*m);     % X(79,2)  theta(2,1)

end

function [theta0,theta1, J_history] = gradientDescent1(X, y, theta0,theta1, alpha, num_iters)

m = length(y); % number of training examples

J_history = zeros(num_iters, 1);

for iter = 1:num_iters

y_hat2=theta0+theta1*X;

temp0 = theta0 - alpha / m * sum(y_hat2 - y);

temp1 = theta1 - alpha / m * sum((y_hat2 - y) .* X(:,1));

theta0=temp0;

theta1=temp1;

J_history(iter) = computeCost1(X, y, theta0,theta1);

end

end

3381bb97f75dcd949f3dad082a2377e1.png

61f439126aa9018d132828db1d4724e3.png

测试数据集:https://download.csdn.net/download/qq_20406597/10370009

单变量的线性回归(用梯度下降法实现,Python语言,MATLAB语言)相关教程

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值