回归(多项式回归)

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

训练数据: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()
相关推荐
xcLeigh几秒前
AI 编程的未来趋势:2025-2026 年你必须关注的六大技术方向
人工智能·ai·ai编程
xcLeigh几秒前
88%在用,不到10%完成规模化部署——AI Agent落地差在哪里
人工智能
一见已难忘几秒前
产业AI落地技术解析:边缘部署、工业视觉检测与多传感器融合预警的工程实践(燎原:我看见的智能中国)
人工智能·计算机视觉·视觉检测
小燕子~~2 分钟前
Photoshop2026新版 AI 功能实测,看这一篇就够了
图像处理·人工智能·ai·aigc·photoshop
星河耀银海3 分钟前
数据解析:AI返回JSON数据在HTML5中的渲染方法
人工智能·json·html5
秦先生在广东6 分钟前
构筑 AI Agent 的实时安全防线:Harness 与 AWS AgentCore Gateway 的深度集成解析
人工智能
秦先生在广东12 分钟前
可审计决策原语:重塑 Agent 循环中的治理与信任
人工智能
米小虾18 分钟前
一周 AI 观察(9.23–9.30):越狱的 Agent、腰斩的价格,与一场关于 GPU 的金融赌局
人工智能
秦先生在广东24 分钟前
AI 时代的交付新瓶颈:从代码生成速度到生产环境持续信任
人工智能
米小虾28 分钟前
把调度器扔了:微软 Agensh 让 1024 个编码 Agent 自组织,但收益正在变平
人工智能