<jupyter_start><jupyter_text>3.10 多层感知机的简洁实现下面我们使用tensorflow来实现上一节中的多层感知机。首先导入所需的包或模块<jupyter_code>import tensorflow as tf
from tensorflow import keras
import sys
sys.path.append("..") 
from tensorflow import keras
fashion_mnist = keras.datasets.fashion_mnist<jupyter_output><empty_output><jupyter_text>3.10.1 定义模型和softmax回归唯一的不同在于，我们多加了一个全连接层作为隐藏层。它的隐藏单元个数为256，并使用ReLU函数作为激活函数。<jupyter_code>model = tf.keras.models.Sequential([
                                    tf.keras.layers.Flatten(input_shape=(28, 28)),
                                    tf.keras.layers.Dense(256, activation='relu',),
                                    tf.keras.layers.Dense(10, activation='softmax')
                                    ])<jupyter_output><empty_output><jupyter_text>3.10.2 读取数据并训练模型我们使用与3.7节中训练softmax回归几乎相同的步骤来读取数据并训练模型。<jupyter_code>fashion_mnist = keras.datasets.fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
x_train = x_train / 255.0
x_test = x_test / 255.0
model.compile(optimizer=tf.keras.optimizers.SGD(lr=0.5),
             loss = 'sparse_categorical_crossentropy',
             metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5,
              batch_size=256,
              validation_data=(x_test, y_test),
              validation_freq=1)<jupyter_output>Train on 60000 samples, validate on 10000 samples
Epoch 1/5
60000/60000 [==============================] - 2s 36us/sample - loss: 0.9844 - accuracy: 0.7100 - val_loss: 0.5575 - val_accuracy: 0.7945
Epoch 2/5
60000/60000 [==============================] - 2s 33us/sample - loss: 0.5038 - accuracy: 0.8141 - val_loss: 0.6090 - val_accuracy: 0.7702
Epoch 3/5
60000/60000 [==============================] - 2s 35us/sample - loss: 0.4334 - accuracy: 0.8396 - val_loss: 0.4691 - val_accuracy: 0.8341
Epoch 4/5
60000/60000 [==============================] - 2s 34us/sample - loss: 0.3969 - accuracy: 0.8535 - val_loss: 0.4293 - val_accuracy: 0.8494
Epoch 5/5
60000/60000 [==============================] - 2s 31us/sample - loss: 0.3754 - accuracy: 0.8621 - val_loss: 0.4657 - val_accuracy: 0.8288
{'fraction_non_alphanumeric': 0.18268770923003347, 'fraction_numerical': 0.10760401721664276, 'mean_word_length': 3.4322033898305087, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '354297', 'license': 'Apache-2.0', 'n_tokens_mistral': 982, 'n_tokens_neox': 852, 'n_words': 123, 'path': 'code/chapter03_DL-basics/3.10_mlp-tensorflow2.0.ipynb', 'repo_name': 'laubob/D2DL', 'size': '2091'}