回归(多项式回归)

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

训练数据: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()
相关推荐
world-wide-wait1 分钟前
机器学习03——matplotlib
python·机器学习·matplotlib
许泽宇的技术分享2 分钟前
当 AI Agent 遇上 MCP:微软 Agent Framework 的“瑞士军刀“式扩展之道
人工智能·microsoft
沉迷单车的追风少年4 分钟前
Diffusion Model与视频超分(2):解读字节开源视频增强模型SeedVR2
人工智能·深度学习·aigc·音视频·强化学习·视频生成·视频超分
Victory_orsh23 分钟前
“自然搞懂”深度学习系列(基于Pytorch架构)——03渐入佳境
人工智能·pytorch·深度学习
Fuly102433 分钟前
AI 大模型应用中的图像,视频,音频的处理
人工智能·音视频
掘金安东尼44 分钟前
Cursor 2.0 转向多智能体 AI 编程,并发布 Composer 模型
人工智能
Small___ming44 分钟前
【人工智能数学基础】如何理解方差与协方差?
人工智能·概率论
好家伙VCC1 小时前
**发散创新:AI绘画编程探索与实践**随着人工智能技术的飞速发展,AI绘
java·人工智能·python·ai作画
兔兔爱学习兔兔爱学习1 小时前
2025年语音识别(ASR)与语音合成(TTS)技术趋势分析对比
人工智能·语音识别
中杯可乐多加冰1 小时前
服务编排搭建案例详解|基于smardaten实现协同办公平台复杂交互
人工智能·低代码