提交 9507caa6 编写于 作者: H hypox64

backup

上级 be28af0b
......@@ -133,4 +133,5 @@ dmypy.json
__pycache__/
tmp/
output/
/sftp-config.json
\ No newline at end of file
/sftp-config.json
test.py
\ No newline at end of file
......@@ -7,6 +7,7 @@ import cv2
import numpy as np
import random
import string
import util
all_img_cnt = 0
......@@ -81,8 +82,12 @@ def find_save_resize_face(input_path):
origin_image = cv2.imread(input_path)
h,w = origin_image.shape[:2]
mask = np.zeros(origin_image.shape[:2],dtype = "uint8")
rat = min(origin_image.shape[:2])/LOADSIZE
image = resize(origin_image, LOADSIZE,interpolation = cv2.INTER_AREA)
if min(h,w) > LOADSIZE:
rat = min(origin_image.shape[:2])/LOADSIZE
image = resize(origin_image, LOADSIZE,interpolation = cv2.INTER_AREA)
else:
rat = 1.0
image = origin_image.copy()
face_locations = face_recognition.face_locations(image,number_of_times_to_upsample=1,model=MODEL)
......@@ -97,13 +102,13 @@ def find_save_resize_face(input_path):
ex=int(((EXTEND-1+0.2*random.random())*(bottom-top))/2)
else:
ex=int(((EXTEND-1)*(bottom-top))/2)
if ((bottom-top)>MINSIZE) and 0.95<abs((bottom-top)/(left-right))<1.05 and (top-ex)>0 and (bottom+ex)<h and (left-ex)>0 and (right+ex)<w:
face = origin_image[top-ex:bottom+ex, left-ex:right+ex]
face = cv2.resize(face, (512,512),interpolation=cv2.INTER_LANCZOS4)
if lapulase(face)>Del_Blur_Score:
cv2.imwrite(os.path.join(outdir_face,random_str()+'.jpg'),face)
count = count+1
if SAVE_FACE:
if ((bottom-top)>MINSIZE) and 0.95<abs((bottom-top)/(left-right))<1.05 and (top-ex)>0 and (bottom+ex)<h and (left-ex)>0 and (right+ex)<w:
face = origin_image[top-ex:bottom+ex, left-ex:right+ex]
face = cv2.resize(face, (512,512),interpolation=cv2.INTER_LANCZOS4)
if lapulase(face)>Del_Blur_Score:
cv2.imwrite(os.path.join(outdir_face,random_str()+'.jpg'),face)
count = count+1
if SAVE_MASK:
try:
if MASK_TYPE=='contour':
......@@ -122,11 +127,17 @@ def find_save_resize_face(input_path):
except Exception as e:
pass
if SAVE_MASK:
if count == mask_count and count > 0:
mask = resize(mask,512,interpolation = cv2.INTER_AREA)
# if count == mask_count and count > 0:
mask = resize(mask,512,interpolation = cv2.INTER_AREA)
if min(origin_image.shape)>1024:
origin_image = resize(origin_image,512,interpolation = cv2.INTER_AREA)
cv2.imwrite(os.path.join(outdir_ori,outname+filename+'.jpg'),origin_image)
cv2.imwrite(os.path.join(outdir_mask,outname+filename+'.png'),mask)
else:
if '.jpg' in input_path:
shutil.copyfile(input_path, os.path.join(outdir_ori,outname+filename+'.jpg'))
else:
cv2.imwrite(os.path.join(outdir_ori,outname+filename+'.jpg'),origin_image)
cv2.imwrite(os.path.join(outdir_mask,outname+filename+'.png'),mask)
return count
except Exception as e:
......@@ -144,8 +155,9 @@ EXTEND = 1.6
Del_Blur_Score = 20 # normal-> 20 | clear -> recommed 50
IS_random_EXTEND = False
MODEL = 'hog' # 'hog' | 'cnn'
SAVE_FACE = False
SAVE_MASK = True
MASK_TYPE = 'rect' # rect | contour
MASK_TYPE = 'contour' # rect | contour
HIGH_MASK = 0.2 # more vertical mask
LOADSIZE = 1024 # load to this size and process
......@@ -154,11 +166,10 @@ outdir='./output/'+outname
outdir_ori = os.path.join(outdir,'origin_image')
outdir_face = os.path.join(outdir,'face')
outdir_mask = os.path.join(outdir,'mask')
if not os.path.isdir(outdir):
os.makedirs(outdir)
os.makedirs(outdir_ori)
os.makedirs(outdir_face)
os.makedirs(outdir_mask)
util.makedirs(outdir)
util.makedirs(outdir_ori)
util.makedirs(outdir_face)
util.makedirs(outdir_mask)
file_list = Traversal(filedir)
imgpath_list = picture_select(file_list)
......
......@@ -45,6 +45,12 @@ def writelog(path,log):
f.write(log+'\n')
f.close()
def loadtxt(path):
f = open(path, 'r')
txt_data = f.read()
f.close()
return txt_data
def makedirs(path):
if os.path.isdir(path):
print(path,'existed')
......
[toc]
# Sublime-settings
## ubuntu
### python
#### anaconda
```json
{
"python_interpreter": "/home/hypo/anaconda3/envs/pytorch/bin/python3",
"supress_word_completions": true,
"supress_explicit_completions": true,
"complete_parameters": true,
"anaconda_linting": false
}
```
#### build system
```json
{
"cmd":["python", "$file"],
"path":"/home/hypo/anaconda3/envs/pytorch/bin",
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
"encoding": "utf-8"
}
```
## windows
### python
#### anaconda
```json
{
"python_interpreter": "C:/Users/hypo/Anaconda3/envs/pytorch_0.4.1/python.exe",
"supress_word_completions": true,
"supress_explicit_completions": true,
"complete_parameters": true,
"anaconda_linting": false
}
```
#### build system
```json
{
"cmd":["python", "$file"],
"path":"C:/Users/hypo/Anaconda3/envs/pytorch_0.4.1",
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
"encoding": "utf-8"
}
```
### java
```json
{
"cmd": ["javac","-encoding","gbk","-d",".","$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java",
"encoding":"gbk",
"variants":
[
{
"name": "Run",
"shell": true,
"cmd" : ["start","cmd","/c", "java ${file_base_name}&pause"],
"working_dir": "${file_path}",
"encoding":"gbk"
}
]
}
```
### c
```json
{
"working_dir": "$file_path",
"cmd": "gcc -Wall \"$file_name\" -o \"$file_base_name\"",
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"selector": "source.c",
"variants":
[
{
"name": "Run",
"shell_cmd": "gcc -Wall \"$file\" -o \"$file_base_name\" && start cmd /c \"\"${file_path}/${file_base_name}\" & pause\""
}
]
}
```
### c++
```json
{
"encoding": "utf-8",
"working_dir": "$file_path",
"shell_cmd": "g++ -Wall -std=c++11 \"$file_name\" -o \"$file_base_name\"",
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"selector": "source.c++",
"variants":
[
{
"name": "Run in sublime",
"shell_cmd": "g++ -Wall -std=c++11 \"$file_name\" -o \"$file_base_name\" && cmd /c \"${file_path}/${file_base_name}\""
},
{
"name": "CMD Run",
"shell_cmd": "g++ -Wall -std=c++11 \"$file\" -o \"$file_base_name\" && start cmd /c \"\"${file_path}/${file_base_name}\" & pause\""
}
]
}
```
### matlab
```json
{
"cmd": ["C:/Program Files/MATLAB/R2015b/bin/matlab.exe", "-nodesktop", "-nosplash", "-r", "\"run('$file')\""],
"selector": "source.m",
"working_dir": "${project_path:${folder}}"
}
```
\ No newline at end of file
```json
{
"$schema": "https://aka.ms/terminal-profiles-schema",
"globals": {
"alwaysShowTabs": true,
"defaultProfile": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
"initialCols": 80,
"initialRows": 25,
"keybindings": [
{
"command": "closeTab",
"keys": [
"ctrl+w"
]
}
],
"requestedTheme": "system",
"showTabsInTitlebar": true,
"showTerminalTitleInTitlebar": true
},
"profiles": [
{
"acrylicOpacity": 0.5,
"closeOnExit": true,
"colorScheme": "Campbell",
"commandline": "powershell.exe",
"cursorColor": "#FFFFFF",
"cursorShape": "bar",
"fontFace": "Hack",
"fontSize": 13,
"guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
"historySize": 9001,
"icon": "ms-appx:///ProfileIcons/{61c54bbd-c2c6-5271-96e7-009a87ff44bf}.png",
"name": "Windows PowerShell",
"padding": "0, 0, 0, 0",
"snapOnInput": true,
"startingDirectory": "%Workspaces%",
"useAcrylic": true
},
{
"guid": "{b453ae62-4e3d-5e58-b989-0a998ec441b8}",
"hidden": false,
"name": "Azure Cloud Shell",
"source": "Windows.Terminal.Azure"
}
],
"schemes": [
{
"background": "#0C0C0C",
"black": "#0C0C0C",
"blue": "#0037DA",
"brightBlack": "#767676",
"brightBlue": "#3B78FF",
"brightCyan": "#61D6D6",
"brightGreen": "#16C60C",
"brightPurple": "#B4009E",
"brightRed": "#E74856",
"brightWhite": "#F2F2F2",
"brightYellow": "#F9F1A5",
"cyan": "#3A96DD",
"foreground": "#CCCCCC",
"green": "#13A10E",
"name": "Campbell",
"purple": "#881798",
"red": "#C50F1F",
"white": "#CCCCCC",
"yellow": "#C19C00"
}
]
}
```
PowerShell 中激活anaconda的虚拟python环境
```shell
conda install -n root -c pscondaenvs pscondaenvs
```
以管理员身份启动PowerShell,并执行
```shell
Set-ExecutionPolicy RemoteSigned
```
注意激活时不要加conda,直接activate env就ok
\ No newline at end of file
[toc]
# CNN
## CNN base
### 数字信号处理中的卷积与CNN中的卷积
在数字信号处理中卷积:
![img](https://bkimg.cdn.bcebos.com/pic/2f738bd4b31c8701160cdc36267f9e2f0608ffac?x-bce-process=image/resize,m_lfit,w_250,h_250,limit_1)
但深度学习中的卷积运算实质上是在滤波器(卷积核->通过反向传播得到的权重)和输入的局部区域之间执行点积。换句话说在目前的很多深度学习框架执行卷积前向计算时不会反转卷积核的操作(一些则会提前将反转后的卷积核储存,但实际进行运算的使用的是点积,而不同框架的实现不同,但是不影响我们的理解)。
![img](https://img2018.cnblogs.com/blog/532548/201901/532548-20190126121605642-122357651.png)
### 卷积层的传入参数以及具体运算过程
```python
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)
'''
in_channels(int) – 输入信号的通道
out_channels(int) – 卷积产生的通道
kernel_size(int or tuple) - 卷积核的尺寸
stride(int or tuple, optional) - 卷积步长
padding(int or tuple, optional) - 输入的每一条边补充0的层数
dilation(int or tuple, optional) – 卷积核元素之间的间距
groups(int, optional) – 从输入通道到输出通道的阻塞连接数
bias(bool, optional) - 如果bias=True,添加偏置。bias与BatchNorm2d一般不共存
'''
```
* 计算公式
$$
out(N_i, C_{out_j})=bias(C_{out_j})+\sum^{C_{in}-1}_{k=0}weight(C{out_j},k)\bigotimes input(N_i,k)
$$
* 输出张量的长度
输入图片大小:W x W ,Filter大小:F x F,Stride:S,Padding :P,输出图片:N x N
$$
N = ( W - F + 2*P )/S + 1
$$
* 一个例子
```python
torch.nn.Conv2d(in_channels=3, out_channels=2, kernel_size=3, stride=2, padding=1)
```
![img](md_imgs/CNN/CNN.gif)
### 卷积和全连接
* 对比
卷积不过是一个稀疏的全连接,全连接也不过是一个画面那么大的卷积。两者本质上都可以理解
为矩阵乘法。在不考虑层数的情况下可以理解conv就是拿一个小点的fc不停的在图片不同位置上跑。
* 深度学习的几大流程同样适用于cnn网络(前向,反向,更新权值),只不过权值由全连接网络中的连接权重变为了卷积核。
* 在卷积激活函数,batchnorm, 池化等操作依然有效。
* 卷积的优点(其实主要都是针对图像的)
卷积的优点:输入更灵活,可以接受任意分辨率的图像;使用stride和polling或空洞卷积减少计算量;可以很好捕捉图像这种有空间相关性输入的特征。
### [感受野]( https://zhuanlan.zhihu.com/p/40267131 )
![img](https://images2018.cnblogs.com/blog/1053881/201806/1053881-20180605143258970-884262444.png)<br>
感受野(receptive field,RF)就是卷积神经网络特征所能看到输入图像的区域。在设计CNN的时候感受野很容易被忽略,但往往对模型效果有很大影响。<br>
* 计算方法
![img](md_imgs/CNN/RF.jpg)
一般来说,CNN最后一层的感受野需要大于原始图像中需要分辨的最大物体的尺寸,这样才能获得比较理想的结果。
* 为什么一般语音信号不直接使用CNN的原因
### 梯度爆炸与梯度消失
![img](https://img-blog.csdn.net/20180807163139589?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2p1bmp1bjE1MDAxMzY1Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
与一般的神经网络类似CNN在反向传播的时候也容易出现梯度爆炸与梯度消失的现象一样。
解决办法:
* 好的参数初始化方式,如He初始化
* 非饱和的激活函数(如 ReLU)
* 批量规范化(Batch Normalization)
* 梯度截断、正则(Gradient Clipping)
* 更好的优化器
```python
# 为了解决这个问题一般的cnn层都含有BatchNorm2d以及ReLU
self.conv = nn.Sequential(
nn.Conv2d(inchannel, 64, kernel_size=7, stride=2, padding=3, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
)
```
## [CNN发展历史](https://zhuanlan.zhihu.com/p/66215918)
### LeNet(5 layers) 1998
LeNet-5是1998年YannLeCun设计用于手写数字识别的模型。<br>
![img](https://pic2.zhimg.com/80/v2-bd5a9c288d4d9e26be5674a0bfac3ba1_720w.jpg)<br>
![img](md_imgs/CNN/niubi.jpg)
### AlexNet(8 layers) 2012
![img](https://pic1.zhimg.com/80/v2-51828e6a40c2a8fe150aefdf6a7a5fec_720w.jpg)<br>
1.相比LeNet,AlexNet设计了更深层的网络。<br>
2.在每个卷机后面添加了Relu激活函数,解决了Sigmoid的梯度消失问题,使收敛更快。<br>
3.添加了归一化LRN(Local Response Normalization,局部响应归一化)层,使准确率更高。<br>
4.设计并使用了dropout层,减轻了模型的过拟合。<br>
5.通过裁剪,旋转等方式增强了训练数据。<br>
6.受于当时的算力限制,Alexnet创新地将图像分为上下两块分别训练,然后在全连接层合并在一起(AlexNet网络图1,可以看到有上下两部分)。<br>
![img](md_imgs/CNN/niubi.jpg)
### VGGNet(19 layers) 2014
![在这里插入图片描述](https://img-blog.csdnimg.cn/20181125223340676.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzE5MzI5Nzg1,size_16,color_FFFFFF,t_70)<br>
1.探索了更深层次的网络结构图,可以看成是AlexNet的加强版本。<br>
2.在卷机设计上,使用了更小的卷机核,验证了小尺寸的卷机核在深度网络中,不仅减少了参数,也达到了更好的效果。<br>
![img](md_imgs/CNN/niubi.jpg)
### GoogleNet(22 layers) 2014
![img](md_imgs/CNN/GoogleNet.jpg)
1.引入Inception概念,在当时流行模型‘加深’情况下,设计了‘加宽’的思路<br>
2.采用Network in Network中用Average pool来代替全连接层的思想。实际在最后一层还是添加了一个全连接层,是为了大家做finetune。<br>
3.另外增加了两个辅助的softmax分支<br>
![img](md_imgs/CNN/niubi.jpg)
<br>
<br>
<br>
<br>
再深性能就下降了?????为什么???<br>
![img](md_imgs/CNN/退化.jpg)<br>
* 过拟合? Overfitting? ×<br>
训练集的错误率也上升了!
* 梯度爆炸/消失? Gradient Exploding/Vanishing?× <br>
批量规范化(Batch Normalization)已经被证明能很好的解决这个问题。
* 网络退化✔
当我们堆叠一个模型时,理所当然的会认为效果会越堆越好。因为,假设一个比较浅的网络已经可以达到不错的效果,那么即使之后堆上去的网络什么也不做,模型的效果也不会变差。<br>
然而事实上,这却是问题所在。让以非线性著称的深度神经网络“什么都不做”恰好是最难做到的东西之一。<br>
《Skip connections eliminate singularities》提出神经网络的退化才是难以训练深层网络根本原因所在,而不是梯度消散<br>
![img](md_imgs/CNN/niubi.jpg)
### ResNet(18~152 layers) 2015
想法很朴素:网络退化的原因许赋予神经网络无限可能性的“非线性”让神经网络模型走得太远,却也让它忘记了为什么出发。那么跳过没必要的非线性不就好了!!!<br>
于是一篇被43969次引用的文章诞生了。<br>
[Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385)<br>
![img](md_imgs/CNN/shortcut.jpg)
中心思想:如果深层网络后面的层都是是恒等映射,那么模型就可以转化为一个浅层网络,就不会出现退化问题了。所以用短路(shortcut)就很简单的解决了恒等映射的实现.<br>
* 实际网络:
$$
H(x) = F(x) + x
$$
* 实际要学习的残差函数:
$$
F(x) = H(x) - x
$$
* 如果不使用残差,为了实现恒等映射需要拟合的是:
$$
F(x) = x
$$
* 使用残差,为了实现恒等映射需要拟合的是:
$$
F(x) = 0
$$
* 网络结构
![img](md_imgs/CNN/resnet.jpg)<br>
![img](md_imgs/CNN/resnet_1.jpg)<br>
<img src="md_imgs/CNN/resnet_result.jpg" alt="img" style="zoom:67%;" /><br>
152层!!!<br>
152层!!!<br>
152层!!!<br>
<img src="md_imgs/CNN/nobug.jpg" alt="img" style="zoom:33%;" /><br>
* 残差块的代码实现
```python
class ResidualBlock(nn.Module):
def __init__(self, inchannel, outchannel,kernel_size,stride=2):
super(ResidualBlock, self).__init__()
self.stride = stride
self.conv = nn.Sequential(
nn.Conv2d(inchannel, outchannel, kernel_size=kernel_size, stride=stride, padding=int((kernel_size-1)/2), bias=False),
nn.BatchNorm2d(outchannel),
nn.ReLU(inplace=True),
nn.Conv2d(outchannel, outchannel, kernel_size=kernel_size, stride=1, padding=int((kernel_size-1)/2), bias=False),
nn.BatchNorm2d(outchannel)
)
self.shortcut = nn.Sequential(
nn.Conv2d(inchannel, outchannel, kernel_size=1, stride=2, bias=False),
nn.BatchNorm2d(outchannel)
)
def forward(self, x):
out = self.conv(x)
if self.stride != 1:
out += self.shortcut(x)
else:
out += x
out = F.relu(out,inplace=True)
return out
```
![img](md_imgs/CNN/niubi.jpg)
### [DenseNet]( https://arxiv.org/abs/1608.06993 )(121~264 layers) 2016
<img src="md_imgs/CNN/DenseNet.jpg" alt="img" style="zoom:50%;" /><br>
![img](md_imgs/CNN/DenseNet_1.jpg)
DenseNet是ResNet的升级版,简单来说就是更密集的shortcut连接以提高特征的利用率(每个层都会接受其前面所有层作为其额外的输入)对于一个 L层的网络,DenseNet共包含L(L+1)/2个连接。另外把网络的每一层设计得很窄,也就是卷积的输出通道数通常很小,只有几十,该层学习非常少的特征图并与输入concat使用,从而实现压缩,ImageNet分类数据集上达到同样的准确率,DenseNet 所需的参数量不到ResNet的一半。<br>
![img](md_imgs/CNN/niubi.jpg)<br>
![img](md_imgs/CNN/whatfack.jpg)<br>
深不了了,深不了了,但是有一些其他的方向。
### SeNet(2017)
[SENET](https://arxiv.org/abs/1709.01507 ): ( ->这个思路效果贼棒)在每层卷积中输出的每个channel,其信息重要性是不同的,我们需要为每个channel的feature map设置一个权重,来重新量化每个channel的特征信息。 简单来说就是把上一层输出特征通过Squeeze 将每个二维的特征通道变成一个实数然后 通过Fex 为每个特征通道生成权重(类似rnn的门机制) ,最后把权值乘回原本的特征图得到输出特征图。
![img](https://pic4.zhimg.com/80/v2-77affb3d6037ab0fa4f564f30c38031b_720w.jpg)<br>
![img](md_imgs/CNN/niubi.jpg)<br>
### MobileNet(V1-V3)(2017-?)
MobileNet(V1-V3)
专注于移动端或者嵌入式设备中的轻量级CNN网络。<br>
使用Google Pixel-1( 骁龙821 )手机测试,MobileNet各版本都能保持运行时间在120ms以下,最新版MobileNetV3-Large( 实现ImageNet数据集Top1准确率达到75.2% )运行时间达到66ms,参数量和计算量更低的MobileNetV3-Small更是能达到22ms(50fps)<br>
* 深度可分离卷积:首先进行3X3的普通卷积提取信号,但此时通道数不改变;然后使用1X1的卷积核进行传统的卷积运算,此时通道数可以进行改变。这将减少8到9倍的计算量。
* 去除了pool层,使用stride来进行降采样,进一步减小运算量
* 倒残差模块(输入首先经过1*1的卷积进行通道扩张,然后使用3X3的depthwise卷积,最后使用1X1的pointwise卷积将通道数压缩回去。)
* 引入SeNet的思想,对通带加入权重
* 使用RELU6 增加了模型的非线性变化,增强了模型的泛化能力。
### other
* Non-Local Networks: 引入Self-Attention机制(当前像素与全图像素的关系) ->后来一些研究表明没啥效果
* Dilated Convolutional Networks: 引入空洞卷积(是在标准的 convolution map 里注入空洞),扩大了感受野的同时不会丢失信息,还能降低运算量。
## 参考资料
[CVRP'2015]Deep Residual Learning for Image Recognition.pdf
[CVRP'2016]Densely Connected Convolutional Networks.pdf
[CVRP'2017]Squeeze-and-Excitation Networks.pdf
https://blog.csdn.net/u010358304/article/details/80472605
https://cs231n.github.io/convolutional-networks/
https://pytorch-cn.readthedocs.io/zh/latest/package_references/torch-nn/
https://zhuanlan.zhihu.com/p/66215918
https://zhuanlan.zhihu.com/p/65459972
https://www.cnblogs.com/dengshunge/p/11334640.html
\ No newline at end of file
[toc]
# Deep Metric Learning (DML) 深度度量学习
## Introduction
### 关于人脸识别最简单的想法
#### 最朴素的想法——图像分类任务
利用图像分类的任务把同一个的人脸归为一类,然后进行训练,类似于ImageNet的分类任务。
![image](./md_imgs/DML/ImageNet.jpg)
* **困难**
1.当人的数量超过一定限度怎么办,比如不是几十几百而是上千万甚至上亿?
2.每当一个新的个体录入到数据库的时候难道要重新训练一遍?
#### 能够做到不需要重新训练的方法——kNN、k-means等基于近邻的算法
![image](./md_imgs/DML/knn.png)
* **困难**:计算量过大,每次推理都需要用到数据库所有的数据,而且准确率很低
### 真正的解决办法——Deep Metric Learning
**深度度量学习(deep metric learning)**的目标是学习一个从原始特征到低维稠密的向量空间(称之为嵌入空间,embedding space)的映射,使得同类对象在嵌入空间上使用常用的距离函数(欧氏距离、cosine距离等)计算的距离比较近,而不同类的对象之间的距离则比较远。深度度量学习在计算机视觉领域取得了非常多的成功的应用,比如**人脸识别、人脸验证、图像检索、签名验证、行人重识别等**以及最新的**Zero/few-shot/meta learning**上的应用。<br>
#### 如何使用DML进行图像分类?
<img src="./md_imgs/DML/mnist.png" alt="image" style="zoom:50%;" /><img src="./md_imgs/DML/dml_eg.jpg" alt="image" style="zoom: 67%;" />
![image](./md_imgs/DML/dml_eg_1.jpg)
### 支付宝是怎么做到快速从数亿张脸中找到我的脸的?
![image](./md_imgs/DML/fecere.jpg)
**简单来说就是 预处理+编码为向量 + 先验条件缩小搜索范围 + 高效率的向量相似度搜索的算法(Facebook的Faiss)**
1.对于使用自己的手机进行支付,在使用网络embedding后可以仅对比自己一个人的数据。
2.对于自动贩卖机刷脸支付<br>
* 物理区域:根据用户手机所在的基站区域或其他用户行为缩小搜索范围
* 历史记录:将使用过某台自动贩卖机的用户储存并进行优先搜索
* 其他先验知识:比如很容易的获得用户的身高范围,性别,预测年龄等
* 栅格化:先对比低分率的小头像,相以度高于某个值的数据集提取出来对比
* 并行化及专用芯片加速:将搜索过程交给高度并行化的算法及服务器或者专用的加速芯片
* 兜底策略:输入手机尾号
## DML-Algorithm
**学习一个度量相似度的距离函数:相似的目标离得近,不相似的离得远.**
### General Pipeline
![image](./md_imgs/DML/General_Pipeline.jpg)
* 1.将Sample mini-batch(一般是C类每类挑K个,共N个数据)提取网络来map embedding
* 2.将每个数据都依次作为anchor(锚点)并使用采样策略组成多个sub-set
* 3.在每个sub-set上计算loss
### Embedding
**可以是现在常用的网络结构,如ResNet50等**但是要训练有素的
### Loss
#### 1.Contrastive loss
![image](./md_imgs/DML/Contrastive loss.jpg)
**contrastive loss只考虑了输入样本对本身的相似性**
#### 2.Triplet loss
![image](./md_imgs/DML/Triplet loss.jpg)
**Triplet-Loss的效果比Contrastive Loss的效果要好,因为他考虑了正负样本与锚点的距离关系。**
#### 3.Triplet loss
### Sampling matters
**提高数据的利用率来加速网络收敛**
### Experiment Setting
## Reference
[1]打个酱油, Deep Metric Learning, https://zhuanlan.zhihu.com/p/68200241
[2]赵赫 Mccree, Face Recognition Loss on Mnist with Pytorch, https://zhuanlan.zhihu.com/p/64427565
[3]杨旭东, 深度度量学习中的损失函数, https://zhuanlan.zhihu.com/p/82199561
[4]find goo, 支付宝是怎么做到快速从数亿张脸中找到我的脸的?,https://www.zhihu.com/question/359431172/answer/935555297
[5]face_recognition, ageitgey, https://github.com/ageitgey/face_recognition#face-recognition
\ No newline at end of file
[toc]
# MultiModal Machine Learning (MMML)
每一种信息的来源或者形式,都可以称为一种模态。例如,人有触觉,听觉,视觉,嗅觉;信息的媒介,有语音、视频、文字等;多种多样的传感器,如雷达、红外、加速度计等。以上的每一种都可以称为一种模态。<br>
多模态机器学习,英文全称 MultiModal Machine Learning (MMML),旨在通过机器学习的方法实现处理和理解多源模态信息的能力。目前比较热门的研究方向是图像、视频、音频、语义之间的多模态学习。<br>
## 研究方向简述
#### 多模态表示学习 Multimodal Representation(P125)
单模态的表示学习负责将信息表示为计算机可以处理的数值向量或者进一步抽象为更高层的特征向量,而多模态表示学习是指通过利用多模态之间的互补性,剔除模态间的冗余性,从而学习到更好的特征表示。主要包括两大研究方向:联合表示(Joint Representations,P125)和协同表示(Coordinated Representations,P139)。<br>
#### 模态转化 Translation(P168)
转化也称为映射,负责将一个模态的信息转换为另一个模态的信息。常见的应用包括:
* **机器翻译(Machine Translation):**将输入的语言A(即时)翻译为另一种语言B。类似的还有唇读(Lip Reading)和语音翻译 (Speech Translation),分别将唇部视觉和语音信息转换为文本信息。
* **图片描述(Image captioning) 或者视频描述(Video captioning):** 对给定的图片/视频形成一段文字描述,以表达图片/视频的内容。
* **语音合成(Speech Synthesis)**:根据输入的文本信息,自动合成一段语音信号。
#### 对齐 Alignment(P178)
多模态的对齐负责对来自同一个实例的不同模态信息的子分支/元素寻找对应关系。这个对应关系可以是时间维度的,又可以是空间维度的。<br>
* **Temporal sequence alignment** 电影画面-语音-字幕的自动对齐
* **图片语义分割 (Image Semantic Segmentation)**:尝试将图片的每个像素对应到某一种类型标签,实现视觉-词汇对齐。
#### 多模态融合 Multimodal Fusion(P206)
多模态融合(Multimodal Fusion )负责联合多个模态的信息,进行目标预测(分类或者回归).应用广泛,如多源信息融合(Multi-source Information Fusion)、多传感器融合(Multi-sensor Fusion)。
#### 协同学习 Co-learning
协同学习是指使用一个资源丰富的模态信息来辅助另一个资源相对贫瘠的模态进行学习。<br>
* **迁移学习(Transfer Learning):**迁移学习比较常探讨的方面目前集中在领域适应性(Domain Adaptation)问题上.目前的分支领域有零样本学习(Zero-Shot Learning)和一样本学习(One-Shot Learning)
* **协同训练(Co-training ):**负责研究如何在多模态数据中将少量的标注进行扩充,得到更多的标注信息。
## 多模态表示学习 Multimodal Representation(P125)
单模态的表示学习负责将信息表示为计算机可以处理的数值向量或者进一步抽象为更高层的特征向量,而多模态表示学习是指通过利用多模态之间的互补性,剔除模态间的冗余性,从而学习到更好的特征表示。主要包括两大研究方向:联合表示(Joint Representations,P125)和协同表示(Coordinated Representations,P139)。<br>
![联合表示和协同表示对比图](https://i.loli.net/2018/12/18/5c18db70a2588.png)
* **联合表示**将多个模态的信息一起映射到一个统一的多模态向量空间(本质就是提取特征,自编码器方法等);<br>应用包括信息检索,也可以用于的分类/回归任务。
* **协同表示**负责将多模态中的每个模态分别映射到各自的表示空间,但映射后的向量之间满足一定的相关性约束(例如线性相关)。<br>例子:《Unifying Visual-Semantic Embeddings with Multimodal Neural Language Models 》利用协同学习到的特征向量之间满足加减算数运算这一特性,可以搜索出与给定图片满足“指定的转换语义”的图片。例如:狗的图片特征向量 - 狗的文本特征向量 + 猫的文本特征向量 = 猫的图片特征向量 -> 在特征向量空间,根据最近邻距离,检索得到猫的图片.
![img](https://i.loli.net/2018/12/18/5c18dc860b902.png)
### Example: SoundNet 从未标记的视频中学习声音表征
SoundNet Learning Sound Representations from Unlabeled Video<br>
通过有效利用大量从野外收集的未标记声音数据,我们学习了丰富 的自然声音表征。使用两百万未标记的视频,我们利用时间和声音的自然同步来学习声学表征。未标记视频的优势是在经济有限情况下也能获得大规模的、包含有用信号的数据。我们提出一种 student-teacher 训练流程,使用未标记视频作为桥梁,能将来自好的视觉识别模型的有识别力的视觉知识迁移到声音形态。在声学场景/识别分类基准上,我们的声音表征对前沿表现有了极大的改进。可视化数据表明一些高层次语义可在该声音网络中自动生成,即使它是在没有 ground truth 标记的情况下训练的。
![img](https://camo.githubusercontent.com/0b88af5c13ba987a17dcf90cd58816cf8ef04554/687474703a2f2f70726f6a656374732e637361696c2e6d69742e6564752f736f756e646e65742f736f756e646e65742e6a7067)
通过SoundNet架构与ImageNet,Place CNN等进行联合训练。首先视频数据集中的每个视频都切分成两部分,一部分为音频,一部分为RGB图像帧。视觉识别网络采用在ImageNet和Places两个大型图像数据集上的预训练VGG模型。ImageNet和Places都是图像识别领域的大型数据集,其中Imagenet是图像目标分类数据集,Places是图像场景分类数据集。将从视频中分割出来的RGB帧输入到预训练的VGG模型(代码中正常使用ResNet34)中,得到的输出结果作为声音识别网络的监督信息。声音识别网络采用8层的全卷积结构,使用从视频中提取出的声音时间序列作为网络的输入,损失函数采用KL-divergence。
## 多模态融合 Multimodal Fusion
多模态融合(Multimodal Fusion )负责联合多个模态的信息,进行目标预测(分类或者回归)
<img src="./md_imgs/MMML/Multimodal Fusion_1.jpg" alt="img" style="zoom:50%;" /><br>
* **应用:**视听语音识别、多媒体事件检测、多模态情感识别等
* **主要分为:**Model free approaches(Early, late, hybrid),Model-based approaches(Kernel Methods,Graphical models,Neural networks)
### Model free approaches
#### early fusion
<img src="./md_imgs/MMML/Multimodal Fusion_free_early.jpg" alt="img" style="zoom:67%;" /><br>
#### late fusion
<img src="./md_imgs/MMML/Multimodal Fusion_free_late.jpg" alt="img" style="zoom:67%;" /><br>
#### hybrid fusion
<img src="./md_imgs/MMML/Multimodal Fusion_free_hybir.jpg" alt="img" style="zoom:67%;" /><br>
### Model-based approaches
#### Kernel Methods
<img src="./md_imgs/MMML/Kernel Methods_3.jpg" alt="img" /><br>
Multiple Kernel Learning是内核支持向量机(SVM)的扩展,它允许使用不同的内核来处理不同的数据模式/视图。由于可以将内核视为数据点之间的相似函数,所以MKL中特定于模式的内核可以更好地融合异构数据
<img src="./md_imgs/MMML/Kernel Methods.jpg" alt="img" style="zoom:67%;" /><br>
<img src="./md_imgs/MMML/Kernel Methods_1.jpg" alt="img" style="zoom:67%;" /><br>
#### Neural networks
Memory Fusion Network for Multi-view Sequential Learning.pdf
<img src="./md_imgs/MMML/LSTM_1.jpg" alt="img" style="zoom: 50%;" />
<img src="./md_imgs/MMML/LSTM_2.jpg" alt="img" style="zoom: 50%;" />
<img src="./md_imgs/MMML/LSTM_3.jpg" alt="img" style="zoom: 50%;" />
<img src="./md_imgs/MMML/LSTM_4.jpg" alt="img" style="zoom: 50%;" />
#### Graphical models
MoodExplorer: Towards Compound Emotion Detection via Smartphone Sensing
## Reference
https://blog.csdn.net/electech6/article/details/85142769
《Tutorial on Multimodal Machine Learning》
Multimodal Machine Learning A Survey and Taxonomy.pdf
[TOC]
上传已有的项目
像上面那样,直接从github上clone你自己已有的项目到本地,在你的电脑上面编辑了项目,上传到github上的话,通过如下命令
# Git
## Base
```shell
git pull origin master # 将远程仓库里面的项目拉下来
$ git rm -r --cached target # 删除target文件夹
$ git add * ###如有新添加的文件执行此行,添加所有的文件
$ git commit -m "输入你本次提交的文字"
git rm -r --cached target # 删除target文件夹
git add * ###如有新添加的文件执行此行,添加所有的文件
git commit -m "输入你本次提交的文字"
git push -u origin master
```
## 合并仓库
大致思路是伪造远程的repo1仓库为repo2的一个分支,然后合并进来;
若是文件有冲突、或要建立子目录,建议在repo1中先解决,再进行如上操作。
example:
目前开发是2个仓库,线上仓库online_a(对应的branch分支为online),测试环境online_b(对应的branch分支为demo),测试环境需要时刻保持onine_a上的最新稳定稳定代码同步过来。
$ git push -u origin master
```shell
#1:在测试仓库onine_b 上执行:测试仓库添加远程生产仓库(切换到自己的测试仓库下执行以下命令,比如我的当期测试online_b.git)
git remote add online_a git@github.com:fantasy/online_a.git#将online_a作为远程仓库,添加到online_b中,设置别名为online_a(自定义,这里我是为了方便区分仓库名)
#2从远程仓库下载,这时我们弄个新的
git fetch online_a #从online_a仓库中抓取数据到本仓库,注意这里是上面设置的别名
# 表格
name | 111 | 222 | 333 | 444
:-: | :-: | :-: | :-: | :-:
aaa | bbb | ccc | ddd | eee|
fff | ggg| hhh | iii | 000|
#3.将online_a仓库抓去的online分支作为新分支checkout到本地,新分支名设定为online_repo1
git checkout -b online_repo1 online-a/online //注意这里也是别名online_a
#4.切换回本地测试的online_b的demo分支
git checkout demo
1、编辑README文件
#5.将online_repo1合并入demo分支
git merge online_repo1
```
大标题(一级标题):在文本下面加等于号,那么上方的文字就变成了大标题,等于号的个数无限制,但一定要大于0
# Markdown
## 表格
| | | |
| ---- | ---- | ---- |
| | | |
| | | |
| | | |
## 标题
```markdown
大标题
====
中标题(二级标题):在文本下面加下划线,那么上方的文本就变成了中标题,下划线个数无限制,中标题比大标题低一级
中标题
-------
1~6级标题:文本大小依次减小,以#号开头,多少个#号就是多少级标题,#号和标题名称要并排写
# 一级标题
## 二级标题
### 三级标题
#### 四级标题
##### 五级标题
###### 六级标题
```
## 列表
插入圆点符号:编辑的时候使用的是星号 *,星号后面要有一个空格,否则为普通星号
* 列表一
* 列表二
* 列表三
二级圆点、三级圆点:多加一个Tab,即第二行一个Tab,第三行两个Tab
* 列表一
* 列表二
*列表三
缩进:
## 缩进
>缩进一
>>缩进二
>>>缩进三
......@@ -63,18 +73,12 @@ fff | ggg| hhh | iii | 000|
>>>>>缩进五
插入链接
## 插入链接图片
[百度](http://baidu.com)
插入网络图片:![](网络图片链接地址),即叹号!+方括号[]+括号(),如果不加叹号!就会变成普通文本,方括号里可以加入一些 标识性的信息
![baidu](http://www.baidu.com/img/bdlogo.gif "百度logo")
<img src=http://www.baidu.com/img/bdlogo.gif style="zoom:50%">
插入GITHub仓库里的图片:![](图片链接地址),即叹号!+方括号[]+括号(),URL写法:http://github.com/自己的用户名/项目名/raw/分支名/存放图片的文件夹/文件夹里的图片名字
给图片加上超链接:即点击一个图片进入指定网页,方括号里写自己起的标识名称,上下两行标识要一致。
......@@ -82,7 +86,7 @@ fff | ggg| hhh | iii | 000|
[![baidu]](http://baidu.com)
[baidu]:http://www.baidu.com/img/bdlogo.gif "百度Logo"
## 插入代码片段
插入代码片段:在代码上下行用```标记,注意`符号是tab键上面那个,要实现语法高亮,则在```后面加上编程语言的名称
复制代码
......@@ -93,6 +97,8 @@ public static void main(String[] args){}
```javascript
document.getElementById("ts").innerHTML="Hello"
```
## 其他
复制代码
换行:使用标签<br>
......
[TOC]
### 用户
* 添加用户
```bash
sudo adduser hypo
```
* 更改密码
```bash
sudo passwd hypo
```
* 更改用户权限
```bash
cd /etc
sudo vim sudosers
hypo ALL=(ALL:ALL) ALL
```
* 删除用户
```bash
sudo userdel -r hypo
```
### 安装显卡驱动
```bash
#卸载旧的驱动
sudo apt-get purge nvidia*
sudo apt-get autoremove #这个命令有时候不用也可以
#
sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt update
ubuntu-drivers devices
ubuntu-drivers devices#选择推荐的驱动版本
sudo apt install nvidia-430
```
### 挂载U盘
......@@ -26,11 +41,6 @@ $ umount /usr
#参数可以是设备文件或安装点
```
### linux应用设置
* 百度盘
```bash
# 无法登录
rm -rf ~/baidunetdisk #这个蛇皮的bug不知道啥时候才能修复
```
* goldendict
```bash
# 安装
......@@ -50,6 +60,7 @@ trans -e google -s auto -t zh-CN -show-original y -show-original-phonetics n -sh
```bash
nautilus #文件管理器
firefox #火狐浏览器
gedit #文本编辑器
```
### 批量杀死应用
```bash
......@@ -122,15 +133,27 @@ $ sudo systemctl enable teamviewerd.service
```
### 压缩解压
```bash
#.tar .tar.xz
tar xvf filename.tar #.tar 解包
tar cvf filename.tar dirname #.tar 打包
tar cvzf - filedir | split -d -b 50m - filename #.tar 分卷打包
cat x* > myzip.tar.gz #.tar 分卷解包
tar xzvf myzip.tar.gz
#.gz
gunzip filename.gz #.gz 解压1
gzip -d filename.gz #.gz 解压2
gzip filename #.gz 压缩
#.tar.gz
tar zxvf filename.tar.gz #.tar.gz 和 .tgz 解压
tar zcvf filename.tar.gz dirname #.tar.gz 和 .tgz 压缩
unzip filename.zip #.zip 解压
#zip
unzip filename.zip -d filedir #.zip 解压
zip filename.zip dirname #.zip 压缩
#rar
rar x filename.rar #.rar 解压
rar a filename.rar dirname #.rar 压缩
......@@ -141,6 +164,18 @@ tar cvf - test.txt | pigz > test.tar.gz
#解压
tar -I pigz -xvf /path/to/archive.tar.gz -C /where/to/unpack/it/
```
### rdesktop(Windows远程桌面)
```
rdesktop -u Administrator -p password ip -g 1280x720
```
### vim
* 模式
1.vim 一打开,就会进入所谓的普通模式(Normal)。在这个模式下,大家输入的所有内容都会被 vim 解析成相应的指令并执行。<br>
2.如果要输入内容,必须键入字母 i 来命令 vim 切换到所谓的插入模式(Insert)。在插入模式下,大家就可以像在其他普通编辑器下那样输入文字了。输入完毕,需要通过按Esc返回普通模式。<br>
* 撤销重做
撤销上次操作用 u,反撤销用 ctrl+r
* 保存退出
保存退出都要在命令模式下完成。保存用 :w path/to.txt,退出用 :q。如果是编辑已经存在的文件可以直接用 :wq 退出。
### ssh
* install
```bash
......@@ -198,3 +233,47 @@ scp /val/test.tar.gz root@www.test.com:/val/test.tar.gz
scp -r root@www.test.com:/val/test/ /val/test/
```
### 常见系统故障
#### 百度盘 无法登录
```bash
rm -rf ~/baidunetdisk #这个蛇皮的bug不知道啥时候才能修复
```
#### nvidia-smi command not found显卡驱动故障
```bash
sudo apt-get purge nvidia*
sudo apt-get autoremove
sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt update
ubuntu-drivers devices
sudo apt install nvidia-430
```
#### ERROR:gzip: stdout: No space left on device(boot空间不足)
内核安装过多导致的空间不足
```bash
#查看boot占用情况
df
#查看当前内核版本
uname -r
#查看已安装内核版本
cd /boot
ls
# 删除多余的内核
sudo apt autoremove linux-image-4.4.0-57-generic
#查看boot占用情况
df
```
#### ssh连接使用方向键出现乱码
原因是新建用户使用了不同的shell
```bash
vim /etc/passwd
root:x:0:0:root:/root:/bin/bash
hypo:x:1001:1001::/home/hypo:/bin/sh
```
只需要把sh改成bash就好
#### ssh秘钥失效
A机器通过ssh-copy-id root@IP(B)添加了链接到B机器的ssh秘钥。但是某天,B机器的密码修改或者机器重装,此时,在A机器上再次ssh IP(B)会报类似如下错误
```bash
ssh-keygen -f "/home/hypo/.ssh/known_hosts" -R "[IP]:poet"
```
\ No newline at end of file
......@@ -198,25 +198,38 @@ s = ['1.dat','10.dat','5.dat']
new = sorted(s,key = lambda i:int(re.match(r'(\d+)',i).group()))
```
### multiprocessing
[https://blog.csdn.net/brucewong0516/article/details/85776194](【python】详解multiprocessing多进程-process模块(一))
* run()
       表示进程运行的方法。可以在子类中重写此方法。标准run() 方法调用传递给对象构造函数的可调用对象作为目标参数(如果有),分别使用args和kwargs参数中的顺序和关键字参数。
* start()
       进程准备就绪,等待CPU调度。
* join([ 超时] )
       如果可选参数timeout是None,则该方法将阻塞,直到join()调用其方法的进程终止。如果timeout是一个正数,它最多会阻塞超时秒。请注意,None如果方法的进程终止或方法超时,则返回该方法。检查进程exitcode以确定它是否终止。
* name
       进程的名称。该名称是一个字符串,仅用于识别目的。
* is_alive()
       返回进程是否存活。从start() 方法返回到子进程终止的那一刻,进程对象仍处于活动状态。
* daemon
       进程的守护进程标志,一个布尔值。必须在start()调用之前设置,当进程退出时,它会尝试终止其所有守护进程子进程。
* pid
       返回进程ID。在产生该过程之前,这将是 None。
* exitcode
       子进程的退出代码。None如果流程尚未终止,这将是。负值-N表示孩子被信号N终止。
```python
import multiprocessing
import time
from multiprocessing import Process, Queue
def preload(pool):
.......
pool.put(data)
def func(msg):
return multiprocessing.current_process().name + '-' + msg
def main():
pool = Queue(opt.image_pool)
for i in range(opt.load_process):
p = Process(target=preload,args=(pool,))
p.daemon = True
p.start()
data = pool.get()
if __name__ == "__main__":
pool = multiprocessing.Pool(processes=4) # 创建4个进程
results = []
for i in range(10):
msg = "hello %d" %(i)
results.append(pool.apply_async(func, (msg, )))
pool.close() # 关闭进程池,表示不能再往进程池中添加进程,需要在join之前调用
pool.join() # 等待进程池中的所有进程执行完毕
print ("Sub-process(es) done.")
for res in results:
print (res.get())
```
### print
* 数字格式化输出
......@@ -276,7 +289,7 @@ data = data[np.argsort(data[:,0])]
## pyinstaller
```bash
pyinstaller test.py-F
pyinstaller test.py -F
```
## opencv-python
[Document](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_table_of_contents_setup/py_table_of_contents_setup.html)
......@@ -303,11 +316,13 @@ cv2.IMREAD_UNCHANGED:加载图像,包括alpha通道
#當我們縮小影像時,使用CV_INTER_AREA會有比較好的效果,當我們放大影像,CV_INTER_CUBIC會有最好的效果,但是計算花費時間較多,CV_INTER_LINEAR能在影像品質和花費時間上取得不錯的平衡。 CV_INTER_LANCZOS4    Lanczos插补,8*8大小的补点
```
### fill
* cv2.rectangle
```python
cv2.rectangle(image, (x,y), (x+w,y+h), (0,255,0), 2)
#参数:pt1,对角坐标1, pt2:对角坐标2
# 注意这里根据两个点pt1,pt2,确定了对角线的位置,进而确定了矩形的位置
```
### imshow
```python
......@@ -347,6 +362,32 @@ cv2.imshow("Green", cv2.merge([zeros, G, zeros]))
cv2.imshow("Red", cv2.merge([zeros, zeros, R]))
```
## matplotlib
### colors markers
```python
colors= ['blue','orange','green','red','purple','brown','pink','gray','olive','cyan']
markers = ['.',',','o','v','^','<','>','1','2','3','4','s','p','*','h','H','+','x','D','d','|','_']
```
### 3d+scatter
```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
arr = np.zeros((300,3))
arr[0:100] = np.random.uniform(0, 1, (100,3))
arr[100:200] = np.random.uniform(1, 2, (100,3))
arr[200:300] = np.random.uniform(2, 3, (100,3))
for i in range(3):
ax.scatter(arr[i*100:(i+1)*100,0], arr[i*100:(i+1)*100,1], arr[i*100:(i+1)*100,2])
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
```
## pytorch
[org](https://pytorch.org/)
......@@ -363,8 +404,121 @@ torch.save(net.cpu().state_dict(), model_name)
net = UNet(n_channels=3, n_classes=1)
net.load_state_dict(torch.load(model_name))
```
### def network
[关于Pytorch几种定义网络的方法](https://zhuanlan.zhihu.com/p/80308275)
* 直接申明
```python
import torch
import torch.nn as nn
from torch.autograd import Variable
from collections import OrderedDict
class Net():
def __init__(self):
super(nn.Module, NN).__init__()
self.fc1 = nn.Linear(10,10)
self.relu1 = nn.ReLU(inplace=True)
self.fc2 = nn.Linear(10,2)
def forward(self,x):
x = self.fc1(x)
x = self.relu1(x)
x = self.fc2(x)
return x
```
* nn.ModuleList()
```python
class Net():
def __init__(self):
super(nn.Module, NN).__init__()
self.base = nn.ModuleList([nn.Linear(10,10), nn.ReLU(), nn.Linear(10,2)])
def forward(self,x):
x = self.base(x)
return x
#nn.ModuleList()接收的参数为一个List,这样就可以很方便的定义一个网络,比如
```
* nn.Sequential()
```python
# nn.Sequential()里面自带了forward函数,可以直接操作输入,而nn.ModuleList()需要定义一个forward函数
class Net():
def __init__(self):
super(nn.Module, NN).__init__()
self.base = nn.Sequential(nn.Linear(10,10), nn.ReLU(), nn.Linear(10,2))
def forward(self,x):
x = self.base(x)
return x
# OrderedDict
class MultiLayerNN5(nn.Module):
def __init__(self):
super(MultiLayerNN5, self).__init__()
self.base = nn.Sequential(OrderedDict([
('0', BasicConv(1, 16, 5, 1, 2)),
('1', BasicConv(16, 32, 5, 1, 2)),
]))
self.fc1 = nn.Linear(32 * 7 * 7, 10)
def forward(self, x):
x = self.base(x)
x = x.view(x.size(0), -1)
x = self.fc1(x)
return x
```
* add_module
```python
class MultiLayerNN4(nn.Module):
def __init__(self):
super(MultiLayerNN4, self).__init__()
self.base = nn.Sequential()
self.base.add_module('0', BasicConv(1, 16, 5, 1, 2))
self.base.add_module('1', BasicConv(16, 32, 5, 1, 2))
self.fc1 = nn.Linear(32 * 7 * 7, 10)
def forward(self, x):
x = self.base(x)
x = x.view(x.size(0),-1)
x = self.fc1(x)
```
* 骚操作 用for定义多路
```python
class lstm(nn.Module):
def __init__(self,input_size,time_step,input_nc,num_classes,Hidden_size=128,Num_layers=2):
super(lstm, self).__init__()
self.input_size=input_size
self.time_step=time_step
self.input_nc=input_nc
self.point = input_size*time_step
for i in range(input_nc):
exec('self.lstm'+str(i) + '=lstm_block(input_size, time_step)')
self.fc = nn.Linear(Hidden_size*input_nc, num_classes)
def forward(self, x):
y = []
x = x.view(-1,self.input_nc,self.time_step,self.input_size)
for i in range(self.input_nc):
y.append(eval('self.lstm'+str(i)+'(x[:,i,:])'))
x = torch.cat(tuple(y), 1)
x = self.fc(x)
return x
```
* 骚操作 用for定义多层
```python
class encoder_2d(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64, n_downsampling=3, n_blocks=9, norm_layer=nn.BatchNorm2d,
padding_type='reflect'):
assert(n_blocks >= 0)
super(encoder_2d, self).__init__()
activation = nn.ReLU(True)
model = [nn.ReflectionPad2d(3), nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0), norm_layer(ngf), activation]
### downsample
for i in range(n_downsampling):
mult = 2**i
model += [nn.ReflectionPad2d(1),nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=0),
norm_layer(ngf * mult * 2), activation]
self.model = nn.Sequential(*model)
def forward(self, input):
return self.model(input)
```
# Anaconda
## install
1.download 'Anaconda3-2019.07-Linux-x86_64.sh'
......
## Haystack
Gadgets and notes for learning and research
### System
* [monitor_linux.py](./System/monitor_linux.py)
A simple Deep Learning Server performance monitor. Written by python without any dependencies.
```bash
(base) hypo@lthpc:~$ python monitor_linux.py
Cpu Temp: 48.0C | Freq: 2499.9MHz
Util: 85.6% [###########################################-------]
Memory Mem: 34354MB/64301MB | Swap: 0MB/62498MB
Mem: 53.0% [#############------------] Swap: 0.0% [-------------------------]
Gpu0: TITAN V Temp: 45.0C | Power: 28w/250w | Mem: 950MB/12066MB | Fan: 31%
Util:0.0% [-------------------------] Mem:7.9% [##-----------------------]
Gpu1: TITAN V Temp: 46.0C | Power: 28w/250w | Mem: 950MB/12066MB | Fan: 31%
Util:0.0% [-------------------------] Mem:7.9% [##-----------------------]
Network ↑ all:10.2GB ↓ all:173.8GB ↑ :147.6Kb/s ↓ :6000.5Kb/s
Filesystem Mounted on Used/Total Used%
udev /dev 0/32G 0%
/dev/sda7 / 9.9G/143G 8%
tmpfs /dev/shm 0/32G 0%
tmpfs /sys/fs/cgroup 0/32G 0%
/dev/sdb1 /home 103G/2.7T 4%
/dev/sdc1 /media/usb 3.6T/3.7T 99%
```
### CV
### CV_Tool
* [find_face.py](./CV/find_face.py)
FInd face in images, then save them.
Depend on face_recognition, opencv-python.
......@@ -47,4 +19,6 @@ Finished! Finall find face: 50 Cost time: 145 s
* [linux.md](./Notes/linux.md)
* [python.md](./Notes/python.md)
* [github.md](./Notes/github.md)
* [Sublime-settings.md](./Notes/Sublime-settings.md)
\ No newline at end of file
* [CNN.md](./Notes/dl/CNN.md)
* [DML.md](./Notes/dl/DML.md)
* [MMML.md](./Notes/dl/MMML.md)
\ No newline at end of file
import os
import time
# -*- coding:utf-8 -*-
#Cpu
###############################################################
# Cpu use
last_worktime=0
last_idletime=0
def get_cpu_use():
global last_worktime, last_idletime
f=open("/proc/stat","r")
line=""
while not "cpu " in line:
line=f.readline()
f.close()
spl=line.split(" ")
worktime=int(spl[2])+int(spl[3])+int(spl[4])
idletime=int(spl[5])
dworktime=(worktime-last_worktime)
didletime=(idletime-last_idletime)
rate=float(dworktime)/(didletime+dworktime)
cpu_t = rate*100
last_worktime=worktime
last_idletime=idletime
if(last_worktime==0):
return 0
return round(cpu_t,2)
# Cpu freq
def get_cpu_freq():
freq_str = os.popen('cat /proc/cpuinfo | grep MHz | uniq').read()
freqs =[]
while freq_str.find('\n') != -1:
freqs.append(float(freq_str[freq_str.find(':')+2:freq_str.find('\n')]))
freq_str=freq_str[freq_str.find('\n')+1:]
return max(freqs)
# Cpu freq
def get_cpu_temp():
if os.path.isfile('/sys/class/thermal/thermal_zone0/temp'):
temp_str = os.popen('cat /sys/class/thermal/thermal_zone0/temp').read()
elif os.path.isfile('/sys/class/hwmon/hwmon0/device/hwmon/hwmon0/temp1_input'):
temp_str = os.popen('cat /sys/class/hwmon/hwmon0/device/hwmon/hwmon0/temp1_input').read()
elif os.path.isfile('/sys/class/hwmon/hwmon0/device/hwmon0/temp1_input'):
temp_str = os.popen('cat /sys/class/hwmon/hwmon0/device/hwmon0/temp1_input').read()
else:
return -1
return (float(temp_str)/1000)
# Mem
###############################################################
def get_mem_use():
mem_str = os.popen('free').read()
if '内存'in mem_str :
mem_str = mem_str[mem_str.find('内存:')+3:mem_str.find('交换')]
else:
mem_str = mem_str[mem_str.find('Mem:')+4:mem_str.find('Swap')]
mem_str = mem_str.split()
total = int(float(mem_str[0])/1024)
used = int(float(mem_str[1])/1024)
percent = int(used/total*100)
return total,used,percent
def get_swap_use():
mem_str = os.popen('free').read()
if '内存'in mem_str :
mem_str = mem_str[mem_str.find('交换:')+3:]
else:
mem_str = mem_str[mem_str.find('Swap:')+5:]
mem_str = mem_str.split()
total = int(float(mem_str[0])/1024)
used = int(float(mem_str[1])/1024)
percent = int(used/total*100)
return total,used,percent
#gpu
###############################################################
gpus_str = os.popen('nvidia-smi -L').read()
gpus =[]
if 'communicate with the NVIDIA driver' not in gpus_str:
while gpus_str.find('\n') != -1:
gpus.append(gpus_str[gpus_str.find(':')+2:gpus_str.find('(')-1])
gpus_str=gpus_str[gpus_str.find('\n')+1:]
def get_gpu_use():
gpu_infos = []
for i in range(len(gpus)):
infos_str = os.popen('nvidia-smi').read()
infos_str = infos_str[infos_str.find(str(i)+' '+gpus[i]):]
infos_str = infos_str[infos_str.find('\n')+1:]
infos_str = infos_str[:infos_str.find('\n')+1]
infos_str = infos_str.split()
#['|', '50%', '42C', 'P0', '19W', '/', '75W', '|', '929MiB', '/', '5050MiB', '|', '14%', 'Default', '|']
if infos_str[1].replace('%','') == 'N/A':
fan = -1
else:
fan = int(infos_str[1].replace('%','')) # %
temp = int(infos_str[2].replace('C','')) # C
if infos_str[4] == 'N/A':
power_used = -1
power_max = -1
else:
power_used = int(infos_str[4].replace('W','')) # W
power_max = int(infos_str[6].replace('W','')) # W
mem_used = int(infos_str[8].replace('MiB','')) # MB
mem_max = int(infos_str[10].replace('MiB','')) # MB
util_used = int(infos_str[12].replace('%','')) # %
gpu_infos.append([fan,temp,power_used,power_max,mem_used,mem_max,util_used])
return gpu_infos
#Net
###############################################################
net_infos_history = [0,0]
def get_net_use(network_adapter = 'all'):
net_str = os.popen('cat /proc/net/dev').read()
infos = []
net_infos = [0,0,0,0]
while net_str.find('\n') != -1:
if net_str[:50].find(':') != -1:
infos.append((net_str[net_str.find(':')+2:net_str.find('\n')-1]).split())
net_str=net_str[net_str.find('\n')+1:]
net_rxs=[];net_txs=[]
for info in infos:
net_rxs.append(int(info[0]))
net_txs.append(int(info[8]))
if network_adapter == 'all':
net_infos[0] = (sum(net_rxs)/1024)
net_infos[1] = (sum(net_txs)/1024)
elif network_adapter == 'auto':
net_infos[0] = (max(net_rxs)/1024)
net_infos[1] = (max(net_txs)/1024)
if net_infos_history[0] == 0:
net_infos[2] = 0
net_infos[3] = 0
else:
net_infos[2] = net_infos[0]-net_infos_history[0]
net_infos[3] = net_infos[1]-net_infos_history[1]
net_infos_history[0] = net_infos[0]
net_infos_history[1] = net_infos[1]
return net_infos
#Disk
###############################################################
def get_disk_use():
disk_str = os.popen('df -h').read()
disk_str = disk_str.split('\n')
disk_infos = []
for line in disk_str:
if 'G' in line[:24] and 'tmpfs' not in line:
line = line.split()
if float(line[1].replace('G',''))>20:
disk_infos.append(line)
elif 'T' in line and 'tmpfs' not in line:
line = line.split()
disk_infos.append(line)
return disk_infos
def get_bar(percent,num = 25):
# graphs = ' ▏▎▍▋▊▉'
percent = round(percent)
bar = '['
for i in range(num):
if i < round(percent/int((100/num))):
bar += '#'
else:
bar += '-'
bar += ']'
return bar
def fill_str(string,num):
if len(string)>num:
return string[:num-3]+'...'
for i in range(num-len(string)):
string +=' '
return string
def main():
while(1):
#cpu
cpu_used = get_cpu_use()
cpu_freq = get_cpu_freq()
cpu_temp = get_cpu_temp()
cpu_used_bar = get_bar(cpu_used,num=50)
#memory
mem_total,mem_used,mem_percent = get_mem_use()
mem_used_bar = get_bar(mem_percent)
swap_total,swap_used,swap_percent = get_swap_use()
swap_used_bar = get_bar(swap_percent)
#gpu
util_used_bars=[];gpu_mem_bars=[]
gpu_infoss = get_gpu_use()
print(gpu_infoss)
for i in range(len(gpus)):
gpu_infos = gpu_infoss[i]
util_used_bars.append(get_bar(gpu_infoss[i][6]))
gpu_mem_bars.append(get_bar(100*gpu_infoss[i][4]/gpu_infoss[i][5]))
#net
net_infos = get_net_use()
#disk
disk_infos = get_disk_use()
####################################print#################################
os.system('clear')
#cpu
print(('Cpu Temp: {0:.1f}C | Freq: {1:.1f}MHz').format(cpu_temp,cpu_freq))
print(('Util: {0:.1f}% '+cpu_used_bar).format(cpu_used))
#memory
print(('\nMemory Mem: {0:d}MB/{1:d}MB | Swap: {2:d}MB/{3:d}MB').format(
mem_used,mem_total,swap_used,swap_total))
print(('Mem: {0:.1f}% '+mem_used_bar+' Swap: {1:.1f}% '+swap_used_bar).format(mem_percent,swap_percent))
#gpu
for i in range(len(gpus)):
print(('\n'+'Gpu'+'{0:d}'+': '+gpus[i].replace('GeForce','')+' Temp: {1:.1f}C | Power: {2:d}w/{3:d}w | Mem: {4:d}MB/{5:d}MB | Fan: {6:d}%').format(
i,gpu_infoss[i][1],gpu_infoss[i][2],gpu_infoss[i][3],
gpu_infoss[i][4],gpu_infoss[i][5],gpu_infoss[i][0]))
print(('Util:{0:.1f}% '+util_used_bars[i]+' Mem:{1:.1f}% '+gpu_mem_bars[i]).format(
gpu_infoss[i][6],100*gpu_infoss[i][4]/gpu_infoss[i][5]))
#net
print(('\nNetwork ↑ all:{0:.1f}GB ↓ all:{1:.1f}GB ↑ :{2:.1f}Kb/s ↓ :{3:.1f}Kb/s').format(
net_infos[1]/1024/1024,net_infos[0]/1024/1024,net_infos[3],net_infos[2]))
#disk
print('\nFilesystem Mounted on Used/Total Used%')
for disk_info in disk_infos:
print(fill_str(disk_info[0], 20),fill_str(disk_info[5], 20),
fill_str(disk_info[2]+'/'+disk_info[1], 20),fill_str(disk_info[4], 15))
time.sleep(1)
if __name__ == '__main__':
main()
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册