scikit-learn/examples/plot_ica_blind_source_separ...

53 lines
1.5 KiB
Python
Raw Normal View History

2010-09-08 20:31:40 +08:00
"""
=====================================
2010-09-08 22:58:08 +08:00
Blind source separation using FastICA
2010-09-08 20:31:40 +08:00
=====================================
2010-09-08 22:58:08 +08:00
2010-11-01 22:11:56 +08:00
:ref:`ICA` is used to estimate sources given noisy measurements.
2010-09-08 22:58:08 +08:00
Imagine 2 instruments playing simultaneously and 2 microphones
recording the mixed signals. ICA is used to recover the sources
ie. what is played by each instrument.
2010-09-08 20:31:40 +08:00
"""
2010-09-08 22:58:08 +08:00
print __doc__
2010-09-08 20:31:40 +08:00
import numpy as np
import pylab as pl
from scikits.learn.fastica import FastICA
###############################################################################
# Generate sample data
np.random.seed(0)
2010-09-08 22:58:08 +08:00
n_samples = 2000
2010-09-08 20:31:40 +08:00
time = np.linspace(0, 10, n_samples)
2010-09-08 22:58:08 +08:00
s1 = np.sin(2*time) # Signal 1 : sinusoidal signal
2010-09-08 20:31:40 +08:00
s2 = np.sign(np.sin(3*time)) # Signal 2 : square signal
S = np.c_[s1,s2].T
2010-09-08 22:58:08 +08:00
S += 0.2*np.random.normal(size=S.shape) # Add noise
2010-09-08 20:31:40 +08:00
2010-09-08 22:58:08 +08:00
S /= S.std(axis=1)[:,np.newaxis] # Standardize data
2010-09-08 20:31:40 +08:00
# Mix data
2010-09-08 22:58:08 +08:00
A = [[1, 1], [0.5, 2]] # Mixing matrix
2010-09-08 20:31:40 +08:00
X = np.dot(A, S) # Generate observations
2010-09-08 22:58:08 +08:00
# Compute ICA
ica = FastICA()
S_ = ica.fit(X).transform(X) # Get the estimated sources
A_ = ica.get_mixing_matrix() # Get estimated mixing matrix
2010-09-08 20:31:40 +08:00
2010-09-08 22:58:08 +08:00
assert np.allclose(X, np.dot(A_, S_))
2010-09-08 20:31:40 +08:00
###############################################################################
# Plot results
pl.figure()
pl.subplot(3, 1, 1)
pl.plot(S.T)
pl.title('True Sources')
pl.subplot(3, 1, 2)
pl.plot(X.T)
pl.title('Observations (mixed signal)')
pl.subplot(3, 1, 3)
pl.plot(S_.T)
pl.title('ICA estimated sources')
pl.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.36)
2010-11-01 22:11:56 +08:00
pl.show()