<jupyter_start><jupyter_text>Construct periodic sample data<jupyter_code># The number of points in the time series. 
n = 1000
n_plot = 500

x = np.linspace(0, 20 * np.pi, 1000)
y = 2 + 3 * np.sin(x) + np.random.normal(0, 0.1, 1000)

figure(figsize=(12, 8))
plot(x, y)<jupyter_output><empty_output><jupyter_text>Calculate the autocorrelation function * Here, N is the number of points in the data set. * The formula follows the mathematical convention to start indexing sequences at 1, rather than the programming convention to start indexing at 0. * Notice that we have subtracted the overall average μ from all values and that the denominator is simply the expression of the numerator for lag k = 0.* Initially, the two signals are perfectly aligned and the correlation is 1. * Then, as we shift the signals against each other, they slowly move out of phase with each other, and the correlation drops.* How quickly it drops tells us how much “memory” there is in the data.<jupyter_code># de-mean
tmp = y - mean(y)

# calculate auto-correlation
offset = concatenate((tmp, zeros_like(tmp)))
corr = []
for k in range(n):
    corr.append(sum(tmp[:n - k] * offset[k:n]))

denom = sum(tmp**2)
corr /= denom

figure(2, figsize=(12, 8))
plot(x[:n_plot], corr[:n_plot])
plot(x[:n_plot], y[:n_plot])<jupyter_output><empty_output><jupyter_text>Use scipy for autocorrelation<jupyter_code># de-mean
tmp = y - mean(y)

# Pad one copy of data on the right with zeros, then form correlation fct
# The function zeros_like(v) creates a vector with the same dimensions
# as the input vector v but with all elements zero.
corr = correlate(concatenate((tmp, zeros_like(tmp))), tmp, mode='valid')

# # Normalize by dividing by the first element
corr /= corr[0]

figure(2, figsize=(12, 8))
plot(x[:n_plot], corr[:n_plot])
plot(x[:n_plot], y[:n_plot])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11194833153928956, 'fraction_numerical': 0.021528525296017224, 'mean_word_length': 5.176079734219269, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '152994', 'license': 'MIT', 'n_tokens_mistral': 652, 'n_tokens_neox': 599, 'n_words': 233, 'path': 'concepts/auto_correlation.ipynb', 'repo_name': 'shawlu95/Data_Science_Toolbox', 'size': '1858'}