# cannot import name 'compute\_psd' from 'mne'

**URL:** <https://mne.discourse.group/t/cannot-import-name-compute-psd-from-mne/7882>\
**Category:** Support & Discussions\
**Created:** [November 21, 2023, 4:12pm UTC](https://mne.discourse.group/t/cannot-import-name-compute-psd-from-mne/7882 "2023-11-21T16:12:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![1973\_shanto](https://avatars.discourse-cdn.com/v4/letter/1/6a8cbe/32.png) [@1973\_shanto](https://mne.discourse.group/u/1973_shanto)\
**Post date:** [November 21, 2023, 4:12pm UTC](https://mne.discourse.group/t/cannot-import-name-compute-psd-from-mne/7882/1 "2023-11-21T16:12:47Z")

</div>

In the python code of epilepsy detetion, after the code of section 1, the codes of section 2 are written with the use of the function ‘psd\_welch’ of the ‘mne.time\_frequency’ module.

Section 1:

!pip install mne -q

import pandas as pd  
import numpy as np  
from matplotlib import pyplot as plt

meta\_df= pd.read\_csv(‘C:\Users\user\Desktop\Python Project\EEGs\_Guinea-Bissau\metadata\_guineabissau.csv’)

display(meta\_df)

#now i need to seprate Epilepsy vs Control subjects  
EP\_sub=meta\_df[‘subject.id’][meta\_df[‘Group’]==‘Epilepsy’]  
CT\_sub=meta\_df[‘subject.id’][meta\_df[‘Group’]==‘Control’]

#read csv files  
Epilepsy=[pd.read\_csv(‘EEGs\_Guinea-Bissau/signal-{}.csv.gz’.format(i), compression=‘gzip’) for i in EP\_sub]  
Control=[pd.read\_csv(‘EEGs\_Guinea-Bissau/signal-{}.csv.gz’.format(i), compression=‘gzip’) for i in CT\_sub]

Epilepsy[0].head()

#remove non eeg channels  
Epilepsy=[i.iloc[:,1:15] for i in Epilepsy]  
Control=[i.iloc[:,1:15] for i in Control]

import mne  
def convertDF2MNE(sub):  
info = mne.create\_info(list(sub.columns), ch\_types=[‘eeg’] \* len(sub.columns), sfreq=128)  
info.set\_montage(‘standard\_1020’)  
data=mne.io.RawArray(sub.T, info)  
data.set\_eeg\_reference()  
data.filter(l\_freq=0.1,h\_freq=45)  
epochs=mne.make\_fixed\_length\_epochs(data,duration=5,overlap=1)  
epochs=epochs.drop\_bad()

```
return epochs

```

%%capture  
#Convert each dataframe to mne object  
Epilepsy=[convertDF2MNE(i) for i in Epilepsy]  
Control=[convertDF2MNE(i) for i in Control]

%%capture  
#concatenate the epochs  
Epilepsy\_epochs=mne.concatenate\_epochs(Epilepsy)  
Control\_epochs=mne.concatenate\_epochs(Control)

Epilepsy\_group=np.concatenate([[i]\*len(Epilepsy[i]) for i in range(len(Epilepsy))])#create a list of list where each sub list corresponds to subject\_no  
Control\_group=np.concatenate([[i]\*len(Control[i]) for i in range(len(Control))])#create a list of list where each sub list corresponds to subject\_no

Epilepsy\_label=np.concatenate([[0]\*len(Epilepsy[i]) for i in range(len(Epilepsy))])  
Control\_label=np.concatenate([[1]\*len(Control[i]) for i in range(len(Control))])

Epilepsy\_group.shape,Control\_group.shape,Epilepsy\_label.shape,Control\_label.shape

#combine data  
data=mne.concatenate\_epochs([Epilepsy\_epochs,Control\_epochs])  
group=np.concatenate((Epilepsy\_group,Control\_group))  
label=np.concatenate((Epilepsy\_label,Control\_label))  
print(len(data),len(group),len(label))

Section 2:

from mne.time\_frequency import psd\_welch  
def eeg\_power\_band(epochs):

```
# specific frequency bands

FREQ_BANDS = {"delta": [0.5, 4.5],
              "theta": [4.5, 8.5],
              "alpha": [8.5, 11.5],
              "sigma": [11.5, 15.5],
              "beta": [15.5, 30],
              "gamma": [30, 45],
              }

psds, freqs = psd_welch(epochs, picks='eeg', fmin=0.5, fmax=45) # Compute the PSD using the Welch method
psds /= np.sum(psds, axis=-1, keepdims=True) # Normalize the PSDs

X = [x]#For each frequency band, compute the mean PSD in that band
for fmin, fmax in FREQ_BANDS.values():
    psds_band = psds[:, :, (freqs >= fmin) & (freqs < fmax)].mean(axis=-1)# Compute the mean PSD in each frequency band.
    X.append(psds_band)

return np.concatenate(X, axis=1) #Concatenate the mean PSDs for each band into a single feature vector

```

from sklearn.ensemble import RandomForestClassifier  
from sklearn.model\_selection import cross\_val\_score

%%capture  
features=[]  
for d in range(len(data)):# get features from each epoch and save in a list  
features.append(eeg\_power\_band(data[d]))

# convert list to array

features=np.concatenate(features)  
features.shape

#do 5 fold cross validation  
clf=RandomForestClassifier()  
accuracies=cross\_val\_score(clf, features,label,groups=group,cv=5)  
print(‘Five fold accuracies’,accuracies)  
print(‘Average accuracy’,np.mean(accuracies))

Output should be like this :  
Five fold accuracies [0.71380697 0.69953052 0.63782696 0.73105298 0.69014085]  
Average accuracy 0.6944716556712932

\*\*\* Now how can I convert the ‘section 2’ of the aforementioned code with the ‘compute\_psd()’ method of the ‘Raw’ or ‘Epochs’ object so that no error is faced, since the function ‘psd\_welch’ is no longer available in the ‘mne.time\_frequency’ module. This is because the function was deprecated in version 1.2 of MNE and removed in version 1.3. # My mentioned code is copied from internet from a github platform, ( [youtube-tutorials/eeg\_epilepsy.ipynb at main · talhaanwarch/youtube-tutorials · GitHub](https://github.com/talhaanwarch/youtube-tutorials/blob/main/eeg_epilepsy.ipynb))  
i am a rookie in this field. He used this ‘mne.time\_frequency’. But at present time, this is not working.

N.B.: The result should remain same and no error must be occurred in the output. Please help me out, I am in a great trouble for this. \*\*My jupyter notebook version is: 3.11.4 | packaged by Anaconda, Inc. | (main, Jul 5 2023, 13:38:37) [MSC v.1916 64 bit (AMD64)] ##Operating system: Windows 11 \*\* You can download the data set from- [https://zenodo.org/record/1252141/files/EEGs\_Guinea-Bissau.zip](https://zenodo.org/record/1252141/files/EEGs_Guinea-Bissau.zip)

---

<div class="post-metadata">

**Author:** ![cbrnr](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/cbrnr/32/1409_2.png) [@cbrnr](https://mne.discourse.group/u/cbrnr)\
**Post date:** [November 21, 2023, 5:10pm UTC](https://mne.discourse.group/t/cannot-import-name-compute-psd-from-mne/7882/2 "2023-11-21T17:10:31Z")

</div>

Please read [How to correctly format your question](https://mne.discourse.group/t/how-to-correctly-format-your-question/7883) and edit your post accordingly.
