import numpy as np from sklearn import datasets from sklearn.linear_model import LinearRegression np.random.seed(10) class Newton(object): def init(self,epochs=50): self.W = None self.epochs = epochs def get_loss(self, X, y, W,b): """ 计算损失 0.5sum(y_pred-y)^2 input: X(2 dim np.array):特征 y(1 dim np.array):标签 W(2 dim np.array):线性回归模型权重矩阵 output:损失函数值 """ #print(np.dot(X,W)) loss = 0.5np.sum((y - np.dot(X,W)-b)2) return loss def first_derivative(self,X,y): """ 计算一阶导数g = (y_pred - y)*x input: X(2 dim np.array):特征 y(1 dim np.array):标签 W(2 dim np.array):线性回归模型权重矩阵 output:损失函数值 """ y_pred = np.dot(X,self.W) + self.b g = np.dot(X.T, np.array(y_pred - y)) g_b = np.mean(y_pred-y) return g,g_b def second_derivative(self,X,y): """ 计算二阶导数 Hij = sum(X.T[i]X.T[j]) input: X(2 dim np.array):特征 y(1 dim np.array):标签 output:损失函数值 """ H = np.zeros(shape=(X.shape[1],X.shape[1])) H = np.dot(X.T, X) H_b = 1 return H, H_b def fit(self, X, y): """ 线性回归 y = WX + b拟合,牛顿法求解 input: X(2 dim np.array):特征 y(1 dim np.array):标签 output:拟合的线性回归 """ self.W = np.random.normal(size=(X.shape[1])) self.b = 0 for epoch in range(self.epochs): g,g_b = self.first_derivative(X,y) # 一阶导数 H,H_b = self.second_derivative(X,y) # 二阶导数 self.W = self.W - np.dot(np.linalg.pinv(H),g) self.b = self.b - 1/H_bg_b print("itration:{} ".format(epoch), "loss:{:.4f}".format( self.get_loss(X, y , self.W,self.b))) def predict(): """ 需要自己实现的代码 """ pass def normalize(x): return (x - np.min(x))/(np.max(x) - np.min(x)) if name == "main": np.random.seed(2) X = np.random.rand(100,5) y = np.sum(X3 + X**2,axis=1) print(X.shape, y.shape) # 归一化 X_norm = normalize(X) X_train = X_norm[:int(len(X_norm)*0.8)] X_test = X_norm[int(len(X_norm)*0.8):] y_train = y[:int(len(X_norm)0.8)] y_test = y[int(len(X_norm)0.8):] # 牛顿法求解回归问题 newton=Newton() newton.fit(X_train, y_train) y_pred = newton.predict(X_test,y_test) print(0.5np.sum((y_test - y_pred)**2)) reg = LinearRegression().fit(X_train, y_train) y_pred = reg.predict(X_test) print(0.5np.sum((y_test - y_pred)**2)) ——修改代码中的问题,并补全缺失的代码,实现牛顿最优化算法
时间: 2024-03-26 20:40:17 浏览: 91
好的,我根据代码中的问题进行了修改和补全缺失的部分,如下所示:
```
import numpy as np
from sklearn import datasets
from sklearn.linear_model import LinearRegression
np.random.seed(10)
class Newton(object):
def __init__(self, epochs=50):
self.W = None
self.b = None
self.epochs = epochs
def get_loss(self, X, y, W, b):
"""
计算损失 0.5sum(y_pred-y)^2
input:
X(2 dim np.array):特征
y(1 dim np.array):标签
W(2 dim np.array):线性回归模型权重矩阵
b(1 dim np.array):线性回归模型偏置
output:损失函数值
"""
y_pred = np.dot(X, W) + b
loss = 0.5 * np.sum((y_pred - y) ** 2)
return loss
def first_derivative(self, X, y):
"""
计算一阶导数g = (y_pred - y)*x
input:
X(2 dim np.array):特征
y(1 dim np.array):标签
output:损失函数值
"""
y_pred = np.dot(X, self.W) + self.b
g = np.dot(X.T, np.array(y_pred - y))
g_b = np.mean(y_pred - y)
return g, g_b
def second_derivative(self, X, y):
"""
计算二阶导数 H_ij = sum(X.T[i]X.T[j])
input:
X(2 dim np.array):特征
y(1 dim np.array):标签
output:损失函数值
"""
H = np.dot(X.T, X)
H_b = 1
return H, H_b
def fit(self, X, y):
"""
线性回归 y = WX + b拟合,牛顿法求解
input:
X(2 dim np.array):特征
y(1 dim np.array):标签
output:拟合的线性回归
"""
self.W = np.random.normal(size=(X.shape[1]))
self.b = 0
for epoch in range(self.epochs):
g, g_b = self.first_derivative(X, y)
H, H_b = self.second_derivative(X, y)
H_inv = np.linalg.inv(H)
self.W = self.W - np.dot(H_inv, g)
self.b = self.b - H_inv @ np.array([g_b])
print("itration:{} ".format(epoch), "loss:{:.4f}".format(self.get_loss(X, y, self.W, self.b)))
def predict(self, X):
"""
线性回归预测
input:
X(2 dim np.array):特征
output:预测结果
"""
y_pred = np.dot(X, self.W) + self.b
return y_pred
def normalize(x):
return (x - np.min(x)) / (np.max(x) - np.min(x))
if __name__ == "__main__":
np.random.seed(2)
X = np.random.rand(100, 5)
y = np.sum(X ** 3 + X ** 2, axis=1)
print(X.shape, y.shape)
# 归一化
X_norm = normalize(X)
X_train = X_norm[:int(len(X_norm) * 0.8)]
X_test = X_norm[int(len(X_norm) * 0.8):]
y_train = y[:int(len(X_norm) * 0.8)]
y_test = y[int(len(X_norm) * 0.8):]
# 牛顿法求解回归问题
newton = Newton()
newton.fit(X_train, y_train)
y_pred = newton.predict(X_test)
print("Newton Method MSE: ", 0.5 * np.sum((y_test - y_pred) ** 2))
# 对比sklearn中的线性回归
reg = LinearRegression().fit(X_train, y_train)
y_pred = reg.predict(X_test)
print("Linear Regression MSE: ", 0.5 * np.sum((y_test - y_pred) ** 2))
```
在这个修改后的代码中,我主要做了以下几个修改和补充:
1. 在 `__init__` 函数中,添加了 `self.b = None`,用于存储线性回归模型的偏置;
2. 在 `get_loss` 函数中,修正了计算损失的公式,将 `b` 加入到了计算中;
3. 在 `fit` 函数中,对牛顿法的求解进行了修改,使用了矩阵求逆的方式来计算 Hessian 矩阵的逆;
4. 在 `predict` 函数中,添加了 `X` 作为输入参数,用于进行预测;
5. 在主函数中,修改了求解 MSE 的计算公式,以及添加了输出方法,用于输出牛顿法求解和 sklearn 中线性回归的 MSE 值。
希望这些修改能够帮助你。
阅读全文