묻고 답해요
167만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨딥러닝 CNN 완벽 가이드 - TFKeras 버전
섹션6 CIFAR10 imshow() 시각화 문제
안녕하세요 교수님!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_labelsset_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)감사합니다!
-
해결됨파이썬을 활용한 머신러닝 딥러닝 입문
LeNet-5 실습 중 loss값 nan이 나오고 있습니다.
강의와 동일하게 코드를 쳐서 진행한 것 같은데 loss값 자체가 nan이 나오고 accuracy는 0.1을 넘기지 못하는 중입니다. 왜 이렇게 나오는 건지 알려주실 수 있을까요?
-
미해결Tensorflow 사용메뉴얼
epoch 1부터 loss가 너무 낮게 나와 학습이 안되네요
ratio = 0.2 x_train = tf.random.normal(shape = (300,), dtype = tf.float32) y_train = 3 * x_train + 1 + ratio * tf.random.normal(shape = (300, ), dtype = tf.float32) x_test = tf.random.normal(shape = (30,), dtype = tf.float32) y_test = 3 * x_test + 1 + ratio * tf.random.normal(shape = (30, ), dtype = tf.float32) class LinearPredictor(Model): def __init__(self): super(LinearPredictor, self).__init__() self.d1 = Dense(1, activation = "linear") def call(self, x): x = self.d1(x) return x model = LinearPredictor() loss_object = tf.keras.losses.MeanSquaredError() optimizer = SGD(learning_rate=0.01) for epoch in range(5): for x, y in zip(x_train, y_train): x = tf.reshape(x, (1, 1)) with tf.GradientTape() as tape: predictions = model(x) loss = loss_object(y, predictions) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) print(f"Epoch: {epoch + 1}") print(f"Train Loss: {loss:.4f}") 강사님이랑 똑같이 코드를 짠것 같은데 train loss가 너무 낮게 나와 학습이 안되네요. 틀린곳이 있는건지 데이터가 너무 심플하게 생성되서 그런건지 잘 모르겠습니다.
-
미해결Tensorflow 사용메뉴얼
텍스트 데이터일 때의 dtype
강의에서 데이터의 형식을 tf.float32로 맞추는 것을 강조하셨는데 텍스트 데이터일때는 어떤 형식을 맞추는 것이 중요한지 궁금합니다.
-
미해결Google 공인! 텐서플로(TensorFlow) 개발자 자격증 취득
tdc 자격증 유효기간지나면
tdc 자격증 유효기간지나면 다시 시험쳐야하는거죠 .?
-
미해결Tensorflow 사용메뉴얼
12강 data split take와 skip
안녕하십니까 강의 너무 잘보고 있습니다!12강 Data Split 부분에서 궁금한 것이 생겨 질문하게 되었습니다.저는 data.skip(10) 코드의 경우 data의 처음 10개 이후의 데이터를 생성해주는 것으로 이해했습니다.그러면 train_validation에서 train을 take(n_train)을 통해 나누고 validation은 skip(n_train)으로 생성하면 되지 않나요?validation 데이터 생성시 skip 이후에 왜 take를 이용해야하는지 궁금합니다.
-
미해결[개정판] 딥러닝 컴퓨터 비전 완벽 가이드
에어리얼 스페이싱? 이 뭔가요
Ratinanet의 FPN 강의를 듣고 있었습니다. 각 구간별 피처맵에서 UPSapleing하여 더해준 후 3X3 covolution 연산을 해준다고 들었는데 그 후 3X3 convolution 연산을 하는 이유가 에어리얼 스페이싱 때문이라는 거 같은데 이게 맞는건지 여쭙고 싶습니다.
-
미해결[개정판] 딥러닝 컴퓨터 비전 완벽 가이드
spp에서 궁금한점이 있습니다.
8*8 region proposal 영역이 아닌 8*9의 region proposal 영역이 있을 때 이를 정확히 4분면으로 나눌 수 없는데 이때는 패딩을 더하나요?
-
미해결딥러닝 CNN 완벽 가이드 - TFKeras 버전
from tensorflow.keras.models import Sequential
제목처럼 Sequenital을 import해서 쓰는 것과 keras.Sequential을 쓰는 것의 차이가 있나요? models의 차이가 있는지 궁금합니다. 실행했을 땐 똑같긴한데.. 굳이 왜 다른지 궁금합니다. Dense(1, input_shape = (2, ), ....) 에서 왜 2가 앞에 쓰이는 건가요?? 앞은 보통 행인데...ㅠㅠkeras가 행은 몇개인지 몰라도 되는데 피쳐는 몇개인지 알아야 하는건가요?
-
미해결[개정판] 딥러닝 컴퓨터 비전 완벽 가이드
confidence score의 정의에 대해
confidence score가 어떤 곳에서는 class score인지 object 인지 아닌지를 판단하는 object score인지 아니면 어떤 곳에서는 저 두개의 곱으로도 나타내더군요.혹시 정의에 대해서 확인해봐도 되겠습니까
-
해결됨딥러닝 CNN 완벽 가이드 - TFKeras 버전
save_weights_only=True로 했을 때 load_model 오류
안녕하세요 교수님!ModelCheckpoint에서 ModelCheckpoint('best_model.h5', save_weights_only=True, monitor='val_loss', save_best_only=True, mode='min')save_weights_only = True로 했을 때 아래와 같은 load_model 에러가 나더라구요..그래서 구글링을 해봤는데 저렇게 설정할 경우에 모델 아키텍처가 저장이 안되어서 load_model을 할 수 없다고 json 파일로 모델을 따로 저장하고 나중에 json 모델을 다시 불러오는 방법을 사용하라고 나왔습니다. 강의 중에도 언급해주셨지만 save_weights_only = True로 했을 때의 이점이 있을까요..? False로 했을 때 교수님께서 모델을 불러올 때 충돌..? 비슷한 것이 난다고 하셨는데 좀 더 세부적인 내용을 알고 싶습니다..!만약에 True로 설정했다면 매번 json으로 모델을 저장하는 과정을 거쳐야 하는 것인지 궁금합니다!model.save() 함수도 있던데 이거는 modelcheckpoint와 달리 학습 중에 저장은 안되는 것 같아서요.. 항상 감사합니다 교수님!!
-
미해결딥러닝을 활용한 자연어 처리 (NLP) 과정 (기초부터 ChatGPT/생성 모델까지)
트랜스포머 추론 단계에서 질문드립니다.
predictions, _ = self.transformer([encoder_input, output], training=False) # seq_len dimension에서 last token을 선택합니다. predictions = predictions[:, -1:, :] # (batch_size, 1, vocab_size) predicted_id = tf.argmax(predictions, axis=-1)트랜스포머 최종 결과값으로batch x seq_len x vocab_size 로 단어의 갯수만큼 확률 분포를 구하는 것을 이해했습니다.그리고 추론단계의 번역이므로 1개의 단어씩 output으로 뽑아야 한다는 것도 알겠는데요.위 코드에서 생성을 위해 seq_len dimension에서 last token을 선택하는 이유(predictions[:, -1:, :] 부분) 는 무엇인가요?
-
미해결딥러닝을 활용한 자연어 처리 (NLP) 과정 (기초부터 ChatGPT/생성 모델까지)
Decoder 전체(10) 부분에서 attn_weight output shape 관련 질문 드립니다.
sample_decoder = Decoder(num_layers=2, d_model=512, num_heads=8, dff=2048, target_vocab_size=8000, maximum_position_encoding=5000) x = tf.random.uniform((64, 26), dtype=tf.int64, minval=0, maxval=200) output, attn = sample_decoder(x, enc_output=sample_encoder_output, training=False, look_ahead_mask=None, padding_mask=None) output.shape, attn['decoder_layer2_block2'].shape위 코드 결과 output은 (TensorShape([64, 26, 512]), TensorShape([64, 8, 26, 62]))인데요.atten output size 64 x 8 x 26 x 62는batch x head num x seq_len x depth(=len_k) 의 사이즈일것 같은데요.depth의 경우, d_model(512) / num_head(8) = 64 가 되야하는게 아닌지요? 62인 이유가 궁금합니다.
-
미해결딥러닝을 활용한 자연어 처리 (NLP) 과정 (기초부터 ChatGPT/생성 모델까지)
트랜스포머 feed forward network 보다가 질문드립니다.
제가 아직 word embedding 이 NN으로 들어갈 때 어떻게 학습하는지 개념이 헷갈리는것 같습니다. 먼저 기초적인 질문이라 죄송합니다 ^^;;교재에서 Position-wise Feed Forward NN는 단어별로 별도로 적용된다고 설명해주셨는데요!예를 들어, 강의 교재의 10(=seq_len=단어의 갯수) x 512(=d model) 이 dff가 2048인 Position-wise Feed Forward NN에 input으로 들어오면,첫번째 단어(1x512 vector)가 feed forward nn에 들어와서 학습 후 동일한 nn에 두번째 단어(1x512 vector)가 들어와서 학습...열번째 단어도 동일한 과정으로 feed forward nn이 학습되는 개념이라고 이해하면 될까요?항상 상세한 답변에 감사드립니다.
-
미해결딥러닝을 활용한 자연어 처리 (NLP) 과정 (기초부터 ChatGPT/생성 모델까지)
LSTM Decoder 모델에서 train 모델과 inference 모델 관련 질문드립니다.
# decoder 는 [h, c] 를 initial state 로 사용 decoder_inputs_ = Input(shape=(max_len_kor,), name="Decoder_Input") # decoder word embedding 은 pre-trained vector 를 사용 않음 decoder_embedding = Embedding(num_words_kor, EMBEDDING_DIM) decoder_inputs_x = decoder_embedding(decoder_inputs_)Q 1-1. training state에서는 위와 같이 decoder input이 한 문장의 seq를 모두 input으로 넣어주는데, 이는 teacher forcing을 위해 매 step 마다 seq 데이터(한 문장 데이터)를 input으로 모두 사용하기 때문인 것인가요? decoder_inputs_single = Input(shape=(1,), name='Decoder_input') x = decoder_embedding(decoder_inputs_single)Q 1-2. inference state에서는 위와 같이 input size가 1인 이유는, 매번 step마다 하나의 단어(번역할 단어=최초 <sos>, 그 후부터 이전 step의 output)만 input으로 사용하기 때문인가요? Q2. LSTM encoder의 경우 encoder output, h, c를 최종 산출물로 리턴해주는데요. h와 c가 context vector로 decoder의 input으로 입력된다고 이해하였습니다. 그렇다면, 번역 모델에서 encoder output은 어떤 값을 갖고 있으며 어떤 용도로 사용될 수 있을까요? 감사합니다!
-
미해결딥러닝 CNN 완벽 가이드 - TFKeras 버전
정보가 손실되는 이유가 궁금합니다!
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 강의 내용을 질문할 경우 몇분 몇초의 내용에 대한 것인지 반드시 기재 부탁드립니다. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.강의에서 conv2d연산을 진행한 후에 softmax연산을 해주기 위해 3차원 데이터를 flatten시켜줬는데 flatten시켜준 후에 바로 softmax함수를 적용시키면 어떤 이유로 정보가 손실되는 이유에 대해서 궁금합니다.dense를 하나 추가하고 softmax를 적용하는 것과 dense없이 flatten후 softmax를 적용하는 것의 차이점에 대해서 궁금증이 생긴 것 같습니다!
-
미해결[개정판] 딥러닝 컴퓨터 비전 완벽 가이드
opencv Yolo v3 inference
안녕하세요. 권철민 강사님유익한 영상 잘 보고 있습니다. 현재 opencv로 Yolov3를 inference하는 파트를 보고 있습니다.nms threshold 값이 예를 들어nms_confidence = 0.4이면 한 상자당 confidence score가 가장 높은 상자를 뽑아 for문을 돌면서 iou 값이 nms_confidence이상이면 제거하는 데 쓰이는 것이 맞는지 확인하고 싶습니다. 그리고 85개의 차원중에 5번째에 있는 객체가 있는지 없는 지를 판단하는 confidence (detection[5])은 안쓰는 지 여쭙고 싶습니다. 본 코드에서는 class_score 부분만 if문에 조건으로 사용하여 의아한 기분이 들어 질문 드립니다.
-
미해결딥러닝 CNN 완벽 가이드 - TFKeras 버전
Validation Data Set Augmentation 문의
안녕하세요.좋은 강의 감사합니다.Validation Data Set Augmentation 관련 문의드립니다.tr_ds = image_dataset(tr_path, tr_label, image_size=IMAGE_SIZE, batch_size=BATCH_SIZE, augmentor=image_augmentor, shuffle=True, pre_func=xcp_preprocess_input) val_ds = image_dataset(val_path, val_label, image_size=IMAGE_SIZE, batch_size=BATCH_SIZE, augmentor=None, shuffle=False, pre_func=xcp_preprocess_input) Validation Set 부분은 Augmentation을 None으로 진행했는데요.Augmentation을 None이 아닌 것으로 진행해도 성능에는 크게 문제가 없을 것으로 생각합니다. (별도 Test Set으로 평가했을 때, 평가 성능이 저하 된다거나 그렇진 않을 것 같아서요.)Validation Set 부분도 Train Set과 마찬가지로 Augmentation을 진행해도 되지 않을까요? 딱히 구글링으로 명확한 답을 찾기 어려워 선생님의 의견을 얻어보고 싶습니다.감사합니다.
-
미해결딥러닝을 활용한 자연어 처리 (NLP) 과정 (기초부터 ChatGPT/생성 모델까지)
Decoder 의 Output Probablilities 계산하는 부분 RNN과 관련하여 질문드립니다.
RNN Decoder의 경우, time step 별로 해당 input 단어에 대한 vocab 사전의 확률분포가 나오면, argmax 하거나, beam searching 하여 output을 최종 산출한다는 것으로 이해했었습니다.강의에서 트랜스포머 Decoder의 경우도 개념은 똑같다고 하셨는데, 트랜스포머도 time step 이 있는건가요? 예를들어,'I love you' 를 '난 널 사랑해' 로 번역할 때,decoder에 attention계산과정 및 Feed Forward 계산과정을 거쳐 나온 최종 attetion vector (seq_len x d model 차원) 가 첫번째 단어 '난' 부터 시작해서 greedy 하게, 혹은 beam search 전략 통하여 확률분포를 구한다고 보면 될까요?
-
미해결딥러닝을 활용한 자연어 처리 (NLP) 과정 (기초부터 ChatGPT/생성 모델까지)
트랜스포머 Encoder Output이 Decoder Input으로 들어갈 때 관련 질문 드립니다.
Encoder의 Output은 attention vector (seq_len x d model) 하나가 나오는데, Decoder의 인풋으로 들어갈 땐 이를 encoder에서 배웠던 Q, K, V 로 나눈뒤, 이중에서 K, V 가 Decoder의 Encoder-Decoder attention layer에서의 K, V로 사용된다고 보면 될까요?