Используя summary_writer для записи журнала в каждую эпоху в папке, затем выполняющей следующее волшебство, работал на меня.
%load_ext tensorboard
%tensorboard --logdir=./logs
Многие ответы здесь являются теперь устаревшими. Так будет моим, я уверен за несколько недель. Но во время этой записи всего я должен был сделать, выполняется эти строки кода от colab. И tensorboard, открытый очень хорошо.
%load_ext tensorboard
%tensorboard --logdir logs
Да определенно, с помощью tensorboard в Google colab довольно легок. Выполните следующие шаги -
1) Загрузка, которую 2) Добавляет tensorboard расширение
%load_ext tensorboard.notebook
, это к обратному вызову
tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)
3 криса) Запускают tensorboard
%tensorboard — logdir logs
Hope, которому это помогает.
Самым простым и легким путем я нашел до сих пор:
Получают setup_google_colab.py файл с помощью 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
, Чтобы выполнить tensorboard в фоне, выставить порт и нажать на ссылку.
я предполагаю, что у Вас есть надлежащая добавленная стоимость, чтобы визуализировать в Вашей сводке и затем объединить все сводки.
import os
os.system("tensorboard --logdir=./logs --host 0.0.0.0 --port 6006 &")
setup_google_colab.expose_port_on_colab(6006)
После выполнения выше операторов Вы будете запрошенный со ссылкой как:
Open https://a1b2c34d5.ngrok.io to access your 6006 port
Направляют следующего мерзавца для дальнейшей справки:
https://github.com/MUmarAmanat/MLWithTensorflow/blob/master/colab_tensorboard.ipynb
Я пытался показать TensorBoard на Google colab сегодня,
# 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
'################
делает обучение
'################
# show tensorboard
%tensorboard --logdir logs/fit
здесь является фактическим примером, сделанным Google. https://colab.research.google.com/github/tensorflow/tensorboard/blob/master/docs/r2/get_started.ipynb
Существует альтернативное решение, но мы должны использовать предварительный просмотр TFv2.0. Таким образом, если у Вас нет проблем с попыткой миграции этим:
установка tfv2.0 для GPU или ЦП (TPU, не доступный все же)
ЦП
импорт 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 или Create, где сохранить журналы (выполняет это строки, прежде чем выполнено обучение 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)
Весело проводят время с TensorBoard! :)
%tensorboard --logdir logs/fit
Здесь официальный colab ноутбук и repo на github
Новая альфа-версия TFv2.0:
ЦП
!pip install -q tensorflow==2.0.0-alpha0
GPU
!pip install -q tensorflow-gpu==2.0.0-alpha0
TensorBoard работает с Google Colab и TensorFlow 2.0
!pip install tensorflow==2.0.0-alpha0
%load_ext tensorboard.notebook
Я попробовал, но не получил результат, но при использовании как ниже получил результаты
import tensorboardcolab as tb
tbc = tb.TensorBoardColab()
import tensorflow as tf
import numpy as np
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'
Для присоединения к ответу @solver149 вот, простой пример, как использовать TensorBoard в google colab
a = tf.constant(3.0, dtype=tf.float32)
b = tf.constant(4.0)
total = a + b
!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)
Кулак всего импорта TensorBoard от tensorboaedcolab (можно использовать 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
, Этим примером был маркер от руководства TF: TensorBoard.