机器学习之多项式回归

多项式回归的实现

// 多项式回归
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(0)
x0 = np.random.random(50)
y = 2 * x0 ** 3 + 1.2 * x0 ** 2 + 1.5


def degreed(x0):
    degreed = 3
    onex = np.c_[np.ones(len(x0))]
    for i in range(1, degreed+1):
        onex = np.c_[onex, x0**i]
    return onex


onex = degreed(x0)
y = np.c_[y]
m, n = onex.shape

#前向传播
def model(theta):
    h = onex.dot(theta)
    return h

#损失函数
def computeCost(h):
    cost = 0.5*np.mean((h-y)**2)
    return cost

#梯度下降
def gradtheta(h):
    d_theta = (1/m)*np.dot(onex.T, h-y)
    return d_theta

#训练模型
def trainModel():
    alpha = 1
    iters = 10000
    Jcost = []
    theta = np.zeros((n, 1))
    for i in range(iters):
        h = model(theta)
        jcost = computeCost(h)
        d_theta = gradtheta(h)
        theta -= alpha*d_theta
        if i % 100 == 0:
            Jcost.append(jcost)
    return theta, Jcost


theta, Jcost = trainModel()
print(theta)

plt.plot(x0, y, 'rx')
x0 = np.sort(x0)
# y0 = theta[0] + theta[1] * x0 + theta[2] * x0 ** 2 + theta[3] * x0 ** 3
onex = degreed(x0)
y0 = model(theta)
plt.plot(x0, y0)
plt.show()

学习讨论群请加QQ群:521364338,扫码进群领取人工智能学习资料,转载标明出处,侵权必究!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XiaoChao_AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值