Skip to content

Instantly share code, notes, and snippets.

@willprice
willprice / b64_image.py
Created April 8, 2020 10:20
Encode/decode images to base64 (useful for Bokeh tooltips)
from PIL import Image
import io
import base64
def encode_to_base64_str(img):
img = Image.fromarray(img)
with io.BytesIO() as f:
img.save(f, format='jpeg')
return base64.b64encode(f.getvalue())
@willprice
willprice / softmax.py
Created April 8, 2020 09:52
Numerically stable softmax in numpy
import numpy as np
def softmax(xs, axis=-1):
xs = xs - np.max(xs, axis=axis, keepdims=True)
xs_exp = np.exp(xs)
return xs_exp / xs_exp.sum(axis=axis, keepdims=True)
def index_dict_of_lists(d, idxs):
"""
Args:
d: dictionary of lists (or subdictionaries of lists)
idxs: list/array of indices
Returns:
Dictionary where all lists/arrays are indexed by idxs.
"""
idx = np.array(idxs)
subset_dict = dict()
@willprice
willprice / collate.py
Created March 20, 2020 11:06
Collate a list of dictionaries into a dictionary of lists
__all__ = ['collate_dicts']
from typing import List, Dict, Any
from collections import defaultdict
def collate_dicts(ds: List[Dict[Any, Any]]) -> Dict[Any, List[Any]]:
"""
Args:
ds: A list of dictionarys all with the same keys.
@willprice
willprice / charades_csv_reader.py
Last active February 12, 2020 16:05
Script to read Charades CSV files (Charades_v1_train.csv, Charades_v1_test.csv) into a pandas DataFrame where each row represents a single action
import pandas as pd
from csv import DictReader
from collections import defaultdict
import numpy as np
def read_charades_csv(path):
def parse_action(action_str):
cls, start, stop = action_str.split(' ')
return {
'class': int(cls[1:]),
'start': float(start),
@willprice
willprice / grid_show.py
Created October 9, 2019 15:36
Matplotlib snippet for visualising matrices nicely.
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(context='paper', style='whitegrid')
def grid_show(grid, horizontal_labels, vertical_labels=None, cmap='binary', grid_color='#efefef'):
ax = plt.gca()
image = ax.imshow(grid,
@willprice
willprice / stack.py
Last active June 20, 2023 14:27
PIL Image stacking
import numpy as np
from PIL import Image
def vstack(images):
if len(images) == 0:
raise ValueError("Need 0 or more images")
if isinstance(images[0], np.ndarray):
images = [Image.fromarray(img) for img in images]
width = max([img.size[0] for img in images])
@willprice
willprice / remove_old_kernels.sh
Created September 9, 2019 09:33
Remove old kernels from ubuntu
#!/bin/bash
set +ex
KEEP_LAST_N=2
OLD_KERNELS=$(dpkg -l | grep -i 'linux-image-[[:digit:]]' | awk '{ print $2 }' | sort -rV | tail -n "+$(($KEEP_LAST_N + 1))")
if [ -n "$OLD_KERNELS" ]; then
apt-get -qy remove --purge $OLD_KERNELS
fi
apt-get -qy autoremove --purge