当前位置:网站首页>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
只因 世界 再大 不过 你和我
用最小回忆 堆成宇宙
——————五月天(因为你 所以我)——————
边栏推荐
- JS image path conversion Base64 format
- Ospfb notes - five messages [ultra detailed] [Hello message, DD message, LSR message, LSU message, lsack message]
- Question bank and answers for chemical automation control instrument operation certificate examination in 2022
- LM small programmable controller software (based on CoDeSys) note 19: errors do not match the profile of the target
- VR线上展览所具备应用及特色
- 什么是权限?什么是角色?什么是用户?
- In the innovation community, the "100 cities Tour" of the gold warehouse of the National People's Congress of 2022 was launched
- MySQL function variable stored procedure
- Section 27 remote access virtual private network workflow and experimental demonstration
- 206. reverse linked list
猜你喜欢

Ten wastes of software research and development: the other side of research and development efficiency

Recommend the best product development process in the Internet industry!

206. reverse linked list

Internet winter, how to spend three months to make a comeback

嵌入式系统开发笔记79:为什么要获取本机网卡IP地址

Account sharing technology enables the farmers' market and reshapes the efficiency of transaction management services

Coinbase in a bear market: losses, layoffs, stock price plunges

【LeetCode】100. Same tree

TCP server communication flow

Daily question - line 10
随机推荐
2022年化工自动化控制仪表操作证考试题库及答案
PgSQL failed to start after installation
How to use maixll dock
It's settled! 2022 JD cloud summit of JD global technology Explorer conference see you in Beijing on July 13
2022 G2 power station boiler stoker examination question bank and G2 power station boiler stoker simulation examination question bank
Custom components in applets
如何看待智慧城市建设中的改变和机遇?
2022年G1工业锅炉司炉特种作业证考试题库及在线模拟考试
Dual Contrastive Learning: Text Classification via Label-Aware Data Augmentation 阅读笔记
Question bank and online simulation examination for special operation certificate of G1 industrial boiler stoker in 2022
Registration of P cylinder filling examination in 2022 and analysis of P cylinder filling
Rule method: number of effective triangles
slf4j 简单实现
Annual inventory review of Alibaba cloud's observable practices in 2021
[recommended algorithm] C interview question of a small factory
Browser top loading (from Zhihu)
Simple implementation of slf4j
什么是uid?什么是Auth?什么是验证器?
软件研发的十大浪费:研发效能的另一面
Odeint and GPU