使用numpy写一个线性回归算法, 方程(模型)为 y = a x + b y=ax+b y=ax+b。要求自己设计训练部分并且收敛到满意效果。
以下是数据产生代码:
import matplotlib.pyplot as plt
import numpy as npclass DataGenerator:"""线性回归数据产生器, 方程:y = ax + b"""def __init__(self, a, b):self.a = aself.b = bdef __call__(self, data_len):xx = np.random.uniform(-50, 50, data_len) # 生成 x 点集yy = self.a * xx + self.b # 生成 y 点集# 加随机误差noise = np.random.normal(0, 20, data_len)yy += noisereturn xx, yya, b = 3.5, 7.1
xx, yy = DataGenerator(a, b)(1000)# 可视化
fig = plt.figure()
ax = fig.add_subplot()
ax.scatter(xx, yy)
plt.show()
现在把方程变换成: y = a x 2 + b y = ax^2+b y=ax2+b
class DataGeneratorSD:"""线性回归数据产生器, 方程:y = a*x*x + b"""def __init__(self, a, b):self.a = aself.b = bdef __call__(self, data_len):xx = np.random.uniform(-50, 50, data_len) # 生成 x 点集yy = self.a * (xx**2) + self.b # 生成 y 点集# 加随机误差noise = np.random.normal(0, 20, data_len) * 50yy += noisereturn xx, yy