# How to do PCA/ICA to an epoch?

**URL:** <https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077>\
**Category:** Support & Discussions\
**Tags:** preprocessing\
**Created:** [June 15, 2022, 6:26am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077 "2022-06-15T06:26:25Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![CliffordTHU](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/cliffordthu/32/1226_2.png) [@CliffordTHU](https://mne.discourse.group/u/CliffordTHU)\
**Post date:** [June 15, 2022, 6:26am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077/1 "2022-06-15T06:26:25Z")

</div>

I used CSP to my data, however the accuracy can only be around 0.6, therefore I want to do ICA/PCA before CSP, after checking the documentation, I got this code:

```python
tmin, tmax = -0.1, 0.3
X = epochs_train.get_data()
pca = UnsupervisedSpatialFilter(PCA(30), average=False)
pca_data = pca.fit_transform(X)
ev = mne.EvokedArray(np.mean(pca_data, axis=0),
                     mne.create_info(30, epochs.info['sfreq'],
                                     ch_types='eeg'), tmin=tmin)
#ev.plot(show=False, window_title="PCA", time_unit='s')

```

My after code is:

```python

scores = []
epochs_data = epochs.get_data()
epochs_data_train = ev
cv = ShuffleSplit(10, test_size=0.2, random_state=42)
cv_split = cv.split(epochs_data_train)

# Assemble a classifier
lda = LinearDiscriminantAnalysis()
csp = CSP(n_components=4, reg=None, log=True, norm_trace=False)

# Use scikit-learn Pipeline with cross_val_score function
clf = Pipeline([('CSP', csp), ('LDA', lda)])
scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1)

```

How to connect the first code with my code? Didn’t found the structure which can be switched

---

<div class="post-metadata">

**Author:** ![richard](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/richard/32/15_2.png) [@richard](https://mne.discourse.group/u/richard)\
**Post date:** [June 15, 2022, 6:40am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077/2 "2022-06-15T06:40:37Z")

</div>

Hello, there is an extensive ICA tutorial on our website,  
[https://mne.tools/stable/auto\_tutorials/preprocessing/40\_artifact\_correction\_ica.html](https://mne.tools/stable/auto_tutorials/preprocessing/40_artifact_correction_ica.html)

---

<div class="post-metadata">

**Author:** ![CliffordTHU](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/cliffordthu/32/1226_2.png) [@CliffordTHU](https://mne.discourse.group/u/CliffordTHU)\
**Post date:** [June 15, 2022, 7:34am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077/3 "2022-06-15T07:34:13Z")

</div>

when I do as tutorial said, an error will come out,

```python
  Traceback (most recent call last):
  File "C:\Users\22100\Desktop\SCNS3\code\AfterPCA.py", line 87, in <module>
    ica = ICA(n_components=15, method='fastica', max_iter="auto").fit(epochs)
  File "<decorator-gen-396>", line 24, in fit
  File "C:\Users\22100\PycharmProjects\pythonProject\venv\lib\site-packages\mne\preprocessing\ica.py", line 574, in fit
    self._fit_epochs(inst, picks, decim, verbose)
  File "C:\Users\22100\PycharmProjects\pythonProject\venv\lib\site-packages\mne\preprocessing\ica.py", line 636, in _fit_epochs
    self._fit(data, 'epochs')
  File "C:\Users\22100\PycharmProjects\pythonProject\venv\lib\site-packages\mne\preprocessing\ica.py", line 765, in _fit
    ica.fit(data[:, sel])
  File "C:\Users\22100\PycharmProjects\pythonProject\venv\lib\site-packages\sklearn\decomposition\_fastica.py", line 673, in fit
    self._fit(X, compute_sources=False)
  File "C:\Users\22100\PycharmProjects\pythonProject\venv\lib\site-packages\sklearn\decomposition\_fastica.py", line 582, in _fit
    if self.max_iter < 1:
TypeError: '<' not supported between instances of 'str' and 'int'

```

didn’t find which str should convert to int

---

<div class="post-metadata">

**Author:** ![CliffordTHU](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/cliffordthu/32/1226_2.png) [@CliffordTHU](https://mne.discourse.group/u/CliffordTHU)\
**Post date:** [June 15, 2022, 7:55am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077/4 "2022-06-15T07:55:09Z")

</div>

code is

```python
# 使用线性离散分析进行分类
filt_raw = raw.copy().filter(l_freq=1., h_freq=None)
filt_raw.pick_types(meg=True, eeg=True, exclude='bads', stim=True).load_data()
filt_raw.filter(1, 30, fir_design='firwin')
# peak-to-peak amplitude rejection parameters
reject = dict(mag=4e-12)
# create longer and more epochs for more artifact exposure
events, _ = events_from_annotations(raw)
epochs = Epochs(raw, events=events, event_id=event_id, tmin=-1, tmax=4, proj=True, picks=picks,
                baseline=None, preload=True)
ica = ICA(n_components=15, method='fastica', max_iter="auto").fit(epochs)

ecg_epochs = create_ecg_epochs(filt_raw, tmin=-.5, tmax=.5)
ecg_inds, scores = ica.find_bads_ecg(ecg_epochs, threshold='auto')

ica.plot_components(ecg_inds)

```

---

<div class="post-metadata">

**Author:** ![sappelhoff](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/sappelhoff/32/3276_2.png) [@sappelhoff](https://mne.discourse.group/u/sappelhoff)\
**Post date:** [June 15, 2022, 8:15am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077/5 "2022-06-15T08:15:29Z")

</div>

looks like you might have mne 0.23 installed. Try `max_iter=None` in the `ICA` … or upgrade to mne 1.0.3

---

<div class="post-metadata">

**Author:** ![CliffordTHU](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/cliffordthu/32/1226_2.png) [@CliffordTHU](https://mne.discourse.group/u/CliffordTHU)\
**Post date:** [June 15, 2022, 8:52am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077/6 "2022-06-15T08:52:23Z")

</div>

it shows

```python
TypeError: '<' not supported between instances of 'NoneType' and 'int'

```

---

<div class="post-metadata">

**Author:** ![sappelhoff](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/sappelhoff/32/3276_2.png) [@sappelhoff](https://mne.discourse.group/u/sappelhoff)\
**Post date:** [June 15, 2022, 9:06am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077/7 "2022-06-15T09:06:52Z")

</div>

🤷 what mne version do you have installed?

you can try `max_iter=100000`

---

<div class="post-metadata">

**Author:** ![CliffordTHU](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/cliffordthu/32/1226_2.png) [@CliffordTHU](https://mne.discourse.group/u/CliffordTHU)\
**Post date:** [June 15, 2022, 9:07am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077/8 "2022-06-15T09:07:43Z")

</div>

mne == 0.22.1  
I will try that 100000

---

<div class="post-metadata">

**Author:** ![sappelhoff](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/sappelhoff/32/3276_2.png) [@sappelhoff](https://mne.discourse.group/u/sappelhoff)\
**Post date:** [June 15, 2022, 9:33am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077/9 "2022-06-15T09:33:58Z")

</div>

you should then also browse the docs for 0.22.1 🙂

see: [mne.preprocessing.ICA — MNE 0.22.1 documentation](https://mne.tools/0.22/generated/mne.preprocessing.ICA.html?highlight=ica#mne.preprocessing.ICA)

this will help you. But I also encourage you to upgrade to 1.0.3 as soon as possible.

---

<div class="post-metadata">

**Author:** ![richard](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/richard/32/15_2.png) [@richard](https://mne.discourse.group/u/richard)\
**Post date:** [June 15, 2022, 9:39am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077/10 "2022-06-15T09:39:08Z")

</div>

> [@CliffordTHU](#):
>
> mne == 0.22.1

This is so old, no-one will really be able to or be willing to help you with it. Please update to 1.0.3, as @sappelhoff suggested.

---

<div class="post-metadata">

**Author:** ![CliffordTHU](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/cliffordthu/32/1226_2.png) [@CliffordTHU](https://mne.discourse.group/u/CliffordTHU)\
**Post date:** [June 15, 2022, 9:57am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077/11 "2022-06-15T09:57:28Z")

</div>

Btw, another question 😭  
I applied " Compute ICA components on Epochs", however it shows:

```python
Traceback (most recent call last):
  File "C:\Users\22100\Desktop\SCNS3\code\AfterPCA.py", line 79, in <module>
    filt_raw.pick_types(meg=True, eeg=False, exclude='bads', stim=True).load_data()
  File "<decorator-gen-44>", line 12, in pick_types
  File "C:\Users\22100\PycharmProjects\pythonProject\venv\lib\site-packages\mne\channels\channels.py", line 678, in pick_types
    self._pick_drop_channels(idx)
  File "<decorator-gen-46>", line 12, in _pick_drop_channels
  File "C:\Users\22100\PycharmProjects\pythonProject\venv\lib\site-packages\mne\channels\channels.py", line 856, in _pick_drop_channels
    pick_info(self.info, idx, copy=False)
  File "<decorator-gen-9>", line 12, in pick_info
  File "C:\Users\22100\PycharmProjects\pythonProject\venv\lib\site-packages\mne\io\pick.py", line 538, in pick_info
    raise ValueError('No channels match the selection.')
ValueError: No channels match the selection.

```

which may means there are not meg exists, then I changedeeg=False to eeg=True, then it shows:

```python
C:\Users\22100\PycharmProjects\pythonProject\venv\lib\site-packages\sklearn\decomposition\_fastica.py:120: ConvergenceWarning: FastICA did not converge. Consider increasing tolerance or the maximum number of iterations.
  warnings.warn(
Traceback (most recent call last):
  File "C:\Users\22100\Desktop\SCNS3\code\AfterPCA.py", line 89, in <module>
    ecg_epochs = create_ecg_epochs(filt_raw, tmin=-.5, tmax=.5)
  File "<decorator-gen-406>", line 12, in create_ecg_epochs
Fitting ICA took 38.2s.
  File "C:\Users\22100\PycharmProjects\pythonProject\venv\lib\site-packages\mne\preprocessing\ecg.py", line 346, in create_ecg_epochs
    events, _, _, ecg = find_ecg_events(
  File "<decorator-gen-405>", line 12, in find_ecg_events
  File "C:\Users\22100\PycharmProjects\pythonProject\venv\lib\site-packages\mne\preprocessing\ecg.py", line 194, in find_ecg_events
    ecg, _ = _make_ecg(raw, start=None, stop=None)
  File "<decorator-gen-407>", line 12, in _make_ecg
  File "C:\Users\22100\PycharmProjects\pythonProject\venv\lib\site-packages\mne\preprocessing\ecg.py", line 383, in _make_ecg
    raise ValueError('Unable to generate artificial ECG channel')
ValueError: Unable to generate artificial ECG channel

```

How can I do ICA/PCA to my raw/epoch then 😭  
(the file is .cnt)

---

<div class="post-metadata">

**Author:** ![richard](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/richard/32/15_2.png) [@richard](https://mne.discourse.group/u/richard)\
**Post date:** [June 15, 2022, 10:01am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077/12 "2022-06-15T10:01:14Z")

</div>

You don’t have an ECG channel in your data. Don’t try to create ECG events.

Also, your ICA did not converge, according to the warning message in the first line. Don’t trust the ICA decomposition.

And most importantly, update to MNE 1.0.3. I will not help you any further if your questions are based on usage issues with such an old version. We have resolved tons of ICA (and other) issues in the meantime.

Locking this thread, please post new questions in a new topic if you still run into problems after updating MNE and carefully inspecting the documentation.

---

<div class="post-metadata">

**Author:** ![richard](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/richard/32/15_2.png) [@richard](https://mne.discourse.group/u/richard)\
**Post date:** [June 15, 2022, 10:01am UTC](https://mne.discourse.group/t/how-to-do-pca-ica-to-an-epoch/5077/13 "2022-06-15T10:01:20Z")

</div>


