Skip to content

Instantly share code, notes, and snippets.

@sunshineatnoon
Last active January 3, 2021 23:04
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 sunshineatnoon/c240bc3debcc1235b253c96556c2bee6 to your computer and use it in GitHub Desktop.
Save sunshineatnoon/c240bc3debcc1235b253c96556c2bee6 to your computer and use it in GitHub Desktop.

Draw histograms from list

import numpy as np
import matplotlib.pyplot as plt

count = [23, 44, 12, 11, 2, 10]
pos = np.arange(len(count))
width = 0.1     # gives histogram aspect to the bar diagram

ax = plt.axes()
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(range(1,len(count)))

plt.bar(pos, count, width, color='b')
plt.show()

Tranverse a folder

#!/usr/bin/python

import os

# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("."):
    path = root.split(os.sep)
    print((len(path) - 1) * '---', os.path.basename(root))
    for file in files:
        print(len(path) * '---', file)

Gradient hook

source

grads = {}
def save_grad(name):
    def hook(grad):
        grads[name] = grad
    return hook

x = Variable(torch.randn(1,1), requires_grad=True)
y = 3*x
z = y**2

# In here, save_grad('y') returns a hook (a function) that keeps 'y' as name
y.register_hook(save_grad('y'))
z.register_hook(save_grad('z'))
z.backward()

print(grads['y'])
print(grads['z'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment