Home>
Error message
I'll ask you a question for the first time.
When I predicted an image using Xception in keras.applications, the value changed according to batch_size.
How can I get the prediction results regardless of batch_size?
Is some setting required?
I'm sorry, but I'd appreciate it if you could teach me somebody.
Thank you.
Append

Thanks to tiitoi, the output layer has the same result.
However, since we are using anomaly detection in Metric Learning, the value we want is the value of the Xception middle layer.
Sorry for not enough words.
How can I get the value of the middle layer of Xception regardless of batch_size?

Applicable source code
import numpy as np
from keras.models import Model
from keras.applications import Xception
image_data = Image data
image_data = np.asarray (image_data)
image_data = image_data.astype ('float32')/255.0
for i in range (100):
    # Build Xception model
    base_model = Xception (include_top = True, weights = 'imagenet', input_shape = (299, 299, 3))
    model = Model (inputs = base_model.input, outputs = base_model.layers [i + 2] .output)
    p1 = model.predict (image_data, batch_size = 1)
    p32 = model.predict (image_data, batch_size = 32)
    judge = (p1 == p32) .all ()
    print (str (i) + ':' + str (judge))
    model.summary ()
    print ()
    if not judge:
        break

When I tried the above code, it seemed that there was a difference in block1_conv2.

Supplemental information (FW/tool version etc.)

The environment is as follows.
Ubuntu 18.04.3 LTS
Python 3.6.8
Keras 2.3.1
tensorflow-gpu 2.0.0

  • Answer # 1

    Since floating-point operations cause rounding errors, it is not normal to compare==to see if they are exactly the same.
    If it is numpy, it can be compared with numpy.allclose, so it is better to judge here.

    Additional
    import numpy as np
    from PIL import Image
    from tensorflow.keras.applications import Xception
    from tensorflow.keras.models import Model
    # Build Xception model
    model = Xception (include_top = True, weights = "imagenet", input_shape = (299, 299, 3))
    img = Image.open ("sample.jpg"). resize ((299, 299))
    img = np.float32 (img)/255
    image_data = np.array ([img for i in range (50)])
    base_model = Xception (include_top = True, weights = "imagenet", input_shape = (299, 299, 3))
    for i in range (100):
        model = Model (inputs = base_model.input, outputs = base_model.layers [i + 2] .output)
        p1 = model.predict (image_data, batch_size = 1)
        p2 = model.predict (image_data, batch_size = 32)
        if not np.allclose (p1, p2, rtol = 1e-03):
            print (p1.ravel () [: 10])
            print (p2.ravel () [: 10])
            break

Related articles