Skip to content

Instantly share code, notes, and snippets.

@nafeesb

nafeesb/numpy.md

Last active Jul 28, 2021
Embed
What would you like to do?
Numpy Idioms

Ouput Zero for divide by zero

length_err_pct = np.divide( pred_length, true_length, out=np.zeros_like(pred_length), where=true_length!=0)

Random subset of indices

sel = np.random.choice(testX.shape[0], samples, replace=False)

Save formatting

np.savetxt(phasefile,phase,fmt='%.6f')

zip mismatched array

for line in itertools.zip_longest( *plants, fillvalue=''):
    f.write('%s %s\n' % line)

Image processing

Save using PIL

yimg = Image.fromarray((out * 255).astype(np.uint8))
yimg.save('nnout.jpg')

Structs

List struct fields: S.dtype.fields

PCA

Explained variance

evr = model.explained_variance_ratio_
cumulative_evr = np.cumsum(evr)

# Number of components needed to explain 95% of variance.
np.argmax( cumulative_evr >= 0.95 ) + 1 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment