Kera高层API

Posted nickchen121

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Kera高层API相关的知识,希望对你有一定的参考价值。

Keras != tf.keras

  • Keras是一个框架

  • datasets

  • layers

  • losses

  • metrics

  • optimizers

Outline1

  • Metrics

  • update_state

  • result().numpy()

  • reset_states

Metrics

Step1.Build a meter

acc_meter = metrics.Accuarcy()
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()

Clear buffer

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()

Outline2

  • Compile

  • Fit

  • Evaluate

  • Predict

Compile + Fit

Individual loss and optimize1

with tf.GradientTape() as tape:
    x = tf.reshape(x, (-1, 28*28))
    out = network(x)
    y_onehot = tf.one_hot(y, depth=10)
    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))

Now1

network.compile(optimizer=optimizers.Adam(lr=0.01),
                loss=tf.losses.CategoricalCrossentropy(fromlogits=True),
                metircs=['accuracy'])

Individual epoch and step2

for epoch in range(epochs):
    for step, (x, y) in enumerate(db):
        # ...

Now2

network.compile(optimizer=optimizers.Adam(lr=0.01),
                loss=tf.losses.CategoricalCrossentropy(fromlogits=True),
                metircs=['accuracy'])

network.fit(db, epochs=10)

Standard Progressbar

技术图片

Individual evaluation3

if step % 500 == 0:
    total, total_correct = 0., 0
    
    for step, (x, y) in enumerate(ds_val):
        x = tf.reshape(x, (-1, 28*28))
        out = network(x)
        pred = tf.argmax(out, axis=1)
        pred = tf.cast(pred, dtype=tf.int32)
        correct = tf.equal(pred, y)
        total_correct += tf.reduce_sum(tf.cast(correct, dtype=tf.int32)).numpy()
        total += x.shape[0]
       
    print(step, 'Evaluate Acc:', total_correct/total)

Now3

network.compile(optimizer=optimizers.Adam(lr=0.01),
                loss=tf.losses.CategoricalCrossentropy(fromlogits=True),
                metircs=['accuracy'])

# validation_freq=2表示2个epochs做一次验证
network.fit(db, epochs=10, validation_data=ds_val, validation_freq=2)

Evaluation

技术图片

Test

network.compile(optimizer=optimizers.Adam(lr=0.01),
                loss=tf.losses.CategoricalCrossentropy(fromlogits=True),
                metircs=['accuracy'])

# validation_freq=2表示2个epochs做一次验证
network.fit(db, epochs=10, validation_data=ds_val, validation_freq=2)

network.evaluate(ds_val)

技术图片

Predict

sample = next(iter(ds_val))
x = sample[0]
y = sample[1]
pred = network.predict(x)
y = tf.argmax(y, axis=1)
pred = tf.argmax(pre, axis=1)

print(pred)
print(y)

以上是关于Kera高层API的主要内容,如果未能解决你的问题,请参考以下文章

飞桨开源框架2.0,带你走进全新高层API,十行代码搞定深度学习模型开发

计算机视觉(CV)基于高层API实现宝石分类

kera 学习-线性回归

python-灰色预测平均房价趋势kera深度学习库的介绍

paddle飞桨框架高层API使用讲解

onActivityResult 未在 Android API 23 的片段上调用