多项式回归(适用线性回归,且特征数量小)

该博客介绍了如何利用线性回归进行非线性曲线的拟合,具体针对sigmoid函数。首先,通过随机生成数据并添加噪声,然后对特征进行多项式扩展和标准化。接着,利用梯度下降法训练模型,并绘制损失函数变化图。最终,计算测试集精度并展示预测结果。
摘要由CSDN通过智能技术生成
import numpy as np,matplotlib.pyplot as plt
# 三、使用线性回归底层完成如下操作,实现多项式拟合非线性曲线sigmoid函数
def data_process():
    # 1、随机生成x向量,100个元素范围在-6到+6之间
    x=np.random.uniform(-6,6,100)
    # 2、创建y向量,对应关系满足sigmoid函数
    y=1/(np.exp(-x)+1)
    # 3、将y向量每个元素添加随机噪声,噪声服从标准正态分布np.random.randn(100) * 0.1
    noise=np.random.randn(100) * 0.1
    # 8、以y向量为标签,以x向量为特征,对特征向量添加特征个数,使得多项式最高次数为3
    y=y+noise
    x_2=x**2
    x_3=x**3
    x=np.c_[x,x_2,x_3]
    # 9、特征缩放:
    # 1.标准化
    x = (x - np.mean(x, axis=0)) / np.std(x, axis=0,ddof=1)
    #2.初始化
    # x_max=np.max(x,axis=0)
    # x_min=np.min(x,axis=0)
    # x=(x-x_min)/(x_max-x_min)
    # 10、特征拼接加截距
    x=np.c_[np.ones((x.shape[0],1)),x]
    y=np.c_[y]

    # 11、洗牌,切分测试集:训练集=3:7
    np.random.seed(10)
    order=np.random.permutation(x.shape[0])
    x=x[order]
    y=y[order]
    return x, y
# 4、创建线性模型函数
def lh(x,theta):
    h=x.dot(theta)
    return h

# 5.通过梯度下降训练模型,
def grad_decent(x,h,y):
    e=h-y
    m=len(h)
    dt=1/m*x.T.dot(e)
    return dt
def acc_func(h,y):
    u=np.sum((h-y)**2)
    y_mean=np.mean(y)
    v=np.sum((y-y_mean)**2)
    acc=1-u/v
    return acc
# 4.要求输出迭代过程中的代价函数值
def loss_func(h,y):
    e=h-y
    m=len(h)
    J=1/(2*m)*np.sum(e**2)
    return J
# 12、训练模型,调整超参数,并画出代价函数图
def train_mode(x,y,alpha=0.1,iters=100):
    theta=np.zeros((x.shape[1],1))
    loss_list=[]
    for i in range(iters):
        h=lh(x,theta)
        loss=loss_func(h,y)
        loss_list.append(loss)
        dt=grad_decent(x,h,y)
        theta=theta-alpha*dt
    return loss_list,theta
x,y=data_process()
loss_list,theta=train_mode(x,y)
# 13、输出测试集精度
h=lh(x,theta)
acc=acc_func(h,y)
print('测试集精度:',acc)
# 14、画出样本点散点图
plt.scatter(x[:,1],y,c='m')
plt.scatter(x[:,1],h,c='r')
plt.show()
# 15、画出预测结果,用红色星型*标注
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值