以下のURLを参照し、kerasモデルのプルーニングを行おうとしました。
https://www.tensorflow.org/model_optimization/guide/pruning/pruning_with_keras
プルーニングを行うために、以下のコードを用いました。
python
1import tempfile 2import os 3import numpy as np 4import pandas as pd 5from datetime import datetime 6import matplotlib.pyplot as plt 7import random 8 9import tensorflow as tf 10from tensorflow import keras 11# import urllib.request 12from keras.datasets import mnist 13import gzip 14import pickle as cPickle 15import sys 16 17# proxy = urllib.request.ProxyHandler({'http': 'http://proxy.olympus.co.jp:8080'}) 18# opener = urllib.request.build_opener(proxy) 19# mnist.urllib.request.install_opener(opener) 20 21# Load MNIST dataset 22f = gzip.open('mnist.pkl.gz', 'rb') 23if sys.version_info < (3,): 24 data = cPickle.load(f) 25else: 26 data = cPickle.load(f, encoding='bytes') 27f.close() 28 29(train_images, train_labels), (test_images, test_labels) = data 30 31 32# Normalize the input image so that each pixel value is between 0 and 1. 33train_images = train_images / 255.0 34test_images = test_images / 255.0 35 36# Define the model architecture. 37model = keras.Sequential([ 38 keras.layers.InputLayer(input_shape=(28, 28)), 39 keras.layers.Reshape(target_shape=(28, 28, 1)), 40 keras.layers.Conv2D(filters=12, kernel_size=(3, 3), activation='relu'), 41 keras.layers.MaxPooling2D(pool_size=(2, 2)), 42 keras.layers.Flatten(), 43 keras.layers.Dense(10) 44]) 45 46# Train the digit classification model 47model.compile(optimizer='adam', 48 loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), 49 metrics=['accuracy']) 50 51model.fit( 52 train_images, 53 train_labels, 54 epochs=4, 55 validation_split=0.1, 56) 57 58_, baseline_model_accuracy = model.evaluate( 59 test_images, test_labels, verbose=0) 60 61print('Baseline test accuracy:', baseline_model_accuracy) 62 63_, keras_file = tempfile.mkstemp('.h5') 64tf.keras.models.save_model(model, keras_file, include_optimizer=False) 65print('Saved baseline model to:', keras_file) 66 67import tensorflow_model_optimization as tfmot 68 69prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude 70 71# Compute end step to finish pruning after 2 epochs. 72batch_size = 128 73epochs = 2 74validation_split = 0.1 # 10% of training set will be used for validation set. 75 76num_images = train_images.shape[0] * (1 - validation_split) 77end_step = np.ceil(num_images / batch_size).astype(np.int32) * epochs 78 79# Define model for pruning. 80pruning_params = { 81 'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(initial_sparsity=0.50, 82 final_sparsity=0.80, 83 begin_step=0, 84 end_step=end_step) 85} 86 87model_for_pruning = prune_low_magnitude(model, **pruning_params) 88 89# `prune_low_magnitude` requires a recompile. 90model_for_pruning.compile(optimizer='adam', 91 loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), 92 metrics=['accuracy']) 93 94model_for_pruning.summary() 95 96# 97logdir = tempfile.mkdtemp() 98 99callbacks = [ 100 tfmot.sparsity.keras.UpdatePruningStep(), 101 tfmot.sparsity.keras.PruningSummaries(log_dir=logdir), 102] 103 104# last row 105model_for_pruning.fit(train_images, train_labels, batch_size=batch_size, epochs=epochs, validation_split=validation_split, callbacks=callbacks)
「# last row」に到達し、pruningされたモデルの再学習を行おうとした際に、エラー「TypeError: '<' not supported between instances of 'InputLayer' and 'Sequential'」が発生しました。
どなたか、解決方法を共有してくださると幸いです。
私の実行環境は以下になります。
OS:Windows10
packages: python 3.6.6 numpy 1.21.0 tensorflow 2.1.0 tensorflow-base 2.1.0 tensorflow-estimator 2.1.0 tensorboard 2.4.0 tensorboard-plugin-wit 1.6.0 keras 2.3.1