Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 25 additions & 21 deletions keras/src/backend/tensorflow/numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -3130,30 +3130,34 @@ def correlate(x1, x2, mode="valid"):
x1 = tf.cast(x1, dtype)
x2 = tf.cast(x2, dtype)

x1_len, x2_len = int(x1.shape[0]), int(x2.shape[0])

if mode == "full":
full_len = x1_len + x2_len - 1

x1_pad = (full_len - x1_len) / 2
x2_pad = (full_len - x2_len) / 2

x1 = tf.pad(
x1, paddings=[[tf.math.floor(x1_pad), tf.math.ceil(x1_pad)]]
)
x2 = tf.pad(
x2, paddings=[[tf.math.floor(x2_pad), tf.math.ceil(x2_pad)]]
def _pack(a, b):
# a: input [N] -> [1,N,1];
# b: filter [M] -> [M,1,1]
return (
tf.reshape(a, (1, tf.shape(a)[0], 1)),
tf.reshape(b, (tf.shape(b)[0], 1, 1)),
)

x1 = tf.reshape(x1, (1, full_len, 1))
x2 = tf.reshape(x2, (full_len, 1, 1))

return tf.squeeze(tf.nn.conv1d(x1, x2, stride=1, padding="SAME"))

x1 = tf.reshape(x1, (1, x1_len, 1))
x2 = tf.reshape(x2, (x2_len, 1, 1))
n = tf.shape(x1)[0]
m = tf.shape(x2)[0]

return tf.squeeze(tf.nn.conv1d(x1, x2, stride=1, padding=mode.upper()))
if mode == "full":
# Pad input with m-1 zeros on both sides; keep filter length m.
pad = tf.maximum(m - 1, 0)
x1 = tf.pad(x1, [[pad, pad]])
x1, x2 = _pack(x1, x2)
out = tf.nn.conv1d(x1, x2, stride=1, padding="VALID")
return tf.squeeze(out)
if mode == "same":
full_ = correlate(x1, x2, mode="full")
full_len = tf.shape(full_)[0]
out_len = tf.maximum(n, m)
start = (full_len - out_len) // 2
return tf.slice(full_, [start], [out_len])
else:
# deal with the "valid" case
x1, x2 = _pack(x1, x2)
return tf.squeeze(tf.nn.conv1d(x1, x2, stride=1, padding=mode.upper()))


def select(condlist, choicelist, default=0):
Expand Down
20 changes: 20 additions & 0 deletions keras/src/ops/numpy_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5133,6 +5133,26 @@ def test_correlate_different_size(self):
knp.Correlate(mode="full")(x, y), np.correlate(x, y, mode="full")
)

def test_correlate_bug(self):
# copied from https://github.com/keras-team/keras/issues/21617
x = np.array([1, 3, 5])
y = np.array([7, 9])
self.assertAllClose(knp.correlate(x, y), np.correlate(x, y))
self.assertAllClose(
knp.correlate(x, y, mode="same"), np.correlate(x, y, mode="same")
)
self.assertAllClose(
knp.correlate(x, y, mode="full"), np.correlate(x, y, mode="full")
)

self.assertAllClose(knp.Correlate()(x, y), np.correlate(x, y))
self.assertAllClose(
knp.Correlate(mode="same")(x, y), np.correlate(x, y, mode="same")
)
self.assertAllClose(
knp.Correlate(mode="full")(x, y), np.correlate(x, y, mode="full")
)

def test_select(self):
x = np.arange(6)
condlist = [x < 3, x > 3]
Expand Down