加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
regression_linear.py 1.54 KB
一键复制 编辑 原始数据 按行查看 历史
nnstrings 提交于 2023-03-08 17:08 . day1
import numpy as np
import matplotlib.pyplot as plt
class RegressionCurve:
def __init__(self, t0, t1):
self.theta_0 = t0
self.theta_1 = t1
def f(self, x):
return self.theta_0 + x * self.theta_1
def E(self, x, y):
return 0.5 * np.sum((y - self.f(x)) ** 2)
def standardize(self, x):
mu = x.mean()
sigma = x.std()
return (x - mu) / sigma
def Regression(self, x, y):
ETA, diff, count = 1e-3, 1, 0
error = self.E(x, y)
while diff > 1e-2:
self.theta_0 = self.theta_0 - ETA * np.sum(self.f(x) - y)
self.theta_1 = self.theta_1 - ETA * np.sum((self.f(x) - y) * x)
current_error = self.E(x, y)
diff = error - current_error
error = current_error
count += 1
log = 'times:{} theta_0:{:.3f} theta_1:{:.3f} diff:{:.4f}'.format(
count, self.theta_0, self.theta_1, diff)
print(log)
def draw(self, train_x, train_y):
x = np.linspace(3, -3, 100)
plt.plot(train_x, train_y, 'o')
plt.plot(x, self.f(x))
plt.show()
if __name__=="__main__":
train = np.loadtxt("click.csv", delimiter=",", skiprows=1)
train_x, train_y = train[:, 0], train[:, 1]
theta_0 = np.random.rand()
theta_1 = np.random.rand()
regression = RegressionCurve(theta_0, theta_1)
train_z = regression.standardize(train_x)
plt.plot(train_z, train_y, 'o')
plt.show()
regression.Regression(train_z, train_y)
regression.draw(train_z, train_y)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化