diff --git a/code/mnist.py b/code/mnist.py new file mode 100644 index 0000000..2902195 --- /dev/null +++ b/code/mnist.py @@ -0,0 +1,57 @@ +import os +import tensorflow as tf +import matplotlib.pyplot as plt +import numpy as np + +mnist = tf.keras.datasets.mnist +(x_train, y_train),(x_test, y_test) = mnist.load_data(path="/home/mnist/data/mnist.npz") #加载mnist数据集 + +#验证mnist数据集大小。x为数据,y为标签。mnist每张图的像素为28*28 +print(x_train.shape) +print(y_train.shape) +print(x_test.shape) +print(y_test.shape) + +#打印训练集中前9张,看看是什么数字 +for i in range(9): + plt.subplot(3,3,1+i) + plt.imshow(x_train[i], cmap='gray') +plt.show() +plt.savefig('./mnist/output/1.jpg') + +#打印相应的标签 +print(y_train[:9]) + +#基操:将像素标准化一下 +x_train, x_test = x_train / 255.0, x_test / 255.0 + +#搭建一个两层神经网络 +model = tf.keras.models.Sequential([ + tf.keras.layers.Flatten(input_shape=(28, 28)), #拉伸图像成一维向量 + tf.keras.layers.Dense(128, activation='relu'), #第一层全连接+ReLU激活 + tf.keras.layers.Dropout(0.2), #dropout层 + tf.keras.layers.Dense(10, activation='softmax') #第二层全连接+softmax激活,输出预测标签 +]) + +#设置训练超参,优化器为sgd,损失函数为交叉熵,训练衡量指标为accuracy +model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) + +#开始训练,训练5个epoch,一个epoch代表所有图像计算一遍。每一个epoch能观察到训练精度的提升 +model.fit(x_train, y_train, epochs=10) + +#计算训练了5个epoch的模型在测试集上的表现 +model.evaluate(x_test, y_test) + + +#直观看一下模型预测结果,打印测试集中的前9张图像 +for i in range(9): + plt.subplot(3,3,1+i) + plt.imshow(x_test[i], cmap='gray') +plt.show() +plt.savefig('./mnist/output/2.jpg') + +#打印模型识别的数字,是否正确? +# np.argmax(model(x_test[:9]).numpy(), axis=1) + +#保存训练好的模型 +model.save("./mnist/output/model_epoch_10") diff --git a/output/1.jpg b/output/1.jpg new file mode 100644 index 0000000..1fc6351 Binary files /dev/null and b/output/1.jpg differ diff --git a/output/2.jpg b/output/2.jpg new file mode 100644 index 0000000..a5526f3 Binary files /dev/null and b/output/2.jpg differ diff --git a/output/model_epoch_10/fingerprint.pb b/output/model_epoch_10/fingerprint.pb new file mode 100644 index 0000000..5a55725 Binary files /dev/null and b/output/model_epoch_10/fingerprint.pb differ diff --git a/output/model_epoch_10/keras_metadata.pb b/output/model_epoch_10/keras_metadata.pb new file mode 100644 index 0000000..99852a9 --- /dev/null +++ b/output/model_epoch_10/keras_metadata.pb @@ -0,0 +1,8 @@ + +%root"_tf_keras_sequential*%{"name": "sequential", "trainable": true, "expects_training_arg": true, "dtype": "float32", "batch_input_shape": null, "must_restore_from_config": false, "preserve_input_structure_in_config": false, "autocast": false, "class_name": "Sequential", "config": {"name": "sequential", "layers": [{"class_name": "InputLayer", "config": {"batch_input_shape": {"class_name": "__tuple__", "items": [null, 28, 28]}, "dtype": "float32", "sparse": false, "ragged": false, "name": "flatten_input"}}, {"class_name": "Flatten", "config": {"name": "flatten", "trainable": true, "dtype": "float32", "batch_input_shape": {"class_name": "__tuple__", "items": [null, 28, 28]}, "data_format": "channels_last"}}, {"class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": "float32", "units": 128, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Dropout", "config": {"name": "dropout", "trainable": true, "dtype": "float32", "rate": 0.2, "noise_shape": null, "seed": null}}, {"class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "dtype": "float32", "units": 10, "activation": "softmax", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}]}, "shared_object_id": 9, "input_spec": [{"class_name": "InputSpec", "config": {"dtype": null, "shape": {"class_name": "__tuple__", "items": [null, 28, 28]}, "ndim": 3, "max_ndim": null, "min_ndim": null, "axes": {}}}], "build_input_shape": {"class_name": "TensorShape", "items": [null, 28, 28]}, "is_graph_network": true, "full_save_spec": {"class_name": "__tuple__", "items": [[{"class_name": "TypeSpec", "type_spec": "tf.TensorSpec", "serialized": [{"class_name": "TensorShape", "items": [null, 28, 28]}, "float32", "flatten_input"]}], {}]}, "save_spec": {"class_name": "TypeSpec", "type_spec": "tf.TensorSpec", "serialized": [{"class_name": "TensorShape", "items": [null, 28, 28]}, "float32", "flatten_input"]}, "keras_version": "2.11.0", "backend": "tensorflow", "model_config": {"class_name": "Sequential", "config": {"name": "sequential", "layers": [{"class_name": "InputLayer", "config": {"batch_input_shape": {"class_name": "__tuple__", "items": [null, 28, 28]}, "dtype": "float32", "sparse": false, "ragged": false, "name": "flatten_input"}, "shared_object_id": 0}, {"class_name": "Flatten", "config": {"name": "flatten", "trainable": true, "dtype": "float32", "batch_input_shape": {"class_name": "__tuple__", "items": [null, 28, 28]}, "data_format": "channels_last"}, "shared_object_id": 1}, {"class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": "float32", "units": 128, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 2}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 3}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 4}, {"class_name": "Dropout", "config": {"name": "dropout", "trainable": true, "dtype": "float32", "rate": 0.2, "noise_shape": null, "seed": null}, "shared_object_id": 5}, {"class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "dtype": "float32", "units": 10, "activation": "softmax", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 6}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 7}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 8}]}}, "training_config": {"loss": "sparse_categorical_crossentropy", "metrics": [[{"class_name": "MeanMetricWrapper", "config": {"name": "accuracy", "dtype": "float32", "fn": "sparse_categorical_accuracy"}, "shared_object_id": 11}]], "weighted_metrics": null, "loss_weights": null, "optimizer_config": {"class_name": "Custom>Adam", "config": {"name": "Adam", "weight_decay": null, "clipnorm": null, "global_clipnorm": null, "clipvalue": null, "use_ema": false, "ema_momentum": 0.99, "ema_overwrite_frequency": null, "jit_compile": false, "is_legacy_optimizer": false, "learning_rate": 0.0010000000474974513, "beta_1": 0.9, "beta_2": 0.999, "epsilon": 1e-07, "amsgrad": false}}}}2 + root.layer-0"_tf_keras_layer*{"name": "flatten", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": {"class_name": "__tuple__", "items": [null, 28, 28]}, "stateful": false, "must_restore_from_config": false, "preserve_input_structure_in_config": false, "autocast": true, "class_name": "Flatten", "config": {"name": "flatten", "trainable": true, "dtype": "float32", "batch_input_shape": {"class_name": "__tuple__", "items": [null, 28, 28]}, "data_format": "channels_last"}, "shared_object_id": 1, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 1, "axes": {}}, "shared_object_id": 12}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 28, 28]}}2 +root.layer_with_weights-0"_tf_keras_layer*{"name": "dense", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "preserve_input_structure_in_config": false, "autocast": true, "class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": "float32", "units": 128, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 2}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 3}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 4, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 2, "axes": {"-1": 784}}, "shared_object_id": 13}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 784]}}2 + root.layer-2"_tf_keras_layer*{"name": "dropout", "trainable": true, "expects_training_arg": true, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "preserve_input_structure_in_config": false, "autocast": true, "class_name": "Dropout", "config": {"name": "dropout", "trainable": true, "dtype": "float32", "rate": 0.2, "noise_shape": null, "seed": null}, "shared_object_id": 5, "build_input_shape": {"class_name": "TensorShape", "items": [null, 128]}}2 +root.layer_with_weights-1"_tf_keras_layer*{"name": "dense_1", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "preserve_input_structure_in_config": false, "autocast": true, "class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "dtype": "float32", "units": 10, "activation": "softmax", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 6}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 7}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 8, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 2, "axes": {"-1": 128}}, "shared_object_id": 14}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 128]}}2 +^root.keras_api.metrics.0"_tf_keras_metric*{"class_name": "Mean", "name": "loss", "dtype": "float32", "config": {"name": "loss", "dtype": "float32"}, "shared_object_id": 15}2 +_root.keras_api.metrics.1"_tf_keras_metric*{"class_name": "MeanMetricWrapper", "name": "accuracy", "dtype": "float32", "config": {"name": "accuracy", "dtype": "float32", "fn": "sparse_categorical_accuracy"}, "shared_object_id": 11}2 \ No newline at end of file diff --git a/output/model_epoch_10/saved_model.pb b/output/model_epoch_10/saved_model.pb new file mode 100644 index 0000000..ad31ed8 Binary files /dev/null and b/output/model_epoch_10/saved_model.pb differ diff --git a/output/model_epoch_10/variables/variables.data-00000-of-00001 b/output/model_epoch_10/variables/variables.data-00000-of-00001 new file mode 100644 index 0000000..5d0681e Binary files /dev/null and b/output/model_epoch_10/variables/variables.data-00000-of-00001 differ diff --git a/output/model_epoch_10/variables/variables.index b/output/model_epoch_10/variables/variables.index new file mode 100644 index 0000000..3f12a25 Binary files /dev/null and b/output/model_epoch_10/variables/variables.index differ