import torch
from matplotlib import pyplot as plt
def loss_fn(t_p,t_c):#注意定义变量是函数名字和变量名字不要混淆
l=(t_p-t_c)**2
return l.mean()#对所有损失求和key 变量.mean()为对变量求和
def model(t_u,w,b):
return w*t_u+b
def d_t(t_p,t_c):
d_t=2*(t_p-t_c)
return d_t
def d_w(t_u):
return t_u
def d_b(t_u, w, b):
return 1.0
def grad_fn(t_u, t_c, t_p, w, b):
grad_w=d_t(t_p,t_c)*d_w(t_u)
grad_b=d_t(t_p,t_c)*d_b(t_u, w, b)
return torch.stack([grad_w.mean(),grad_b.mean()])
def training_loop(iterations, learning_rate, params, t_u, t_c,
print_params = True, verbose=1):
for epoch in range(1, iterations + 1):
# if params.grad is not None:
# params.grad.zero_() # 这可以在调用backward之前在循环中的任何时候完成
w,b=params
t_p = model(t_u, w,b)
loss = loss_fn(t_p, t_c)
params=params-learning_rate*grad_fn(t_u,t_c,t_p,w,b)
# params.grad.zero_()
if epoch % 500 == 0:
print('Epoch %d, Loss %f' % (epoch, float(loss)))
return params
#t_c是摄氏度数,t_u是未知单位度数
t_c = [0.5, 14.0, 15.0, 28.0, 11.0, 8.0, 3.0, -4.0, 6.0, 13.0, 21.0]
t_u = [35.7, 55.9, 58.2, 81.9, 56.3, 48.9, 33.9, 21.8, 48.4, 60.4, 68.4]
t_c = torch.tensor(t_c)
t_u = torch.tensor(t_u)
t_cn=t_c/21.0#正则化
t_un=t_u/68.4#为x
[w_last,b_last]=training_loop(5000,1e-2,torch.tensor([1.0,0.0],requires_grad=True),t_un,t_cn)#注意点params为2维度矩阵
print(w_last,b_last)
t_p = model(t_un,w_last,b_last) # 记住你是在规范后数据上训练的
# fig = plt.figure(dpi=600)
plt.xlabel("t_un")
plt.ylabel("t_p")
# plt.plot(t_un, t_p) # 在原数据上作图t_p.detach().numpy()
# plt.plot(t_un, t_cn, 'o')
# plt.show()
plt.plot(t_un.detach().numpy(), t_p.detach().numpy()) # 在原数据上作图t_p.detach().numpy()
plt.plot(t_un.detach().numpy(), t_cn.detach().numpy(), 'o')
plt.show()
#复习自己写的
# import matplotlib.pyplot as plt
# import torch
# from matplotlib import pyplot
# #t_c是实际摄氏度数,t_u是未知单位度数
# t_c = [0.5, 14.0, 15.0, 28.0, 11.0, 8.0, 3.0, -4.0, 6.0, 13.0, 21.0]
# t_u = [35.7, 55.9, 58.2, 81.9, 56.3, 48.9, 33.9, 21.8, 48.4, 60.4, 68.4]
# t_c = torch.tensor(t_c)
# t_u = torch.tensor(t_u)
# def model(w,b,t_u):
# return w*t_u+b
# def loss_fn(t_p,t_c):
# lossfunction=(t_p-t_c)**2
# return lossfunction.mean()
# def dw_loss(t_p):#(w*t_u+b-t_c)**2
# dw=2*(t_p-t_c)*t_u
# return dw.mean()
# def db_loss(t_p):
# db=2*(t_p-t_c)
# return db.mean()
# def loss_w_grad(w,lr,t_p):
# w=w-dw_loss(t_p)*lr
# return w
# def loss_b_grad(b,lr,t_p):
# b=b-db_loss(t_p)*lr
# return b
# def train(t_c,t_u,w,b,iterations,lr):
# for i in range(iterations):
# t_p=model(w,b,t_u)
# w=loss_w_grad(w,lr,t_p)
# b=loss_b_grad(b,lr,t_p)
# # w = w - dw_loss(t_p) * lr
# # b = b - db_loss(t_p) * lr
# loss=loss_fn(t_p,t_c)
#
# print('w为',w,'b为',b,'损失为',loss)
# return w,b
# t_c=t_c/21
# t_u=t_u/68.4
# [w,b]=train(t_c,t_u,1.4,0,5000,0.002)
# print(w,b)
# plt.xlabel("t_u")
# plt.ylabel("t_p")
# plt.plot(t_u, model(w,b,t_u)) # 在原数据上作图t_p.detach().numpy()
# plt.plot(t_u, t_c, 'o')
# plt.show()
温度计问题(未使用优化器)
最新推荐文章于 2024-03-16 09:55:21 发布