本文整理汇总了Python中mne.preprocessing.ICA.fit方法的典型用法代码示例。如果您正苦于以下问题:Python ICA.fit方法的具体用法?Python ICA.fit怎么用?Python ICA.fit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mne.preprocessing.ICA
的用法示例。
在下文中一共展示了ICA.fit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_eog_channel
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def test_eog_channel(method):
"""Test that EOG channel is included when performing ICA."""
_skip_check_picard(method)
raw = read_raw_fif(raw_fname, preload=True)
events = read_events(event_name)
picks = pick_types(raw.info, meg=True, stim=True, ecg=False,
eog=True, exclude='bads')
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True)
n_components = 0.9
ica = ICA(n_components=n_components, method=method)
# Test case for MEG and EOG data. Should have EOG channel
for inst in [raw, epochs]:
picks1a = pick_types(inst.info, meg=True, stim=False, ecg=False,
eog=False, exclude='bads')[:4]
picks1b = pick_types(inst.info, meg=False, stim=False, ecg=False,
eog=True, exclude='bads')
picks1 = np.append(picks1a, picks1b)
ica.fit(inst, picks=picks1)
assert (any('EOG' in ch for ch in ica.ch_names))
# Test case for MEG data. Should have no EOG channel
for inst in [raw, epochs]:
picks1 = pick_types(inst.info, meg=True, stim=False, ecg=False,
eog=False, exclude='bads')[:5]
ica.fit(inst, picks=picks1)
assert not any('EOG' in ch for ch in ica.ch_names)
示例2: apply_ica
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def apply_ica(fname_filtered, n_components=0.99, decim=None):
''' Applies ICA to a list of (filtered) raw files. '''
import mne
from mne.preprocessing import ICA
import os
if isinstance(fname_filtered, list):
fnfilt = fname_filtered
else:
if isinstance(fname_filtered, str):
fnfilt = list([fname_filtered])
else:
fnfilt = list(fname_filtered)
# loop across all filenames
for fname in fnfilt:
name = os.path.split(fname)[1]
print ">>>> perform ICA signal decomposition on : "+name
# load filtered data
raw = mne.io.Raw(fname,preload=True)
picks = mne.pick_types(raw.info, meg=True, exclude='bads')
# ICA decomposition
ica = ICA(n_components=n_components, max_pca_components=None)
ica.fit(raw, picks=picks, decim=decim, reject={'mag': 5e-12})
# save ICA object
fnica_out = fname.strip('-raw.fif') + '-ica.fif'
# fnica_out = fname[0:len(fname)-4]+'-ica.fif'
ica.save(fnica_out)
示例3: run_ica
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def run_ica(method):
ica = ICA(n_components=20, method=method, random_state=0)
t0 = time()
ica.fit(raw, picks=picks, reject=reject)
fit_time = time() - t0
title = ('ICA decomposition using %s (took %.1fs)' % (method, fit_time))
ica.plot_components(title=title)
示例4: test_n_components_and_max_pca_components_none
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def test_n_components_and_max_pca_components_none(method):
"""Test n_components and max_pca_components=None."""
_skip_check_picard(method)
raw = read_raw_fif(raw_fname).crop(1.5, stop).load_data()
events = read_events(event_name)
picks = pick_types(raw.info, eeg=True, meg=False)
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True)
max_pca_components = None
n_components = None
random_state = 12345
tempdir = _TempDir()
output_fname = op.join(tempdir, 'test_ica-ica.fif')
ica = ICA(max_pca_components=max_pca_components, method=method,
n_components=n_components, random_state=random_state)
with pytest.warns(None): # convergence
ica.fit(epochs)
ica.save(output_fname)
ica = read_ica(output_fname)
# ICA.fit() replaced max_pca_components, which was previously None,
# with the appropriate integer value.
assert_equal(ica.max_pca_components, epochs.info['nchan'])
assert ica.n_components is None
示例5: test_plot_ica_overlay
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def test_plot_ica_overlay():
"""Test plotting of ICA cleaning."""
import matplotlib.pyplot as plt
raw = _get_raw(preload=True)
picks = _get_picks(raw)
ica = ICA(noise_cov=read_cov(cov_fname), n_components=2,
max_pca_components=3, n_pca_components=3)
# can't use info.normalize_proj here because of how and when ICA and Epochs
# objects do picking of Raw data
with pytest.warns(RuntimeWarning, match='projection'):
ica.fit(raw, picks=picks)
# don't test raw, needs preload ...
with pytest.warns(RuntimeWarning, match='projection'):
ecg_epochs = create_ecg_epochs(raw, picks=picks)
ica.plot_overlay(ecg_epochs.average())
with pytest.warns(RuntimeWarning, match='projection'):
eog_epochs = create_eog_epochs(raw, picks=picks)
ica.plot_overlay(eog_epochs.average())
pytest.raises(TypeError, ica.plot_overlay, raw[:2, :3][0])
ica.plot_overlay(raw)
plt.close('all')
# smoke test for CTF
raw = read_raw_fif(raw_ctf_fname)
raw.apply_gradient_compensation(3)
picks = pick_types(raw.info, meg=True, ref_meg=False)
ica = ICA(n_components=2, max_pca_components=3, n_pca_components=3)
ica.fit(raw, picks=picks)
with pytest.warns(RuntimeWarning, match='longer than'):
ecg_epochs = create_ecg_epochs(raw)
ica.plot_overlay(ecg_epochs.average())
plt.close('all')
示例6: test_n_components_none
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def test_n_components_none():
"""Test n_components=None."""
raw = read_raw_fif(raw_fname).crop(1.5, stop).load_data()
events = read_events(event_name)
picks = pick_types(raw.info, eeg=True, meg=False)
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True)
max_pca_components = 10
n_components = None
random_state = 12345
tempdir = _TempDir()
output_fname = op.join(tempdir, 'test_ica-ica.fif')
ica = ICA(max_pca_components=max_pca_components,
n_components=n_components, random_state=random_state)
with warnings.catch_warnings(record=True): # convergence
ica.fit(epochs)
ica.save(output_fname)
ica = read_ica(output_fname)
# ICA.fit() replaced max_pca_components, which was previously None,
# with the appropriate integer value.
assert_equal(ica.max_pca_components, 10)
assert_is_none(ica.n_components)
示例7: test_plot_instance_components
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def test_plot_instance_components():
"""Test plotting of components as instances of raw and epochs."""
import matplotlib.pyplot as plt
raw = _get_raw()
picks = _get_picks(raw)
ica = ICA(noise_cov=read_cov(cov_fname), n_components=2,
max_pca_components=3, n_pca_components=3)
with pytest.warns(RuntimeWarning, match='projection'):
ica.fit(raw, picks=picks)
fig = ica.plot_sources(raw, exclude=[0], title='Components')
for key in ['down', 'up', 'right', 'left', 'o', '-', '+', '=', 'pageup',
'pagedown', 'home', 'end', 'f11', 'b']:
fig.canvas.key_press_event(key)
ax = fig.get_axes()[0]
line = ax.lines[0]
_fake_click(fig, ax, [line.get_xdata()[0], line.get_ydata()[0]],
'data')
_fake_click(fig, ax, [-0.1, 0.9]) # click on y-label
fig.canvas.key_press_event('escape')
plt.close('all')
epochs = _get_epochs()
fig = ica.plot_sources(epochs, exclude=[0], title='Components')
for key in ['down', 'up', 'right', 'left', 'o', '-', '+', '=', 'pageup',
'pagedown', 'home', 'end', 'f11', 'b']:
fig.canvas.key_press_event(key)
# Test a click
ax = fig.get_axes()[0]
line = ax.lines[0]
_fake_click(fig, ax, [line.get_xdata()[0], line.get_ydata()[0]], 'data')
_fake_click(fig, ax, [-0.1, 0.9]) # click on y-label
fig.canvas.key_press_event('escape')
plt.close('all')
示例8: test_ica_ctf
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def test_ica_ctf():
"""Test run ICA computation on ctf data with/without compensation."""
method = 'fastica'
raw = read_raw_ctf(ctf_fname, preload=True)
events = make_fixed_length_events(raw, 99999)
for comp in [0, 1]:
raw.apply_gradient_compensation(comp)
epochs = Epochs(raw, events, None, -0.2, 0.2, preload=True)
evoked = epochs.average()
# test fit
for inst in [raw, epochs]:
ica = ICA(n_components=2, random_state=0, max_iter=2,
method=method)
with pytest.warns(UserWarning, match='did not converge'):
ica.fit(inst)
# test apply and get_sources
for inst in [raw, epochs, evoked]:
ica.apply(inst)
ica.get_sources(inst)
# test mixed compensation case
raw.apply_gradient_compensation(0)
ica = ICA(n_components=2, random_state=0, max_iter=2, method=method)
with pytest.warns(UserWarning, match='did not converge'):
ica.fit(raw)
raw.apply_gradient_compensation(1)
epochs = Epochs(raw, events, None, -0.2, 0.2, preload=True)
evoked = epochs.average()
for inst in [raw, epochs, evoked]:
with pytest.raises(RuntimeError, match='Compensation grade of ICA'):
ica.apply(inst)
with pytest.raises(RuntimeError, match='Compensation grade of ICA'):
ica.get_sources(inst)
示例9: test_ica_eeg
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def test_ica_eeg():
"""Test ICA on EEG."""
method = 'fastica'
raw_fif = read_raw_fif(fif_fname, preload=True)
with pytest.warns(RuntimeWarning, match='events'):
raw_eeglab = read_raw_eeglab(input_fname=eeglab_fname,
montage=eeglab_montage, preload=True)
for raw in [raw_fif, raw_eeglab]:
events = make_fixed_length_events(raw, 99999, start=0, stop=0.3,
duration=0.1)
picks_meg = pick_types(raw.info, meg=True, eeg=False)[:2]
picks_eeg = pick_types(raw.info, meg=False, eeg=True)[:2]
picks_all = []
picks_all.extend(picks_meg)
picks_all.extend(picks_eeg)
epochs = Epochs(raw, events, None, -0.1, 0.1, preload=True)
evoked = epochs.average()
for picks in [picks_meg, picks_eeg, picks_all]:
if len(picks) == 0:
continue
# test fit
for inst in [raw, epochs]:
ica = ICA(n_components=2, random_state=0, max_iter=2,
method=method)
with pytest.warns(None):
ica.fit(inst, picks=picks)
# test apply and get_sources
for inst in [raw, epochs, evoked]:
ica.apply(inst)
ica.get_sources(inst)
with pytest.warns(RuntimeWarning, match='MISC channel'):
raw = read_raw_ctf(ctf_fname2, preload=True)
events = make_fixed_length_events(raw, 99999, start=0, stop=0.2,
duration=0.1)
picks_meg = pick_types(raw.info, meg=True, eeg=False)[:2]
picks_eeg = pick_types(raw.info, meg=False, eeg=True)[:2]
picks_all = picks_meg + picks_eeg
for comp in [0, 1]:
raw.apply_gradient_compensation(comp)
epochs = Epochs(raw, events, None, -0.1, 0.1, preload=True)
evoked = epochs.average()
for picks in [picks_meg, picks_eeg, picks_all]:
if len(picks) == 0:
continue
# test fit
for inst in [raw, epochs]:
ica = ICA(n_components=2, random_state=0, max_iter=2,
method=method)
with pytest.warns(None):
ica.fit(inst)
# test apply and get_sources
for inst in [raw, epochs, evoked]:
ica.apply(inst)
ica.get_sources(inst)
示例10: test_plot_ica_properties
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def test_plot_ica_properties():
"""Test plotting of ICA properties."""
import matplotlib.pyplot as plt
res = 8
raw = _get_raw(preload=True)
raw.add_proj([], remove_existing=True)
events = _get_events()
picks = _get_picks(raw)[:6]
pick_names = [raw.ch_names[k] for k in picks]
raw.pick_channels(pick_names)
with warnings.catch_warnings(record=True): # bad proj
epochs = Epochs(raw, events[:10], event_id, tmin, tmax,
baseline=(None, 0), preload=True)
ica = ICA(noise_cov=read_cov(cov_fname), n_components=2,
max_pca_components=2, n_pca_components=2)
with warnings.catch_warnings(record=True): # bad proj
ica.fit(raw)
# test _create_properties_layout
fig, ax = _create_properties_layout()
assert_equal(len(ax), 5)
topoargs = dict(topomap_args={'res': res, 'contours': 0, "sensors": False})
ica.plot_properties(raw, picks=0, **topoargs)
ica.plot_properties(epochs, picks=1, dB=False, plot_std=1.5, **topoargs)
ica.plot_properties(epochs, picks=1, image_args={'sigma': 1.5},
topomap_args={'res': 10, 'colorbar': True},
psd_args={'fmax': 65.}, plot_std=False,
figsize=[4.5, 4.5])
plt.close('all')
assert_raises(ValueError, ica.plot_properties, epochs, dB=list('abc'))
assert_raises(ValueError, ica.plot_properties, epochs, plot_std=[])
assert_raises(ValueError, ica.plot_properties, ica)
assert_raises(ValueError, ica.plot_properties, [0.2])
assert_raises(ValueError, plot_ica_properties, epochs, epochs)
assert_raises(ValueError, ica.plot_properties, epochs,
psd_args='not dict')
fig, ax = plt.subplots(2, 3)
ax = ax.ravel()[:-1]
ica.plot_properties(epochs, picks=1, axes=ax, **topoargs)
fig = ica.plot_properties(raw, picks=[0, 1], **topoargs)
assert_equal(len(fig), 2)
assert_raises(ValueError, plot_ica_properties, epochs, ica, picks=[0, 1],
axes=ax)
assert_raises(ValueError, ica.plot_properties, epochs, axes='not axes')
plt.close('all')
# Test merging grads.
raw = _get_raw(preload=True)
picks = pick_types(raw.info, meg='grad')[:10]
ica = ICA(n_components=2)
ica.fit(raw, picks=picks)
ica.plot_properties(raw)
plt.close('all')
示例11: decompose
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def decompose(self, X, y=None):
raw_inst = RawArray(X.T, create_info(self.channel_names, self.fs, 'eeg', None))
ica = ICA(method='extended-infomax')
ica.fit(raw_inst)
filters = np.dot(ica.unmixing_matrix_, ica.pca_components_[:ica.n_components_]).T
topographies = np.linalg.inv(filters).T
scores = self.get_scores(X, filters)
return scores, filters, topographies
示例12: test_ica_full_data_recovery
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def test_ica_full_data_recovery(method):
"""Test recovery of full data when no source is rejected."""
# Most basic recovery
_skip_check_picard(method)
raw = read_raw_fif(raw_fname).crop(0.5, stop).load_data()
events = read_events(event_name)
picks = pick_types(raw.info, meg=True, stim=False, ecg=False,
eog=False, exclude='bads')[:10]
with pytest.warns(RuntimeWarning, match='projection'):
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True)
evoked = epochs.average()
n_channels = 5
data = raw._data[:n_channels].copy()
data_epochs = epochs.get_data()
data_evoked = evoked.data
raw.set_annotations(Annotations([0.5], [0.5], ['BAD']))
methods = [method]
for method in methods:
stuff = [(2, n_channels, True), (2, n_channels // 2, False)]
for n_components, n_pca_components, ok in stuff:
ica = ICA(n_components=n_components, random_state=0,
max_pca_components=n_pca_components,
n_pca_components=n_pca_components,
method=method, max_iter=1)
with pytest.warns(UserWarning, match=None): # sometimes warns
ica.fit(raw, picks=list(range(n_channels)))
raw2 = ica.apply(raw.copy(), exclude=[])
if ok:
assert_allclose(data[:n_channels], raw2._data[:n_channels],
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(data[:n_channels] - raw2._data[:n_channels])
assert (np.max(diff) > 1e-14)
ica = ICA(n_components=n_components, method=method,
max_pca_components=n_pca_components,
n_pca_components=n_pca_components, random_state=0)
with pytest.warns(None): # sometimes warns
ica.fit(epochs, picks=list(range(n_channels)))
epochs2 = ica.apply(epochs.copy(), exclude=[])
data2 = epochs2.get_data()[:, :n_channels]
if ok:
assert_allclose(data_epochs[:, :n_channels], data2,
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(data_epochs[:, :n_channels] - data2)
assert (np.max(diff) > 1e-14)
evoked2 = ica.apply(evoked.copy(), exclude=[])
data2 = evoked2.data[:n_channels]
if ok:
assert_allclose(data_evoked[:n_channels], data2,
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(evoked.data[:n_channels] - data2)
assert (np.max(diff) > 1e-14)
pytest.raises(ValueError, ICA, method='pizza-decomposision')
示例13: test_ica_full_data_recovery
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def test_ica_full_data_recovery():
"""Test recovery of full data when no source is rejected"""
# Most basic recovery
raw = Raw(raw_fname).crop(0.5, stop, False)
raw.load_data()
events = read_events(event_name)
picks = pick_types(raw.info, meg=True, stim=False, ecg=False,
eog=False, exclude='bads')[:10]
with warnings.catch_warnings(record=True): # bad proj
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True)
evoked = epochs.average()
n_channels = 5
data = raw._data[:n_channels].copy()
data_epochs = epochs.get_data()
data_evoked = evoked.data
for method in ['fastica']:
stuff = [(2, n_channels, True), (2, n_channels // 2, False)]
for n_components, n_pca_components, ok in stuff:
ica = ICA(n_components=n_components,
max_pca_components=n_pca_components,
n_pca_components=n_pca_components,
method=method, max_iter=1)
with warnings.catch_warnings(record=True):
ica.fit(raw, picks=list(range(n_channels)))
raw2 = ica.apply(raw, exclude=[], copy=True)
if ok:
assert_allclose(data[:n_channels], raw2._data[:n_channels],
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(data[:n_channels] - raw2._data[:n_channels])
assert_true(np.max(diff) > 1e-14)
ica = ICA(n_components=n_components,
max_pca_components=n_pca_components,
n_pca_components=n_pca_components)
with warnings.catch_warnings(record=True):
ica.fit(epochs, picks=list(range(n_channels)))
epochs2 = ica.apply(epochs, exclude=[], copy=True)
data2 = epochs2.get_data()[:, :n_channels]
if ok:
assert_allclose(data_epochs[:, :n_channels], data2,
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(data_epochs[:, :n_channels] - data2)
assert_true(np.max(diff) > 1e-14)
evoked2 = ica.apply(evoked, exclude=[], copy=True)
data2 = evoked2.data[:n_channels]
if ok:
assert_allclose(data_evoked[:n_channels], data2,
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(evoked.data[:n_channels] - data2)
assert_true(np.max(diff) > 1e-14)
assert_raises(ValueError, ICA, method='pizza-decomposision')
示例14: test_plot_ica_scores
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def test_plot_ica_scores():
"""Test plotting of ICA scores
"""
raw = _get_raw()
ica_picks = pick_types(raw.info, meg=True, eeg=False, stim=False, ecg=False, eog=False, exclude="bads")
ica = ICA(noise_cov=read_cov(cov_fname), n_components=2, max_pca_components=3, n_pca_components=3)
ica.fit(raw, picks=ica_picks)
ica.plot_scores([0.3, 0.2], axhline=[0.1, -0.1])
assert_raises(ValueError, ica.plot_scores, [0.2])
plt.close("all")
示例15: test_plot_ica_components
# 需要导入模块: from mne.preprocessing import ICA [as 别名]
# 或者: from mne.preprocessing.ICA import fit [as 别名]
def test_plot_ica_components():
"""Test plotting of ICA solutions."""
import matplotlib.pyplot as plt
res = 8
fast_test = {"res": res, "contours": 0, "sensors": False}
raw = _get_raw()
ica = ICA(noise_cov=read_cov(cov_fname), n_components=2,
max_pca_components=3, n_pca_components=3)
ica_picks = _get_picks(raw)
with warnings.catch_warnings(record=True):
ica.fit(raw, picks=ica_picks)
warnings.simplefilter('always', UserWarning)
with warnings.catch_warnings(record=True):
for components in [0, [0], [0, 1], [0, 1] * 2, None]:
ica.plot_components(components, image_interp='bilinear',
colorbar=True, **fast_test)
plt.close('all')
# test interactive mode (passing 'inst' arg)
ica.plot_components([0, 1], image_interp='bilinear', inst=raw, res=16)
fig = plt.gcf()
# test title click
# ----------------
lbl = fig.axes[1].get_label()
ica_idx = int(lbl[-3:])
titles = [ax.title for ax in fig.axes]
title_pos_midpoint = (titles[1].get_window_extent().extents
.reshape((2, 2)).mean(axis=0))
# first click adds to exclude
_fake_click(fig, fig.axes[1], title_pos_midpoint, xform='pix')
assert ica_idx in ica.exclude
# clicking again removes from exclude
_fake_click(fig, fig.axes[1], title_pos_midpoint, xform='pix')
assert ica_idx not in ica.exclude
# test topo click
# ---------------
_fake_click(fig, fig.axes[1], (0., 0.), xform='data')
c_fig = plt.gcf()
labels = [ax.get_label() for ax in c_fig.axes]
for l in ['topomap', 'image', 'erp', 'spectrum', 'variance']:
assert_true(l in labels)
topomap_ax = c_fig.axes[labels.index('topomap')]
title = topomap_ax.get_title()
assert_true(lbl == title)
ica.info = None
assert_raises(ValueError, ica.plot_components, 1)
assert_raises(RuntimeError, ica.plot_components, 1, ch_type='mag')
plt.close('all')