0
0
ML Pythonml~10 mins

Autocorrelation analysis in ML Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to calculate the autocorrelation of a time series using numpy.

ML Python
import numpy as np

data = np.array([1, 2, 3, 4, 5])
mean = np.mean(data)
variance = np.var(data)

autocorr = np.correlate(data - mean, data - mean, mode=[1])[len(data)-1] / (variance * len(data))
print(autocorr)
Drag options to blanks, or click blank then click option'
A'full'
B'valid'
C'same'
D'none'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'valid' or 'same' mode which returns smaller arrays and misses some lags.
Not subtracting the mean before correlation.
2fill in blank
medium

Complete the code to compute the autocorrelation function for lags up to max_lag.

ML Python
def autocorrelation(data, max_lag):
    n = len(data)
    mean = sum(data) / n
    var = sum((x - mean) ** 2 for x in data) / n
    result = []
    for lag in range(max_lag + 1):
        cov = sum((data[i] - mean) * (data[i + lag] - mean) for i in range(n - lag)) / n
        result.append(cov / [1])
    return result
Drag options to blanks, or click blank then click option'
An
Bmean
Cmax_lag
Dvar
Attempts:
3 left
💡 Hint
Common Mistakes
Dividing by mean or length instead of variance.
Not normalizing covariance, resulting in incorrect scale.
3fill in blank
hard

Fix the error in the code to correctly compute the autocorrelation using pandas.

ML Python
import pandas as pd

data = pd.Series([1, 2, 3, 4, 5])
autocorr_value = data.autocorr(lag=[1])
print(autocorr_value)
Drag options to blanks, or click blank then click option'
A-1
B0
C1
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using lag=0 which returns 1 always.
Using lag greater than series length causing NaN.
4fill in blank
hard

Fill both blanks to create a dictionary of autocorrelations for lags 0 to max_lag.

ML Python
def autocorr_dict(data, max_lag):
    return {lag: data.autocorr(lag=[1]) for lag in range([2])}
Drag options to blanks, or click blank then click option'
Alag
Bmax_lag + 1
Cmax_lag
Dlag + 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using fixed lag instead of loop variable.
Using range(max_lag) which excludes max_lag.
5fill in blank
hard

Fill all three blanks to compute and plot the autocorrelation function using matplotlib.

ML Python
import matplotlib.pyplot as plt

def plot_autocorr(data, max_lag):
    autocorrs = [data.autocorr(lag=[1]) for lag in range([2])]
    plt.stem(range([3]), autocorrs, use_line_collection=True)
    plt.xlabel('Lag')
    plt.ylabel('Autocorrelation')
    plt.title('Autocorrelation Function')
    plt.show()
Drag options to blanks, or click blank then click option'
Alag
Bmax_lag + 1
Cmax_lag
Dlag + 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using max_lag instead of max_lag + 1, missing last lag.
Using fixed lag instead of loop variable.