SlideShare a Scribd company logo
MNIST, tensorboard
안성현
1
MNIST
• MNIST는 간단한 컴퓨터 비전 데이터셋
• train-images-idx3-ubyte.gz: training set images (9912422 bytes)
train-labels-idx1-ubyte.gz: training set labels (28881 bytes)
t10k-images-idx3-ubyte.gz: test set images (1648877 bytes)
t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes
2
MNIST Images
• 파일이 아님.
• 하나의 이미지를 784개의 데이터로 표현
3
MNIST Label
• 글자 이미지가 실제 어떤 글자인지를 나타낸다.
• [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] => 각 인덱스가 숫자를 나타냄
• 1 = [0, 1, 0, 0, 0, 0, 0, 0, 0, 0] , 9 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
4
Tensorflow 설치하기
-pip install --upgrade tensorflow
-소스빌드해서 설치가능
5
MNIST Tensorflow 에서 불러오기
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/")
6
MNIST Tensorflow 에서 불러오기
# -*- coding:utf-8 -*-
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
for key in ['train', 'test', 'validation']:
print("mnist.%s :" % key)
minst_dataset= getattr(mnist, key)
print("tnum_examples : %d" % minst_dataset.num_examples)
print("timages count : %d" % len(minst_dataset.images))
print("tlabels count : %d" % len(minst_dataset.labels))
print("timages[0] len : %d" % len(minst_dataset.images[0]))
print("tlabels[0] len : %d" % len(minst_dataset.labels[0]))
print("tlabels[0] : %s" % str(minst_dataset.labels[0]))
7
MNIST Tensorflow 에서 불러오기
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
for key in ['train', 'test', 'validation']:
print("mnist.%s :" % key)
minst_dataset= getattr(mnist, key)
print("tnum_examples : %d" % minst_dataset.num_examples)
print("timages count : %d" % len(minst_dataset.images))
print("tlabels count : %d" % len(minst_dataset.labels))
print("timages[0] len : %d" % len(minst_dataset.images[0]))
print("tlabels[0] len : %d" % len(minst_dataset.labels[0]))
8
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:7)
0SX) Python3.x SSL Error
9
tensorBoard 띄우기
Usage : tensorboard --help
$ usage: tensorboard [-h]
[--logdir LOGDIR]
[--debug DEBUG]
[--nodebug]
[--host HOST]
[--port PORT]
10
tensorboard 띄우기
$ tensorboard --logdir=log
$ TensorBoard b'54' at http://anui-MacBook-Pro.local:6006
- http://127.0.0.1:6006 접속
$ tensorboard --logdir=log --host 0.0.0.0 --port 6006
- 외부에서 접속가능
11
CNN 구성
https://hunkim.github.io/ml/
12
CNN 구성
# L1 ImgIn shape=(?, 28, 28, 1)
# 필터의 크기 3X3, 32개의 필터
W1 = tf.Variable(tf.random_normal([3, 3, 1, 32], stddev=0.01))
# Conv -> (?, 28, 28, 32)
# Pool -> (?, 14, 14, 32)
# 이동거리 1
L1 = tf.nn.conv2d(X_img, W1, strides=[1, 1, 1, 1], padding='SAME')
L1 = tf.nn.relu(L1)
L1 = tf.nn.max_pool(L1, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
'''
Tensor("Conv2D:0", shape=(?, 28, 28, 32), dtype=float32)
Tensor("Relu:0", shape=(?, 28, 28, 32), dtype=float32)
Tensor("MaxPool:0", shape=(?, 14, 14, 32), dtype=float32)
'''
13
CNN 구성
# L2 ImgIn shape=(?, 14, 14, 32)
W2 = tf.Variable(tf.random_normal([3, 3, 32, 64], stddev=0.01))
# Conv ->(?, 14, 14, 64)
# Pool ->(?, 7, 7, 64)
L2 = tf.nn.conv2d(L1, W2, strides=[1, 1, 1, 1], padding='SAME')
L2 = tf.nn.relu(L2)
L2 = tf.nn.max_pool(L2, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
L2_flat = tf.reshape(L2, [-1, 7 * 7 * 64])
W3 = tf.get_variable("W3", shape=[7 * 7 * 64, 10],
initializer=tf.contrib.layers.xavier_initializer())
b = tf.Variable(tf.random_normal([10]), name='b')
logits = tf.matmul(L2_flat, W3) + b
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
14
CNN-MNIST 결과 tensorboard 연결하기
saver 를 이용해서 model 을 --logdir path 에 저장
15
CNN-MNIST 결과 tensorboard 연결하기
• Data Point <= Label, Images
• metadata file
• Label : .tsv 파일
• Images : 단일 sprite image, 8192 X 8192 까지 지원
• projector_config.pbtxt
• API 를 이용해서 생성
16
embedding = tf.Variable(tf.zeros([1024, 10]), name="test_embedding")
assignment = embedding.assign(logits)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
writer = tf.summary.FileWriter(LOGDIR + "/embedding")
writer.add_graph(sess.graph)
config = tf.contrib.tensorboard.plugins.projector.ProjectorConfig()
embedding_config = config.embeddings.add()
embedding_config.tensor_name = embedding.name
embedding_config.metadata_path = LOGDIR + 'labels_1024.tsv‘ # 메타데이터 지정
embedding_config.sprite.image_path = LOGDIR + 'sprite_1024.png‘ # sprite 이미지 파일 지정
embedding_config.sprite.single_image_dim.extend([28, 28]) # 이미지 사이즈 지정
tf.contrib.tensorboard.plugins.projector.visualize_embeddings(writer, config)
if i % 500 == 0:
sess.run(assignment, feed_dict={X: mnist.test.images[:1024], Y: mnist.test.labels[:1024]})
saver.save(sess, os.path.join(LOGDIR, "model.ckpt"), i) 17
생성 : projector_config.pbtxt
CNN-MNIST 결과 tensorboard 연결하기
• https://github.com/jireh-father/tensorboard-embedding-visualization
18
Reference
• https://tensorflowkorea.gitbooks.io/tensorflow-kr/content/g3doc/tutorials/mnist/beginners/
• http://bcho.tistory.com/1154
• https://www.google.co.kr/search?q=image+to+mnist+format&oq=image+to+mnisr+&aqs=chrome.1.69i57j0l2.6888j0j4&sourceid=chrom
e&ie=UTF-8
• http://goodtogreate.tistory.com/entry/Hands-on-TensorBoard-TensorFlow-Dev-Summit2017
• 모두의 딥러닝 : https://hunkim.github.io/ml/
• http://sanghyukchun.github.io/75/
• http://yujuwon.tistory.com/entry/TENSORFLOWCNN2
• http://yujuwon.tistory.com/entry/TENSORFLOW-Image-AutoEncoder
19

More Related Content

PDF
Families of Triangular Norm Based Kernel Function and Its Application to Kern...
PDF
Replication
ODP
HDDM: Hierarchical Bayesian estimation of the Drift Diffusion Model
PDF
Gentle intro to SVM
PPTX
GPU-Accelerated Parallel Computing
PDF
Efficient Variable Size Template Matching Using Fast Normalized Cross Correla...
TXT
Database growth
PDF
Complex models in ecology: challenges and solutions
Families of Triangular Norm Based Kernel Function and Its Application to Kern...
Replication
HDDM: Hierarchical Bayesian estimation of the Drift Diffusion Model
Gentle intro to SVM
GPU-Accelerated Parallel Computing
Efficient Variable Size Template Matching Using Fast Normalized Cross Correla...
Database growth
Complex models in ecology: challenges and solutions

What's hot (19)

PDF
脳の計算論 第3章「リズム活動と位相応答」
PPTX
Artificial neural network
PDF
Personalized news recommendation engine
PPT
02 combinational logic
PPTX
PyTorch Tutorial for NTU Machine Learing Course 2017
PDF
ISCAS2013_v5
PDF
Time Series Analysis:Basic Stochastic Signal Recovery
PPTX
Ac cuda c_3
PDF
数学カフェ 確率・統計・機械学習回 「速習 確率・統計」
PDF
Glm talk Tomas
PDF
Accelerating HPC Applications on NVIDIA GPUs with OpenACC
PPT
Chapter14
PPTX
2013 1
KEY
Cocos2dを使ったゲーム作成の事例
PDF
NAS EP Algorithm
PDF
2D_BLIT_software_Blackness
PDF
Statistics for Economics Midterm 2 Cheat Sheet
DOCX
พรรณิภา กองเกตุใหญ่
PDF
Dm part03 neural-networks-handout
脳の計算論 第3章「リズム活動と位相応答」
Artificial neural network
Personalized news recommendation engine
02 combinational logic
PyTorch Tutorial for NTU Machine Learing Course 2017
ISCAS2013_v5
Time Series Analysis:Basic Stochastic Signal Recovery
Ac cuda c_3
数学カフェ 確率・統計・機械学習回 「速習 確率・統計」
Glm talk Tomas
Accelerating HPC Applications on NVIDIA GPUs with OpenACC
Chapter14
2013 1
Cocos2dを使ったゲーム作成の事例
NAS EP Algorithm
2D_BLIT_software_Blackness
Statistics for Economics Midterm 2 Cheat Sheet
พรรณิภา กองเกตุใหญ่
Dm part03 neural-networks-handout
Ad

Similar to 실용주의 머신러닝 CNN MNIST TENSORBOARD (20)

PDF
[신경망기초] 합성곱신경망
PDF
Simple, fast, and scalable torch7 tutorial
PPTX
An introduction to Deep Learning with Apache MXNet (November 2017)
PDF
Tech day ngobrol santai tensorflow
PPTX
Explanation on Tensorflow example -Deep mnist for expert
KEY
Numpy Talk at SIAM
PPTX
5707_10_auto-encoder.pptx
DOCX
assignment_7_sc report for soft comptuing
PDF
About RNN
PDF
About RNN
PDF
On Beyond (PostgreSQL) Data Types
PDF
How to use SVM for data classification
PDF
dfdshofdifhdifhdfhgfoighfgofgfgfgfgdfdfdfdf
PDF
Power ai tensorflowworkloadtutorial-20171117
PPT
Order-Picking-Policies.ppt
PPTX
Font classification with 5 deep learning models using tensor flow
PPTX
Noise Contrastive Estimation-based Matching Framework for Low-Resource Securi...
[신경망기초] 합성곱신경망
Simple, fast, and scalable torch7 tutorial
An introduction to Deep Learning with Apache MXNet (November 2017)
Tech day ngobrol santai tensorflow
Explanation on Tensorflow example -Deep mnist for expert
Numpy Talk at SIAM
5707_10_auto-encoder.pptx
assignment_7_sc report for soft comptuing
About RNN
About RNN
On Beyond (PostgreSQL) Data Types
How to use SVM for data classification
dfdshofdifhdifhdfhgfoighfgofgfgfgfgdfdfdfdf
Power ai tensorflowworkloadtutorial-20171117
Order-Picking-Policies.ppt
Font classification with 5 deep learning models using tensor flow
Noise Contrastive Estimation-based Matching Framework for Low-Resource Securi...
Ad

More from SeongHyun Ahn (18)

PDF
MQTT 를 이용한 주문시스템 개선
PDF
github : 유용한 기능들
PDF
카피캣으로 시작하는 오픈소스
PDF
파이썬 웹프로그래밍 1탄
PDF
파이썬 기본 문법
PDF
파이썬 모듈 패키지
PDF
파이썬 파일처리 및 문자열 처리
PDF
파이썬 데이터베이스 연결 1탄
PDF
파이썬 웹 프로그래밍 2탄
PDF
파이썬 데이터베이스 연결 2탄
PDF
파이썬 유용한 라이브러리
PDF
파이썬 소개
PPTX
Pycon APAC 2016 후기
PPTX
Introduction of scrum 안성현 20120606
PPTX
디자인 패턴 데코레이터 패턴
PPTX
파이썬 스터디 15장
PPTX
파이썬 스터디 9장
PPTX
빠르게 활용하는 파이썬3 스터디(ch1~4)
MQTT 를 이용한 주문시스템 개선
github : 유용한 기능들
카피캣으로 시작하는 오픈소스
파이썬 웹프로그래밍 1탄
파이썬 기본 문법
파이썬 모듈 패키지
파이썬 파일처리 및 문자열 처리
파이썬 데이터베이스 연결 1탄
파이썬 웹 프로그래밍 2탄
파이썬 데이터베이스 연결 2탄
파이썬 유용한 라이브러리
파이썬 소개
Pycon APAC 2016 후기
Introduction of scrum 안성현 20120606
디자인 패턴 데코레이터 패턴
파이썬 스터디 15장
파이썬 스터디 9장
빠르게 활용하는 파이썬3 스터디(ch1~4)

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Big Data Technologies - Introduction.pptx
PDF
Empathic Computing: Creating Shared Understanding
PPTX
1. Introduction to Computer Programming.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PPT
Teaching material agriculture food technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Electronic commerce courselecture one. Pdf
PDF
cuic standard and advanced reporting.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Programs and apps: productivity, graphics, security and other tools
MYSQL Presentation for SQL database connectivity
Big Data Technologies - Introduction.pptx
Empathic Computing: Creating Shared Understanding
1. Introduction to Computer Programming.pptx
20250228 LYD VKU AI Blended-Learning.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Approach and Philosophy of On baking technology
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Teaching material agriculture food technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
SOPHOS-XG Firewall Administrator PPT.pptx
gpt5_lecture_notes_comprehensive_20250812015547.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Advanced methodologies resolving dimensionality complications for autism neur...
NewMind AI Weekly Chronicles - August'25-Week II
Electronic commerce courselecture one. Pdf
cuic standard and advanced reporting.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Programs and apps: productivity, graphics, security and other tools

실용주의 머신러닝 CNN MNIST TENSORBOARD

  • 2. MNIST • MNIST는 간단한 컴퓨터 비전 데이터셋 • train-images-idx3-ubyte.gz: training set images (9912422 bytes) train-labels-idx1-ubyte.gz: training set labels (28881 bytes) t10k-images-idx3-ubyte.gz: test set images (1648877 bytes) t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes 2
  • 3. MNIST Images • 파일이 아님. • 하나의 이미지를 784개의 데이터로 표현 3
  • 4. MNIST Label • 글자 이미지가 실제 어떤 글자인지를 나타낸다. • [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] => 각 인덱스가 숫자를 나타냄 • 1 = [0, 1, 0, 0, 0, 0, 0, 0, 0, 0] , 9 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1] 4
  • 5. Tensorflow 설치하기 -pip install --upgrade tensorflow -소스빌드해서 설치가능 5
  • 6. MNIST Tensorflow 에서 불러오기 from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/") 6
  • 7. MNIST Tensorflow 에서 불러오기 # -*- coding:utf-8 -*- from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) for key in ['train', 'test', 'validation']: print("mnist.%s :" % key) minst_dataset= getattr(mnist, key) print("tnum_examples : %d" % minst_dataset.num_examples) print("timages count : %d" % len(minst_dataset.images)) print("tlabels count : %d" % len(minst_dataset.labels)) print("timages[0] len : %d" % len(minst_dataset.images[0])) print("tlabels[0] len : %d" % len(minst_dataset.labels[0])) print("tlabels[0] : %s" % str(minst_dataset.labels[0])) 7
  • 8. MNIST Tensorflow 에서 불러오기 from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) for key in ['train', 'test', 'validation']: print("mnist.%s :" % key) minst_dataset= getattr(mnist, key) print("tnum_examples : %d" % minst_dataset.num_examples) print("timages count : %d" % len(minst_dataset.images)) print("tlabels count : %d" % len(minst_dataset.labels)) print("timages[0] len : %d" % len(minst_dataset.images[0])) print("tlabels[0] len : %d" % len(minst_dataset.labels[0])) 8
  • 9. urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:7) 0SX) Python3.x SSL Error 9
  • 10. tensorBoard 띄우기 Usage : tensorboard --help $ usage: tensorboard [-h] [--logdir LOGDIR] [--debug DEBUG] [--nodebug] [--host HOST] [--port PORT] 10
  • 11. tensorboard 띄우기 $ tensorboard --logdir=log $ TensorBoard b'54' at http://anui-MacBook-Pro.local:6006 - http://127.0.0.1:6006 접속 $ tensorboard --logdir=log --host 0.0.0.0 --port 6006 - 외부에서 접속가능 11
  • 13. CNN 구성 # L1 ImgIn shape=(?, 28, 28, 1) # 필터의 크기 3X3, 32개의 필터 W1 = tf.Variable(tf.random_normal([3, 3, 1, 32], stddev=0.01)) # Conv -> (?, 28, 28, 32) # Pool -> (?, 14, 14, 32) # 이동거리 1 L1 = tf.nn.conv2d(X_img, W1, strides=[1, 1, 1, 1], padding='SAME') L1 = tf.nn.relu(L1) L1 = tf.nn.max_pool(L1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') ''' Tensor("Conv2D:0", shape=(?, 28, 28, 32), dtype=float32) Tensor("Relu:0", shape=(?, 28, 28, 32), dtype=float32) Tensor("MaxPool:0", shape=(?, 14, 14, 32), dtype=float32) ''' 13
  • 14. CNN 구성 # L2 ImgIn shape=(?, 14, 14, 32) W2 = tf.Variable(tf.random_normal([3, 3, 32, 64], stddev=0.01)) # Conv ->(?, 14, 14, 64) # Pool ->(?, 7, 7, 64) L2 = tf.nn.conv2d(L1, W2, strides=[1, 1, 1, 1], padding='SAME') L2 = tf.nn.relu(L2) L2 = tf.nn.max_pool(L2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') L2_flat = tf.reshape(L2, [-1, 7 * 7 * 64]) W3 = tf.get_variable("W3", shape=[7 * 7 * 64, 10], initializer=tf.contrib.layers.xavier_initializer()) b = tf.Variable(tf.random_normal([10]), name='b') logits = tf.matmul(L2_flat, W3) + b cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost) 14
  • 15. CNN-MNIST 결과 tensorboard 연결하기 saver 를 이용해서 model 을 --logdir path 에 저장 15
  • 16. CNN-MNIST 결과 tensorboard 연결하기 • Data Point <= Label, Images • metadata file • Label : .tsv 파일 • Images : 단일 sprite image, 8192 X 8192 까지 지원 • projector_config.pbtxt • API 를 이용해서 생성 16
  • 17. embedding = tf.Variable(tf.zeros([1024, 10]), name="test_embedding") assignment = embedding.assign(logits) saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) writer = tf.summary.FileWriter(LOGDIR + "/embedding") writer.add_graph(sess.graph) config = tf.contrib.tensorboard.plugins.projector.ProjectorConfig() embedding_config = config.embeddings.add() embedding_config.tensor_name = embedding.name embedding_config.metadata_path = LOGDIR + 'labels_1024.tsv‘ # 메타데이터 지정 embedding_config.sprite.image_path = LOGDIR + 'sprite_1024.png‘ # sprite 이미지 파일 지정 embedding_config.sprite.single_image_dim.extend([28, 28]) # 이미지 사이즈 지정 tf.contrib.tensorboard.plugins.projector.visualize_embeddings(writer, config) if i % 500 == 0: sess.run(assignment, feed_dict={X: mnist.test.images[:1024], Y: mnist.test.labels[:1024]}) saver.save(sess, os.path.join(LOGDIR, "model.ckpt"), i) 17 생성 : projector_config.pbtxt
  • 18. CNN-MNIST 결과 tensorboard 연결하기 • https://github.com/jireh-father/tensorboard-embedding-visualization 18
  • 19. Reference • https://tensorflowkorea.gitbooks.io/tensorflow-kr/content/g3doc/tutorials/mnist/beginners/ • http://bcho.tistory.com/1154 • https://www.google.co.kr/search?q=image+to+mnist+format&oq=image+to+mnisr+&aqs=chrome.1.69i57j0l2.6888j0j4&sourceid=chrom e&ie=UTF-8 • http://goodtogreate.tistory.com/entry/Hands-on-TensorBoard-TensorFlow-Dev-Summit2017 • 모두의 딥러닝 : https://hunkim.github.io/ml/ • http://sanghyukchun.github.io/75/ • http://yujuwon.tistory.com/entry/TENSORFLOWCNN2 • http://yujuwon.tistory.com/entry/TENSORFLOW-Image-AutoEncoder 19

Editor's Notes

  • #2: 간단하게 mnist 를 이용해서 CNN 을 텐서플로우로 해보고 그 결과를 tensorboard 를 이용해서 해봤습니다. Mnist 에 대해서 설명하고, 텐서보드를 이용하는 방법을 설명드리겠습니다.
  • #3: 컴퓨터 비전 셋이고 구글에서 치면 해당 홈페이지로 이동 가능하고, 가보면 총 4개의 파일을 다운받을수 있게 되어 있습니다. 2개는 트레이닝 셋 나머지 2개는 테스트 셋으로 각각 이미지와 라벨로 구성되어 있습니다.
  • #4: 실제로 압축을 풀어보면 이미지라고 해서 실제 이미지 파일이 들어 있는게 아니라 하나의 이미지를 784개의 데이터로 표현하고 있다.
  • #5: 레이블은 해당 이미지가 어떤 글자인지를 나타낸다. 0~9까지의 1차원 배열이 있고, 그 안에서 해당 숫자에 해당하는 인덱스를 1로 표시를 한다.
  • #6: Mnist 를 tensorflow 에서 사용하기 위해서는 일단 tensorflow 를 받아야 한다. 소스빌드를 이용해서 설치할 경우에는 성능이 소폭 향상 된다고 실제로 PIP 로 설치할 경우 실행하면, 여러가지 설치를 하라고 뜨고 있습니다.
  • #7: MNIST 데이터를 TENSORFLOW 에서 가져오는 코드는 2줄이면 된다. Read_data_set 함수에서 어디에 다운로드를 받고 압축을 풀 것인지 지정하면 되고 위의 코드를 실행하면 4개의 파일에 있는 데이터가 mnist 객체로 들어가게 된다. 그 안을 보면 크게 트레이닝, 테스트, 벨리데이션으로 나눠져 있다.
  • #8: 좀더 안이 어떻게 구성되어 있는지 확인차 돌려봤는데
  • #9: 이런식으로 train 은 55000 개 테스트는 10000개 validation 는 5000 개가 쌍으로 이미지와 레이블이 있는것을 확인 할 수 가 있다.
  • #12: 중요한 점은 반드시 –logdir 을 지정해야 한다는 점. 지정하지 않으면 오류가 발생한다. --host 옵션과 –port 옵션을 통해서 서버에서 띄울 경우 위와 같이 외부 접속을 허용할 수 있다.
  • #13: 간단하게 CNN을 구성해 봤고, 머신러닝을 잘 몰라서 모두의 딥러닝을 따라했습니다. 그래서 컨벌루션 레이어 2개, 맥스풀링 레이어 2개를 다는 식으로 구성했습니다.
  • #14: 첫번째 필터에서는 입력값이 28X28 에 3X3 필터 32개를 적용했고, RELU 와 맥스필터를 거쳐서 14X14 32개가 출력으로 나왓습니다.
  • #15: 두번째 필터에서는 입력값이 첫번째 필터의 결과로 받고 3X3 필터 64개를 적용했고, RELU 와 맥스필터를 거쳐서 7X7 64개가 출력으로 나왓습니다. 이걸 SOFTMAX 를 거쳐서 출력값이 나오도록 수정했습니다. 이런식으로 CNN 을 구성했고, 이 부분은 모두의 딥러닝 부분을 많이 따라해서 나중에 해당 부분의 CNN 부분을 들어보시면 좀더 이해가 잘 될것이구요
  • #16: 그래서 이제 그 결과를 tensorboard 에 저장을 하면 되는데 어떻게 저장할것인가? 하면 Tensorflow 에서 제공하는 saver 라는 것을 통해서 앞에서 말한 tensorboard 의 –logdir 위치에 넣으면됩니다. 넣고 띄워보면 파란색 점만 많이 나오는 것을 볼 수 있는데요 뭐가 뭔지 알수가 없습니다.
  • #17: 그래서 텐서보드에서는 데이터 포인트에 라벨과 이미지를 붙일수 있는 기능을 제공하고 있는데요 Metadata 파일오 label 의 경우 tsv 형태, 이미지의 스프라이트 이미지를 지원하고 있습니다. 스프라이트 이미지는 여러 이미지를 하나로 붙인것으로 순서가 중요한데 lefttop – rightbottom 으로 배열하고 있습니다. 즉 mnist 에 학습결과를 보고 싶으면 이미지가 필요합니다. 그리고 그런 이미지와 라벨데이터를 연결해주기 위해서 projector_config.pbtxt 가 필요한데 이건 Api를 통해서 생성할 수 있습니다.
  • #18: 메타데이터는 mnist.test.label 을 통해서 가져올 수 있다 여기서는 1024 개의 테스트 데이터를 가져와서 tensorboard 에 결과를 넣을것 때문에 1024, 10 으로 잡았고, name 을 주었는데 저 name이 실제 tensorboad 에 보이는 이름입니다. 그리고 writer 를 지정하고 log directory 밑에 embedding 이라고 적어서 그 안에 embedding 관련 내용들이 들어가게 됩니다. 그리고 메타데이터 경로와 이미지 경로를 지정해 주고 이미지 사이즈를 지정해 줘야 합니다. 왜냐하면 스프라이트 이미지이기 때문에 tensorboard 에서 그 크기를 알아야 하기 때문입니다. 그리고 나서 500번 실행시 마다 test 에서 1024개를 가져와서 결과를 기록하게 하였습니다. 그리고 나서 tensorboard 를 띄워보면 이렇게 나옵니다. PCA 는 주성분 분석이고 차원을 줄이는 것으로 알고 있고 t-sne 는 비선형 차원 감소기술로 지역적인 구조를 유지해서 이웃탐색이나 클러스터를 찾는데 유용하다고 합니다.
  • #19: 이렇게 해서 tensorboard 를 띄우느것 까지 해봤는데요. 사실 학습시킨 모델을 저장하고, 테스트 데이터로 테스트할때 사용하면 좋을것 같고 매번 이렇게 코딩 하는것 보다는 모델을 복원해서 잘 분류되었는지 눈으로 볼떄 좋을것 같은데요 저 링크에 가보시면, embedding 을 별도로 모듈화 시켜서 학습과 별도로 쉽게 붙일수 있는 것을 만들어 놓기도 하였습니다. 참고해 보시면 될것 같습니다.