日常笔记tools

// 查看GPU下有哪些进程
	sudo fuser -v /dev/nvidia*
//杀死对应PID下的GPU进程
	sudo kill -9  PID
//查看显卡状态刷新
	watch -n 5 nvidia-smi
// 发送文件或压缩包到另一台服务器
	# 若是压缩包
	scp 压缩包名称.tar.gz xxx@192.xxx.xxx.xx:/anaconda3/envs/
	# 若是文件夹
	scp -r 目录名 xxx@192.xxx.xxx.xx:/anaconda3/envs/

// 创建环境
conda create -n xxxx
// 激活环境
conda activate xxxx
//下载包
conda install pytorch
//卸载包
conda uninstall xxx
//进入requirements文件路径
conda install --yes --file requirements.txt
//卸载环境 , 即可删除mo
conda remove -n your_env_name(虚拟环境名称) --all
//安装jupyter
conda install jupyter torch torchvision
//打开jupyter
jupyter notebook
//查看conda当前环境装了哪些包
conda list
//查看conda创建了哪些虚拟环境
conda env list
// Linux命令
输出当前绝对路径 pwd
复制文件夹 cp -r 
创建文件 touch
git下载 git clone https://...
下载网络资源  wget https://...
解压.tgz压缩包  tar -xzf  xxx.tgz
创建文件夹 mkdir 
删除文件夹 rm -rf
查看显卡状态 nvidia-smi
启动tensorboard   tensorboard --logdir=runs      # 在当前runs文件夹所在路径上一层
获得某层的权重参数:
output_1=model.fc1.bias.data
output_1=model.fc1.weight.data

网络层信息

nn.Linear()和nn.Conv2d()网络的相关信息,复习一下。
nn.Linear()用于设置全连接层,输入输出均为二维张量,形状为[batch_size, size],nn.Conv2d()卷积层要求输入输出为四维张量.

nn.Linear(in_features ,out_features)

线性层就是用权重矩阵,将一个in_features空间映射到一个out_features空间。一般来说,权重矩阵定义了一个线性函数,它把一个有四个元素的一维张量映射成一个有三个元素的一维张量。全连接层的主要作用就是将前层(卷积、池化等层)计算得到的特征空间映射样本标记空间。简单的说就是将特征表示整合成一个值,其优点在于减少特征位置对于分类结果的影响,提高了整个网络的鲁棒性。
y = x A T + b y = xA^T + b y=xAT+b
也可以把它理解为,当前样本与特征构成的矩阵 X X X 类别与特征构成的权重矩阵 A A A的关系。输出的结果 y y y 就是,样本与类别的关系。
在CV里,nn.Linear()输入的形状为[batch_size, size],这里的size是 c h a n n e l ∗ h e i g h t ∗ w i d t h channel*height*width channelheightwidth,也就是说,把一个样本的所有特征都放在了一行。

fc1 = nn.Linear(in_features = 784, out_features=392)
此时生成的权重矩阵的shape是(392,784),再计算时才会转置。

比如说:
tensor是[28,1,28,28] #[batch,inchannel,heigth,width]
先被reshape成[28,784] #[batch,channelheigthwidth]
接着在二分类中会被降维成[28,2] #[batch,outchannel]

具体的操作方法在pytorch中的实现是:

data.reshape(-1, 1*28*28)
dense1 = nn.Linear(in_features=784, out_features=392)
dense2 = nn.Linear(in_features=392, out_features=196)
dense3 = nn.Linear(in_features=196, out_features=2)

截取部分源码:

class Linear(Module):
    r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`

    Args:
        in_features: size of each input sample
        out_features: size of each output sample
        bias: If set to ``False``, the layer will not learn an additive bias.
            Default: ``True``

    Shape:
        - Input: :math:`(N, *, H_{in})` where :math:`*` means any number of
          additional dimensions and :math:`H_{in} = \text{in\_features}`
        - Output: :math:`(N, *, H_{out})` where all but the last dimension
          are the same shape as the input and :math:`H_{out} = \text{out\_features}`.
    Examples::

        >>> m = nn.Linear(20, 30)
        >>> input = torch.randn(128, 20)
        >>> output = m(input)
        >>> print(output.size())
        torch.Size([128, 30])
          """
    def __init__(self, in_features, out_features, bias=True):
        super(Linear, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.weight = Parameter(torch.Tensor(out_features, in_features))
        if bias:
            self.bias = Parameter(torch.Tensor(out_features))
        else:
            self.register_parameter('bias', None)
        self.reset_parameters()

input: 表示输入的Tensor,可以有多个维度
weights: 表示可学习的权重,shape=(output_feature,in_feature)
bias: 表示可学习的偏置,shape=(output_feature)
in_feature: nn.Linear 初始化的第一个参数,即输入Tensor最后一维的通道数
out_feature: nn.Linear 初始化的第二个参数,即返回Tensor最后一维的通道数
output: 表示输入的Tensor,可以有多个维度

原文链接:https://blog.csdn.net/sazass/article/details/123568203
in_features 是输入的二维张量的size,比如示例[128,20]中的20,
out_features 是输出的二维张量的size,比如示例[128,30]中的30,
最终得到[128,30]的张量.

nn.Conv2d()

卷积层参数比Linear多不少,这里只复习in_channels和out_channels
in_channel: 输入数据的通道数,例RGB图片通道数为3;
out_channel: 输出数据的通道数,这个根据模型调整;

class Conv2d(_ConvNd):
"""      
    Args:
            in_channels (int): Number of channels in the input image
            out_channels (int): Number of channels produced by the convolution
            kernel_size (int or tuple): Size of the convolving kernel
            stride (int or tuple, optional): Stride of the convolution. Default: 1
            padding (int or tuple, optional): Zero-padding added to both sides of the input. Default: 0
            padding_mode (string, optional). Accepted values `zeros` and `circular` Default: `zeros`
            dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
            groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
            bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
"""
            def __init__(self, in_channels, out_channels, kernel_size, stride=1,
                 padding=0, dilation=1, groups=1,
                 bias=True, padding_mode='zeros'):
                kernel_size = _pair(kernel_size)
                stride = _pair(stride)
                padding = _pair(padding)
                dilation = _pair(dilation)
                super(Conv2d, self).__init__(
                    in_channels, out_channels, kernel_size, stride, padding, dilation,
                    False, _pair(0), groups, bias, padding_mode)

来源于https://www.jianshu.com/p/edd081f57218

nn.Linear和kernel=1的nn.Conv的区别

相同点:
都是线性运算,可以看成矩阵相乘,感受野都为1

不同点:
pytorch中初始化方案不同,nn.Conv有更好的初始化

一维卷积是单个像素位置的全部通道进行线性加权,而全连接是把所有输入平铺为一维向量,更偏向于对像素级别的加权。

速度不同,Linear的速度要比nn.Conv快一个数量级,因为Linear是用高效的矩阵相乘实现的,而Conv是卷积核移动实现的

输入尺寸不同,Conv是[batch, input_channel, H, W,…],linear是[batch, …, input_channel]但这一点其实不重要

linear速度快很多,如果tensor的尺寸方便调整的话还是建议用linear。

参考链接:
https://stackoverflow.com/questions/55576314/conv1d-with-kernel-size-1-vs-linear-layer

卷积层与全连接层

卷积层的作用只是提取特征,但是很多物体可能都有同一类特征,比如猫、狗、鸟都有眼睛。如果只用局部特征的话不足与确定具体类别。

这时就需要使用组合特征来判别了。全连接就是组合这些特征来最终确定是哪一个分类,所以全连接就是组合特征和分类器功能。因此权重矩阵中的每一行,就是该类对每个特征的权重。让输入矩阵 @ 权重矩阵,判断每一个样本和每个类的关系。

全连接层会丢失一些位置信息,因为把feature map进行了flatten操作。为什么叫全连接,是因为全连接层中的每一个神经元都与上一次所有节点都连接。这里的每一层神经元数量,就是该层要输出的out_feature数量,因此每个神经元就是来判断上一层所有feature map与这个神经元代表特征的关系,每个神经元里面的权重向量就是上一层所有特征与该节点特征的关系权重。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值