梯度下降法实现最简单线性回归问题python实现

本文通过使用梯度下降法优化线性回归问题,为深度学习提供基础。展示了如何利用Python和numpy实现批处理梯度下降,通过迭代更新参数以最小化成本函数。

梯度下降法是非常常见的优化方法,在神经网络的深度学习中更是必会方法,但是直接从深度学习去实现,会比较复杂。本文试图使用梯度下降来优化最简单的LSR线性回归问题,作为进一步学习的基础。

import numpy as np
import pandas as pd
from numpy import *
from pandas import *
import matplotlib.pyplot as plt


x = np.array([[1,2],[2,1],[3,2.5],[4,3],
              [5,4],[6,5],[7,2.7],[8,4.5],
              [9,2]])

m, n = np.shape(x)
x_data = np.ones((m,n))
x_data[:,:-1] = x[:,:-1]
y_data = x[:,-1]

print(x_data.shape)
print(y_data.shape)
m, n = np.shape(x_data)
theta = np.ones(n)


def batchGradientDescent(maxiter,x,y,theta,alpha):
    xTrains = x.transpose()
    for i in range(0,maxiter):
        hypothesis = np.dot(x,theta)
        loss = (hypothesis-y)
        gradient = np.dot(xTrains,loss)/m
        theta = theta - alpha * gradient
        cost = 1.0/2*m*np.sum(np.square(np.dot(x,np.transpose(theta))-y))
        print("cost: %f"%cost)
    return theta

result = batchGradientDescent(10,x_data,y_data,theta,0.01)
print(result)
newy = np.dot(x_data,result)
fig, ax = plt.subplots()
ax.plot(x[:,0],newy, 'k--')
ax.plot(x[:,0],x[:,1], 'ro')
plt.show()
print("final: " + result)

 

转载于:https://www.cnblogs.com/kidsitcn/p/9889106.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值