Skip to content

Instantly share code, notes, and snippets.

View GongXinyuu's full-sized avatar
🏡
WFH

Xinyu Gong GongXinyuu

🏡
WFH
View GitHub Profile
@GongXinyuu
GongXinyuu / beautiful_idiomatic_python.md
Created June 22, 2017 04:07 — forked from JeffPaine/beautiful_idiomatic_python.md
Transforming Code into Beautiful, Idiomatic Python: notes from Raymond Hettinger's talk at pycon US 2013. The code examples and direct quotes are all from Raymond's talk. I've reproduced them here for my own edification and the hopes that others will find them as handy as I have!

Transforming Code into Beautiful, Idiomatic Python

Notes from Raymond Hettinger's talk at pycon US 2013 video, slides.

The code examples and direct quotes are all from Raymond's talk. I've reproduced them here for my own edification and the hopes that others will find them as handy as I have!

Looping over a range of numbers

for i in [0, 1, 2, 3, 4, 5]:
@GongXinyuu
GongXinyuu / rotation.py
Created January 29, 2019 06:25
image rotation function
import numpy as np
from imageio import imsave, imread
import matplotlib.pyplot as plt
import math
from numpy.linalg import inv
img_name = 'xxx.jpg'
img = imread(img_name)
h, w, c = np.shape(img)
@GongXinyuu
GongXinyuu / integral.py
Last active January 30, 2019 17:09
integral image
import numpy as np
from imageio import imsave, imread
import matplotlib.pyplot as plt
img_name = 'xxx.jpg'
img = imread(img_name)
class IntegralImage(object):
def __init__(self, img):
assert len(np.shape(img))==2
@GongXinyuu
GongXinyuu / FLOPs_calculator.py
Created March 13, 2019 18:46
pytorch version FLOPs_calculator
import torch
def print_model_parm_nums(model):
"""
Used for calculate models' parameter number.
:param model:
:return:
"""
total = sum([param.nelement() for param in model.parameters()])
print(' + Number of params: %.2fM' % (total / 1e6))
@GongXinyuu
GongXinyuu / gumbel_max_pytorch.py
Last active March 23, 2024 08:32
A temporary function to avoid nan in the pytorch gumbel_softmax function.
import torch
import torch.nn.functional as F
def gumbel_softmax(logits, tau=1, hard=False, eps=1e-10, dim=-1):
# type: (Tensor, float, bool, float, int) -> Tensor
r"""
Samples from the `Gumbel-Softmax distribution`_ and optionally discretizes.
You can use this function to replace "F.gumbel_softmax".
@GongXinyuu
GongXinyuu / utils.py
Created October 19, 2019 03:16
RunningStats
import collections
class RunningStats:
def __init__(self, WIN_SIZE):
self.mean = 0
self.run_var = 0
self.WIN_SIZE = WIN_SIZE
self.window = collections.deque(maxlen=WIN_SIZE)
# Learning towards Minimum Hyperspherical Energy
# https://github.com/wy1iu/MHE/blob/master/code/architecture.py
# https://github.com/rmlin/CoMHE/blob/master/adversarial_projection/architecture.py
@torch.no_grad()
def hypersphereenergy(filt, filt_target=None, paired=False, model=None, power='0', device='cuda:0', mem_efficient=False):
# TODO if filt_target is None: filt energy itself; if filt_target is not None: filt energy against filt_target
# TODO paired: if size of filt and filt_target are same: only compare diagonal
# tensorflow: [ksize, ksize, n_input, n_filt]
# pytorch: [n_filt, n_input, ksize, ksize]
n_filt = filt.size(0)
@GongXinyuu
GongXinyuu / functions.py
Last active February 7, 2021 02:58
GAN training
def train(args, gen_net: nn.Module, dis_net: nn.Module, gen_optimizer, dis_optimizer, gen_avg_param,
train_loader, epoch, writer_dict, image_counter=None, schedulers=None):
writer = writer_dict['writer']
gen_step = 0
# train mode
gen_net = gen_net.train()
dis_net = dis_net.train()
for iter_idx, (imgs, _) in enumerate(tqdm(train_loader)):
class BiHingeLinearTransform:
"""
f(x) = max(0, (x - max_thres) * s) + max(0, (min_thres - x) * s)
"""
def __init__(self, scaling, min_thres, max_thres):
self.scaling = scaling
assert min_thres <= max_thres
self.min_thres = min_thres
self.max_thres = max_thres
def get_fair_ch_idx(channels_list, inp_choice_idx) -> Tuple:
"""
This function will return the actual channel index based on fair sampling.
:param channels_list:
:param inp_choice_idx:
:return:
"""
min_channel = min(channels_list)
base_ch = min_channel
max_channel = max(channels_list)