服务器上的python指令

  • ctrl+c: 前台进程终止 ,直接终止当前正在运行的进程。
  • ctrl+z :中断任务执行,类似于暂停执行的意思,执行该操作意味着当前的进程被挂起。
  • 被挂起的进程只有在当下窗口,可以用jobs查看
  • jobs :查看在后台执行的进程。注意:如果退出当前终端,则无法再次进入终端查看到后台进程。jobs -l 看到pid
  • ps -u查看隶属于自己的进程,
  • linux 中查看python后台运行的程序:ps -ef | grep python

Linux后台运行python程序_linux train.py恢复进程_等待戈多。的博客-CSDN博客

常用loss合集

TV loss

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class TVLoss(nn.Module):
def __init__(self,TVLoss_weight=1):
super(TVLoss,self).__init__()
self.TVLoss_weight = TVLoss_weight

def forward(self,x):
batch_size = x.size()[0]
h_x = x.size()[2]
w_x = x.size()[3]
count_h = self._tensor_size(x[:,:,1:,:]) #channel * (h-1) * w
count_w = self._tensor_size(x[:,:,:,1:]) #channel * h * (w-1)
h_tv = torch.pow((x[:,:,1:,:]-x[:,:,:h_x-1,:]),2).sum()
w_tv = torch.pow((x[:,:,:,1:]-x[:,:,:,:w_x-1]),2).sum()
return self.TVLoss_weight*2*(h_tv/count_h+w_tv/count_w)/batch_size

def _tensor_size(self,t):
return t.size()[1]*t.size()[2]*t.size()[3]

个人理解 *2 的意思是TV是四个方向的,所以两个方向计算下来需要 * 2

将测试图片网页展示

安装与准备

pip install dominate

html.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import dominate
from dominate.tags import meta, h3, table, tr, td, p, a, img, br
import os


class HTML:
"""This HTML class allows us to save images and write texts into a single HTML file.

It consists of functions such as <add_header> (add a text header to the HTML file),
<add_images> (add a row of images to the HTML file), and <save> (save the HTML to the disk).
It is based on Python library 'dominate', a Python library for creating and manipulating HTML documents using a DOM API.
"""

def __init__(self, web_dir, title, refresh=0):
"""Initialize the HTML classes

Parameters:
web_dir (str) -- a directory that stores the webpage. HTML file will be created at <web_dir>/index.html; images will be saved at <web_dir/images/
title (str) -- the webpage name
refresh (int) -- how often the website refresh itself; if 0; no refreshing
"""
self.title = title
self.web_dir = web_dir
self.img_dir = os.path.join(self.web_dir, 'images')
if not os.path.exists(self.web_dir):
os.makedirs(self.web_dir)
if not os.path.exists(self.img_dir):
os.makedirs(self.img_dir)

self.doc = dominate.document(title=title)
if refresh > 0:
with self.doc.head:
meta(http_equiv="refresh", content=str(refresh))

def get_image_dir(self):
"""Return the directory that stores images"""
return self.img_dir

def add_header(self, text):
"""Insert a header to the HTML file

Parameters:
text (str) -- the header text
"""
with self.doc:
h3(text)

def add_images(self, ims, txts, links, width=400):
"""add images to the HTML file

Parameters:
ims (str list) -- a list of image paths
txts (str list) -- a list of image names shown on the website
links (str list) -- a list of hyperref links; when you click an image, it will redirect you to a new page
"""
self.t = table(border=1, style="table-layout: fixed;") # Insert a table
self.doc.add(self.t)
with self.t:
with tr():
for im, txt, link in zip(ims, txts, links):
with td(style="word-wrap: break-word;", halign="center", valign="top"):
with p():
with a(href=os.path.join('images', link)):
img(style="width:%dpx" % width, src=os.path.join('images', im))
br()
p(txt)

def save(self):
"""save the current content to the HMTL file"""
html_file = '%s/index.html' % self.web_dir
f = open(html_file, 'wt')
f.write(self.doc.render())
f.close()


if __name__ == '__main__': # we show an example usage here.
html = HTML('web/', 'test_html')
html.add_header('hello world')

ims, txts, links = [], [], []
for n in range(4):
ims.append('image_%d.png' % n)
txts.append('text_%d' % n)
links.append('image_%d.png' % n)
html.add_images(ims, txts, links)
html.save()

测试时

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from utils import html
def save_web_images(self, webpage, data, images, epoch):
if self.cfg.model.type == "Baseline":
img_path_relative = (data["image_A_path"][0]).split("/")[-1]
save_path = self.results_path / img_path_relative
save_path.parent.mkdir(exist_ok=True, parents=True)
webpage.add_header(save_path.stem)
txts = ['input','enhanced','GT','changemap','mask']
ims, links = [], []
width = 450
str_epoch = '_'+str(epoch)
root = str(save_path.parent)+'/'+str(save_path.stem)+str_epoch+".png"
self.to_pil(self.denorm(data["image_A"][0])).save(root)
self.to_pil(self.denorm(images["fake_B"][0])).save(save_path.parent / f"{save_path.stem}_enhanced.png")
self.to_pil(self.denorm(images["latent"][0]/3)).save(save_path.parent / f"{save_path.stem}_latent.png")
self.to_pil(self.denorm(data["image_B"][0])).save(save_path.parent / f"{save_path.stem}_gt.png")
self.to_pil((data["input_mask"])[0]).save(save_path.parent / f"{save_path.stem}_mask.png")
ims.append(root)
ims.append(save_path.parent / f"{save_path.stem}_enhanced.png")
ims.append(save_path.parent / f"{save_path.stem}_gt.png")
ims.append(save_path.parent / f"{save_path.stem}_latent.png")
ims.append(save_path.parent / f"{save_path.stem}_mask.png")
webpage.add_images(ims, txts, ims, width=width)
else:
raise "Unknown visualisation config"
web_dir = 'where images folder'
webpage = html.HTML(web_dir, 'Experiment = %s, Epoch = %s' % (cfg.model.type, cfg.model.load_epoch))

for images in results
    visualizer.save_web_images(webpage, data, images, epoch)

优雅的python深度学习

根目录下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
conf
    train.yaml
    test.yaml
data
    __init__.py           //最外层 get_dataset(dataset_name)
    datasets.py //各种个样dataset(paired unpaired combaind..)
    transform.py //制作dataset的时候,用到的数据变化 比如norm crop等
    utils.py //读取 加载 图片类型转化 padding等data用到的工具

model
    vgg19.weight

models
    auxiliary.py //作为特征提取或者vggloss 辅助网络
    discriminators.py //组成鉴别器的不同组件 以及不同鉴别器
    generators.py      //组成生成器的不同组件 以及不同生成器
    losses.py //比较复杂的loss 例如GAN perceptual loss
    engan.py //实验的完整网络和对比网络 由G和D和loss共同构成
    utils.py //初始化网络 初始化权重等 models部分用到的工具
outputs
    实验输出
utils
    metrics.py //一些评价指标
    utils.py              //系统时间啊 get device啊
    visualize.py //图片可视化和保存

eval.py
train.py
test.py
README.md

Hydra使用

最简单使用

安装

1
pip install hydra-core

初步测试

目前的代码结构

1
2
3
4
folder
├── conf
│ └── recoro_train.yaml
└── main.py

其中main.py

1
2
3
4
5
6
7
8
9
10
11
12
13
from omegaconf import DictConfig, OmegaConf
import hydra

@hydra.main(config_path="./conf", config_name="recoro_train")
def main(cfg: DictConfig):
    running_dir = str(hydra.utils.get_original_cwd())
working_dir = str(Path.cwd())
print(f"The current running directory is {running_dir}")
print(f"The current working directory is {working_dir}")


if __name__ == "__main__":
main()

结果

1
2
The current running directory is C:\Users\xx\xx\xx\folder\
The current working directory is C:\Users\xx\xx\xx\folder\outputs\2023-02-08\22-47-06

可以看到hydra运行时,会自动建立一个输出文件夹,包含日期和时间信息,然后还会直接将路径调到里面去,以方便保存脚本内的各种东西。这就是初步测试,全部都在这一行:配置的路径在”conf”,配置的文件名为”recoro_train”

因此,无论在代码的任何地方,新建文件都会在working directory下 进行新建写入。

【Python】Hydra 库使用记录_Kin__Zhang的博客-CSDN博客_python hydra

python常用指令

查看pytorch版本

1
2
import torch
print(torch.__version__)

python 文件管理

文件列表
1
2
3
4
filefolder = os.listdir(root)
filefolder.sort()
for f in filefolder:
    print(f)
删除文件
1
2
3
4
5
6
7
8
import os
import shutil

os.remove(path) #删除文件
os.removedirs(path) #删除空文件夹

os.rmdir(path) #删除空文件夹
shutil.rmtree(path) #递归删除文件夹,即:删除非空文件夹
文件读取
1
2
3
4
with open('./loss.txt','a+') as f:   
for key in losssum:
f.write(f"test_img : losses {key}: {losssum[key]/items}\n")
f.close()

python 直接使用os.system

1
2
3
command = 'ffmpeg -i ./results/%s/'%(datasetname[i]) +'%06d.png ./results'+'/%s.mp4'%(datasetname[i])
print(command)
os.system(command)

python 读写、创建 文件 - juandx - 博客园

python超参传递

1
2
3
4
5
6
7
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-in", "--inputA", help="this is parameter a", type=str, default="")
parser.add_argument("-out", "--outputB", help="this is parameter b", type=str, default="")
args = parser.parse_args()
print(args.inputA)
1
python3 /Users/PeppaZhu/Desktop/studio_light/zoom_VB/test_V4_1NGF.py -in test_video_gfdebug/peppa_13test.mov -out peppa_13test_V4_4

cplusplus文件管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;
std::string path = "/Users/oliverzhu/Desktop/test_video/";
for (const auto &entry : fs::directory_iterator(path)){
        //将文件夹下所有文件名得到
std::string inputpath = entry.path();
std::string::size_type nPos1 = std::string::npos;
std::string::size_type nPos2 = std::string::npos;
nPos1 = inputpath.find_last_of("/");
nPos2 = inputpath.find_last_of(".");
        //截取/开始 长度为nPos2-nPos1-1的字符串
std::string strPath = inputpath.substr(nPos1 + 1, nPos2-nPos1-1);
std::string input_path;
std::string output_path;
if (nPos2-nPos1 > 1)
{
// vaild input path
input_path = inputpath;
output_path = "/Users/oliverzhu/Desktop/results/" + strPath + ".mp4";
std::cout << input_path << std::endl;
std::cout << output_path << std::endl;
        }

https://codeantenna.com/a/vhWRDy0wan

cplusplus里数据类型的大小和存储方式

不同数据类型的大小

相同位数的系统下,每一个变量的地址大小相同

1
2
3
4
5
6
7
8
9
        int32_t va; int32_t* vb; double vc; double* vd; uint8_t ve; uint8_t* vf; intptr_t vg;

        int32_t a = sizeof(&va); //8
int32_t b = sizeof(&vb); //8
int32_t d = sizeof(&vc); //8
int32_t e = sizeof(&vd); //8
int32_t f = sizeof(&ve); //8
int32_t g = sizeof(&vf); //8
int32_t h = sizeof(&vg); //8

以上变量地址大小都是 8 ,因为在64位体统下。

相同位数的系统下,不同类型变量占有的空间大小不同

1
2
3
4
5
6
7
8
9
10
int32_t va; int32_t* vb; double vc; double* vd; uint8_t ve; uint8_t* vf; intptr_t vg;

int32_t a = sizeof(va); //4
int32_t b = sizeof(vb); //8
int32_t d = sizeof(vc); //8
int32_t e = sizeof(vd); //8
int32_t f = sizeof(ve); //1
int32_t g = sizeof(vf); //8
int32_t h = sizeof(vg); //8
int32_t i = sizeof(*vb); //4

这里*vb == vb[0]

不同位数的系统下,不同/相同变量占有的大小不同

当申请一块 uint_8* buff 时,系统划分出一个8字节的大小,存储了一个指向随机位置的指针。

buff = (uint_8*)calloc(seizeof(*buff) * 10,0 ); 时,buff指向了一块地址。这块地址保存的都是十个 1字节的uint_8数据。

1
2
3
4
5
6
7
8
        uint8_t* aa;
aa = (uint8_t*)zltCMemoryBasic::zlt_calloc(sizeof(*aa) * bufSizeB * 12, 0);

        aa[0] = 1; aa[1] = 2;
uint8_t a = aa[0]; //1
uint8_t c = aa[1]; //2
uint8_t b = *aa; //1
uint8_t d = *(aa+1); //2

uint8 int float double 怎么在计算机内存储

uint8:占一个字节八位, 无符号数,0~255,算数or逻辑左移右移就是左右移动,舍去移动的位数然后补零

int32 :四个字节32位,有符号数,最高位代表符号。

最大数2147483647的原码为0111 1111 1111 1111 1111 1111 1111 1111

最小数-2147483648的补码表示为1000 0000 0000 0000 0000 0000 0000 0000,在32位没有原码。

对有符号数逻辑左右移动不考虑符号,算数右移补符号位。

float32: 四字节32位,有符号数,最高位代表符号。E代表指数 2E M代表尾数

https://zhuanlan.zhihu.com/p/84453627