基于PyTorch的CNN、RNN、LSTM使用记录

基于PyTorch的CNN、RNN、LSTM使用记录

  1. Conv2d

https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html#torch.nn.Conv2d

  1. Linnear

https://pytorch.org/docs/stable/generated/torch.nn.Linear.html#torch.nn.Linear

  1. Dropout

基于PyTorch的CNN、RNN、LSTM使用记录_第1张图片

基于PyTorch的CNN、RNN、LSTM使用记录_第2张图片

https://pytorch.org/docs/stable/tensors.html?highlight=floattensor

  1. Variable

    Tensor是Pytorch的一个完美组件(可以生成高维数组),但是要构建神经网络还是远远不够的,我们需要能够计算图的Tensor,那就是Variable。Variable是对Tensor的一个封装,操作和Tensor是一样的,但是每个Variable都有三个属性,Varibale的Tensor本身的.data,对应Tensor的梯度.grad,以及这个Variable是通过什么方式得到的.grad_fn。

  2. 使用view时报错:

    RuntimeError: view size is not compatible with input tensor’s size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(…) instead.

    tensor不是contiguous 引起的错误。查看targets.is_contiguous()为False。

    两种解决办法:1)按照提示使用reshape代替;2)将变量先转为contiguous ,再进行view:

targets.contiguous().view(targets.size(0)*targets.size(1),-1)
  1. lstm使用的注意

    报错:RuntimeError: Expected hidden[0] size (1, 1024, 3), got (1024, 3)

    查找资料如下:

在tensor输入维度上可以选择第一位是batch size,或者第二位是batch size。理论上说这是个人习惯问题,只要前后统一就可以;但是在pytorch中内置的lstm层只接受batch second 的hidden层tensor。虽然在lstm层或padding层上可以定义batch_first=True,但是这只定义了输入tensor;hidden层仍然必须是batch second 格式。

引用自CSDN博主「Edward Tivrusky IV」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yuuyuhaksho/article/details/87560640

https://blog.csdn.net/xpy870663266/article/details/100002592?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160295113919725271700099%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=160295113919725271700099&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_v2~rank_v28-1-100002592.pc_first_rank_v2_rank_v28&utm_term=RuntimeError%3A+Expected+hidden%5B&spm=1018.2118.3001.4187

用google colab报错:Input and hidden tensors are not at the same device, found input tensor at cuda:0 and hidden tensor at cpu

你可能感兴趣的:(Pytorch,pytorch,神经网络,深度学习)