Search code examples
pythonnumpytensorflowtensorflow-probability

Autocorrelation with Tensorflow


I want to compute the autocorrelation of some values with tensorflow. I can do the calculations with scipy / numpy but I haven't figured out, if it is possible with tensorflow.

What I want is:

import tensorflow as tf
from scipy import signal
import numpy as np
import tensorflow_probability as tfp
import matplotlib.pyplot as plt

test_data = tf.random.normal((100,))

plt.plot(signal.correlate(test_data, test_data, mode='full', method='auto'))
plt.plot(np.correlate(test_data, test_data, mode='full'))

as expected the output of scipy and numpy are identical. With Tensorflow I tried

plt.plot(tfp.stats.auto_correlation(test_data))

which I initially assumed, would do the same but gives a completly different result. Is there a tensorflow function, that does the same as numpy / scipy?


Solution

  • Try this

    td = tf.pad(test_data, [[0, len(test_data)]])[..., tf.newaxis]
    plt.plot(tf.nn.conv1d(td[tf.newaxis, :], td[:, tf.newaxis], stride=1, padding='SAME')[0, :, 0])