回归(多项式回归)

例子:回归(多项式回归)

训练数据:text.csv

复制代码
x,y
235,591
216,539
148,413
35,310
85,308
204,519
49,325
25,332
173,498
191,498
134,392
99,334
117,385
112,387
162,425
272,659
159,400
159,427
59,319
198,522
python 复制代码
import numpy as np
import matplotlib.pyplot as plt

#读入训练数据
train = np.loadtxt('text.csv',delimiter=',',skiprows=1)
train_x = train[:,0]
train_y = train[:,1]

#展示训练数据
#plt.plot(train_x,train_y,'o')
#plt.show()

#标准化数据
mu = train_x.mean()
sigma = train_x.std()
def standardize(x):
    return (x - mu)/sigma

train_z = standardize(train_x)
#plt.plot(train_z,train_y,'o')
#plt.show()

#均方误差
#在停止重复的条件里用上
def MSE(x,y):
    return (1/x.shape[0])*np.sum((y-f(x)) ** 2)

#生成三个随机数 代表三个参数 theta是参数列表
theta = np.random.rand(3)

#均方误差的历史记录
errors = []

#创建训练数据的矩阵
#因为训练数据很多 把它们都放在一个矩阵里
#直接和theta相乘
#theta0 + theta1*x1 + theta2*x2
def to_matrix(x):
    return np.vstack([np.ones(x.shape[0]),x,x**2]).T

X = to_matrix(train_z)

#预测函数
#theta0 + theta1*x1 + theta2*x2
#dot:矩阵乘法
def f(x):
    return np.dot(x,theta)

#目标函数 error误差 最小二乘法
def E(x,y):
    return 0.5*np.sum((y-f(x))**2)

#learning rate 学习率
ETA = 1e-3

#误差的差值
diff = 1;

#重复学习
errors.append(MSE(X,train_y))
error = E(X,train_y)
while diff>1e-2:
    #更新参数
    theta = theta - ETA*np.dot(f(X)-train_y,X)

    #计算差值
    errors.append(MSE(X,train_y))
    current_error = E(X,train_y)
    diff = errors[-2] - errors[-1]
    #不用均方误差的diff
    #diff = error - current_error
    error = current_error

'''
图表拟合展示
x = np.linspace(-3,3,100)
plt.plot(train_z,train_y,'o')
plt.plot(x,f(to_matrix(x)))
plt.show()
'''

#绘制误差变化图
x = np.arange(len(errors))
plt.plot(x,errors)
plt.show()
相关推荐
D-海漠6 分钟前
安全光幕Muting功能程序逻辑设计
服务器·网络·人工智能
顾默@18 分钟前
个人电脑部署私有化大语言模型LLM
人工智能·语言模型·自然语言处理
AI视觉网奇22 分钟前
语音识别数据集
人工智能·语音识别
卓码软件测评27 分钟前
软件项目中标需要哪些东西?软件工程投标需要准备什么材料?
人工智能·功能测试·软件构建·开源软件·软件需求
martian66527 分钟前
深度学习核心:卷积神经网络 - 原理、实现及在医学影像领域的应用
人工智能·深度学习·机器学习·cnn·卷积神经网络·dicom医学影像
悟乙己33 分钟前
译 | 结合聚类与注意力机制的强化学习在个性化促销中的应用
机器学习·数据挖掘·聚类
weixin_4640780738 分钟前
机器学习sklearn:聚类
机器学习·聚类·sklearn
万俟淋曦41 分钟前
人工智能图像生成的道德利弊
人工智能·aigc·图像识别
W.KN43 分钟前
机器学习【一】线性模型
人工智能·机器学习
_Meilinger_44 分钟前
论文研读|基于图像修复的AI生成图像检测(CVPR 2025)
人工智能·深度学习·计算机视觉·ai·aigc·图像取证·生成图像检测