0

Below is a simple example in numpy of what I would like to do:

import numpy as np

y_true = np.array([0,0,1])
y_pred = np.array([0.1,0.2,0.7])

yc = (1-y_true).astype('bool')

desired = y_pred[yc]

>>> desired
>>> array([0.1, 0.2])

So the prediction corresponding to the ground truth is 0.7, I want to operate on an array containing all the elements of y_pred, except for the ground truth element.

I am unsure of how to make this work within Keras. Here is a working example of the problem in the loss function. Right now 'desired' isn't accomplishing anything, but that is what I need to work with:

# using tensorflow 2.0.0 and keras 2.3.1

import tensorflow.keras.backend as K
import tensorflow as tf
from tensorflow.keras.layers import Input,Dense,Flatten
from tensorflow.keras.models import Model
from keras.datasets import mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()

# Normalize data.
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255

# Convert class vectors to binary class matrices.
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)

input_shape = x_train.shape[1:]


x_in = Input((input_shape))

x = Flatten()(x_in)
x = Dense(256,'relu')(x)
x = Dense(256,'relu')(x)
x = Dense(256,'relu')(x)

out = Dense(10,'softmax')(x)




def loss(y_true,y_pred):


    yc = tf.math.logical_not(kb.cast(y_true, 'bool'))
    desired = tf.boolean_mask(y_pred,yc,axis = 1)    #Remove and it runs


    CE = tf.keras.losses.categorical_crossentropy(
        y_true,
        y_pred)

    L = CE

    return L



model = Model(x_in,out)

model.compile('adam',loss = loss,metrics = ['accuracy'])


model.fit(x_train,y_train)

I end up getting an error

ValueError: Shapes (10,) and (None, None) are incompatible

Where 10 is the number of categories. The end purpose is to implement this: ComplementEntropy in Keras, where my issue seems to be lines 26-28.

thushv89
  • 10,865
  • 1
  • 26
  • 39
Nick Merrill
  • 104
  • 9

2 Answers2

0

You can remove axis=1 from the Boolean_mask and it will run. And frankly, I don't see why you need axis=1 here.

def loss(y_true,y_pred):


    yc = tf.math.logical_not(K.cast(y_true, 'bool'))
    print(yc.shape)
    desired = tf.boolean_mask(y_pred, yc)    #Remove axis=1 and it runs


    CE = tf.keras.losses.categorical_crossentropy(
        y_true,
        y_pred)

    L = CE

    return L

This is probably what happens. You have y_pred which is a 2D tensor (N=2). Then you have a 2D mask (K=2). But there's this condition K + axis <= N. And if you pass axis=1 this fails.

thushv89
  • 10,865
  • 1
  • 26
  • 39
  • Yeah that makes sense. I will try to finish the rest of the code. When I run it I get this, ```WARNING:tensorflow:Entity .initialize_variables at 0x000002CBB3D7E168> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: ``` It still runs, but any idea why? – Nick Merrill Dec 23 '19 at 00:10
  • @NickMerrill, not really sure why this comes up. Ill have a look – thushv89 Dec 23 '19 at 04:18
0

Using thushv89's answer, here is the full code for how I implemented COT on LeNet from the referenced paper. The one trick is I am not actually flipping back and forth between the two objectives, instead there is just a random weight that flips s.

# using tensorflow 2.0.0 and keras 2.3.1

import tensorflow.keras.backend as kb
import tensorflow as tf
from tensorflow.keras.layers import Conv2D, Input, Dense,Flatten,AveragePooling2D,GlobalAveragePooling2D
from tensorflow.keras.models import Model
from keras.datasets import mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()

# Normalize data.
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255

#exapnd dims to fit chn format
x_train = np.expand_dims(x_train,axis=3)
x_test = np.expand_dims(x_test,axis=3)


# Convert class vectors to binary class matrices.
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)

input_shape = x_train.shape[1:]

x_in = Input((input_shape))

act = 'tanh'
x = Conv2D(32, (5, 5), activation=act, padding='same',strides = 1)(x_in)
x = AveragePooling2D((2, 2),strides = (2,2))(x)
x = Conv2D(16, (5, 5), activation=act)(x)
x = AveragePooling2D((2, 2),strides = (2,2))(x)

conv_out = Flatten()(x)
z = Dense(120,activation = act)(conv_out)#120
z = Dense(84,activation = act)(z)#84
last = Dense(10,activation = 'softmax')(z)

model = Model(x_in,last)



def loss(y_true,y_pred, axis=-1):

    s = kb.round(tf.random.uniform( (1,), minval=0, maxval=1, dtype=tf.dtypes.float32))
    s_ = 1 - s

    y_pred = y_pred + 1e-8

    yg = kb.max(y_pred,axis=1)
    yc = tf.math.logical_not(kb.cast(y_true, 'bool'))
    yp_c = tf.boolean_mask(y_pred, yc)  

    ygc_ = 1/(1-yg+1e-8)
    ygc_ = kb.expand_dims(ygc_,axis=1)

    Px = yp_c*ygc_ +1e-8

    COT = kb.mean(Px*kb.log(Px),axis=1)

    CE = -kb.mean(y_true*kb.log(y_pred),axis=1)

    L = s*CE +s_*(1/(10-1))*COT

    return L


model.compile(loss=loss, 
              optimizer='adam', metrics=['accuracy'])


model.fit(x_train,y_train,epochs=20,batch_size = 128,validation_data= (x_test,y_test))

pred = model.predict(x_test)

pred_label = np.argmax(pred,axis=1)
label = np.argmax(y_test,axis=1)

cor = (pred_label == label).sum()
acc = print('acc:',cor/label.shape[0])
Nick Merrill
  • 104
  • 9