%%html
<style>div.output_area pre {white-space: pre; word-wrap: normal;}.container {    width:100% !important; }</style>
from d2l import tensorflow as d2l
import tensorflow as tf

batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

Initializing Model Parameters

net = tf.keras.Sequential()
net.add(tf.keras.layers.Flatten(input_shape=(28,28)))
weight_initializer = tf.keras.initializers.RandomNormal(mean=0.0, stddev=0.01)
net.add(tf.keras.layers.Dense(10,kernel_initializer=weight_initializer))

Defining the Loss Function

loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)

Optimization Algorithm

trainer = tf.keras.optimizers.SGD(learning_rate=.1)

Training

num_epochs = 10
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> 2021-03-01T16:41:28.541956 image/svg+xml Matplotlib v3.3.4, https://matplotlib.org/
import inspect
lines = inspect.getsource(d2l.train_ch3)
print(lines)
def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):
    """Train a model (defined in Chapter 3)."""
    animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9],
                        legend=['train loss', 'train acc', 'test acc'])
    for epoch in range(num_epochs):
        train_metrics = train_epoch_ch3(net, train_iter, loss, updater)
        test_acc = evaluate_accuracy(net, test_iter)
        animator.add(epoch + 1, train_metrics + (test_acc,))
    train_loss, train_acc = train_metrics
    assert train_loss < 0.5, train_loss
    assert train_acc <= 1 and train_acc > 0.7, train_acc
    assert test_acc <= 1 and test_acc > 0.7, test_acc