PyTorch学习之路1

PyTorch学习之路1

"""
A Simple PyTorch Tutorial_1
"""
# import package 导入包
import torch
import numpy as np 

# creat an empty 5x3 tensor 创建一个5x3的空张量
x = torch.empty(5, 3)
print(x)

# creat a random tensor
x = torch.rand(5, 3)
print(x)

# creat a zero tensor ,the type is long
x = torch.zeros(5, 3, dtype=torch.long)

# creat tensors from array
x = torch.tensor([5.5, 3])

# creat a 5x3 tensor, the type is double
x = torch.ones(5, 3, dtype=torch.double)

# creat a new tensor of the same dimension from an existing tensor and redefine the type as float
x = torch.randn_like(x, dtype=torch.float)

# print a tensor's dimension
print(x.size())

# add two tensors
y = torch.rand(5, 3)
print(x + y)

# take the first column of the tensor
print(x[:, 1])

# resize a 4x4 tensor into a one-dimensional tensor
x = torch.randn(4, 4)
y = x.view(16)
print(x.size(), y.size())

# get the numbers from the tensor
# only one element tensors can be converted to Python scalars
x = torch.randn(1)
print(x)
print(x.item())

# change the tensor to numpy
a = torch.ones(5)
print(a)

b = a.numpy()
print(b)

# change numpy to tensor
a = np.ones(5)
b = torch.from_numpy(a)

print(a)
print(b)

# do whatever you want on tensor
y = x + 2
print(y)
print(y.grad_fn)

# do something on y
z = y * y * 3
out = z.mean()

print(z)
print(out)

# Back propagate out
out.backward()

# print gradiant d(out)/dx
print(x.grad) # out=0.25*Σ3(x+2)^2

# creat a tensor caculation (y=x*2^n)
x = torch.randn(3, requires_grad=True)

y = x * 2
while y.data.norm() < 1000:
    y = y * 2

print(y)

# caculate the gradient of v = [0.1, 1.0, 0.0001]
v = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)
y.backward(v)

print(x.grad)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值