Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2019年5月-8月 #6

Closed
NarcissusInMirror opened this issue May 3, 2019 · 69 comments
Closed

2019年5月-8月 #6

NarcissusInMirror opened this issue May 3, 2019 · 69 comments

Comments

@NarcissusInMirror
Copy link
Owner

2019.5.3工作日志

Batch Normalization introduction

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented May 6, 2019

2019.5.4~2019.5.6工作日志

  • 撰写毕业论文,现已达到字数要求,差背景介绍部分、部分图表、和排版工作
  • 梯度弥散&梯度消失&梯度爆炸?
    Tex

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented May 12, 2019

2019.5.12工作日志

使用LaTex和Word进行毕业论文排版中遇到的问题

Mac字体的问题

image
sheng-qiang/BUPTBachelorThesis#17 (comment)

Word的中行距调整

  • 在表格中想调整文字行距时,选中段落后右键发现没有段落的选项,只有表格的设置选项。因此需点击导航栏Format → Paragraph进行修改

LaTex中表格过宽问题:

  • \begin{table}[htbp]
    \center
    
    \caption{ Example}
    
     \resizebox{\textwidth}{12mm}{ %12可随机设置,调整到适合自己的大小为止
    
    \begin{tabular}{lll}
    \hline
    Example&  Example&  Example\\
    \hline
    S1& Example&Example \\
    S2& Example&ExampleExampleExampleExampleExample \\
    \hline
    \end{tabular}}%注意这里还有一个半括号
    \end{table}
    
    即在begin tabular上套上 \resizebox{\textwidth}{12mm}{ },其中12是可调的参数,可以调到50~60的样子

LaTex表格绘制

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented May 13, 2019

2019.5.13工作日志

CUDA、cuDNN的区别

  • CUDA是英伟达开发的用于自家GPU的并行计算框架

    a general purpose parallel computing platform and programming model that leverages the parallel compute engine in NVIDIA GPUs to solve many complex computational problems in a more efficient way than on a CPU.

    而cuDNN是CUDA Deep Neural Network library,是英伟达打造的针对深度神经网络的加速库,是一个用于深层神经网络的GPU加速库

查看CUDA和cuDNN版本

  • 使用nvcc -V查询CUDA的版本和博客中所示查出来的版本可能不同,原因是服务器上装了多个版本的CUDA,而nvcc -V查出来的版本是正在使用的版本。

numpy的concatenate

  • concatenate只能连接维度数相同的数组,如果想将一个二维数组接到三维数组上,需先将二维数组reshape到三维
    >>> a = np.array([[1,2],[3,4]])
    >>> b = np.array([[5,6],[7,8]])
    >>> np.concatenate((a,b)) # 直接连接得到的仍然是二维的数组
    array([[1, 2],
         [3, 4],
         [5, 6],
         [7, 8]])
    >>> a = a.reshape([1, 2, 2]) # 将a reshape为三维数组
    array([[[1, 2],
          [3, 4]]])
    >>> a.concatenate((a,b)) # 将二维数组和三维数组进行连接会报错
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: all the input arrays must have same number of dimensions
    >>> a = np.concatenate((a,b))
    >>> a
    array([[[1, 2],
            [3, 4]],
    
           [[5, 6],
            [7, 8]]])
    

opencv写如视频时的报错

  • cv2.error: OpenCV(3.4.2) /opt/concourse/worker/volumes/live/9523d527-1b9e-48e0-7ed0-a36adde286f0/volume/opencv-suite_1535558719691/work/modules/videoio/src/cap_ffmpeg.cpp:296: error: (-215:Assertion failed) image.depth() == 0 in function 'write'
  • 一个github中相关的issue
  • 这里出现的问题depth像素深度的问题。像素深度与通道数不同,指的是每一个像素用多少位来编码。

文件大小问题

  • 文件大小和占用磁盘空间是不同的,占用磁盘空间往往比文件大小要大。
  • Linux上查询文件大小的命令是ls -lh filename,也可以使用ls -lht查看当前目录下所有文件的大小
  • 查询文件占用空间的命令是du -hs filename,其中h代表human-readable即输出带有KB、MB、GB单位的大小,否则输出一个没有单位的数字。注意参数顺序,如果先打s再打h则会忽略h。

视频文件格式、视频封装格式、视频编码方式的区别

  • 视频封装格式对应着容器这一个比较抽象的概念,还需进一步理解。
  • image

FOURCC常用编码器

CV_FOURCC('P','I','M','1') = MPEG-1 codec
CV_FOURCC('M','J','P','G') = motion-jpeg codec
CV_FOURCC('M', 'P', '4', '2') = MPEG-4.2 codec
CV_FOURCC('D', 'I', 'V', '3') = MPEG-4.3 codec
CV_FOURCC('D', 'I', 'V', 'X') = MPEG-4 codec
CV_FOURCC('U', '2', '6', '3') = H263 codec
CV_FOURCC('I', '2', '6', '3') = H263I codec
CV_FOURCC('F', 'L', 'V', '1') = FLV1 codec

opencv的videowriter只能输出.avi,如果在指定输出文件名时出现后缀.mp4等则会报错,改为.avi即可*

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented May 15, 2019

2019.5.15工作日志

预测与决策

  • stack overflow的回答Frank Harrel的博客
  • 问题首先出现在多标签分类时
  • 网络的目标是减小loss,在交叉熵函数里面让标签为0的输出值更接近0,标签为1的输出值更接近1,选用0.5作为衡量准确率的阈值也是因为0.5是0和1中间的数字,输出的值并非概率值
  • 那么设定为0.5究竟是否合理呢?

神经网络和概率

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented May 16, 2019

2019.5.16工作日志

python写入excel

  • Python向excel中写入数据

  • 其实就是将每行数据写入列表中,按行写入表格

    from openpyxl import Workbook
    wb = Workbook()
    ws = wb.create_sheet("aaa")
    buffer = [0, 1, 2, 3, 4]
    ws.append(buffer) # 在sheet中写入一行
    wb.save("data.xlsx") # 保存表格
    
  • 这里要注意,如果从文本中截取数字并写入文件,写入之前最好将数字部分强制转换为int型,否则导入excel中表面上看着没有问题,但无法作图。将错误数据复制到sublime中可以看到,每个数字还带了两个引号。
    image

  • 如果要向已有表格中添加sheet则需要使用如下语句

    from openpyxl import load_workbook
    
    wb = load_workbook("data.xlsx")
    ws = wb.create_sheet("bbb")   # 将在原有表格内创建新的sheet
    ···
    wb.save("data.xlsx")
    

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented May 18, 2019

2019.5.17工作日志

各类卷积核

python读写.dat文件

下表为struct.pack的第一个参数的可选项
image

  • python写.dat文件
    import struct # 使用struct模块
    
    data = 0x00000000
    
    with open('sample_struct.dat', 'wb') as f: # 打开要写的文件,打开方式为'wb',write binary
        sn=struct.pack('B', data) # 写入的关键语句,第一个参数为存储类型,具体见上表;第二个参数为存储数据
        f.write(sn) 
    
  • python读.dat文件
    with open('sample_struct.dat', 'rb') as f: # 打开要写的文件,打开方式为'rb',read binary
        sn = f.read(1) # 这里的数字代表读出数据要预留的buffer大小,根据二进制文件中存储的数据类型对应相应的大小,可在上表中查出
        data = struct.unpack('B', sn)
    

@NarcissusInMirror
Copy link
Owner Author

2019.5.21工作日志

毕设相关工作,查重报告、评分表签字

opencv中修改图片大小

h,w,depth=img.shape
img=cv2.resize(img,(int(w/2),int(h/2)),interpolation=cv2.INTER_AREA) # 交换height和width的顺序

其中,interpolation参数代表所使用的插值方法,其选项如图所示
image

视频编解码

@NarcissusInMirror
Copy link
Owner Author

2019.5.22工作日志

  • python文件读写参数选项表:
    Screenshot 2019-05-22 at 15 14 37

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented May 24, 2019

2019.5.24工作日志

不小心执行了rm -f,除了跑路,如何恢复?

Screenshot 2019-05-24 at 10 18 23

@NarcissusInMirror
Copy link
Owner Author

@NarcissusInMirror
Copy link
Owner Author

2019.5.29工作日志

  • python中在写文件时如果不把句柄关掉,f.close(),使用os.path.getsize()得到的文件大小不是最终的文件大小。例如预期得到的文件大小为72000byte,如果在关掉句柄之前就读文件,得到的大小会小于72000

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented May 30, 2019

2019.5.30工作日志

  • 通过python脚本将txt文本中的数据导入excel中,出现无法作图的现象,原因见5.16工作日志

C++读写二进制文件

  • 定义文件句柄,使用.open函数设定相关参数。
  • 与python中不同,c++中需要自己定义数组作为缓冲区
  • 写文件时使用out.write()函数,参数的意义在下面代码的注释中
  • 读写二进制文件的核心在于每次操作一个字节,不关心数据类型,关注点在大小上,这也是为什么任何指针都可以被强制转换成char型指针。char型指针每次增加一个字节的地址大小,即8位。
#include <iostream>
#include <fstream>     //读写文件要包含的头部
using namespace std;

int main()
{
    unsigned char a[8] = {0, 255, 52, 53, 54, 55, 56, 57};  //写文件的buffer
    unsigned char b[8]; //读文件的buffer
    
    // 写文件
    ofstream ouF;
    ouF.open("./me.dat", std::ofstream::binary); //第二个参数是读写二进制文件的关键
    ouF.write(reinterpret_cast<const char*>(a), sizeof(int) * 2); 
    // 第一个参数是将指针强制转换成char型的,我的理解是读取二进制数据时需要每次读一个字节,
    // 指针自加时每次增加一个字节。
    // 第二个参数是读出的字节数,填数字即可,这里sizeof(int)*2和8是等价的,即读出八个字节
    ouF.close();
    
    // 读出文件
    ifstream inF;
    inF.open("./me.dat", std::ifstream::binary);
    int counter = 0;
    
    char * c = reinterpret_cast<char*>(b); // 将指针转换为char型
    
    // 下方的条件用以判断是否读到文件末尾。使用!inF.eof()会导致多读一个字节,原因不明。
    while(inF.peek() != EOF)  
    {
        inF.read(c, sizeof(unsigned char) * 1); //每次读出一个字节到数组b中
        cout<<counter<<endl; 
        cout<<c<<endl; //打印出指针所指地址的值,即当前读出的字节
        counter ++; 
        c ++ ; //指针自加
    }

    inF.close();
    return 0;

}

Python中调用C++代码

  • C++代码其实很难调用,原因大概是,编译的标准有很多,与python的接口标准也有很多,在编译时也有很多选项。因此很容易造成各种不统一。
  • 下面是参考这篇博客的方法进行的一次实践
    • 在cpp代码中加入c的wrapper:
      //测试发现,如果不加入wraper,在python程序中只能找到主函数int main()且不能有任何参数
      //楷神说这就是接口标准之类的一系列问题导致的,main函数可以找到是因为这是程序的入口,所以有一个标准的规定,其他函数就不一定了(大概是这意思,回头再改)
      extern "C"
      {
          void compress_data(char * read_path, char * write_path);//需要在python中调用的函数的声明
      }
      
    • 将cpp文件编译成动态库,生成.so文件调用
      # 在mac上可以使用以下两行代码,在linux上好像参数W1得改成Wl(小写的l)这个实在是有点扯,1和l也太像了,怎么会挑这么两个相似的参数
      $ g++ -c -fPIC foo.cpp -o foo.o
      $ g++ -shared -W1, -soname, foo.so -o foo.so foo.o
      # 或者使用如下命令
      $ g++ foo.cpp -shared -o foo.so
      # 也有可能要添加一个参数
      $ g++ -fPIC foo.cpp -shared -o foo.so
      
    • 在python文件中需要包含如下代码,ctype的官方文档注意要看python3版本的!!!
      import ctypes
      
      lib = ctypes.cdll.LoadLibrary("./foo.so")
      lib.compress_data.argtypes = [ctypes.c_char_p, ctypes.c_char_p] //这里把调用的C++函数的参数列表的类型改成ctype的相关类型,具体对应关系见官方文档
      lib.compress_data(ctypes.c_char_p('./original/sample_struct_0.dat'.encode("ASCII")), ctypes.c_char_p('./simple.dat'.encode("ASCII"))) //调用函数,这里需要使用相应的函数包裹一下参数才行,不然会有typeerror;.encode("ASCII")没有也可以正常运行
      
      

@NarcissusInMirror NarcissusInMirror changed the title 2019年5月 2019年5月&6月 Jun 3, 2019
@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Jun 3, 2019

2019.6.3工作日志

阅读论文 CBAM: Convolutional Block Attention Module

C++的编译过程

@NarcissusInMirror
Copy link
Owner Author

2019.6.6工作日志

pytorch中torch.nn和torch.nn.functional的区别

  • nn.functional.xxx是函数接口,而nn.Xxx是nn.functional.xxx的类封装,并且nn.Xxx都继承于一个共同祖先nn.Module。这一点导致nn.Xxx除了具有nn.functional.xxx功能之外,内部附带了nn.Module相关的属性和方法,例如train(), eval(),load_state_dict, state_dict 等。

  • 可以参考知乎pytorch的官方社区上的解释

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Jun 10, 2019

2019.6.10工作日志

python中__all__的作用

  • 对于模块example.py,如果在模块内定义了__all__则当example.py被其他文件使用from example import *导入时,只导入__all__中定义的对象。
  • 只在使用from example import *时有影响,不影响使用其他导入语句正常导入
    image

pytorch.nn.ReLU函数中inplace参数的意义

image
image

@NarcissusInMirror
Copy link
Owner Author

2019.6.13工作日志

word中目录的操作

  • 自动生成的目录有的标题没包含上怎么办
  • 首先点击视图→侧栏→导航,会出现侧栏,里面的获取的标题就是目录中会出现的标题且实时更新,这样会提高修改效率。
  • word本质上还是通过标题格式来识别标题的,如果有某个标题怎么也包含不上,就用格式刷刷一下可以被识别的标题,复制一下格式,一般就可以了

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Jun 20, 2019

2019.6.29工作日志

Python中的 // 操作符

Python3中 /直接是浮点运算,//代表整型运算,即对结果进行flooring操作。而在Python2/中默认是整型运算,除非其中的一个操作数为浮点数

屏幕快照 2019-06-20 14 17 00

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Jun 21, 2019

2019.6.21工作日志

Pytorch 实战总结

输入数据维度:(sample_size, 25)
标签:(sample_size)

CrossEntropyLoss

image
可以看到,要求的输入维度形状,即output = model.forward(input_data)output的形状为(批大小,分类个数 ),维度为2;输入的标签维度应为(批大小,),维度为1,且以0~N-1代表N个类别,不接受二维的one-hot编码,这些需要在进行数据处理时注意。

BatchNorm1d

image
image

1d的batchnorm输入的向量是2维或者3维的,即(批大小,特征维数)(批大小,通道数,特征维数)。当输入为2维时features参数为特征维数;当输入为3维时,features参数为通道数。但实际上都是沿着channel的维度进行的batchnorm。

BatchNorm2d

image
image

顺带学习一下2d的batchnorm。batchnorm2d的输入必须是4维的,(批大小,通道数,图像高度,图像宽度),num_features为通道数。

batch1d又称为temporal batchnorm, batch2d又称为spatial batchnormal

image
image

numpy axis选择

以np.mean(nparray, axis)为例

>>> a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9], [10, 11, 12])
>>> a
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])
>>> a.shape
(4, 3)
>>> np.mean(a, axis=0)
array([5.5, 6.5, 7.5])
>>> np.mean(a, axis=1)
array([ 2.,  5.,  8., 11.])

以axis=0为例,a.shape=[4, 3]四行三列,当选择axis=0时,即选中4,求平均时则求的是4个元素的平均,即按列平均。同理,axis=1时,选中3,求平均时则求的是三个元素的平均,即按行平均。

torch.max 返回值和索引

torch.max(input, dim, keepdim=False, out=None) -> (Tensor, LongTensor)

>>> a = torch.randn(3,3)
>>> a
-0.7845 -1.7758 -1.5602
 1.9941 -1.2037 -0.2332
 0.1480 -0.0921  0.4939
[torch.FloatTensor of size 3x3]

>>> torch.max(a)
1.9940658807754517

>>> torch.max(a,0)
(
 1.9941
-0.0921
 0.4939
[torch.FloatTensor of size 3]
,
 1
 2
 2
[torch.LongTensor of size 3]
)

pytorch Variable的detach和detach_

先占个坑,本次实验中,需要把forward后的向量转成numpy数组进行一些操作,而输入的tensor经过了如下操作,大概是改为gpu向量,具体还需了解,回头补上。

data, label = data.cuda(), label.cuda()
data, label = Variable(data), Variable(label)
optimizer.zero_grad()
output = model.forward(data)

因此进行操作前需要先detach出来并且放到cpu中output = output.detach().cpu()

scipy的softmax

image

from scipy.special import softmax
output = softmax(output, axis=1)

存储和加载模型

image

存储:

torch.save(model, PATH),model为定义过的nn.Module的子类模块

加载:

model = torch.load(PATH)
model.eval()

Adaptive AvgPool2d

image

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Jun 25, 2019

2019.6.25工作日志

Linux的Tee命令

Lniux tee 命令
image
遇到如下场景:
在调试神经网络代码过程中,需要打印出网络中各处的向量形状,但是由于每个epoch都会重复打印,会占据屏幕大量位置,使得训练结果被隐藏。使用如下命令,将形状信息写入result.txt中,同时将含有关键字epoch的行打印在屏幕上。

python test.py | tee result.txt | grep epoch

pytorch——resnet

image

Resnet源码里有两个类,分别是BasicBlockBottleneck类,其中BasicBlock对应着图中Resnet-18和Resnet-34中的含有两个卷积层的模块;Bottleneck类对应着图中Resnet-50、Resnet-101和Resnet152中的含有三个卷积层的模块。

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Jun 26, 2019

2019.6.26工作日志

Affine Transformation 仿射变换

image
简单的说,仿射变换就是:
image

@NarcissusInMirror
Copy link
Owner Author

2019.6.27工作日志

用Python将list中的string转换为int

@NarcissusInMirror
Copy link
Owner Author

2019.6.28工作日志

对于最小二乘法的思考

@NarcissusInMirror NarcissusInMirror changed the title 2019年5月&6月 2019年5月-7月 Jul 1, 2019
@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Jul 1, 2019

2019.7.1工作日志

Python 列表元素替换

在准备数据中遇到的相关问题

任务描述如下:共有50个包含不同图片数量的文件夹,目标是大致将文件夹均分为5份,并且移动到五个文件夹内。拆分后任务可分为

  1. 获得每个文件夹的大小和文件夹内文件的数目
  2. 将文件夹按大小分组(尽量均分)
  3. 将分组后的文件夹移动至相应五个文件夹下

任务1 使用os模块中的相应函数即可

num_list = os.listdir(PATH)
file_num = len(num_list)

任务2 使用如下算法进行均分
Python List sort()方法

num_list = [...] # 所有文件夹内包含的数目,共50个元素
num_list.sort(reverse=True)

gourps = 5 # 分为5组

load_balance_groups = [[] for grp in range(groups)] # 构建一个有五个空列表元素的列表

for v in num_list:
    load_balance_groups.sort(key=lambda x: sum(x)) # 分别计算五个列表内元素的和并进行排序
    load_balance_groups[0].append(v) # 向最小的列表中加入目前最大的元素

for per in load_balance_groups:
    print(sum(per))

任务3 要实现通过代码进行文件夹的移动,则需要使用字典进行对数值和文件夹名的映射,并且要解决一对多的问题,即若干个文件有相同的大小,一个键(文件数目)对应了多个值(文件夹)。这里使用如下方法进行了解决,参考:Python 字典的一键多值,即一个键对应多个值Python 字典(Dictionary) setdefault()方法

# 首先获得文件数目-文件夹名称的字典
for file in file_list:
    num = len(img_list)
    file_dict = {}
    # 字典的setdefault()方法dict.setdefault(key, default=None),给定key,返回该键对应的值,如果该键不存在则返回default设置的值,并添加键值对key-default,在这里即通过这一方法进行键值对的添加,并且应对了一对多的问题
    file_dict.setdefault(num, []).append(file) 

# 接下来将load_balance_groups中五个列表里的数目替换成对应的文件夹名称
for index, i in enumerate(load_balance_groups):
    for x in i:
        file_name = file_dict[x][0]  # 字典里的每一个值都是列表,取列表中的第一个值
        del file_dict[x][0] # 删除掉已经被检索到的文件夹名,防止出现重复
        print(file_name)
        rep_groups[index].append(file_name)

关于局部变量的理解&栈&栈帧

image
image

  • 图中的空间是系统栈空间,代码空间则是存储代码的内存段,对应着下面参考链接中的text段

  • 程序运行时的内存空间分布

    • 内存中有若干段,程序代码是被存放在text段中的
  • 栈帧:一个函数执行时在栈中开辟的空间
    函数内的局部变量存在在该函数的栈帧中,在函数调用结束后就会释放。

  • 如何正确理解栈和堆?

    • 这篇文章虽然写得乱七八糟,但是几张图还是比较形象的
      image对于基本数据类型来说,变量是被在栈中分配内存的,对于如下代码,上图可以解释内存分配的情况,a和b在栈中有独立的内存,因此改变b不会对a造成影响,字符串也是被分配在栈中的(存疑)
      >>> a = 10
      >>> b = a
      >>> b += 10
      >>> a
      10
      >>> b
      20
      
      imageimage
      而对于数组等对象则是在堆中开辟内存空间,在栈中存放相应的堆地址。
      >>> a = []
      >>> b = []
      >>> b.append('a')
      >>> b
      ['a']
      >>> a
      ['a']
      

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Jul 5, 2019

2019.7.5工作日志

十大高明的Google搜索技巧

@NarcissusInMirror
Copy link
Owner Author

2019.7.9工作日志

恢复在VNC中删除的文件

VNC中删除的文件都没有被真正删除,而是被放在了目录~/.local/share/Trash/files
进入目录后通过正则表达式匹配需要恢复的文件,例如今天误删了开头为C0102153的若干张图片,使用命令mv C0102153* /home/qiushuhao/recover即可将当前目录下所有开头为C0102153的文件移动到/home/qiushuhao/recover目录下。

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Jul 18, 2019

2019.7.18工作日志

关于图片坐标表示

  • YOLO分割中得到的四元数组是(boundbox中心x坐标,boundbox中心y坐标,boundbox x轴上长度,boundingbox y轴上长度)
    假设boundbox中心的位置是(100,200),即矩阵的100行,200列,这里要注意的是,100对应的是y坐标,而200对应的是横坐标,而非反过来,因为100在前面认为100是横坐标。

  • PIL中的矩形框的表示
    (left, top, right, bottom) 这里不能按照数组的方式进行理解,例如(left, top)这一点中,left是x轴坐标,top是y轴坐标,但如果对应到数组索引中,则这一点对应的则是[top行, left列]
    image

在Linux中重命名

使用mv a.jpg b.jpga.jpg改名为b.jpg
使用mv a.jpg ./images/b如果images目录下存在b目录,则命令表示将a.jpg移动到b目录下,如果不存在b目录,或b为一个文件,则将a移动到images且改名为b,替换掉原来的b文件。

easydict

image

pathlib

This module offers classes representing filesystem paths with semantics appropriate for different operating systems.
可以通过/运算符进行路径的拼接

>>> from pathlib import Path
>>> father_path = Path('data')
>>> sub_path = 'image'
>>> father_path / sub_path
PosixPath('data/image')
>>> father_path
PosixPath('data')

module.eval()

    def eval(self):
        """Sets the module in evaluation mode.

        This has any effect only on modules such as Dropout or BatchNorm.
        """
        return self.train(False)

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Jul 19, 2019

2019.7.19工作日志

如何在服务器上自己起一个jupyter的端口(没有root权限)

输入命令:$ jupyter notebook --no-browser --port=9999 --ip='*' [--allow-root]
会返回一个地址http://localhost:10000/?token=255f60f4ab56f391b40fdda50ac1970736e091d86fd7f97a
http://localhost改为服务器的ip即可,例如10.106.128.96:10000/?token=255f60f4ab56f391b40fdda50ac1970736e091d86fd7f97a

即不想保存jupyter日志,又需要看一下token,可以使用tee命令:
nohup jupyter notebook --no-browser --port=9999 --ip='*' | tee /dev/null &

如何在jupyter notebook中添加kernel

参考1
参考2
参考3
运行find . -name “kernel.json”会得到以下结果

/home/lixie/.local/share/jupyter/kernels/python3/kernel.json
/home/lixie/anaconda3/envs/py35_1/share/jupyter/kernels/python3/kernel.json
/home/lixie/anaconda3/pkgs/ipykernel-5.1.1-py37h39e3cac_0/share/jupyter/kernels/python3/kernel.json
/home/lixie/anaconda3/pkgs/ipykernel-5.1.1-py37h39e3cac_0/share/jupyter/kernels/py35/kernel.json
/home/lixie/anaconda3/share/jupyter/kernels/python3/kernel.json
/home/lixie/anaconda3/share/jupyter/kernels/py35/kernel.json

其中最后两行是关键部分,在/home/lixie/anaconda3/share/jupyter/kernels/中创建虚拟环境对应的文件夹,在其中创建kernel.json文件,文件内容为,

{
 "argv": [
  "/home/lixie/anaconda3/envs/py35/bin/python",       #python路径
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ],
 "display_name": "py35",   # 在notebook显示的名字
 "language": "python"
}

编辑完成后打开jupyter notebook可以看到新增的kernel,但是无法连接,因为虚拟环境下没有安装ipython kernel,运行命令

$ conda activate lcyVenv          
$ pip install ipykernel  
$ ipython kernel install --user 

如果是系统自带的python,运行上面最后一条命令会报错,应选择下述命令

$ python2 -m pip install ipykernel
$ python2 -m ipykernel install --use

即可。
注意:

  • 虚拟环境影城不能与根用户的虚拟环境名相同,否则会报错
  • 实际编辑时不能包含注释!!!!
  • centos7系统自带python的位置为/usr/bin/python2

centos 7 firewall(防火墙)开放端口/删除端口/查看端口

centos需要打开防火墙,打开特定端口,否则通过上述网址无法访问。(本机可以访问本机的端口,其他机器是不能随意访问端口的,也就是说,如果是在服务器上打开浏览器是可以访问上述地址的,但是远程登录访问主机,如果没有提前将端口开放,是无法访问的)

firewall-cmd --zone=public --add-port=9999/tcp --permanent
firewall-cmd --reload

jupyter notebook没有python3的kernel

运行以下两条命令即可:
image

@NarcissusInMirror
Copy link
Owner Author

rpm: Red hat Package Manager 是给centos用的!!!!

apt install 是给ubuntu用的

nohup python -u python_file.py &会默认在当前目录下生成一个nohup.out文件
使用tail -f filename实时显示文件

os.environ["CUDA_VISIBLE_DEVICES"] = "0, 1, 2"这句话只是设置了最多可以用的GPU数,要想实现多GPU并行还是需要写出相应的代码的。

@NarcissusInMirror
Copy link
Owner Author

  • python -u

@NarcissusInMirror
Copy link
Owner Author

  • 错误arguments are located on different GPUs:把CUDA_VISIBLE_DIVICES改为一块即可
  • 错误got an unexpected keyword argument "serialized_options",issue地址
    image

@NarcissusInMirror
Copy link
Owner Author

@NarcissusInMirror
Copy link
Owner Author

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Sep 12, 2019

2019.9.11工作日志

  • 配置鼎桥的服务器
    centos 7 网络配置( 网关、dns、ip地址配置)
    服务器有两块网卡 对应的主机上有两个接口 网线插在那个接口上就配置那块网卡
    image
    添加 nameserver 114.114.114.114 DNS服务器,否则无法解析域名,只能识别IP地址(只能pingIP地址)

  • 9.12更新:
    发现修改配置文件不起作用,需要手动给网卡设置ip地址

$ ip address add 10.106.130.66/21 dev eno2 # 设置网卡eno2的ip地址为10.106.130.66,子网掩码21位
$ ip route add default via 10.106.129.1 dev eno2# 设置默认网关为10.106.129.1
$ ip route del default via 10.106.129.1 # 删除默认设置 
$ ip route add default via 10.106.130.1 # 设置默认网关为10.106.130.1
$ ip route del default via 10.106.130.1 # 删除默认设置 
$ ip route add 10.0.0.0/8 via 10.106.128.1 dev eno2

以上的命令中运行完前两条就可以上网并且使用ssh了

$ ip address add 10.106.130.66/21 dev eno2 # 设置网卡eno2的ip地址为10.106.130.66,子网掩码21位
$ ip route add default via 10.106.129.1 dev eno2# 设置默认网关为10.106.129.1
$ ip route add 10.0.0.0/8 via 10.106.128.1 dev eno2 # 访问10.0.0.0网段的地址走10.106.128.1路由

如果后两句颠倒会出现network unreachable的情况

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Sep 16, 2019

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Sep 17, 2019

Centos 安装mmpeg

sudo yum install epel-release -y
sudo yum update -y
sudo shutdown -r now # 重启生效

sudo rpm --import http://li.nux.ro/download/nux/RPM-GPG-KEY-nux.ro
sudo rpm -Uvh http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-5.el7.nux.noarch.rpm

sudo yum install ffmpeg ffmpeg-devel -y

image

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Sep 19, 2019

配置安装opencv2.4.13

cmake ../ -DCMAKE_BUILD_TYPE=RELEASE \
          -DCMAKE_INSTALL_PREFIX=/usr/local \ 
          -DBUILD_TIFF=ON \
          -DWITH_CUDA=ON \
          -DENABLE_FAST_MATH=1 \
          -DCUDA_FAST_MATH=1 \
          -DWITH_CUBLAS=1 \
          -DWITH_FFMPEG=1 \
          -DINSTALL_C_EXAMPLES=OFF \
          -DCUDA_GENERATION=Kepler \
          -DBUILD_opencv_cudacodec=OFF \
          -DENABLE_PRECOMPILED_HEADERS=OFF

CMake Error: The following variables are used in this project, but they are set to NOTFOUND. Please set them or make sure they are set and tested correctly in the CMake files: opencv_dep_CUDA_nppi_LIBRARY

解决办法:修改FindCUDA.cmake, OpenCVDetectCUDA.cmake, common.hpp文件中的内容
下图中的内容可以不用改,由于版本原因在文件里可能找不到对应的语句
image

按照以上方法,cmake可以通过,但是make会报错nvcc fatal unsupported gpu architecture 'compute_20' opencv
解决办法:清空build文件夹,重新cmake,添加参数-DCUDA_GENERATION=Kepler

在68%左右出现fatal error: dynlink_nvcuvid.h: No such file or directory
解决方法
image

编译caffe

make: protoc: Command not found

image

跑验证程序 Check failed: error == cudaSuccess (209 vs. 0) no kernel image is available

解决办法

在Makefile.config文件中,将这一段代码

CUDA_ARCH := -gencode arch=compute_20,code=sm_20 \
             -gencode arch=compute_20,code=sm_21 \
             -gencode arch=compute_30,code=sm_30 \
             -gencode arch=compute_35,code=sm_35 \
             -gencode arch=compute_50,code=sm_50 \
             -gencode arch=compute_52,code=sm_52 \
             -gencode arch=compute_61,code=sm_61

替换为如下代码

CUDA_ARCH := -gencode arch=compute_30,code=sm_30 \
             -gencode arch=compute_35,code=sm_35 \
             -gencode arch=compute_50,code=sm_50 \
             -gencode arch=compute_52,code=sm_52 \
             -gencode arch=compute_60,code=sm_60 \
             -gencode arch=compute_61,code=sm_61 \
             -gencode arch=compute_61,code=compute_61

彻底删除numpy:

运行pip uninstall numpy,报错Cannot uninstall 'numpy'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

解决方法:从/usr/lib64/python2.7/site-packages中将包含numpy的文件夹全部删除即可

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Sep 22, 2019

2019.9.22工作日志

在anaconda中配置python2.7的虚拟环境,可以直接import caffe,除了以下问题:
ImportError: No module named google.protobuf.internal
解决方法见网址
image
此处的/home/username/anaconda3/bin/pip是指定pip命令的位置

@NarcissusInMirror
Copy link
Owner Author

标准 文件 下载

中国通信标准化协会
image
上边栏中选“技术标准”
image

@NarcissusInMirror
Copy link
Owner Author

“OpenCV” is considered to be NOT FOUND
报错:

CMake Warning at /usr/local/opencv-2.4.13/cmake/OpenCVConfig.cmake:163 (message):
  Found OpenCV Windows Pack but it has not binaries compatible with your configuration.

  You should manually point CMake variable OpenCV_DIR to your build of OpenCV library.
Call Stack (most recent call first):
  CMakeLists.txt:57 (find_package)


CMake Warning at CMakeLists.txt:57 (find_package):
  Found package configuration file:

    /usr/local/opencv-2.4.13/cmake/OpenCVConfig.cmake

but it set OpenCV_FOUND to FALSE so package "OpenCV" is considered to be NOT FOUND.

解决方法是在cmake命令加上参数 -D
cmake -D OpenCV_DIR=/usr/local/opencv-2.4.13/build/ ..

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Oct 14, 2019

caffe训练问题记录

  • train_val.prototxt和solver.protxt的区别
    image
  • resize图片的方法
    image
  • data layer中
    mirror=True表示会随机镜像翻转图片

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Oct 15, 2019

2019.10.15工作日志

caffe .solverstate文件的使用

我们在使用caffe训练过程中会生成.caffemodel和.solverstate文件,一个是模型文件,一个是中间状态文件(生成多少个取决于你自己设定的snapshot)。当训练过程中断,你想继续运行数据学习,此时只需要调用.solverstate文件即可。

./build/tools/caffe train \
     --solver=examples/test/solver.prototxt --snapshot=examples/test/test_100000.solverstate

caffe solver.prototxt文件中test_interval 和test_iter的作用
test_interval 的值表示训练多少个iteration进行一次测试,test_iter的是一次测试进行多少次迭代,意思是每次测试使用test_iter * val_batch_size张验证集的图片进行测试。

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Oct 18, 2019

2019.10.17

  • 重新编译caffe步骤
$ make clean
$ make -j32
$ make test -j32

在鼎桥的机器上j可以取到32,但偶尔会报错,改为16或8即可

/home/qiushuhao/caffe下修改了CAFFEROOT/src/caffe/layers/sigmoid_cross_entropy_loss_layer.cpp
image
解决了loss没有除以标签数的问题。

因为是Adam是继承的SGD,所以输出信息里看到的输出是从sgd.cpp输出的
image

@NarcissusInMirror
Copy link
Owner Author

2019.10.21

关于nohup重定向到指定文件

image

MobilenetV2训练总在特定iteration loss变为NaN

这个issue解决了问题,是batchnorm层的问题

@NarcissusInMirror
Copy link
Owner Author

@NarcissusInMirror
Copy link
Owner Author

2019.11.5

caffe训练时先看一下测试有没有内存问题,如果测试batchsize过在测试阶段报错

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Nov 12, 2019

2019.11.12

Centos安装MATLAB R2017b

参考(CSDN)
参考(简书)

下载Linux版的MATLAB,下载后目录内容如下

屏幕快照 2019-11-12 19 00 27

crack解压后内容如下图

屏幕快照 2019-11-12 19 00 33

创建挂载点,用以挂载安装盘(ISO镜像文件)

$ mkdir -p /mnt/cdrom

挂载镜像,挂在后在/mnt/cdrom目录下会有一些文件生成

$ mount -o loop R2017b_glnxa64_dvd1.iso /mnt/cdrom

复制出activate.iniinstaller_input.txt文件到/home/MATLAB_R2017b_Linux/

$ cp /mnt/cdrom/activate.ini .
$ cp /mnt/cdrom/installer_input.txt .

修改复制出来的installer_input.txt文件(去掉对应注释),会提示是只读文件,保存时用:wq!即可

fileInstallationKey=09806-07443-53955-64350-21751-41297(具体key找自己的crack包)
agreeToLicense=yes
mode=silent

安装

$/mnt/cdrom/install -inputFile /home/MATLAB_R2017b_Linux/installer_input.txt
安装完成后提示插入第二张盘

另外打开一个终端,弹出dvd1的挂载点,挂载第二块镜像,挂在成功后第一个终端立即开始安装

$ umount /mnt/cdrom
$ mount -o loop R2017b_glnxa64_dvd2.iso /mnt/cdrom

第一个终端继续安装,在第二个终端中编辑activate.ini文件

activateCommand=activateOffline
licenseFile=/home/MATLAB_R2017b_Linux/license_standalone.lic
activationKey=09806-07443-53955-64350-21751-41297

安装成功后,会提示successful

替换破解文件

$ cp /home/MATLAB_R2017b_Linux/Crack/libmwservices.so /usr/local/MATLAB/R2017b/bin/glnxa64/

对于2015b,替换步骤为
$ cp /[Your crack directory]/Matlab_R2015b/Matlab_2015b_Linux64_Crack/R2015b/bin/glnxa64/* /usr/local/MATLAB/R2015b/bin/glnxa64

激活

$ /usr/local/MATLAB/R2017b/bin/activate_matlab.sh -propertiesFile /home/MATLAB_R2017b_Linux/activate.ini

配置环境变量

vim /etc/profile
在底部添加
export PATH=$PATH:/usr/local/MATLAB/R2017b/bin

测试

$ matlab

扩容分区

vim /etc/fstab
/dev/mapper/centos-home /home xfs defaults 0 0注释掉
reboot

$ sudo lvremove /dev/mapper/centos-home # 删除/home所在的逻辑卷
$ sudo lvextend -L +1T /dev/mapper/centos-root # 增加1T
$ xfs_growfs /dev/mapper/centos-root # 扩大文件系统

Centos卸载MATLAB R2017b

$ rm -rf /usr/local/MATLAB即可

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Nov 13, 2019

2019.11.13

caffe编译matlab接口

Makefile.config文件中添加matlab的路径:
MATLAB_DIR := /usr/local/MATLAB/R2015b #到这一级即可
在Makefile文件中的CXXFLAGS += -MMD -MP下添加CXXFLAGS += -std=c++11

make -j8
make matcaffe

caffe的matlab接口编译错误

背景:编译caffe通过,matcaffe也可以通过,但是mattest不通过
报错情况类似于这个issue
按照下图修改后,会报出类似libstdc++.so.6: version GLIBCXX_3.4.20 not found的错误,
image

  • 上图中的操作解决的问题是,编译caffe使用的libstdc++.so库和安装matlab时matlab指定的libstdc++.so库版本不一致,所以无法调用caffe,通过修改后让matlab使用和caffe一样的库,从而解决问题。
  • 按照上图修改后报另一个错误是因为,MATLABR2017b使用的gcc编译器版本高于编译caffe时使用的,而系统gcc版本是不能随便修改的,因此只能选择修改MATLAB的版本,改为R2015b后问题解决此报错(但make mattest还有其他错误)
  • matlab版本支持的gcc版本见链接

在命令行中运行matlab程序

$ matlab -nodisplay -nosplash -nodesktop -r "run('path/to/your/script.m');exit;"
-r后的字符串里是需要执行的命令,以;隔开即可

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Nov 14, 2019

2019.11.14

Multi-GPU execution not available - rebuild with USE_NCCL

解决方法

  1. 在用户目录下运行$ git clone https://github.com/NVIDIA/nccl
  2. 编译$ cd nccl && make -j src.build
  3. Makefile.config中添加,位置如下
    image
    USE_NCCL := 1
    INCLUDE_DIRS += /home/qiushuhao/nccl/build/include
    LIBRARY_DIRS += /home/qiushuhao/nccl/build/lib
    
  4. 确保Makefile中包含
    image
  5. 重新编译即可$ make clean && make -j8

OpenCV Docker error "ImportError: libSM.so.6: cannot open shared object file: No such file or directory"

apt install libsm6 
apt install libxrender-dev

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Nov 18, 2019

2019.11.18

ipython notebook主题背景颜色更改

$ pip install --upgrade jupyterthemes
$ jt -l
Available Themes:
   chesterish
   grade3
   monokai
   oceans16
   onedork
   solarizedd
   solarizedl
$ jt -t 主题名称 #更换主题
$ jt -r # 恢复默认

caffe添加新的层

  1. 将cosin_add_m_layer.hpp拷贝到目录: ./caffe/include/caffe/layers/下
  2. 将cosin_add_m_layer.cpp 、 cosin_add_m_layer.cu 拷贝到目录: ./caffe/src/caffe/layers/下
  3. 根据proto文件,对应修改./caffe/src/caffe/proto/caffe.proto文件
    proti文件中有两处需要修改,一处是开头层的声明,另一处是层的结构体定义
    以以上为例
message LayerParameter
{
  /*****************************************
  *add this*
  ******************************************/
  optional AdaCosAddmScaleParameter adacos_add_m_scale_param = 211;
}

message AdaCosAddmScaleParameter {
  optional float m = 1 [default = 0.5];
  optional float num_classes = 2 [default = 8750];
  optional bool transform_test = 3 [default = false];
}

显示两个目录下文件的差异

$ yum install tree
$ diff <(tree -Ci --noreport /path/to/dir1) <(tree -Ci --noreport /path/to/dir2) # <和(之间没有空格

<代表的行是directory1中有而directory2没有的文件,>则相反,是directory2中有而directory1中没有。

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Nov 24, 2019

2019.11.24

VScode 下对python代码debug配置

  • 首先,对于服务器上每个用户都需要安装python插件才能进行debug
  • 安装Remote -SSH插件,在左侧边栏中找到相应图标,添加ssh连接,连接成功后会自动打开新窗口
  • 点击上边栏Debug > Open Configuration,选择Python file,会在.vscode文件夹下生成launch.json文件
  • 默认生成配置如下
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [

        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "cwd" : ""${workspaceFolder}" //代码运行位置
        }

    ]
}
  • 上述文件配置选项详解见链接
  • 建立ssh连接打开新窗口后,可能会询问添加python解释器,选择后会在.vscode文件夹下生成settins.json,内容如下
{
    "python.pythonPath": "/root/miniconda3/envs/retina_face/bin/python"
}
  • 设置args的时候记得将参数选项和参数值分开,如
{
    "args" : ["--init_checkpoint", "license-plate-recognition-barrier-0007/model.ckpt",  "--path_to_config",  "chinese_lp/config.py"]
}

@NarcissusInMirror
Copy link
Owner Author

2019.11.27

Centos修改时区(时间)

@NarcissusInMirror
Copy link
Owner Author

2019.12.5

修改vmnet8的默认ip网段 地址

@NarcissusInMirror
Copy link
Owner Author

2019.12.9

caffe使用gpu
image

@NarcissusInMirror
Copy link
Owner Author

NarcissusInMirror commented Dec 23, 2019

2019.12.23

Linux date格式化

$ date "+%Y-%m-%d"  
2013-02-19
$ date "+%H:%M:%S"   
13:13:59
$ date "+%Y-%m-%d %H:%M:%S"  
2013-02-19 13:14:19
$ date "+%Y_%m_%d %H:%M:%S"    
2013_02_19 13:14:58
$ date -d today   
Tue Feb 19 13:10:38 CST 2013
$ date -d now  
Tue Feb 19 13:10:43 CST 2013
$ date -d tomorrow  
Wed Feb 20 13:11:06 CST 2013
$ date -d yesterday  
Mon Feb 18 13:11:58 CST 2013 

crontab定时运行脚本

# crontab -e 进入文本编辑页面
30 18 1,15 * * sh /usr/bin/fileback.sh # 表示每月的1号和15号的18时30分执行fileback.sh这个脚本
:wq

shell while循环变量作用范围

shell查看进行运行时间

function show_elapsed_time()
{
 user_hz=$(getconf CLK_TCK) #mostly it's 100 on x86/x86_64
 pid=$1
 jiffies=$(cat /proc/$pid/stat | cut -d" " -f22)
 sys_uptime=$(cat /proc/uptime | cut -d" " -f1)
 last_time=$(( ${sys_uptime%.*} - $jiffies/$user_hz ))
 echo "the process $pid lasts for $last_time seconds."
}

show elapsed_time 12345 # 传入进程号即可

shell中获取数组长度

${#array[@]}

for(( i=0;i<${#array[@]};i++)) do
#${#array[@]}获取数组长度用于循环
echo ${array[i]};
done;

@NarcissusInMirror
Copy link
Owner Author

2019.12.24

关于batchnorm
甲方在转换模型的时候提出了如下问题权重中有很多值过大
把权重中的值打印出来之后发现,数值比较大的值均出现在了batchNormalization层

image
BN层的原理如上图

  1. 对于网络的每一层,对每个minibatch计算每个通道的均值和方差
  2. 使用步骤1中求出的均值和方差对数据进行归一化
  3. 对归一化后的数据进行数据分布的迁移(乘以beta加上gamma)

以上步骤是对于训练过程,在推理过程中,每次只输入一张图片,没有batch,故无法计算均值方差,因此推理过程中使用的是训练过程记录的均值和方差的均值进行归一化,再用训练好的beta和gamma进行分布迁移

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant