Object Detection을 진행한 이미지에서 bndbox 영역만 crop 한 후classfication 진행.

원본 이미지를 학습된 classifier에 넣고 Grad-Cam 적용. 

Cam 이미지에서 다시 bndbox 영역을 Crop 한 후 원본 이미지에 Paste 해주기.

 

import os
from PIL import Image

# Get annotation
bndbox_area = (xmin, ymin, xmax, ymax)

# image crop
crop_image = cam_image.crop(bndbox_area)

# paste image
origin_image.paste(crop_image, (xmin, ymin))

# save image
origin_image.save('./result/{0}'.format(cam_images))

 

GPU 사용 현황 보기.

  • nvidia-smi
  • watch -n 1 -d nvidia-smi : 1 초마다 반복 실행.

.tar 압축 

  • tar -cvf 파일명.tar 폴더명

.tar 압축 해제

  • tar -xvf 파일명.tar

현재 동작하는 process 확인.

  • ps -ef | grep python

현재 동작하는 process 종료
ex ) answn34+  4226  3595  0 11:39 pts/0    00:00:00 grep python

  • sudo kill -9 3595 ( 강제 종료 )
  • sudo kill -15 3595 ( 정상 종료 )
  • sudo pkill -9 python (python 실행 파일 모두 종료)

권한 변경 ( -R 폴더전체 )

  • sudo chmod  777 file : 해당 file만 권한 변경

  • sudo chmod -R 777 folder/ : 해당 폴더안에 file들 권한 변경

 

소유자

  • sudo chown  answn3475.answn3475 : file 해당 file만 권한 변경

  • sudo chown -R answn3475.answn3475 folder/ : 해당 폴더안에 file들 소유자

파일 이동

  • sudo option mv 옮길파일 목적지 

  • sudo option  mv 옮길파일 목적지

파일 복사

  • sudo option cp 옮길파일 목적지 

  • sudo option cp 옮길파일 목적지 

 

삭제

  • rm file

  • rm -r folder

option

  • -b: 같은 이름의 파일이나 디렉터리가 존재하면 기존 파일을 백업한 뒤에 이동.

  • -f: 같은 이름의 파일이나 디렉터리가 존재하면 덮씀.

  • -i: 같은 이름의 파일이나 디렉터리가 존재하면 덮어쓸 때 물어봄.

  • -r:파일이면 그냥 복사, 디렉터리라면 디렉터리 전체가 복사.

 

https://github.com/MOONJOOYOUNG/Uncertainty-In-DeepLearning

pytorch imagenet multiprocessing-distributed training

 

imagenet을 학습 시킬 일이 있어서 작성....

 

보통 사용하는 torch.nn.DataParallel을 사용할 시 GPU-Util을 확인해 보면, 50% 정도밖에 사용하지 못하는 모습을 볼 수 있다.

DistributedDataParallel를 사용하면 이를 해결 할 수있고, 좀더 빠르게 학습이 가능하다....

원본 코드는 아래의 pytorch imagenet official 이며, 이를 바탕으로 수정

https://github.com/pytorch/examples/tree/master/imagenet

 

원본 코드에선 사용하는 GPU 수 만큼 log들이 모두 출력되도록 작성되어 있다.

몇몇 코드를 수정 하고 추가해서 이를 해결 했다.

 

기존 코드 log
수정 코드 log

실행 commander : -save_path './test/' --gpu_count 4 이 부분만 수정하고 돌리면 된다.

-save_path : 저장 경로, --gpu_count : 사용할 gpu 갯수이다.

 

python main.py -a resnet50 --dist-url 'tcp://127.0.0.1:2222' --dist-backend 'nccl' --multiprocessing-distributed --world-size 1 --rank 0 none --save_path './test/' --gpu_count 4

 

reduce_tensor 에서 사용하는 gpu log들을 모아 평균 계산.

 

전체 코드

https://github.com/MOONJOOYOUNG/pytorch_imagenet_multiprocessing-distributed

for i, (images, target) in enumerate(val_loader):
  data_time.update(time.time() - end)

  if args.gpu is not None:
  images = images.cuda(args.gpu, non_blocking=True)
  target = target.cuda(args.gpu, non_blocking=True)

  output = model(images)
  loss = criterion(output, target)

  acc1, acc5, correct = util.accuracy(output, target, topk=(1, 5))

  reduced_loss = reduce_tensor(loss.data)
  reduced_top1 = reduce_tensor(acc1[0].data)
  reduced_top5 = reduce_tensor(acc5[0].data)

  losses.update(reduced_loss.item(), images.size(0))
  top1.update(reduced_top1.item(), images.size(0))
  top5.update(reduced_top5.item(), images.size(0))
	
  if dist.get_rank() == 0:
    if i % args.print_freq == 0:
      progress.display(i)

def reduce_tensor(tensor):
    rt = tensor.clone()
    dist.all_reduce(rt, op=dist.reduce_op.SUM)
    # gpu 갯수로 나눠줌.
    rt /= args.gpu_count
    return rt

 

https://www.2025ad.com/news

https://observer.com/2019/08/self-driving-fed-policy-trump-kills-obama-era-advisory-group/

 

첫 번째 사이트에서 url과 title

두 번재 사이트에서 content를 긁어보겟다.

 

# -*- coding: utf-8 -*-
"""
Created on Tue Aug 13 14:09:57 2019

@author: User
"""

import json
import requests
import datetime
import random
import time
from bs4 import BeautifulSoup
from selenium import webdriver

# 셀레늄 기본 ..
driver = webdriver.Chrome(r'C:\Users\User\Desktop\chromedriver_win32\chromedriver')
driver.get('https://www.2025ad.com/news')
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
print(soup)
time.sleep(5)

# request 기본.
# url = 'https://www.2025ad.com/news'
# html = requests.get(url).text
# soup = BeautifulSoup(html, 'html.parser')
time.sleep(5)

 

# url 크롤링 하기.
list_urls = []
list_titles = []
for i in soup.find_all("a", {'class':'hs-rss-title'}) :
    list_titles.append(i.getText())
    list_urls.append(i['href'])


for i in list_urls:
    print(i)

for i in list_titles:
    print(i)

# 내용 크롤링하기 
driver.get('https://observer.com/2019/08/self-driving-fed-policy-trump-kills-obama-era-advisory-group/')
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

list_contents = []
contents = driver.find_elements_by_tag_name('p')
for i in contents :
   list_contents.append(i.text)
print(list_contents)

# 수집한 url 바탕으로 url 별 내용 크롤링
total_content = []
for i in list_urls:
    driver.get('{0}'.format(i))
    html = driver.page_source
    soup = BeautifulSoup(html, 'html.parser')
    
    list_contents = []
    contents = driver.find_elements_by_tag_name('p')
    for i in contents :
       list_contents.append(i.text)
       
    total_content.append(list_contents)
    
print(total_content)

 

# 다른방식으로도 사용할 수 있는 코드
################################################## 
url_contents = driver.find_elements_by_class_name('hs-rss-title') 


list_urls = [] 
for i in url_contents : 
    list_urls.append(i.get_attribute('href'))

 

#post-1194880 > div > p:nth-child(2) 
list_contents = [] 
title = '' 
for i in soup.find_all("div", {'class':'content-area'}) : 
    list_contents.append(i.getText()) 
     
     
for i in list_contents: 
    print(i) 

soup.select('#post-1194880 > div > p:nth-of-type(2)')     

################################################ 
     







불러오는 중입니다...

 

 

+ Recent posts