Torch - 官方例子

From:Torch7官网

1 Define a positive definite quadratic form

  • rand() - creates tensor drawn from uniform distribution
  • t() - transposes a tensor (note it returns a new view)
  • dot() - performs a dot product between two tensors
  • eye() - returns a identity matrix
  • * - operator over matrices (which performs a matrix-vector or matrix-matrix multiplication)

例子:

require 'torch'

torch.manualSeed(1234) -- make sure the random seed is the same for everyone

N = 5 -- choose a dimension
A = torch.rand(N, N) -- create a random NxN matrix
A = A*A:t() -- make it symmetric positive
A:add(0.001, torch.eye(N)) -- make it definite
b = torch.rand(N) -- add a linear term


function J(x) -- create the quadratic form
   return 0.5*x:dot(A*x)-b:dot(x)
end
print(J(torch.rand(N))) -- print the function value

2. Find the exact minimum

xs = torch.inverse(A)*b -- inverse the matrix
print(string.format('J(x^*) = %g', J(xs)))

3. Search the minimum by gradient descent

function dJ(x) -- define the gradient w.r.t. x of J(x)
  return A*x-b
end

x = torch.rand(N) -- define some current solution
lr = 0.01 -- given learning rate lr
for i=1,20000 do
  x = x - dJ(x)*lr
  print(string.format('at iter %d J(x) = %f', i, J(x))) -- print the value of the objective function at each iteration
end

output:

...
at iter 19995 J(x) = -3.135664
at iter 19996 J(x) = -3.135664
at iter 19997 J(x) = -3.135665
at iter 19998 J(x) = -3.135665
at iter 19999 J(x) = -3.135665
at iter 20000 J(x) = -3.135666

4. Using the optim package

luarocks install optim

Training with optim:

require 'optim'

state = { -- define a state for conjugate gradient
   verbose = true,
   maxIter = 100
}

x = torch.rand(N)
optim.cg(JdJ, x, state)

output:

after 120 evaluation J(x) = -3.136835
after 121 evaluation J(x) = -3.136836
after 122 evaluation J(x) = -3.136837
after 123 evaluation J(x) = -3.136838
after 124 evaluation J(x) = -3.136840
after 125 evaluation J(x) = -3.136838

5. Plot

luarocks install gnuplot

5.1 Store intermediate function evaluations

evaluations = {}
time = {}
timer = torch.Timer()
neval = 0
function JdJ(x)
   local Jx = J(x)
   neval = neval + 1
   print(string.format('after %d evaluations, J(x) = %f', neval, Jx))
   table.insert(evaluations, Jx)
   table.insert(time, timer:time().real)
   return Jx, dJ(x)
end

-- trian
state = {
   verbose = true,
   maxIter = 100
}

x0 = torch.rand(N)
cgx = x0:clone() -- make a copy of x0
timer:reset()
optim.cg(JdJ, cgx, state)

-- convert the evaluations and time tables to tensors for plotting:
cgtime = torch.Tensor(time)
cgevaluations = torch.Tensor(evaluations)

5.2 Add support for stochastic gradient descent

-- add the training with stochastic gradient, using optim

evaluations = {}
time = {}
neval = 0
state = {
  lr = 0.1
}

-- start from the same starting point than for CG
x = x0:clone()

-- reset the timer!
timer:reset()

-- note that SGD optimizer requires to do the loop
for i=1,1000 do
  optim.sgd(JdJ, x, state)
  table.insert(evaluations, Jx)
end

sgdtime = torch.Tensor(time)
sgdevaluations = torch.Tensor(evaluations)

5.3 Final plot

require 'gnuplot'

gnuplot.figure(1)
gnuplot.title('CG loss minimisation over time')
gnuplot.plot(cgtime, cgevaluations)

gnuplot.figure(2)
gnuplot.title('SGD loss minimisation over time')
gnuplot.plot(sgdtime, sgdevaluations)

require 'gnuplot'

gnuplot.pngfigure('plot.png')
gnuplot.plot(
   {'CG',  cgtime,  cgevaluations,  '-'},
   {'SGD', sgdtime, sgdevaluations, '-'})
gnuplot.xlabel('time (s)')
gnuplot.ylabel('J(x)')
gnuplot.plotflush()

这里写图片描述

在Python的包管理工具pip中,`.whl`是Wheel的文件格式,是一种Python的分发包格式,用于替代旧的`.egg`格式。Wheel文件通常在`pip`安装Python包时被使用,它们包含预先构建的二进制模块,可以加快安装过程并减少构建过程中可能遇到的问题。 要下载特定版本的Wheel文件,比如`torch-1.8.1+cpu-cp38-cp38-linux_x86_64.whl`,你可以访问该软件包的官方发布页面或者使用Python包索引(PyPI)的搜索功能。PyPI是Python的包管理系统,提供了一个中央仓库,允许开发者上传和下载包。 以下是下载指定`.whl`文件的大致步骤: 1. 确认你的Python环境和系统架构是否与`.whl`文件的要求相匹配。在这个例子中,文件名暗示它是为Python 3.8版本,CPU架构,以及适用于Linux x86_64(64位Linux系统)系统。 2. 打开PyPI网站,在搜索框中输入“torch-1.8.1”并搜索。找到对应PyTorch官方包。 3. 根据搜索结果,你应该能够看到多个版本和不同的`.whl`文件。选择与你的系统和Python版本匹配的`.whl`文件。 4. 点击对应的`.whl`文件下载链接,保存到你的本地系统上。 另外,你也可以使用`pip`命令直接下载。例如: ```bash pip download torch==1.8.1+cpu -d <下载目录> ``` 请将`<下载目录>`替换为你希望保存Wheel文件的本地目录路径。 请注意,下载和安装PyTorch的`.whl`文件之前,确保你遵守了相应的许可协议,并且有适当的权限进行下载和安装操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值