梯度下降法------python实现

今天也是第一次编写python,最近学习了感知机,上了机器学习基石关于这个地方的课程,收获很多

今天一天,太浪费时间了,为了配置sublime text3,和numpy库,弄了一下午,困难前行吧!

然后照着别人的程序,写了一下梯度下降法

o,对了,python的空格对齐问题真的是很烦;

import numpy as np
import matplotlib.pyplot as plt

#datasets
x=np.linspace(-1,6,num=141)
y=(x-2.5)**2-1

#求导数
def  dj(theta):
	return 2*(theta-2.5)

#损失函数
def J(theta):
	return(theta-2.5)**2-1

#梯度下降法
theta =0.0     #初值
step_a=0.09     #步长   当步长设置成0.1时,收敛速度慢一点

#收敛精度
epsilon =1e-8
theta_history=[theta]     #存储更新的x值


#开始迭代
while True:
	gradient=dj(theta)
	last_theta =theta
	theta-=step_a*gradient
	theta_history.append(theta)
	if(abs(J(theta)-J(last_theta))<epsilon):
		break


plt.plot(x, y)
plt.plot(np.array(theta_history), J(np.array(theta_history)), color='R', marker = 'o')
plt.xlabel("theta")
plt.ylabel("J")
plt.show()
print("theta = " , str(theta))
print("J(theta) = " ,str(J(theta)))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值