当前位置:网站首页>Pytorch(三) —— 函数优化
Pytorch(三) —— 函数优化
2022-07-01 04:35:00 【CyrusMay】
Pytorch(三) —— 函数优化
1.优化方法
import torch
import torch.nn.functional as F
from torch import nn
model # 搭建模型
data # 准备数据
target # 数据标签
epochs # 迭代次数
loss = nn.CrossEntropyLoss() # 损失函数
opt = torch.optim.Adam(model.parameters(),lr=0.001) # 创建优化器
for i in range(epochs):
outputs = model(x)
loss_value = loss(outputs,target)
opt.zero_grad() # 梯度清零
loss_value.backward() # 反向传播计算梯度
opt.step() # 梯度更新
2. 优化实列
2.1 优化函数
import torch
import torch.nn.functional as F
from torch import nn
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
def f(x):
return (x[0]**2+x[1]-11)**2 + (x[0]+x[1]**2-7)**2
x = np.linspace(-6,6,100)
y = np.linspace(-6,6,100)
x,y = np.meshgrid(x,y)
z = f([x,y])
fig = plt.figure()
ax = fig.gca(projection="3d")
ax.plot_surface(x,y,z)
plt.show()

2.2 优化计算过程
import torch
from torch import nn
import torch.nn.functional as F
def f(x):
return (x[0]**2+x[1]-11)**2 + (x[0]+x[1]**2-7)**2
x = torch.tensor([0,0],dtype=torch.float64,requires_grad=True) # 初始值
opt = torch.optim.Adam([x],lr=0.001)
epochs = 10000
for i in range(epochs):
y = f(x)
opt.zero_grad()
y.backward()
opt.step()
if (i+1) % 1000 == 0:
print("step:{},x:{},y:{}".format(i+1,x.tolist(),y.item()))
step:1000,x:[1.2701438632350366, 1.1183999805060867],y:88.53216019860564
step:2000,x:[2.3323811541207116, 1.9535729950538283],y:13.766112350520348
step:3000,x:[2.85199573044325, 2.114162286626475],y:0.6711343725212155
step:4000,x:[2.9819641054212, 2.0271570475493847],y:0.01492722663566651
step:5000,x:[2.9991264478402497, 2.0014778659773924],y:3.98608554435595e-05
step:6000,x:[2.999994001590949, 2.0000102031302087],y:1.9012429241084185e-09
step:7000,x:[2.9999999988119166, 2.0000000020209616],y:7.529268955707826e-17
step:8000,x:[2.9999999999999893, 2.0000000000000124],y:4.1809627976713626e-27
step:9000,x:[2.9999999999999933, 2.0000000000000093],y:1.8238464128709793e-27
step:10000,x:[2.999999999999996, 2.0000000000000053],y:6.310887241768094e-28
by CyrusMay 2022 06 29
只因 世界 再大 不过 你和我
用最小回忆 堆成宇宙
——————五月天(因为你 所以我)——————
边栏推荐
- PgSQL failed to start after installation
- 细数软件研发效能的七宗罪
- 2022年G1工业锅炉司炉特种作业证考试题库及在线模拟考试
- JS rotation chart
- How to choose the right server for website data collection?
- 2. Use of classlist (element class name)
- It's settled! 2022 JD cloud summit of JD global technology Explorer conference see you in Beijing on July 13
- [recommended algorithm] C interview question of a small factory
- In the innovation community, the "100 cities Tour" of the gold warehouse of the National People's Congress of 2022 was launched
- 扩展-Fragment
猜你喜欢

Simple implementation of slf4j

VIM简易使用教程

Introduction of Spock unit test framework and its practice in meituan optimization___ Chapter I

2022年T电梯修理题库及模拟考试
![[godot] unity's animator is different from Godot's animplayer](/img/51/48f40a7b6736d7f78040eabbbd3395.jpg)
[godot] unity's animator is different from Godot's animplayer

Applications and features of VR online exhibition

Measurement of quadrature axis and direct axis inductance of three-phase permanent magnet synchronous motor

2022 gas examination question bank and online simulation examination

ThreeJS开篇
![[ue4] event distribution mechanism of reflective event distributor and active call event mechanism](/img/44/6a26ad24d56ddd5156f3a31fa7e0b9.jpg)
[ue4] event distribution mechanism of reflective event distributor and active call event mechanism
随机推荐
Common thread methods and daemon threads
Knowledge supplement: redis' basic data types and corresponding commands
Applications and features of VR online exhibition
2022危险化学品生产单位安全生产管理人员题库及答案
About the transmission pipeline of stage in spark
嵌入式系統開發筆記80:應用Qt Designer進行主界面設計
软件研发的十大浪费:研发效能的另一面
CUDA development and debugging tool
OSPF notes [multiple access, two multicast addresses with OSPF]
Caijing 365 stock internal reference | the first IPO of Beijing stock exchange; the subsidiary of the recommended securities firm for gambling and gambling, with a 40% discount
ThreeJS开篇
Odeint and GPU
2022.2.7-2.13 AI industry weekly (issue 84): family responsibilities
Redis (VII) optimization suggestions
The junior college students were angry for 32 days, four rounds of interviews, five hours of soul torture, and won Ali's offer with tears
Browser top loading (from Zhihu)
[godot] unity's animator is different from Godot's animplayer
2022年T电梯修理题库及模拟考试
JMeter learning notes 2 - brief introduction to graphical interface
What is uid? What is auth? What is a verifier?