0

TensorFlow 2.0 RC1

import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Multiply

import numpy as np

Expected output:

Multiply()([np.array([1,2,3,4,4,4]).reshape(2,3), np.array([1,0])])

enter image description here

Problem:

input_1 = Input(shape=(None,3))
mask_1 = Input(shape=(None,))

net = Multiply()([input_1, mask_1])
net = Model(inputs=[input_1, mask_1], outputs=net)

net.predict([np.array([1,2,3,4,4,4]).reshape(1,2,3), np.array([1,0]).reshape(1,2)]) # 1 = batch size

enter image description here

How to fix this problem?

Alexey Golyshev
  • 792
  • 6
  • 11

3 Answers3

3

Reshape the second array in the last line of code as np.array([1,0]).reshape(-1)

net.predict([np.array([1,2,3,4,4,4]).reshape(1,2,3), np.array([1,0]).reshape(-1)]) # 1 = batch size
stephen_mugisha
  • 889
  • 1
  • 8
  • 18
3

It depends on how the input shape is specified. In the Multiply() example(element-wise multiplication), the batch size is 2 and the feature size is 3 for Input and 1 for mask. So, when specifying the input shape in Keras, only the feature size needs to be specified.

input_1 = Input(shape=(3,))
mask_1 = Input(shape=(1,))
net = Multiply()([input_1, mask_1])
net = Model(inputs=[input_1, mask_1], outputs=net)
output = net.predict([np.array([1,2,3,4,4,4]).reshape(2,3), np.array([1,0])])
print(output)

[[1. 2. 3.] [0. 0. 0.]]

Manoj Mohan
  • 5,654
  • 1
  • 17
  • 21
2

Number of dimensions should match, by modifying the input shape of the 2nd input to (None, 1) and adding an extra-dimension to the [1, 0] array

import numpy as np
from tensorflow.keras.layers import Multiply
from tensorflow.keras import Model, Input

input_1 = Input(shape=(2,3))
mask_1 = Input(shape=(2,1))

net = Multiply()([input_1, mask_1])
net = Model(inputs=[input_1, mask_1], outputs=net)

net.summary()

print(net.predict([np.array([1,2,3,4,4,4]).reshape((1,2,3)), np.array([1,0]).reshape((1,2,1))]))
Raphael Meudec
  • 686
  • 5
  • 10