The problem of adding custom evaluation indicators in the K eras model The problem of adding custom evaluation indicators in the Keras model K E R & lt A S -mode type in the self- given -defined assessment value refers to mark the additive added to ask questions
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow. keras. layers import Dense, Flatten, Conv2D
from tensorflow. keras import Model
import numpy as np
print ( tf. __version__)
print ( np. __version__)
Mnist data set
mnist = np. load( "mnist.npz" )
x_train, y_train, x_test, y_test = mnist[ 'x_train' ] , mnist[ 'y_train' ] , mnist[ 'x_test' ] , mnist[ 'y_test' ]
x_train, x_test = x_train / 255.0 , x_test / 255.0
import matplotlib. pyplot as plt
fig, ax = plt. subplots(
nrows= 2 ,
ncols= 5 ,
sharex= True ,
sharey= True , )
ax = ax. flatten( )
for i in range ( 10 ) :
img = x_train[ y_train == i] [ 0 ] . reshape( 28 , 28 )
ax[ i] . imshow( img, cmap= 'Greys' , interpolation= 'nearest' )
ax[ 0 ] . set_xticks( [ ] )
ax[ 0 ] . set_yticks( [ ] )
plt. tight_layout( )
x_train = x_train[ . . . , tf. newaxis]
x_test = x_test[ . . . , tf. newaxis]
y_train = tf. one_hot( y_train, depth= 10 )
y_test = tf. one_hot( y_test, depth= 10 )
train_ds = tf. data. Dataset. from_tensor_slices( ( x_train, y_train) ) . shuffle( 10000 ) . batch( 32 )
test_ds = tf. data. Dataset. from_tensor_slices( ( x_test, y_test) ) . shuffle( 100 ) . batch( 32 )
class MyModel ( Model) :
def __init__ ( self) :
super ( MyModel, self) . __init__( )
self. conv1 = Conv2D( 32 , 3 , activation= 'relu' )
self. flatten = Flatten( )
self. d1 = Dense( 128 , activation= 'relu' )
self. d2 = Dense( 10 , activation= 'softmax' )
def call ( self, x) :
x = self. conv1( x)
x = self. flatten( x)
x = self. d1( x)
return self. d2( x)
class CatgoricalTruePositives ( tf. keras. metrics. Metric) :
def __init__ ( self, name= 'categorical_true_positives' , ** kwargs) :
super ( CatgoricalTruePositives, self) . __init__( name= name, ** kwargs)
self. true_positives = self. add_weight( name= 'tp' , initializer= 'zeros' )
def update_state ( self, y_true, y_pred, sample_weight= None ) :
y_pred = tf. argmax( y_pred, axis= - 1 )
y_true = tf. argmax( y_true, axis= - 1 )
values = tf. equal( tf. cast( y_true, 'int32' ) , tf. cast( y_pred, 'int32' ) )
values = tf. cast( values, 'float32' )
if sample_weight is not None :
sample_weight = tf. cast( sample_weight, 'float32' )
values = tf. multiply( values, sample_weight)
self. true_positives. assign_add( tf. reduce_sum( values) )
def result ( self) :
return self. true_positives
def reset_states ( self) :
self. true_positives. assign( 0 . )
model = MyModel( )
model. compile ( optimizer = tf. keras. optimizers. Adam( 0.001 ) ,
loss = tf. keras. losses. CategoricalCrossentropy( ) ,
metrics = [ tf. keras. metrics. CategoricalAccuracy( ) ,
CatgoricalTruePositives( ) ,
]
)
model. fit( train_ds, epochs= 5 , validation_data= test_ds)