在tf.keras中,metrics其实就是起到了一个测量表的作用,即测量损失或者模型精度的变化。metrics的使用分为以下四步:

step1:Build a meter

acc_meter = metrics.Accuracy()
loss_meter = metrics.Mean()

step2:Update data

loss_meter.update_state(loss)
acc_meter.update_state(y,pred)

step3:Get Average data

print(step,'loss:',loss_meter.result().numpy())
print(step,'Evaluate Acc:',total_correct/total,acc_meter.result().numpy())

清除缓存:

if step % 100 == 0:
print(step,'loss:',loss_meter.result().numpy())
loss_meter.reset_states() if step % 500 ==0:
total,total_correct = 0.,0
acc_meter.reset_states()

实战:

import  tensorflow as tf
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics def preprocess(x, y): x = tf.cast(x, dtype=tf.float32) / 255.
y = tf.cast(y, dtype=tf.int32) return x,y 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) 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) acc_meter = metrics.Accuracy()
loss_meter = metrics.Mean() 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)) loss_meter.update_state(loss) grads = tape.gradient(loss, network.trainable_variables)
optimizer.apply_gradients(zip(grads, network.trainable_variables)) if step % 100 == 0: print(step, 'loss:', loss_meter.result().numpy())
loss_meter.reset_states() # evaluate
if step % 500 == 0:
total, total_correct = 0., 0
acc_meter.reset_states() for step, (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] acc_meter.update_state(y, pred) print(step, 'Evaluate Acc:', total_correct/total, acc_meter.result().numpy())

最新文章

  1. 使用HTML5的cavas实现的一个画板
  2. java替换包含html标签
  3. Kotlin 介绍
  4. 【环境配置】php5.5 + apache2.4 安装配置【转+修改】
  5. javascript事件监听与事件委托
  6. (转)HTTP长连接和短连接
  7. myeclipse操作记录
  8. IOS开发中的几种设计模式介绍
  9. robotframework笔记23
  10. uploadify 上传文件出现HTTP 404错误
  11. MTTR是什么?或者说为什么别给婴儿喝白兰地
  12. UITextFiled自动补全输入,选中补全内容。NSRange和UITextRange的相互转换。-b
  13. Django写的投票系统2(转)
  14. [CSS] Transitions动画效果(1)
  15. FunDA(9)- Stream Source:reactive data streams
  16. 10 - 函数嵌套-作用域-闭包-LEGB-函数销毁
  17. 春招实习汇总(7个offer)
  18. autofac学习
  19. EntityFramework 学习 一 三种开发模式
  20. Java日志框架-Logback手册中文版以及官方配置文档教程

热门文章

  1. SpringBoot Jpa 分页查询最新配置方式
  2. num10---适配器模式
  3. 【题解】P3373 【模板】线段树 2
  4. HTTP&HTTPS协议详解之HTTP篇
  5. javascript检测客户端环境是否是pc端
  6. ELF文件之五——使用链接脚本-2个函数-data-bss
  7. pycharm template 设置
  8. OSPF配置实验(一)
  9. Rust学习--变量
  10. Go语言基础之面向对象编程中