00.语法

Google Colab教学

文件目录为/content,挂载后/content/drive/MyDrive

from google.colab import drive
drive.mount('/content/drive', force_remount=True)

Pytorch教学

DNN: 深度神经网路

  1. 下载Data
  2. 搭建网络
  3. 定义损失函数
  4. Optimizer帮助计算gradient design步骤
  5. Training就是拿data来训练网络
  6. Validattion用来看网络是否进步
  7. 最后Testing
    在这里插入图片描述

Tensor

在这里插入图片描述
Tensor:高纬矩阵

Tensor数据类型

Data typedtypetensor
32-bit floating pointtorch.floattorch.FloatTensor
64-bit integer (signed)torch.longtorch.LongTensor

Tensor形状

在这里插入图片描述

Tensor构造

# From list / NumPy array
x = torch.tensor([[1, -1], [-1, 1]])
x = torch.from_numpy(np.array([[1, -1], [-1, 1]]))
tensor([[1., -1.],
		[-1., 1.]])

# Zero tensor
x = torch.zeros([2, 2])
tensor([[0., 0.],
		[0., 0.]])
# Unit tensor
x = torch.ones([1, 2, 5])
tensor([[[1., 1., 1., 1., 1.],
		 [1., 1., 1., 1., 1.]]])

Tensor操作

Squeeze

Squeeze: remove the specified dimension with length=1

>>> x = torch.zeros([1, 2, 3])
>>> x.shape
torch.Size([1, 2, 3])
>>> x = x.squeeze(0)
>>> x.shape
torch.Size([2, 3])
Unsqueeze

Unsqueeze: expand a new dimension

>>> x = torch.zeros([2, 3])
>>> x.shape
torch.Size([2, 3])
>>> x = x.unsqueeze(1)
>>> x.shape
torch.Size([2, 1, 3])
Transpose

Transpose: transpose two specified dimensions

>>> x = torch.zeros([2, 3])
>>> x.shape
torch.Size([2, 3])
>>> x = x.transpose(0, 1)
>>> x.shape
torch.Size([3, 2])
Cat

Cat: concatenate multiple tensors

>>> x = torch.zeros([2, 1, 3])
>>> y = torch.zeros([2, 3, 3])
>>> z = torch.zeros([2, 2, 3])
>>> w = torch.cat([x, y, z], dim=1)
>>> w.shape
torch.Size([2, 6, 3])

在这里插入图片描述

Tensor-Operators

如何计算梯度

在这里插入图片描述

Dataset & Dataloader

from torch.utils.data import Dataset, DataLoader
class MyDataset(Dataset):
  def __init__(self, file):
    self.data = ...

  def __getitem__(self, idx):
    return self.data[idx]
  
  def __len__(self):
    return len(self.data)

dataset = MyDataset(file)
dataloader = DataLoader(dataset, batch_size, shuffle=True)
# shuffle只有在Training才为True

在这里插入图片描述

torch.nn

Neural Network Layers

>>> layer = torch.nn.Linear(32, 64)
>>> layer.weight.shape
torch.Size([64, 32])
>>> layer.bias.shape
torch.Size([64])

在这里插入图片描述

激活函数

在这里插入图片描述

损失函数

Mean Squared Error (for linear regression) nn.MSELoss()
Cross Entropy (for classification) nn.CrossEntropyLoss()

torch.optim

Stochastic Gradient Descent (SGD)
torch.optim.SGD(params, lr, momentum = 0)

构建自己的神经网络

import torch 
import torch.nn as nn
class MyModel(nn.Module):
  def __init__(self):
    super(MyModel, self).__init__()
    self.net = nn.Sequential(
        nn.Linear(10, 32),
        nn.Sigmoid(),
        nn.Linear(32, 1)
    )
  def forward(self, x):
    return self.net(x)

神经网络训练

dataset = MyDataset(file)
tr_set = DataLoader(dataset, 16, shuffle=True)
model = MyModel().to(device)
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), 0.1)
...

神经网络save/load

Save torch.save(model.state_dict(), path)
Load ckpt = torch.load(path)
model.load_state_dict(ckpt)

PyTorch v.s. NumPy

PyTorchNumPy
x.shapex.shape
x.dtypex.dtype
x.reshape / x.viewx.reshape
x.squeeze()x.squeeze()
x.unsqueeze(1)np.expand_dims(x, 1)

Tensor – Device

  • 默认使用CPU
  • CPU x=x.to(‘cpu’)
  • GPU x=x.to(‘cuda’)
    检查设备是否有 NVIDIA GPU
    torch.cuda.is_available()
  • 28
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

倾海、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值