기계학습 (0907) 1주차

이미지자료분석
Author

김보람

Published

September 7, 2022

기계학습특강

# 우리의 1차 목표: 이미지 -> 개/고양이 판단하는 모형을 채용하고, 그 모형에 데이터를 넣어서 학습하고, 그 모형의 결과를 판단하고 싶다. (즉 클래시파이어를 만든다는 소리)
# 우리의 2차 목표: 그 모형에 "새로운" 자료를 전달하여 이미지를 분류할 것이다. (즉 클래시파이어를 쓴다는 소리)
from fastai.vision.all import *
path=untar_data(URLs.PETS)/'images'
100.00% [811712512/811706944 01:16<00:00]
path
Path('/root/.fastai/data/oxford-iiit-pet/images')
PILImage.create('/root/.fastai/data/oxford-iiit-pet/images/Abyssinian_1.jpg')

_lst = '/root/.fastai/data/oxford-iiit-pet/images/Abyssinian_1.jpg','/root/.fastai/data/oxford-iiit-pet/images/Abyssinian_10.jpg'
_lst[0]
'/root/.fastai/data/oxford-iiit-pet/images/Abyssinian_1.jpg'
faaaa = get_image_files(path)
#교수님은 filenames로 설정함
faaaa[0]
Path('/root/.fastai/data/oxford-iiit-pet/images/leonberger_137.jpg')
PILImage.create('/root/.fastai/data/oxford-iiit-pet/images/newfoundland_28.jpg')

PILImage.create(faaaa[0])

print(faaaa[1])
PILImage.create(faaaa[1])
/root/.fastai/data/oxford-iiit-pet/images/Birman_139.jpg

print(faaaa[3])
PILImage.create(faaaa[3])
/root/.fastai/data/oxford-iiit-pet/images/Egyptian_Mau_148.jpg

print(faaaa[6])
PILImage.create(faaaa[6])
/root/.fastai/data/oxford-iiit-pet/images/Siamese_79.jpg

'A'.isupper()
True
'abdjlkfwe.jpg'[0]
'a'
def f(fname):
  if fname[0].isupper():
    return 'cat'
  else:
    return 'dog'
dls = ImageDataLoaders.from_name_func(path,faaaa,f,item_tfms=Resize(224))
dls.show_batch(max_n=25)

# 우리의 1차 목표: 이미지 -> 개/고양이 판단하는 모형을 채용하고, 그 모형에 데이터를 넣어서 학습하고, 그 모형의 결과를 판단하고 싶다. (즉 클래시파이어를 만든다는 소리)
# 우리의 2차 목표: 그 모형에 "새로운" 자료를 전달하여 이미지를 분류할 것이다. (즉 클래시파이어를 쓴다는 소리)



## 오브젝트.. 오브젝트에는 동사와 명사 가 있어요

### 명사
# (1) 데이터
# (2) 채용한 모형의 이론
# (3) 평가기준 matric




### 동사
# (1) 학습
# (2) 판단
ysj = cnn_learner(dls,resnet34,metrics=error_rate)

##저항률 확인(잘 파악하는지 확인하기 위해서 metrics=error_rate 이용)

ysj.fine_tune(1)                  
              ## 3을 쓰면 1보다는 많이 한다는 뜻  
              ## 학습하다..동사,,
/usr/local/lib/python3.7/dist-packages/fastai/vision/learner.py:284: UserWarning: `cnn_learner` has been renamed to `vision_learner` -- please update your code
  warn("`cnn_learner` has been renamed to `vision_learner` -- please update your code")
/usr/local/lib/python3.7/dist-packages/torchvision/models/_utils.py:209: UserWarning: The parameter 'pretrained' is deprecated since 0.13 and will be removed in 0.15, please use 'weights' instead.
  f"The parameter '{pretrained_param}' is deprecated since 0.13 and will be removed in 0.15, "
/usr/local/lib/python3.7/dist-packages/torchvision/models/_utils.py:223: UserWarning: Arguments other than a weight enum or `None` for 'weights' are deprecated since 0.13 and will be removed in 0.15. The current behavior is equivalent to passing `weights=ResNet34_Weights.IMAGENET1K_V1`. You can also use `weights=ResNet34_Weights.DEFAULT` to get the most up-to-date weights.
  warnings.warn(msg)
Downloading: "https://download.pytorch.org/models/resnet34-b627a593.pth" to /root/.cache/torch/hub/checkpoints/resnet34-b627a593.pth
epoch train_loss valid_loss error_rate time
0 0.147350 0.014042 0.004060 00:56
epoch train_loss valid_loss error_rate time
0 0.053051 0.012090 0.004736 00:52
?cnn_learner
PILImage.create(faaaa[1])

ysj.predict(PILImage.create(faaaa[1]))
('cat', TensorBase(0), TensorBase([1.0000e+00, 3.0773e-10]))

ysj.predict(PILImage.create(faaaa[6])) #동사이고.. 뒤에 점찍었으니까 함수다 생각하기 # 입력을 이미지 자체로 넣었는데, 이미지가 저장된 path만 넣어도 되지않을까?

ysj.predict(faaaa[6])
('cat', TensorBase(0), TensorBase([1.0000e+00, 2.2963e-10]))
ysj.show_results()

##ysj가 잘구현이 되는지 체크를 해야함
# 체크를 하는 object를 만들어야함
checker = Interpretation.from_learner(ysj)
checker.plot_top_losses(16)

# 첫번째 사진에서 5.59는 로스이고 1퍼의 확률로 강아지라고 생각함
# 로스는 몇퍼의 확률로 잘못생각했느냐에 따라서 달라질 수 있음
# 맞추는 걸 넘어서 확실해야 로스가 적다. (확신의여부)

# 오버피팅 아냐..? 과대적합..? 자기들이 이미 다학습된 내용 가지고 보여주는거아냐? 생각->새로운 이미지 부여

img=PILImage.create(requests.get('https://dimg.donga.com/ugc/CDB/SHINDONGA/Article/5e/0d/9f/01/5e0d9f011a9ad2738de6.jpg').content)
ysj.predict(img)
('dog', TensorBase(1), TensorBase([2.8106e-06, 1.0000e+00]))
img=PILImage.create(requests.get('https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FcnSq1X%2Fbtq4o9AdWTH%2FHTm9TZG4AszSwLPFlVfGW0%2Fimg.jpg').content)
ysj.predict(img)
('dog', TensorBase(1), TensorBase([1.0909e-06, 1.0000e+00]))
img=PILImage.create(requests.get('https://image.edaily.co.kr/images/photo/files/NP/S/2022/04/PS22042501396.jpg').content)
ysj.predict(img)
('cat', TensorBase(0), TensorBase([1.0000e+00, 2.6542e-12]))
img=PILImage.create(requests.get('https://blog.kakaocdn.net/dn/zfQQi/btrydI0vGzm/3YY3KrPEwKN558e27H6t0k/img.jpg').content)
ysj.predict(img)
('cat', TensorBase(0), TensorBase([0.9805, 0.0195]))
PILImage.create('/강아지사진1.jpg')