此页面由 Cloud Translation API 翻译。
Switch to English

在Keras例如权聚类

查看上TensorFlow.org 在谷歌Colab运行 GitHub上查看源代码 下载笔记本

概观

欢迎来到端至端例如用于权聚类 ,所述TensorFlow模型优化工具包的一部分。

其他网页

的介绍,什么权聚类是,并确定是否应该使用它(包括什么支持),请参阅概述页面

要快速找到您需要为您的使用情况(超出完全聚类16个簇的模型)API的,看到全面的指导

内容

在本教程中,你会:

  1. 培养出tf.keras从零开始的MNIST数据集模型。
  2. 微调模式通过将权聚类API,看看正确。
  3. 创建集群6倍小TF和TFLite模型。
  4. 创建一个从组合权重的集群和培训后的量化一个8X小TFLite模型。
  5. 见精度从TF到TFLite持久性。

建立

您可以在本地运行此Jupyter笔记本的virtualenvcolab 。对于建立依赖关系的详细信息,请参阅安装指南

 pip install -q tensorflow-model-optimization
 import tensorflow as tf
from tensorflow import keras

import numpy as np
import tempfile
import zipfile
import os
 

训练tf.keras模型MNIST无集群

 # Load MNIST dataset
mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# Normalize the input image so that each pixel value is between 0 to 1.
train_images = train_images / 255.0
test_images  = test_images / 255.0

# Define the model architecture.
model = keras.Sequential([
    keras.layers.InputLayer(input_shape=(28, 28)),
    keras.layers.Reshape(target_shape=(28, 28, 1)),
    keras.layers.Conv2D(filters=12, kernel_size=(3, 3), activation=tf.nn.relu),
    keras.layers.MaxPooling2D(pool_size=(2, 2)),
    keras.layers.Flatten(),
    keras.layers.Dense(10)
])

# Train the digit classification model
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

model.fit(
    train_images,
    train_labels,
    validation_split=0.1,
    epochs=10
)
 
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11493376/11490434 [==============================] - 0s 0us/step
Epoch 1/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.3352 - accuracy: 0.9039 - val_loss: 0.1543 - val_accuracy: 0.9575
Epoch 2/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.1535 - accuracy: 0.9559 - val_loss: 0.0948 - val_accuracy: 0.9745
Epoch 3/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.1003 - accuracy: 0.9715 - val_loss: 0.0750 - val_accuracy: 0.9788
Epoch 4/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0791 - accuracy: 0.9768 - val_loss: 0.0652 - val_accuracy: 0.9828
Epoch 5/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0669 - accuracy: 0.9803 - val_loss: 0.0663 - val_accuracy: 0.9807
Epoch 6/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0589 - accuracy: 0.9820 - val_loss: 0.0581 - val_accuracy: 0.9833
Epoch 7/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0528 - accuracy: 0.9840 - val_loss: 0.0584 - val_accuracy: 0.9832
Epoch 8/10
1688/1688 [==============================] - 8s 5ms/step - loss: 0.0479 - accuracy: 0.9854 - val_loss: 0.0560 - val_accuracy: 0.9838
Epoch 9/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0434 - accuracy: 0.9867 - val_loss: 0.0550 - val_accuracy: 0.9853
Epoch 10/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0393 - accuracy: 0.9880 - val_loss: 0.0571 - val_accuracy: 0.9845

<tensorflow.python.keras.callbacks.History at 0x7fd1a1e18668>

评估基准模型,并保存供以后使用

 _, baseline_model_accuracy = model.evaluate(
    test_images, test_labels, verbose=0)

print('Baseline test accuracy:', baseline_model_accuracy)

_, keras_file = tempfile.mkstemp('.h5')
print('Saving model to: ', keras_file)
tf.keras.models.save_model(model, keras_file, include_optimizer=False)
 
Baseline test accuracy: 0.9805999994277954
Saving model to:  /tmp/tmpphs68ctq.h5

微调聚类预先训练模式

应用cluster_weights() API将整个预先训练模型来演示应用压缩,同时保持体面的准确性后降低模型大小的有效性。对于如何更好地平衡精度和压缩率供您使用,请参阅每层示例中的综合指南

定义模型并应用群集API

之前您传递模型到集群API,确保它是训练有素,显示了一些可接受的精度。

 import tensorflow_model_optimization as tfmot

cluster_weights = tfmot.clustering.keras.cluster_weights
CentroidInitialization = tfmot.clustering.keras.CentroidInitialization

clustering_params = {
  'number_of_clusters': 16,
  'cluster_centroids_init': CentroidInitialization.LINEAR
}

# Cluster a whole model
clustered_model = cluster_weights(model, **clustering_params)

# Use smaller learning rate for fine-tuning clustered model
opt = tf.keras.optimizers.Adam(learning_rate=1e-5)

clustered_model.compile(
  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
  optimizer=opt,
  metrics=['accuracy'])

clustered_model.summary()
 
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
cluster_reshape (ClusterWeig (None, 28, 28, 1)         0         
_________________________________________________________________
cluster_conv2d (ClusterWeigh (None, 26, 26, 12)        136       
_________________________________________________________________
cluster_max_pooling2d (Clust (None, 13, 13, 12)        0         
_________________________________________________________________
cluster_flatten (ClusterWeig (None, 2028)              0         
_________________________________________________________________
cluster_dense (ClusterWeight (None, 10)                20306     
=================================================================
Total params: 20,442
Trainable params: 54
Non-trainable params: 20,388
_________________________________________________________________

微调模型和评估对基线的准确性

微调与聚类1个划时代的机型。

 # Fine-tune model
clustered_model.fit(
  train_images,
  train_labels,
  batch_size=500,
  epochs=1,
  validation_split=0.1)
 
108/108 [==============================] - 2s 16ms/step - loss: 0.0535 - accuracy: 0.9821 - val_loss: 0.0692 - val_accuracy: 0.9803

<tensorflow.python.keras.callbacks.History at 0x7fd18437ee10>

对于这个例子,有在聚类后测试精度损失最小,相对于基线。

 _, clustered_model_accuracy = clustered_model.evaluate(
  test_images, test_labels, verbose=0)

print('Baseline test accuracy:', baseline_model_accuracy)
print('Clustered test accuracy:', clustered_model_accuracy)
 
Baseline test accuracy: 0.9805999994277954
Clustered test accuracy: 0.9753000140190125

创建6X从集群小排量车型

strip_clustering和应用标准压缩算法(例如,经由gzip的)是必要的,见聚类的压缩的好处。

首先,创建TensorFlow可压缩模型。在这里, strip_clustering删除所有变量(例如tf.Variable用于存储聚类中心和索引)培训,这将在推理,否则添加到模型的大小在聚类只需要。

 final_model = tfmot.clustering.keras.strip_clustering(clustered_model)

_, clustered_keras_file = tempfile.mkstemp('.h5')
print('Saving clustered model to: ', clustered_keras_file)
tf.keras.models.save_model(final_model, clustered_keras_file, 
                           include_optimizer=False)
 
Saving clustered model to:  /tmp/tmpfnmtfvf8.h5

然后,TFLite创建可压缩模型。您可以在集群模式转换成格式,对您的目标后台运行的。 TensorFlow精简版是你可以用它来部署到移动设备的例子。

 clustered_tflite_file = '/tmp/clustered_mnist.tflite'
converter = tf.lite.TFLiteConverter.from_keras_model(final_model)
tflite_clustered_model = converter.convert()
with open(clustered_tflite_file, 'wb') as f:
  f.write(tflite_clustered_model)
print('Saved clustered TFLite model to:', clustered_tflite_file)
 
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/training/tracking/tracking.py:111: Model.state_updates (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.
Instructions for updating:
This property should not be used in TensorFlow 2.0, as updates are applied automatically.
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/training/tracking/tracking.py:111: Layer.updates (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.
Instructions for updating:
This property should not be used in TensorFlow 2.0, as updates are applied automatically.
INFO:tensorflow:Assets written to: /tmp/tmpe966h_56/assets
Saved clustered TFLite model to: /tmp/clustered_mnist.tflite

定义一个辅助函数实际上通过压缩gzip的模型和测量压缩大小。

 def get_gzipped_model_size(file):
  # It returns the size of the gzipped model in bytes.
  import os
  import zipfile

  _, zipped_file = tempfile.mkstemp('.zip')
  with zipfile.ZipFile(zipped_file, 'w', compression=zipfile.ZIP_DEFLATED) as f:
    f.write(file)

  return os.path.getsize(zipped_file)
 

比较看,该模型是从6倍小集群

 print("Size of gzipped baseline Keras model: %.2f bytes" % (get_gzipped_model_size(keras_file)))
print("Size of gzipped clustered Keras model: %.2f bytes" % (get_gzipped_model_size(clustered_keras_file)))
print("Size of gzipped clustered TFlite model: %.2f bytes" % (get_gzipped_model_size(clustered_tflite_file)))
 
Size of gzipped baseline Keras model: 78076.00 bytes
Size of gzipped clustered Keras model: 13362.00 bytes
Size of gzipped clustered TFlite model: 12982.00 bytes

创建一个从组合权重的集群和培训后的量化的8倍小TFLite模型

你可以申请培训后量化为额外的好处群集模式。

 converter = tf.lite.TFLiteConverter.from_keras_model(final_model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_quant_model = converter.convert()

_, quantized_and_clustered_tflite_file = tempfile.mkstemp('.tflite')

with open(quantized_and_clustered_tflite_file, 'wb') as f:
  f.write(tflite_quant_model)

print('Saved quantized and clustered TFLite model to:', quantized_and_clustered_tflite_file)
print("Size of gzipped baseline Keras model: %.2f bytes" % (get_gzipped_model_size(keras_file)))
print("Size of gzipped clustered and quantized TFlite model: %.2f bytes" % (get_gzipped_model_size(quantized_and_clustered_tflite_file)))
 
INFO:tensorflow:Assets written to: /tmp/tmpg0gw8r5x/assets

INFO:tensorflow:Assets written to: /tmp/tmpg0gw8r5x/assets

Saved quantized and clustered TFLite model to: /tmp/tmp43crqft1.tflite
Size of gzipped baseline Keras model: 78076.00 bytes
Size of gzipped clustered and quantized TFlite model: 9830.00 bytes

看到TF精度的持久性TFLite

定义一个辅助函数来评估对测试数据集的TFLite模型。

 def eval_model(interpreter):
  input_index = interpreter.get_input_details()[0]["index"]
  output_index = interpreter.get_output_details()[0]["index"]

  # Run predictions on every image in the "test" dataset.
  prediction_digits = []
  for i, test_image in enumerate(test_images):
    if i % 1000 == 0:
      print('Evaluated on {n} results so far.'.format(n=i))
    # Pre-processing: add batch dimension and convert to float32 to match with
    # the model's input data format.
    test_image = np.expand_dims(test_image, axis=0).astype(np.float32)
    interpreter.set_tensor(input_index, test_image)

    # Run inference.
    interpreter.invoke()

    # Post-processing: remove batch dimension and find the digit with highest
    # probability.
    output = interpreter.tensor(output_index)
    digit = np.argmax(output()[0])
    prediction_digits.append(digit)

  print('\n')
  # Compare prediction results with ground truth labels to calculate accuracy.
  prediction_digits = np.array(prediction_digits)
  accuracy = (prediction_digits == test_labels).mean()
  return accuracy
 

你评估模型,已聚集和量化,然后看到TensorFlow仍然存在精度的TFLite后端。

 interpreter = tf.lite.Interpreter(model_content=tflite_quant_model)
interpreter.allocate_tensors()

test_accuracy = eval_model(interpreter)

print('Clustered and quantized TFLite test_accuracy:', test_accuracy)
print('Clustered TF test accuracy:', clustered_model_accuracy)
 
Evaluated on 0 results so far.
Evaluated on 1000 results so far.
Evaluated on 2000 results so far.
Evaluated on 3000 results so far.
Evaluated on 4000 results so far.
Evaluated on 5000 results so far.
Evaluated on 6000 results so far.
Evaluated on 7000 results so far.
Evaluated on 8000 results so far.
Evaluated on 9000 results so far.


Clustered and quantized TFLite test_accuracy: 0.975
Clustered TF test accuracy: 0.9753000140190125

结论

在本教程中,您看到了如何与TensorFlow模型优化工具包API创建集群模型。更具体地讲,你已经通过一个终端到终端的例如用于创建MNIST 8倍的小模型,最小精度差。我们鼓励你去尝试这种新功能,它可以在资源有限的环境中部署尤为重要。