1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
| """ 此文件代码已经上传保存到google colab上,可以直接运行。 colab地址为:https://colab.research.google.com/drive/1sFxDyFvHRZr5YvV8S2PFw-583RaucKS3 运行的主要环境包括:Python 3.12.13、tensorflow 2.20.0 """
import os import tensorflow as tf
from tensorflow.keras import models from tensorflow.keras import layers
tf.random.set_seed(666)
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()
X_train = X_train/255.
X_test = X_test/255.
X_train.shape, X_test.shape, y_train.shape, y_test.shape
X_train = X_train.astype("float32").reshape(-1, 28, 28, 1) X_test = X_test.astype("float32").reshape(-1, 28, 28, 1)
def get_teacher_model(): model = models.Sequential() model.add(layers.Conv2D(16, (5, 5), activation="relu", input_shape=(28, 28, 1))) model.add(layers.MaxPooling2D(pool_size=(2, 2))) model.add(layers.Conv2D(32, (5, 5), activation="relu")) model.add(layers.MaxPooling2D(pool_size=(2, 2))) model.add(layers.Dropout(0.2)) model.add(layers.Flatten()) model.add(layers.Dense(128, activation="relu")) model.add(layers.Dense(10))
return model
loss_func = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
optimizer = tf.keras.optimizers.Adam()
train_ds = tf.data.Dataset.from_tensor_slices((X_train, y_train)).shuffle(100).batch(64)
test_ds = tf.data.Dataset.from_tensor_slices((X_test, y_test)).batch(64)
teacher_model = get_teacher_model()
teacher_model.compile(loss=loss_func, optimizer=optimizer, metrics=["accuracy"])
history = teacher_model.fit(train_ds, validation_data=test_ds, epochs=10)
print("Test accuracy: {:.2f}".format(teacher_model.evaluate(test_ds)[1]*100))
teacher_model.save_weights("teacher_model.weights.h5")
def get_student_model(): model = models.Sequential() model.add(layers.Input(shape=(28, 28, 1))) model.add(layers.Flatten()) model.add(layers.Dense(48, activation="relu")) model.add(layers.Dense(10))
return model
def get_kd_loss(student_logits, teacher_logits, temperature=0.5): """ 知识蒸馏的核心损失函数。 作用:计算学生模型和教师模型在“软目标(Soft Targets)”上的差异。 """
teacher_probs = tf.nn.softmax(teacher_logits / temperature) kd_loss = tf.compat.v1.losses.softmax_cross_entropy(teacher_probs, student_logits / temperature, temperature**2) return kd_loss
student_model = get_student_model()
optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)
train_loss = tf.keras.metrics.Mean(name="train_loss") valid_loss = tf.keras.metrics.Mean(name="test_loss")
train_acc = tf.keras.metrics.SparseCategoricalAccuracy(name="train_acc") valid_acc = tf.keras.metrics.SparseCategoricalAccuracy(name="valid_acc")
@tf.function def model_train(images, labels, teacher_model, student_model, optimizer, temperature): teacher_logits = teacher_model(images)
with tf.GradientTape() as tape: student_logits = student_model(images) loss = get_kd_loss(student_logits, teacher_logits, temperature)
gradients = tape.gradient(loss, student_model.trainable_variables) optimizer.apply_gradients(zip(gradients, student_model.trainable_variables))
train_loss(loss) train_acc(labels, tf.nn.softmax(student_logits))
@tf.function def model_validate(images, labels, teacher_model, student_model, temperature): teacher_logits = teacher_model(images)
student_logits = student_model(images) loss = get_kd_loss(student_logits, teacher_logits, temperature)
valid_loss(loss) valid_acc(labels, tf.nn.softmax(student_logits))
def train_model(epochs, teacher_model, student_model, optimizer, temperature=0.5): for epoch in range(epochs): for (images, labels) in train_ds: model_train(images, labels, teacher_model, student_model, optimizer, temperature)
for (images, labels) in test_ds: model_validate(images, labels, teacher_model, student_model, temperature)
(loss, acc) = train_loss.result(), train_acc.result() (val_loss, val_acc) = valid_loss.result(), valid_acc.result()
train_loss.reset_state(), train_acc.reset_state() valid_loss.reset_state(), valid_acc.reset_state()
template = "Epoch {}, loss: {:.3f}, acc: {:.3f}, val_loss: {:.3f}, val_acc: {:.3f}" print (template.format(epoch+1, loss, acc, val_loss, val_acc))
return teacher_model, student_model
_, student_model = train_model(10, teacher_model, student_model, optimizer)
student_model.save_weights("student_model.weights.h5")
os.system("ls -lh *.h5")
teacher_model.summary()
student_model.summary()
def representative_data_gen(): for input_value in tf.data.Dataset.from_tensor_slices(X_train).batch(1).take(100): yield [input_value]
def convert_to_tflite(model, tflite_file): converter = tf.lite.TFLiteConverter.from_keras_model(model) converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.representative_dataset = representative_data_gen converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8] converter.inference_input_type = tf.int8 converter.inference_output_type = tf.int8 tflite_quant_model = converter.convert()
open(tflite_file, 'wb').write(tflite_quant_model)
convert_to_tflite(teacher_model, "teacher.tflite")
convert_to_tflite(student_model, "student.tflite")
os.system("ls -lh *.tflite")
print(f"tensorflow's version:{tf.version.VERSION}")
plt.figure(figsize=(10, 6))
plt.plot(history.history['loss'], label='Train Loss', color='blue')
plt.plot(history.history['val_loss'], label='Validation Loss', color='red', linestyle='--')
plt.title('Training and Validation Loss over Epochs')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.grid(True)
plt.show()
|