震精!18行代码实现通用线性回归算法问题

mac2024-09-28  67

线性回归通用算法

话不多说,直接上代码

import numpy as np # 定义假设函数:X是一个行向量 W是一个列向量 def hyFunction(X, W): return X.dot(W) # 梯度函数 def gradientFunction(X, W, y): return (X.dot(W) - y).dot(X) # 行向量 #梯度下降算法 def gradientDescent(X, w, y, hyFunc, gFunc, lamb = 0.001 , tolance = 1.0e-8, times = 2000000): W = w result = hyFunc(X,W) t=0 while t<times: g = gFunc(X,W, y) next_w = W - g*lamb next_result = hyFunc(X,next_w) if np.sum(abs(next_result - result))/X.shape[0]<tolance: print("迭代了",t,"次完成") return next_w else: W,result = next_w,next_result t += 1 #以下为测试部分 # 构造数据:验证高阶有效性 # 下列x和y是使用函数:y=0.5*x*x*x+1.2*x*x-2.3*x+10 大致计算出来的 x = np.array([-3, -2.3, -1.6, -1, -0.3, 0.3, 1, 1.6, 2.3, 3]) y = np.array([14.2, 15.5, 14.8, 13., 10.8, 9.4, 9.4, 11.8, 17.5, 27.4]) def make_x_ext(X): x_ext = np.c_[X[:,np.newaxis], np.ones(len(X))] # 追加全1列 x_ext = np.insert(x_ext, 0, np.power(X, 2), axis=1) # 插入x*x数据列 x_ext = np.insert(x_ext, 0, np.power(X, 3), axis=1) # 插入x*x*x数据列 return x_ext w_init = np.array([2.5, 3.0, 1.2, 0.7]) # 猜测这就是最优的系数 x_ext = make_x_ext(x) w = gradientDescent(x_ext, w_init, y, hyFunction, gradientFunction) print(w) # 构造数据:验证多元线性有效性 ''' X = np.array([[3, 0],[4, 1], [5,2], [7,3]]) y = np.array([9, 12,15, 20]) row = X.shape[0] one = np.ones(row) print(one) one = one[:,np.newaxis] print(one) X = np.hstack((X, one)) print(X) w = gradientDescent(X, np.array([100, 200, 20]), y, hyFunction, gradientFunction) print(w) '''
最新回复(0)