class Linear_model(object):
def __init__(self):
self.w = np.random.randn(1)[0]
self.b = np.random.randn(1)[0]
print('--------------------起始生成的斜率和截距:',self.w,self.b)
# 方程式
def model(self,x):
return self.w*x + self.b
# 损失函数
def loss(self,x,y):
cost = (y - self.model(x))**2
g_w = 2*(y-self.model(x))*(-x)
g_b = 2*(y-self.model(x))*(-1)
return g_w,g_b
# 梯度下降
def gradient_descend(self,g_w,g_b,step=0.01):
self.w = self.w - g_w*step
self.b = self.b - g_b*step
# 训练
def fit(self,x,y):
count = 1
precsion = 0.0001
w_last = self.w + 1
b_last = self.b + 1
size = x.shape[0]
while True:
if (np.abs(w_last - self.w) < precsion) and (np.abs(b_last - self.b) < precsion):
break
if count > 3000:
break
# w_last, b_last = self.w, self.b
g_w = 0
g_b = 0
for xi,yi in zip(x,y):
g_w += self.loss(xi,yi)[0]/size
g_b += self.loss(xi,yi)[1]/size
w_last = self.w
b_last = self.b
self.gradient_descend(g_w,g_b)
count += 1
# 方程系数
def coef_(self):
return self.w
# 方程截距
def intercept(self):
return self.b
sklearn.linear_model.LinearRegression的算法实现
最新推荐文章于 2024-04-12 14:15:19 发布