简体   繁体   中英

One command-line in python to automatize code

I am newbie in Python. I am using it for machine learning in EEG. This is my function to extract the "features". Is there a way to improve it? I mean, I don't want to be changing the frequencies each time I need other range. So, in PART B you'll see my attempt.

PART A

def computePowerBands(f, amp):
    return (np.mean(amp[(f >= 0.5)*(f <= 4.5)]),
            np.mean(amp[(f >= 4.5)*(f <= 8.5)]),
            np.mean(amp[(f >= 8.5)*(f <= 11.5)]),
            np.mean(amp[(f >= 11.5)*(f <= 15.5)]),
            np.mean(amp[(f >= 15.5)*(f <= 32.5)]) )

PART B

def computePowerBands(f, amp, fce):
    return (np.mean(amp[k * k for k in fce]))

Is there any way I can do this?

I am not entirely sure what you are trying to achieve, as it is really obfuscated chunk of code, but by simple code refactoring you can parametrize it through the list of pairs:

def computePowerBands(f, amp, fce):
    return [np.mean(amp[(f >= low)*(f <= up)]) for low, up in fce]

and call it with

computePowerBands(f, amp, [(0.5, 4.5), (4.5, 8.5)])

and so on.

Or if the following bands always share ends:

def computePowerBands(f, amp, fce):
    return [np.mean(amp[(f >= fce[fid])*(f <= fce[fid+1])])
            for fid in range(len(fce)-1)]

and call it with

computePowerBands(f, amp, [0.5, 4.5, 8.5])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM