import tensorflow as tf
import matplotlib. pyplot as plt
mnist= tf. keras. datasets. mnist
( x_train, y_train) , ( x_test, y_test) = mnist. load_data( )
x_train, x_test= x_train/ 255.0 , x_test/ 255.0
plt. figure( )
for i in range ( 10 ) :
plt. subplot( 1 , 10 , i+ 1 )
plt. imshow( x_train[ i] )
print ( y_train[ i] )
model= tf. keras. models. Sequential( [
tf. keras. layers. Flatten( ) ,
tf. keras. layers. Dense( 50 , activation= 'relu' ) ,
tf. keras. layers. Dense( 100 , activation= 'softmax' )
] )
model. compile ( optimizer= 'adam' ,
loss= tf. keras. losses. SparseCategoricalCrossentropy( from_logits= False ) ,
metrics= [ 'sparse_categorical_accuracy' ] )
model. fit( x_train, y_train, batch_size= 32 , epochs= 50 , validation_data= ( x_test, y_test) , validation_freq= 1 )
model. summary( )
import tensorflow as tf
from tensorflow. keras. layers import Dense, Flatten
from tensorflow. keras import Model
mnist= tf. keras. datasets. mnist
( x_train, y_train) , ( x_test, y_test) = mnist. load_data( )
x_train, x_test= x_train/ 255.0 , x_test/ 255.0
class MnistModel ( Model) :
def __init__ ( self) :
super ( MnistModel, self) . __init__( )
self. flatten= Flatten( )
self. d1= Dense( 128 , activation= 'relu' )
self. d2= Dense( 10 , activation= 'softmax' )
def call ( self, x) :
x= self. flatten( x)
x= self. d1( x)
y= self. d2( x)
return y
model= MnistModel( )
model. compile ( optimizer= 'adam' ,
loss= tf. keras. losses. SparseCategoricalCrossentropy( from_logits= False ) ,
metrics= [ 'sparse_categorical_accuracy' ] )
model. fit( x_train, y_train, batch_size= 32 , epochs= 5 , validation_data= ( x_test, y_test) , validation_freq= 1 )
model. summary( )