1.對於指定數組,取特定值,其它設置爲0, 比如pytorch segmentation結果包含多個類,只取特定類,如何做?
#classp = [0,1,2,2,3,0,5,2]這樣,後面box,score,mask與之對應
ids = torch.where(classp==0)#選擇人類別
classp = classp[ids]
box = box[ids]
score = score[ids]
mask = mask[ids[0], :]
類似的也可以更簡單
#classp = [0,1,2,2,3,0,5,2]這樣,後面box,score,mask與之對應
ids = (classp==0)#選擇人類別
classp = classp[ids]
box = box[ids]
score = score[ids]
mask = mask[ids, :]
2. pytorch在inference階段,如何保證模型沒有梯度信息?
使用with torch.no_grad(), 修飾
with torch.no_grad():
cudnn.fastest = True
torch.set_default_tensor_type('torch.cuda.FloatTensor')
print('yolact loading model...', end='')
net = Yolact()
net.load_weights(config.yolact['model_path'])
net.eval()
print(' Done.')
self.net = net.cuda()
self.net.detect.use_fast_nms = True
self.net.detect.use_cross_class_nms = False
3.如何把numpy數組,轉化爲pytorch tensor, 在轉換到cuda上
torch.from_numpy(np_array).cuda().float()
4.vs code裏面如何調試一個文件?如何加入調試參數,很多args?如何使用conda環境的python?如何指定調試的工作目錄?
1)通過圖形界面操作,生成launch.json
2)編輯,加入args:["--thresh=0.5", "--cuda"
3)加入pythonPath:"/home/silva/anaconda3/envs/py372/bin/python"
4)加入cwd:"/home/silva/work"
{
// 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}",
"pythonPath": "/home/silva/anaconda3/envs/py372/bin/python",
"cwd": "${fileDirname}",
"args": [
"--trained_model=weights/yolact_resnet50_54_800000.pth",
"--score_threshold=0.15",
"--top_k=15",
"--video_multiframe=4",
"--video=0"
]
}
]
}
5. numpy array 作爲函數參數傳遞,是作爲引用傳遞,還是拷貝傳遞?
以前經常搞錯,原來是引用傳遞。在函數內部,修改了array, 那麼調用函數的那個array也會修改。
def abc(arr): arr = np.zeros((3,3))
調用a=np.ones((3,3)), 那麼abc(a), 執行後,print(a)是多少?不變
如果def abc(arr): arr+=3, abc(a)執行後?增加了3
如果def abc(arr): arr[1][1]=34, abc(a)執行後?a對應元素變爲了34
參考 https://stackoverflow.com/questions/11585793/are-numpy-arrays-passed-by-reference
6.pytorch, detectron2 如何從pth的checkpoint中,更改類別數,重新訓練?
detection_checkpoint.py做如下更改
def _load_file(self, filename):
if filename.endswith(".pkl"):
with PathManager.open(filename, "rb") as f:
data = pickle.load(f, encoding="latin1")
if "model" in data and "__author__" in data:
# file is in Detectron2 model zoo format
self.logger.info("Reading a file from '{}'".format(data["__author__"]))
return data
else:
# assume file is from Caffe2 / Detectron1 model zoo
if "blobs" in data:
# Detection models have "blobs", but ImageNet models don't
data = data["blobs"]
data = {k: v for k, v in data.items() if not k.endswith("_momentum")}
return {"model": data, "__author__": "Caffe2", "matching_heuristics": True}
loaded = super()._load_file(filename) # load native pth checkpoint
model_dict = loaded['model']
#model_dict = pretrained_model.state_dict()
pretrained_dict = {k: v for k, v in model_dict.items() if k in model_dict and "roi_heads" not in k}#去掉roi_heads
#model_dict.update(pretrained_dict)
loaded['model'] = pretrained_dict
loaded['optimizer']['state']={} #去掉optimizer
print("loaded new model")
if "model" not in loaded:
loaded = {"model": loaded}
return loaded
參考https://github.com/facebookresearch/maskrcnn-benchmark/pull/324/files