沐神动手深度学习 01 数据操作

import torch
x=torch.arange(12)
x

tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

x.shape

torch.Size([12])

x.numel()

12

x.reshape(3,4)

tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])

torch.tensor([[1,2,3,4],[4,5,6,7],[2,3,4,5]]).shape

torch.Size([3, 4])

x=torch.tensor([1.0,2,3,4])
y=torch.tensor([2,5,7,9])
x+y,x-y,x*y,x/y,x**y

(tensor([ 3., 7., 10., 13.]),
tensor([-1., -3., -4., -5.]),
tensor([ 2., 10., 21., 36.]),
tensor([0.5000, 0.4000, 0.4286, 0.4444]),
tensor([1.0000e+00, 3.2000e+01, 2.1870e+03, 2.6214e+05]))

torch.exp(x)

tensor([ 2.7183, 7.3891, 20.0855, 54.5981])

x=torch.arange(12,dtype=torch.float32).reshape(3,4)
y=torch.tensor([[1,2,3,4],[2,3,0,5],[0,4,5,6]])
torch.cat((x,y),dim=0)
torch.cat((x,y),dim=1)

tensor([[ 0., 1., 2., 3., 1., 2., 3., 4.],
[ 4., 5., 6., 7., 2., 3., 0., 5.],
[ 8., 9., 10., 11., 0., 4., 5., 6.]])

x.sum()

tensor(66.)

a=torch.arange(3).reshape(3,1)
b=torch.arange(2).reshape(1,2)
a,b

(tensor([[0],
[1],
[2]]),
tensor([[0, 1]]))

a+b

tensor([[0, 1],
[1, 2],
[2, 3]])

x

tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])

x[-1]

tensor([ 8., 9., 10., 11.])

x[1:3]

tensor([[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])

x[1:3]=12
x

tensor([[ 0., 1., 2., 3.],
[12., 12., 12., 12.],
[12., 12., 12., 12.]])

x[1:3,]=13
x

tensor([[ 0., 1., 2., 3.],
[13., 13., 13., 13.],
[13., 13., 13., 13.]])

before=id(x)
x=x+y
id(x)==before

False

z=torch.zeros_like(y)
before=id(z)
z[:]=x+y
id(z)==before

True

z=x+y
z

tensor([[ 3., 7., 11., 15.],
[19., 22., 13., 28.],
[13., 25., 28., 31.]])

z[:]=x+y
z

tensor([[ 3., 7., 11., 15.],
[19., 22., 13., 28.],
[13., 25., 28., 31.]])

before=id(x)
x+=y
id(x)==before

True

A=x.numpy()
B=torch.tensor(A)
type(A),type(B),

(numpy.ndarray, torch.Tensor)

c=torch.tensor([3.5])
c,c.item(),float(c),int(c)

(tensor([3.5000]), 3.5, 3.5, 3)

a=torch.arange(12)
b=a.reshape([3,4])
b[:]=2
a

tensor([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值