2021-11-26 深度学习:Pytorch和CNN基础知识

1. PyTorch

(1) 认识tensor:表示,numpy转换,简单计算
import numpy as np
import torch
# create a tensor in a similar way to numpy np array
x_numpy = np.array([0.1,0.2,0.3])
x_torch = torch.tensor([0.1,0.2,0.3])
print('x_numpy','x_torch')
print(x_numpy,x_torch)
print()

#to and from numpy ,pytorch
print('to and from numpy ,pytorch:')
print(torch.from_numpy(x_numpy),x_torch.numpy)
print()

#basic operations
y_numpy = np.array([3,4,5])
y_torch = torch.tensor([3,4,5])
print('add:')
print(x_numpy+y_numpy,x_torch+y_torch)
print()

#many functions that are in numpy are also in pytorch
print('norm,即二范数:')
print(np.linalg.norm(x_numpy),torch.norm(x_torch))
print()

#to apply an operation allong a dimension
print('mean along the 0th dimension:')
z_numpy = np.array([[1,2],[3,4.]])
z_torch = torch.tensor([[1,2],[3,4.]])
print(np.mean(z_numpy,axis=0),torch.mean(z_torch,dim=0))#keyword有些不一样

'''result:
x_numpy x_torch
[0.1 0.2 0.3] tensor([0.1000, 0.2000, 0.3000])

to and from numpy ,pytorch:
tensor([0.1000, 0.2000, 0.3000], dtype=torch.float64) <built-in method numpy of Tensor object at 0x0000020A30088090>

add:
[3.1 4.2 5.3] tensor([3.1000, 4.2000, 5.3000])

norm,即二范数:
0.37416573867739417 tensor(0.3742)

mean along the 0th dimension:
[2. 3.] tensor([2., 3.])
'''
(2) 形状改变:Tensor.view
#view
N,C,W,H = 10000,3,28,28
X = torch.randn(N,C,W,H)
print(X.shape)
print(X.view(N,C,784).shape)
print(X.view(-1,C,784).shape)#-1,可以自动算出0维的数量
'''result
torch.Size([10000, 3, 28, 28])
torch.Size([10000, 3, 784])
torch.Size([10000, 3, 784])
'''
(3) broacasting
#brocasting
x = torch.ones(5,1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值