inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

딥러닝 CNN 완벽 가이드 - TFKeras 버전

섹션6 CIFAR10 imshow() 시각화 문제

해결된 질문

318

kjyn0124

작성한 질문수 5

0

안녕하세요 교수님!

5강 시작부분에서 get_preprocessed_data의 scaling 파라미터 값을 False로 하셨는데, 그러면 픽셀값을 255로 나누지 않는 것인데 이렇게 하면 다음과 같은 흰색 배경만 뜨더라구요..

그래서 구글링을 해보니까 plt.imshow() 함수가 0 ~ 1 사이의 float형이나 0 ~ 255 사이의 int형만 가능하다고 해서 다음과 같이 바꾸었는데 제대로 출력되더라구요..!

...

def get_preprocessed_data(images, labels, scaling=True):
    if scaling: # 직접 scaling을 한다고 했을때?
        images = np.array(images/255.0, dtype=np.float32)
    else:
        images = np.array(images, dtype=np.int32) # 이 부분을 수정했습니다.
    
    oh_labels = np.array(labels, dtype=np.float32)
    return images, oh_labels

def get_preprocessed_ohe(images, labels):
    images,labels = get_preprocessed_data(images, labels, scaling=False)
    
    # OHE
    oh_labels = to_categorical(labels)
    return images, oh_labels

...

교수님 코드랑 다른 부분이 없는데 저는 흰 배경으로만 나오고, 저렇게 설정해야지만 올바르게 나오는 점이 이상해서 여쭤보고자 합니다ㅠㅠ!

 

혹시 몰라서 해당 부분 전체 코드 올리겠습니다!

from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
from sklearn.model_selection import train_test_split

# seed 설정
def set_random_seed(seed_value):
    np.random.seed(seed_value)
    python_random.seed(seed_value)
    tf.random.set_seed(seed_value)

def get_preprocessed_data(images, labels, scaling=True):
    if scaling: # 직접 scaling을 한다고 했을때?
        images = np.array(images/255.0, dtype=np.float32)
    else:
        images = np.array(images, dtype=np.float32)
    
    oh_labels = np.array(labels, dtype=np.float32)
    return images, oh_labels

def get_preprocessed_ohe(images, labels):
    images,labels = get_preprocessed_data(images, labels, scaling=False)
    
    # OHE
    oh_labels = to_categorical(labels)
    return images, oh_labels

def get_train_valid_test_set(train_images, train_labels, test_images, test_labels, valid_size=0.15, random_state=2023):
    train_images, train_ohe_labels = get_preprocessed_ohe(train_images, train_labels)
    test_images, test_ohe_labels = get_preprocessed_ohe(test_images, test_labels)
    
    train_images, valid_images, train_ohe_labels, valid_ohe_labels = train_test_split(train_images, train_ohe_labels, test_size=valid_size, random_state=random_state)
    return train_images, train_ohe_labels, valid_images, valid_ohe_labels, test_images, test_ohe_labels
set_random_seed(2023)
(train_images, train_labels), (test_images, test_labels) = cifar10.load_data()
print(train_images.shape, train_labels.shape, test_images.shape, test_labels.shape)

train_images, train_ohe_labels, valid_images, valid_ohe_labels, test_images, test_ohe_labels = get_train_valid_test_set(train_images, train_labels, test_images, test_labels, valid_size=0.15, random_state=2023)
print(train_images.shape, train_ohe_labels.shape, valid_images.shape, valid_ohe_labels.shape, test_images.shape, test_ohe_labels.shape)
NAMES = np.array(['Airplane', 'Automobile', 'Bird', 'Cat', 'Deer', 'Dog', 'Frog', 'Horse', 'Ship', 'Truck'])
def show_images(images, labels, ncols=8):
    figure, axs = plt.subplots(nrows=1, ncols=ncols, figsize=(22, 6))
    
    for i in range(ncols):
        axs[i].imshow(images[i])
        label = labels[i].squeeze()
        axs[i].set_title(NAMES[int(label)])

show_images(train_images[:8], train_labels[:8], ncols=8)
show_images(train_images[8:16], train_labels[8:16], ncols=8)
show_images(train_images[16:24], train_labels[16:24], ncols=8)

감사합니다!

머신러닝 딥러닝 keras tensorflow kaggle cnn

답변 1

0

권 철민

안녕하십니까,

네 맞습니다. plt.imshow() 함수가 0 ~ 1 사이의 float형이나 0 ~ 255 사이의 int형을 가진 array일 때 제대로 시각화 해줍니다.

제 생각엔 get_preprocessed_data()를 변경하실 필요까지는 없고 시각화 할때만 0~255 사이의 값을 가질 경우에 int형으로 변경만 해주시면 될 것 같습니다.

그러니까 시각화 할때만 plt.imshow(train_data[:8].astype(np.int32))

로만 적용해 주시면 될 것 같습니다.

 

감사합니다.

resize 질문

0

50

1

20251212 Kaggle 런타임에 scikit-learn 설치 실패 트러블 슈팅

0

75

1

Loss와 매트릭 관계

0

61

2

Boston 코랩 실습

0

162

2

배치 정규화의 이해와 적용 2 강의 질문

0

134

2

Augmentation원본에 적용해서 데이터 갯수 자체를 늘리는 행위는 의미가있나요?

0

144

2

Conv함수 안에 activation 을 넣지 않는 이유가 뭔지 궁금합니다.

0

203

2

소프트맥스 관련 질문입니다

0

208

1

강의 관련 질문입니다

0

151

2

residual block과 identity block의 차이

0

185

2

옵티마이저와 경사하강법의 차이가 궁금합니다.

1

238

1

실습 환경

0

165

2

입력 이미지 크기

0

243

2

데이터 증강

0

195

2

albumentations ShiftScaleRotate

0

205

1

Model Input Size 관련

0

279

1

마지막에 bird -> frog 말고도 deer -> frog 도 잘못된것 아닌가요??

0

204

1

일반적인 질문 (kaggle notebook사용)

0

272

2

실무에서 Augmentation 적용 시

0

337

2

안녕하세요 교수님

0

231

1

가중치 초기화(Weight Initialization) 질문입니다.

0

327

1

테스트 데이터셋 predict의 'NoneType' object has no attribute 'shape' 오류

0

407

1

학습이 이상하게 됩니다.

2

1036

2

boston import가 안됩니다

0

228

1