Google Colab에서 TensorBoard를 사용할 수 있나요?
Google Colab에서 TensorFlow 모델을 학습 할 때 TensorBoard를 사용하는 방법이 있나요?
편집 : TensorFlow 1.13부터 제공되는 공식 %tensorboard
마법 을 사용하고 싶을 것입니다 .
%tensorboard
마법 이 존재하기 전에이를 달성하는 표준 방법은 ngrok를 사용하여 네트워크 트래픽을 Colab VM에 프록시하는 것이 었 습니다 . Colab 예제는 여기 에서 찾을 수 있습니다 .
다음은 단계입니다 (코드 스 니펫은 colab에서 "code"유형의 셀을 나타냄).
백그라운드에서 TensorBoard를 실행합니다. 이 답변에서
영감을 얻었습니다 .LOG_DIR = '/tmp/log' get_ipython().system_raw( 'tensorboard --logdir {} --host 0.0.0.0 --port 6006 &' .format(LOG_DIR) )
ngrok를 다운로드하고 압축을 풉니 다 .
전달 된wget
링크를 OS에 맞는 올바른 다운로드 링크로 바꿉니다 .! wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip ! unzip ngrok-stable-linux-amd64.zip
ngrok 백그라운드 프로세스 시작 ...
get_ipython().system_raw('./ngrok http 6006 &')
... 공개 URL을 검색합니다. 출처
! curl -s http://localhost:4040/api/tunnels | python3 -c \ "import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])"
다음은 Google Colab에서 동일한 ngrok 터널링 방법을 수행하는 더 쉬운 방법입니다.
!pip install tensorboardcolab
그때,
from tensorboardcolab import TensorBoardColab, TensorBoardColabCallback
tbc=TensorBoardColab()
Keras를 사용한다고 가정합니다.
model.fit(......,callbacks=[TensorBoardColabCallback(tbc)])
여기 에서 원본 게시물을 읽을 수 있습니다 .
tensorboardcolab을 사용하여 Google Colab에서 실행되는 TensorFlow 용 TensorBoard. 터널링을 위해 내부적으로 ngrok를 사용합니다.
- TensorBoardColab 설치
!pip install tensorboardcolab
- tensorboardcolab 객체 만들기
tbc = TensorBoardColab()
이렇게하면 사용할 수있는 TensorBoard 링크가 자동으로 생성됩니다. 이 Tensorboard는 './Graph'에서 데이터를 읽고 있습니다.
- 이 위치를 가리키는 FileWriter 만들기
summary_writer = tbc.get_writer()
tensorboardcolab 라이브러리에는 위의 './Graph'위치를 가리키는 FileWriter 객체를 반환하는 메서드가 있습니다.
- summary_writer 개체를 사용하여 './Graph'위치의 이벤트 파일에 요약 정보 추가 시작
스칼라 정보, 그래프 또는 히스토그램 데이터를 추가 할 수 있습니다.
참조 : https://github.com/taomanwai/tensorboardcolab
시도했지만 결과를 얻지 못했지만 아래와 같이 사용하면 결과를 얻었습니다.
import tensorboardcolab as tb
tbc = tb.TensorBoardColab()
이 후 출력에서 링크를 엽니 다.
import tensorflow as tf
import numpy as np
Graph 개체를 명시 적으로 생성
graph = tf.Graph()
with graph.as_default()
완전한 예 :
with tf.name_scope("variables"):
# Variable to keep track of how many times the graph has been run
global_step = tf.Variable(0, dtype=tf.int32, name="global_step")
# Increments the above `global_step` Variable, should be run whenever the graph is run
increment_step = global_step.assign_add(1)
# Variable that keeps track of previous output value:
previous_value = tf.Variable(0.0, dtype=tf.float32, name="previous_value")
# Primary transformation Operations
with tf.name_scope("exercise_transformation"):
# Separate input layer
with tf.name_scope("input"):
# Create input placeholder- takes in a Vector
a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a")
# Separate middle layer
with tf.name_scope("intermediate_layer"):
b = tf.reduce_prod(a, name="product_b")
c = tf.reduce_sum(a, name="sum_c")
# Separate output layer
with tf.name_scope("output"):
d = tf.add(b, c, name="add_d")
output = tf.subtract(d, previous_value, name="output")
update_prev = previous_value.assign(output)
# Summary Operations
with tf.name_scope("summaries"):
tf.summary.scalar('output', output) # Creates summary for output node
tf.summary.scalar('product of inputs', b, )
tf.summary.scalar('sum of inputs', c)
# Global Variables and Operations
with tf.name_scope("global_ops"):
# Initialization Op
init = tf.initialize_all_variables()
# Collect all summary Ops in graph
merged_summaries = tf.summary.merge_all()
# Start a Session, using the explicitly created Graph
sess = tf.Session(graph=graph)
# Open a SummaryWriter to save summaries
writer = tf.summary.FileWriter('./Graph', sess.graph)
# Initialize Variables
sess.run(init)
def run_graph(input_tensor):
"""
Helper function; runs the graph with given input tensor and saves summaries
"""
feed_dict = {a: input_tensor}
output, summary, step = sess.run([update_prev, merged_summaries, increment_step], feed_dict=feed_dict)
writer.add_summary(summary, global_step=step)
# Run the graph with various inputs
run_graph([2,8])
run_graph([3,1,3,3])
run_graph([8])
run_graph([1,2,3])
run_graph([11,4])
run_graph([4,1])
run_graph([7,3,1])
run_graph([6,3])
run_graph([0,2])
run_graph([4,5,6])
# Writes the summaries to disk
writer.flush()
# Flushes the summaries to disk and closes the SummaryWriter
writer.close()
# Close the session
sess.close()
# To start TensorBoard after running this file, execute the following command:
# $ tensorboard --logdir='./improved_graph'
Google Colab에서 모델을 인라인으로 표시하는 방법은 다음과 같습니다. 다음은 자리 표시자를 표시하는 매우 간단한 예입니다.
from IPython.display import clear_output, Image, display, HTML
import tensorflow as tf
import numpy as np
from google.colab import files
def strip_consts(graph_def, max_const_size=32):
"""Strip large constant values from graph_def."""
strip_def = tf.GraphDef()
for n0 in graph_def.node:
n = strip_def.node.add()
n.MergeFrom(n0)
if n.op == 'Const':
tensor = n.attr['value'].tensor
size = len(tensor.tensor_content)
if size > max_const_size:
tensor.tensor_content = "<stripped %d bytes>"%size
return strip_def
def show_graph(graph_def, max_const_size=32):
"""Visualize TensorFlow graph."""
if hasattr(graph_def, 'as_graph_def'):
graph_def = graph_def.as_graph_def()
strip_def = strip_consts(graph_def, max_const_size=max_const_size)
code = """
<script>
function load() {{
document.getElementById("{id}").pbtxt = {data};
}}
</script>
<link rel="import" href="https://tensorboard.appspot.com/tf-graph-basic.build.html" onload=load()>
<div style="height:600px">
<tf-graph-basic id="{id}"></tf-graph-basic>
</div>
""".format(data=repr(str(strip_def)), id='graph'+str(np.random.rand()))
iframe = """
<iframe seamless style="width:1200px;height:620px;border:0" srcdoc="{}"></iframe>
""".format(code.replace('"', '"'))
display(HTML(iframe))
"""Create a sample tensor"""
sample_placeholder= tf.placeholder(dtype=tf.float32)
"""Show it"""
graph_def = tf.get_default_graph().as_graph_def()
show_graph(graph_def)
현재 로컬에서 실행하는 방식으로 Google Colab에서 Tensorboard 서비스를 실행할 수 없습니다. 또한 전체 로그를 다음과 같은 방법으로 드라이브로 내보낼 수 없으므로 summary_writer = tf.summary.FileWriter('./logs', graph_def=sess.graph_def)
다운로드하여 로컬에서 볼 수 있습니다.
Google 드라이브의 백업을 사용하고 https://www.google.com/drive/download/backup-and-sync/ 동기화 합니다. 훈련 중에 내 Google 드라이브에 일반적으로 저장되는 이벤트 파일은 내 컴퓨터의 폴더에 자동으로 동기화됩니다. 이 폴더를 logs
. 텐서 보드의 시각화에 액세스하려면 명령 프롬프트를 열고 동기화 된 Google 드라이브 폴더로 이동 한 후 다음을 입력 tensorboard --logdir=logs
합니다..
따라서 내 드라이브를 내 컴퓨터와 자동으로 동기화 (백업 및 동기화 사용)하면 마치 내 컴퓨터에서 훈련하는 것처럼 텐서 보드를 사용할 수 있습니다.
편집 : 도움이 될 수있는 노트북이 있습니다. https://colab.research.google.com/gist/MartijnCa/961c5f4c774930f4bdd32d51829da6f6/tensorboard-with-google-drive-backup-and-sync.ipynb
@ solver149 답변에 참여하려면 다음은 Google colab에서 TensorBoard를 사용하는 간단한 예입니다.
1. 그래프를 만듭니다. 예 :
a = tf.constant(3.0, dtype=tf.float32)
b = tf.constant(4.0)
total = a + b
2. Tensorboard 설치
!pip install tensorboardcolab # to install tensorboeadcolab if it does not it not exist
==> 내 경우 결과 :
Requirement already satisfied: tensorboardcolab in /usr/local/lib/python3.6/dist-packages (0.0.22)
3. 그것을 사용하십시오 :)
tensorboaedcolab에서 모든 가져 오기 TensorBoard의 주먹 ( import*
한 번에 모든 것을 가져 오는 데 사용할 수 있음 ) 그런 다음 다음과 같이 작성자를 첨부 한 후 tensorboeardcolab을 만듭니다.
from tensorboardcolab import *
tbc = TensorBoardColab() # To create a tensorboardcolab object it will automatically creat a link
writer = tbc.get_writer() # To create a FileWriter
writer.add_graph(tf.get_default_graph()) # add the graph
writer.flush()
==> 결과
Using TensorFlow backend.
Wait for 8 seconds...
TensorBoard link:
http://cf426c39.ngrok.io
4. 주어진 링크 확인 : D
이 예제는 TF 가이드 : TensorBoard의 토큰입니다 .
대체 솔루션이 있지만 TFv2.0 미리보기를 사용해야합니다. 따라서 마이그레이션에 문제가 없으면 다음을 시도하십시오.
GPU 또는 CPU 용 tfv2.0 설치 (TPU는 아직 제공되지 않음)
CPU
tf-nightly-2.0-preview
GPU
tf-nightly-gpu-2.0-preview
%%capture
!pip install -q tf-nightly-gpu-2.0-preview
# Load the TensorBoard notebook extension
%load_ext tensorboard.notebook
평소처럼 TensorBoard를 가져옵니다.
from tensorflow.keras.callbacks import TensorBoard
Clean or Create folder where to save the logs (run this lines before run the training fit()
)
# Clear any logs from previous runs
import time
!rm -R ./logs/ # rf
log_dir="logs/fit/{}".format(time.strftime("%Y%m%d-%H%M%S", time.gmtime()))
tensorboard = TensorBoard(log_dir=log_dir, histogram_freq=1)
Have fun with TensorBoard! :)
%tensorboard --logdir logs/fit
Here the official colab notebook and the repo on github
New TFv2.0 alpha release:
CPU
!pip install -q tensorflow==2.0.0-alpha0
GPU
!pip install -q tensorflow-gpu==2.0.0-alpha0
TensorBoard works with Google Colab and TensorFlow 2.0
!pip install tensorflow==2.0.0-alpha0
%load_ext tensorboard.notebook
I tried to show TensorBoard on google colab today,
# in case of CPU, you can this line
# !pip install -q tf-nightly-2.0-preview
# in case of GPU, you can use this line
!pip install -q tf-nightly-gpu-2.0-preview
# %load_ext tensorboard.notebook # not working on 22 Apr
%load_ext tensorboard # you need to use this line instead
import tensorflow as tf
'################
do training
'################
# show tensorboard
%tensorboard --logdir logs/fit
here is actual example made by google. https://colab.research.google.com/github/tensorflow/tensorboard/blob/master/docs/r2/get_started.ipynb
Simple and easiest way I have found so far:
Get setup_google_colab.py file using wget
!wget https://raw.githubusercontent.com/hse-aml/intro-to- dl/master/setup_google_colab.py -O setup_google_colab.py
import setup_google_colab
To run tensorboard in background, expose port and click on the link.
I am assuming that you have proper added value to visualize in your summary and then merge all summaries.
import os
os.system("tensorboard --logdir=./logs --host 0.0.0.0 --port 6006 &")
setup_google_colab.expose_port_on_colab(6006)
After running above statements you will prompted with a link like:
Open https://a1b2c34d5.ngrok.io to access your 6006 port
Refer following git for further help:
https://github.com/MUmarAmanat/MLWithTensorflow/blob/master/colab_tensorboard.ipynb
Yes definitely, using tensorboard in google colab is quite easy. Follow the following steps-
1) Load the tensorboard extension
%load_ext tensorboard.notebook
2) Add it to keras callback
tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)
3) Start tensorboard
%tensorboard — logdir logs
Hope it helps.
Many of the answers here are now obsolete. So will be mine I'm sure in a few weeks. But at the time of this writing all I had to do is run these lines of code from colab. And tensorboard opened up just fine.
%load_ext tensorboard
%tensorboard --logdir logs
Using summary_writer to write log at every epoch in a folder then running the following magic worked for me.
%load_ext tensorboard
%tensorboard --logdir=./logs
참고 URL : https://stackoverflow.com/questions/47818822/can-i-use-tensorboard-with-google-colab
'development' 카테고리의 다른 글
NumPy의 Convolve 이해 (0) | 2020.12.04 |
---|---|
'isblank'함수를 부정하는 방법 (0) | 2020.12.04 |
VIM의 다중 선택 (0) | 2020.12.04 |
iPhone 상태 표시 줄 높이 가져 오기 (0) | 2020.12.04 |
HTML 이메일을 보내는 방법 (0) | 2020.12.04 |