pytorch实现线性拟合方式
作者:wangqianqianya 时间:2021-12-30 01:50:32
一维线性拟合
数据为y=4x+5加上噪音
结果:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
from torch.autograd import Variable
import torch
from torch import nn
X = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
Y = 4*X + 5 + torch.rand(X.size())
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression, self).__init__()
self.linear = nn.Linear(1, 1) # 输入和输出的维度都是1
def forward(self, X):
out = self.linear(X)
return out
model = LinearRegression()
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-2)
num_epochs = 1000
for epoch in range(num_epochs):
inputs = Variable(X)
target = Variable(Y)
# 向前传播
out = model(inputs)
loss = criterion(out, target)
# 向后传播
optimizer.zero_grad() # 注意每次迭代都需要清零
loss.backward()
optimizer.step()
if (epoch + 1) % 20 == 0:
print('Epoch[{}/{}], loss:{:.6f}'.format(epoch + 1, num_epochs, loss.item()))
model.eval()
predict = model(Variable(X))
predict = predict.data.numpy()
plt.plot(X.numpy(), Y.numpy(), 'ro', label='Original Data')
plt.plot(X.numpy(), predict, label='Fitting Line')
plt.show()
多维:
from itertools import count
import torch
import torch.autograd
import torch.nn.functional as F
POLY_DEGREE = 3
def make_features(x):
"""Builds features i.e. a matrix with columns [x, x^2, x^3]."""
x = x.unsqueeze(1)
return torch.cat([x ** i for i in range(1, POLY_DEGREE+1)], 1)
W_target = torch.randn(POLY_DEGREE, 1)
b_target = torch.randn(1)
def f(x):
return x.mm(W_target) + b_target.item()
def get_batch(batch_size=32):
random = torch.randn(batch_size)
x = make_features(random)
y = f(x)
return x, y
# Define model
fc = torch.nn.Linear(W_target.size(0), 1)
batch_x, batch_y = get_batch()
print(batch_x,batch_y)
for batch_idx in count(1):
# Get data
# Reset gradients
fc.zero_grad()
# Forward pass
output = F.smooth_l1_loss(fc(batch_x), batch_y)
loss = output.item()
# Backward pass
output.backward()
# Apply gradients
for param in fc.parameters():
param.data.add_(-0.1 * param.grad.data)
# Stop criterion
if loss < 1e-3:
break
def poly_desc(W, b):
"""Creates a string description of a polynomial."""
result = 'y = '
for i, w in enumerate(W):
result += '{:+.2f} x^{} '.format(w, len(W) - i)
result += '{:+.2f}'.format(b[0])
return result
print('Loss: {:.6f} after {} batches'.format(loss, batch_idx))
print('==> Learned function:\t' + poly_desc(fc.weight.view(-1), fc.bias))
print('==> Actual function:\t' + poly_desc(W_target.view(-1), b_target))
来源:https://blog.csdn.net/wangqianqianya/article/details/102764971
标签:pytorch,线性,拟合
0
投稿
猜你喜欢
pygame游戏之旅 添加游戏界面按键图形
2023-06-30 21:48:38
Python drop方法删除列之inplace参数实例
2023-07-23 23:26:49
点球小游戏python脚本
2022-07-17 23:28:03
Python中内置的日志模块logging用法详解
2023-07-25 05:04:12
静态网页加密工具
2009-01-05 12:05:00
不需要用到正则的Python文本解析库parse
2022-11-08 17:28:09
Python Opencv轮廓常用操作代码实例解析
2023-01-03 08:46:59
关于搜索建议的两点小问题
2011-09-16 20:15:29
python滑块验证码的破解实现
2023-11-27 11:46:17
Python matplotlib 动画绘制详情
2022-04-12 14:36:52
Oracle9iPL/SQL编程的经验小结
2010-07-23 12:49:00
SQL Server 2000 占内存居高不下可能的原因及其解决方法
2010-04-25 10:39:00
Python卸载模块的方法汇总
2022-03-14 16:50:21
Java动态-代理实现AOP
2023-07-15 09:33:43
Python openpyxl读取单元格字体颜色过程解析
2023-02-09 06:57:02
如何提升JavaScript的运行速度(函数篇)
2010-05-17 13:27:00
python密码学各种加密模块教程
2021-03-10 05:32:55
Python学习之字符串常用方法总结
2021-12-19 02:19:46
Visual Studio Code搭建django项目的方法步骤
2022-11-28 22:04:00
python实现按任意键继续执行程序
2021-02-12 12:47:10