Skip to content

Instantly share code, notes, and snippets.

@vaclavcadek
Created October 22, 2021 17:29
Show Gist options
  • Save vaclavcadek/fd39f92e9522547aedfd6ba0ca7e04d1 to your computer and use it in GitHub Desktop.
Save vaclavcadek/fd39f92e9522547aedfd6ba0ca7e04d1 to your computer and use it in GitHub Desktop.
A not so successful attempt to perform single channel ICA using Wavelet Transform.
import itertools
from scipy import signal
import pywt
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import FastICA
# #############################################################################
# Generate sample data
np.random.seed(0)
n_samples = 2_000
time = np.linspace(0, 8, n_samples)
s1 = np.sin(2 * time) # Signal 1 : sinusoidal signal
s2 = signal.sawtooth(2 * np.pi * time) # Signal 2 : sinusoidal signal
# Mix data as sum not through mixing matrix - is it valid?
S = s1 + s2
coeffs = pywt.swt(S, 'db4', level=4)
decomposition = tuple(a for a, d in coeffs)
# X = np.c_[S, decomposition]
X = np.c_[tuple([decomposition[0], decomposition[1]])]
# Compute ICA
ica = FastICA(n_components=2, whiten=False)
S_ = ica.fit_transform(X) # Reconstruct signals
A_ = ica.mixing_ # Get estimated mixing matrix
# We can `prove` that the ICA model applies by reverting the unmixing.
# assert np.allclose(X, np.dot(S_, A_.T) + ica.mean_)
# #############################################################################
# Plot results
plt.figure()
recovered_signals = pywt.iswt([S_], "db4")
models = [S[:, np.newaxis], np.c_[s1, s2], recovered_signals, recovered_signals.sum(axis=1)[:, np.newaxis]]
names = [
'Observations (mixed signal)',
'True Sources',
'ICA recovered sources',
'ICA recovered (mixed signal)'
]
colors = ['red', 'steelblue']
for ii, (model, name) in enumerate(zip(models, names), 1):
plt.subplot(4, 1, ii)
plt.title(name)
for sig, color in zip(model.T, colors):
plt.plot(sig, color=color)
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment