ML:使用线性回归实现多项式拟合

2018-09-05  本文已影响130人  ACphart

介绍

描述

import numpy as np
import matplotlib.pyplot as plt
from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.ast_node_interactivity = 'all'

模拟数据

np.random.seed(20180824)
m = 200

x = np.linspace(-3, 3, m).reshape(m,1)
y = x**2 + np.random.randn(m,1)

_ = plt.scatter(x, y)
_ = plt.plot(x, x**2, 'Black')

损失函数和梯度函数

def loss_func(X, y, theta):
    loss = np.dot(X, theta) - y
    ridge = np.dot(theta, theta)
    return 1./(2*m) * np.dot(loss.T, loss) + ridge

def grad_func(X, y, theta):
    loss = np.dot(X, theta) - y
    return 1./m * np.dot(X.T, loss) + 2*theta

生成多项式特征矩阵

def X_poly(x, n):
    tx = x
    X = np.ones((m, n+1))
    for i in range(1, n+1):
        X[:,i] = tx.reshape(m)
        tx = tx*x
    return X

训练算法

np.random.seed(20180824)

n = 2
alpha = 0.01
accuracy = 1e-6

i = 1
index = 1
c = np.array([0.8, 0.8, 0.8])

X = X_poly(x, n)
theta = np.random.randn(n+1, 1)
grad = grad_func(X, y, theta)

while not np.all(abs(grad) <= accuracy):
    theta = theta - alpha*grad
    grad = grad_func(X, y, theta)
    i = i+1
#     if i > 1e3:
#         break
    if i%index == 0:
        _ = plt.plot(x, np.dot(X, theta), color=c)
        index = index*2
        c = c - [0., 0.1, 0.1]

_ = plt.scatter(x, y, alpha=0.5, color='b')
_ = plt.ylim(-2, 10)
_ = plt.plot(x, x**2, 'Black', lw=2)
# print(" t0: {0[0]:.4f} \n t1: {0[1]:.4f} \n t2: {0[2]:.4f}".format(theta.ravel()))
上一篇 下一篇

猜你喜欢

热点阅读