Copy % matplotlib inline
import tensorflow as tf
!pip install d2l
from d2l import tensorflow as d2l
Copy ( x_train, y_train) , ( x_test, y_test) = tf. keras. datasets. fashion_mnist. load_data( )
Copy
x_train. shape, y_train. shape
Copy ((60000, 28, 28), (60000,))
Copy
y_train_hot = tf. one_hot( y_train[ : ] , 10 )
y_train_hot. shape
Copy TensorShape([60000, 10])
Copy x_train_shaped = tf. reshape( x_train, [ 60000 , - 1 ] ) / 255
x_train_shaped. shape, x_train_shaped[ : 1 ]
Copy (TensorShape([60000, 784]),
<tf.Tensor: shape=(1, 784), dtype=float32, numpy=
array([[0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. ]], dtype=float32)>)
Copy net = tf. keras. Sequential( [
tf. keras. layers. Dense( units= 10 , input_dim= 784 , activation= tf. keras. activations. softmax)
] )
sgd = tf. keras. optimizers. SGD( learning_rate= 0.01 )
net. compile ( optimizer= sgd, loss= 'mse' , metrics= [ 'accuracy' ] )
Copy history = net. fit( x_train_shaped, y_train_hot, batch_size= 1000 , epochs= 500 , validation_split= 0.2 )
net. summary( )
Copy Epoch 1/500
48/48 [==============================] - 0s 4ms/step - loss: 0.0957 - accuracy: 0.0224 - val_loss: 0.0950 - val_accuracy: 0.0231
Epoch 500/500
48/48 [==============================] - 0s 2ms/step - loss: 0.0347 - accuracy: 0.7809 - val_loss: 0.0346 - val_accuracy: 0.7787
Model: "sequential_2"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_3 (Dense) (None, 10) 7850
=================================================================
Total params: 7,850
Trainable params: 7,850
Non-trainable params: 0
_________________________________________________________________
Copy print ( x_test. shape)
x_test_shaped = tf. reshape( x_test, [ 10000 , - 1 ] ) / 255
y_test_hot = tf. one_hot( y_test, 10 )
x_test_shaped. shape, y_test_hot. shape
Copy (10000, 28, 28)
(TensorShape([10000, 784]), TensorShape([10000, 10]))
Copy net. evaluate( x_test_shaped, y_test_hot)
Copy 313/313 [==============================] - 1s 2ms/step - loss: 0.0357 - accuracy: 0.7704
[0.03569139540195465, 0.7703999876976013]
Copy
import matplotlib. pyplot as plt
print ( "keys: " , history. history. keys( ) )
plt. plot( history. history[ "loss" ] , label= "loss" )
plt. plot( history. history[ "accuracy" ] , label= "accuracy" )
plt. plot( history. history[ "val_loss" ] , label= "val_loss" )
plt. plot( history. history[ "val_accuracy" ] , label= "val_accuracy" )
plt. legend( )
plt. show( )
Copy keys: dict_keys(['loss', 'accuracy', 'val_loss', 'val_accuracy'])
Copy py = net. predict( x_test_shaped)
py. argmax( axis= 1 ) . shape
Copy 313/313 [==============================] - 0s 866us/step
(10000,)