tensorflow 2.0 随机梯度下降 之 tensorboard可视化

工具

  1. TensorBoard
    在这里插入图片描述
  2. Visdom
    在这里插入图片描述

TensorBoard

  1. installation

    pip install tensorboard

  2. Curves (accuary, loss)
  3. images visualization

工作原理

  1. 监听目录 (listen logdir)
  2. 建立 summary 实例 (build summary instance)
  3. 给实例喂数据 (fed data into summary instance)

第一步: run listener
在对应工作目录下监听 logs 文件夹

tensorboard --logdir logs

第二步:build summary

current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
log_dir = 'logs/' + current_time
summary_writer = tf.summary.create_file_writer(log_dir)

第三步:fed scalar, fed image

with summary_writer.as_default():
	tf.summary.scalar('test-acc', float(total_correct /total), step=step)
   	tf.summary.image("val-onebyone-images:", val_images, max_outputs=25, step=step)

在这里插入图片描述

with summary_writer.as_default():
	tf.summary.scalar('train-loss', float(loss), step=step)

在这里插入图片描述
fed multi-images
tensorboard 没有显示 images 接口

方法一: 劣

val_images = x[:25]
val_images = tf.reshape(val_iamges, [-1, 28, 28, 1])
with summary_writer.as_default():
	tf.summary.scalar('test-acc', float(loss), step=step)
	tf.summary.image('val-onebyone-images:', val_images, max_outputs=25, step=step)

在这里插入图片描述

方法二:优

val_images = tf.reshape(val_images, [-1, 28, 28])
figure = image_grid(val_images)
tf.summary.image('val-images:', plot_to_image(figure), step=step)
def plot_to_image(figure):
    """Converts the matplotlib plot specified by 'figure' to a PNG image and
    returns it. The supplied figure is closed and inaccessible after this call."""
    # Save the plot to a PNG in memory.
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    # Closing the figure prevents it from being displayed directly inside
    # the notebook.
    plt.close(figure)
    buf.seek(0)
    # Convert PNG buffer to TF image
    image = tf.image.decode_png(buf.getvalue(), channels=4)
    # Add the batch dimension
    image = tf.expand_dims(image, 0)
    return image


def image_grid(images):
    """Return a 5x5 grid of the MNIST images as a matplotlib figure."""
    # Create a figure to contain the plot.
    figure = plt.figure(figsize=(10, 10))
    for i in range(25):
        # Start next subplot.
        plt.subplot(5, 5, i + 1, title='name')
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(images[i], cmap=plt.cm.binary)

    return figure

在这里插入图片描述

完整代码

import tensorflow as tf
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
import datetime
from matplotlib import pyplot as plt
import io
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


def preprocess(x, y):

    x = tf.cast(x, dtype=tf.float32) / 255.
    y = tf.cast(y, dtype=tf.int32)

    return x, y


def plot_to_image(figure):
    """Converts the matplotlib plot specified by 'figure' to a PNG image and
    returns it. The supplied figure is closed and inaccessible after this call."""
    # Save the plot to a PNG in memory.
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    # Closing the figure prevents it from being displayed directly inside
    # the notebook.
    plt.close(figure)
    buf.seek(0)
    # Convert PNG buffer to TF image
    image = tf.image.decode_png(buf.getvalue(), channels=4)
    # Add the batch dimension
    image = tf.expand_dims(image, 0)
    return image


def image_grid(images):
    """Return a 5x5 grid of the MNIST images as a matplotlib figure."""
    # Create a figure to contain the plot.
    figure = plt.figure(figsize=(10, 10))
    for i in range(25):
        # Start next subplot.
        plt.subplot(5, 5, i + 1, title='name')
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(images[i], cmap=plt.cm.binary)

    return figure


batchsz = 128
(x, y), (x_val, y_val) = datasets.mnist.load_data()
print('datasets:', x.shape, y.shape, x.min(), x.max())


db = tf.data.Dataset.from_tensor_slices((x, y))
db = db.map(preprocess).shuffle(60000).batch(batchsz).repeat(10)

ds_val = tf.data.Dataset.from_tensor_slices((x_val, y_val))
ds_val = ds_val.map(preprocess).batch(batchsz, drop_remainder=True)


network = Sequential([layers.Dense(256, activation='relu'),
                      layers.Dense(128, activation='relu'),
                      layers.Dense(64, activation='relu'),
                      layers.Dense(32, activation='relu'),
                      layers.Dense(10)])
network.build(input_shape=(None, 28 * 28))
network.summary()

optimizer = optimizers.Adam(lr=0.01)


current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
log_dir = 'logs/' + current_time
summary_writer = tf.summary.create_file_writer(log_dir)

# get x from (x,y)
sample_img = next(iter(db))[0]
# get first image instance
sample_img = sample_img[0]
sample_img = tf.reshape(sample_img, [1, 28, 28, 1])
with summary_writer.as_default():
    tf.summary.image("Training sample:", sample_img, step=0)

for step, (x, y) in enumerate(db):

    with tf.GradientTape() as tape:
        # [b, 28, 28] => [b, 784]
        x = tf.reshape(x, (-1, 28 * 28))
        # [b, 784] => [b, 10]
        out = network(x)
        # [b] => [b, 10]
        y_onehot = tf.one_hot(y, depth=10)
        # [b]
        loss = tf.reduce_mean(
            tf.losses.categorical_crossentropy(
                y_onehot, out, from_logits=True))

    grads = tape.gradient(loss, network.trainable_variables)
    optimizer.apply_gradients(zip(grads, network.trainable_variables))

    if step % 100 == 0:

        print(step, 'loss:', float(loss))
        with summary_writer.as_default():
            tf.summary.scalar('train-loss', float(loss), step=step)

    # evaluate
    if step % 500 == 0:
        total, total_correct = 0., 0

        for _, (x, y) in enumerate(ds_val):
            # [b, 28, 28] => [b, 784]
            x = tf.reshape(x, (-1, 28 * 28))
            # [b, 784] => [b, 10]
            out = network(x)
            # [b, 10] => [b]
            pred = tf.argmax(out, axis=1)
            pred = tf.cast(pred, dtype=tf.int32)
            # bool type
            correct = tf.equal(pred, y)
            # bool tensor => int tensor => numpy
            total_correct += tf.reduce_sum(tf.cast(correct,
                                                   dtype=tf.int32)).numpy()
            total += x.shape[0]

        print(step, 'Evaluate Acc:', total_correct / total)

        # print(x.shape)
        val_images = x[:25]
        val_images = tf.reshape(val_images, [-1, 28, 28, 1])
        with summary_writer.as_default():
            tf.summary.scalar(
                'test-acc',
                float(
                    total_correct /
                    total),
                step=step)
            tf.summary.image(
                "val-onebyone-images:",
                val_images,
                max_outputs=25,
                step=step)

            val_images = tf.reshape(val_images, [-1, 28, 28])
            figure = image_grid(val_images)
            tf.summary.image('val-images:', plot_to_image(figure), step=step)

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是使用TensorFlow 2.0实现梯度下降的示例代码: ``` import tensorflow as tf # 定义训练数据 x_train = [1.0, 2.0, 3.0, 4.0] y_train = [2.0, 4.0, 6.0, 8.0] # 定义模型参数 W = tf.Variable(1.0) b = tf.Variable(1.0) # 定义模型 def model(x): return W * x + b # 定义损失函数 def loss(predicted_y, desired_y): return tf.reduce_mean(tf.square(predicted_y - desired_y)) # 定义训练函数 def train(x, y, learning_rate): with tf.GradientTape() as t: current_loss = loss(model(x), y) dW, db = t.gradient(current_loss, [W, b]) W.assign_sub(learning_rate * dW) b.assign_sub(learning_rate * db) # 训练模型 for epoch in range(100): for x, y in zip(x_train, y_train): train(x, y, learning_rate=0.01) current_loss = loss(model(x_train), y_train) print(f"Epoch {epoch}: Loss: {current_loss.numpy()}") # 测试模型 x_test = [5.0, 6.0, 7.0, 8.0] y_test = [10.0, 12.0, 14.0, 16.0] predicted_y = model(x_test) print(f"Predicted Y: {predicted_y.numpy()}") print(f"Desired Y: {y_test}") ``` 在这个例子中,我们使用TensorFlow 2.0实现了一个简单的线性回归模型,并使用梯度下降算法对其进行了训练。我们首先定义了训练数据,然后定义了模型参数W和b。接下来,我们定义了模型函数,它将输入x映射到输出y。然后,我们定义了损失函数,它将模型的预测输出y与真实输出y进行比较,并计算它们之间的平方差。最后,我们定义了一个训练函数,它使用梯度带自动计算模型参数W和b的梯度,并使用学习率更新它们。在训练过程中,我们迭代地将训练数据馈送给训练函数,直到达到指定的训练轮数。最后,我们使用训练好的模型对测试数据进行预测,并将预测结果与真实结果进行比较。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TransientYear

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值