pip install tensorboard
# ************** step
1、cmd ==> tensorboard --logdir logs(文件夹名)
2、open url ==> http://localhost:6006
3、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)
4、fed scalar:
with summary_writer.as_default():
tf.summary.scalar("loss:",float(loss),step = epoch)
tf.summary.scalar("accuracy:",float(train_accuracy),step = epoch)
5、fed single image:
with summay_writer.as_default():
tf.summary.image("training_sample:",sample_image,step = 0)
6、fed multi-images:
with summary_writer.as_default():
tf.summary.image("one_by_one_images:",images,max_outputs=25,step = epoch)
# ***************** 实战 **********************
def preprocess(x,y):
x = tf.cast(x,dtype=tf.float32)/255.
y = tf.cast(y,dtype=tf.int32)
return x,y
import matplotlib.pyplot as plt
import io
def image_grid(images,shape):
figure = plt.figure(figsize = (10,10))
for i in range(int(shape[0]*shape[1])):
plt.subplot(shape[0],shape[1],i+1,title = "{}".format(i+1))
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(images[i],cmap = plt.cm.binary)
return figure
def plot_to_image(figure):
buf = io.BytesIO()
plt.savefig(buf,format="png")
plt.close(figure)
buf.seek(0)
image = tf.image.decode_png(buf.getvalue(),channels=4)
image = tf.expand_dims(image,0)
return image
# 加载数据集 及 数据预处理
(x,y),(x_test,y_test) = datasets.fashion_mnist.load_data()
db = tf.data.Dataset.from_tensor_slices((x,y))
db_test = tf.data.Dataset.from_tensor_slices((x_test,y_test))
db = db.map(preprocess).shuffle(10000).batch(128)
db_test = db_test.map(preprocess).shuffle(10000).batch(128)
# 构建模型
model = Sequential([
layers.Dense(256,activation=tf.nn.relu),
layers.Dense(128,activation=tf.nn.relu),
layers.Dense(64,activation=tf.nn.relu),
layers.Dense(10)
])
model.build(input_shape=(None,28*28))
model.summary()
optimizer = optimizers.Adam(lr = 1e-3)
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)
for epoch in range(30):
for step,(x,y) in enumerate(db):
x = tf.reshape(x,[-1,28*28])
with tf.GradientTape() as tape:
logits = model(x)
loss = tf.reduce_mean(tf.losses.categorical_crossentropy(tf.one_hot(y,depth=10),logits,from_logits = True))
with summary_writer.as_default():
tf.summary.scalar("loss:",loss,step = (step+1)*(epoch+1))
grads = tape.gradient(loss,model.trainable_variables)
optimizer.apply_gradients(zip(grads,model.trainable_variables))
total_num,total_correct = 0,0
for (x_test,y_test) in db_test:
x_test = tf.reshape(x_test,[-1,28*28])
logits = model(x_test)
prob = tf.nn.softmax(logits)
pred = tf.argmax(prob,axis = 1)
correct = tf.reduce_sum(tf.cast(tf.equal(y_test,tf.cast(pred,dtype=tf.int32)),dtype=tf.int32))
total_num += x_test.shape[0]
total_correct += correct
ACC = total_correct/total_num
with summary_writer.as_default():
tf.summary.scalar("accuracy for test:",ACC,step=(step+1)*(epoch+1))
if step%500 == 0:
val_images = x[:25]
val_images = tf.reshape(val_images,[-1,28,28])
figure = image_grid(val_images,[5,5])
with summary_writer.as_default():
tf.summary.image("images:",plot_to_image(figure),step = step)
本文为参考龙龙老师的“深度学习与TensorFlow 2入门实战“课程书写的学习笔记
by CyrusMay 2022 04 17