当前位置:网站首页>Pytoch (III) -- function optimization
Pytoch (III) -- function optimization
2022-07-01 04:46:00 【CyrusMay】
Pytorch( 3、 ... and ) —— Function optimization
1. An optimization method
import torch
import torch.nn.functional as F
from torch import nn
model # Build a model
data # Prepare the data
target # Data labels
epochs # The number of iterations
loss = nn.CrossEntropyLoss() # Loss function
opt = torch.optim.Adam(model.parameters(),lr=0.001) # Create optimizer
for i in range(epochs):
outputs = model(x)
loss_value = loss(outputs,target)
opt.zero_grad() # Gradient clear
loss_value.backward() # Back propagation calculation gradient
opt.step() # Gradient update
2. Optimize real columns
2.1 Optimization function
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 Optimize the calculation process
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) # Initial value
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
only because The world No matter how big however You And I
With the smallest memory Pile up the universe
—————— May day ( Because of you So I )——————
边栏推荐
- 【硬十宝典】——1.【基础知识】电源的分类
- Shell之Unix运维常用命令
- 2022 G2 power station boiler stoker examination question bank and G2 power station boiler stoker simulation examination question bank
- Leecode question brushing record 1332 delete palindrome subsequence
- 1076 Forwards on Weibo
- Daily algorithm & interview questions, 28 days of special training in large factories - the 13th day (array)
- How to do the performance pressure test of "Health Code"
- 2022-02-15 (399. Division evaluation)
- Neural network - nonlinear activation
- RuntimeError: mean(): input dtype should be either floating point or complex dtypes. Got Long instead
猜你喜欢

Why is Internet thinking not suitable for AI products?

RuntimeError: “max_pool2d“ not implemented for ‘Long‘

Pytorch convolution operation

C - detailed explanation of operators and summary of use cases
![解决:Thread 1:[<*>setValue:forUndefinedKey]:this class is not key value coding-compliant for the key *](/img/88/0b99d1db2cdc70ab72d2b3c623dfaa.jpg)
解决:Thread 1:[<*>setValue:forUndefinedKey]:this class is not key value coding-compliant for the key *

手动实现一个简单的栈

Neural network convolution layer

解决:拖动xib控件到代码文件中,报错setValue:forUndefinedKey:this class is not key value coding-compliant for the key

RuntimeError: “max_pool2d“ not implemented for ‘Long‘

Pytorch(二) —— 激活函数、损失函数及其梯度
随机推荐
Pytorch(四) —— 可视化工具 Visdom
Collect the annual summary of laws, regulations, policies and plans related to trusted computing of large market points (national, ministerial, provincial and municipal)
测量三相永磁同步电机的交轴直轴电感
Neural networks - use of maximum pooling
2022-02-15 (399. Division evaluation)
Neural network convolution layer
2022 Shanghai safety officer C certificate examination question simulation examination question bank and answers
Basic skeleton of neural network nn Use of moudle
【硬十宝典】——1.【基础知识】电源的分类
1076 Forwards on Weibo
Pytorch neural network construction template
Pytest automated testing - compare robotframework framework
2022 question bank and answers for safety production management personnel of hazardous chemical production units
2022.2.7-2.13 AI industry weekly (issue 84): family responsibilities
Shell之Unix运维常用命令
C#读写应用程序配置文件App.exe.config,并在界面上显示
Extension fragment
Software testing needs more and more talents. Why do you still not want to take this path?
[difficult] sqlserver2008r2, can you recover only some files when recovering the database?
Use of dataloader