Skip to content

Instantly share code, notes, and snippets.

@nafeesb
Last active July 28, 2021 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nafeesb/7b1111fc914772494f2c921635cd3aea to your computer and use it in GitHub Desktop.
Save nafeesb/7b1111fc914772494f2c921635cd3aea to your computer and use it in GitHub Desktop.
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