Skip to content

Instantly share code, notes, and snippets.

View dboyliao's full-sized avatar

dboyliao dboyliao

View GitHub Profile
@dboyliao
dboyliao / strided_iter_product.py
Last active June 4, 2021 08:39
pure python implementation of strided slice
import numpy as np
class StridedIterator:
"""
Reference:
- https://github.com/python/cpython/blob/b2bf2bc1ece673d387341e06c8d3c2bc6e259747/Modules/itertoolsmodule.c#L2342
"""
def __init__(self, begin, end, strides):
self._idx_cnt = list(begin)
"""
Just for fun: https://www.facebook.com/groups/706762492694458/permalink/4414710665232937/
"""
import numpy as np
class Word:
__map = {
("金", "金"): "鍂",
@dboyliao
dboyliao / np_tuplize.py
Last active October 21, 2020 12:39
Broadcasted tuple
#!/usr/bin/env python3
# https://gist.github.com/dboyliao/ccb5970ccafd6d5c0420d39514cb0464
from pprint import pprint
import numpy as np
class _Tuple:
def __init__(self, *values):
self.__values = values
import numpy as np
def distance_vec(X):
# (x - y)^2 = x^2 + y^2 - 2xy
prod = -2 * X.dot(X.T)
sq = (X ** 2).sum(axis=-1)
return sq + sq[:, None] + prod
import numpy as np
from itertools import combinations
def distance_loop(X):
N, M = X.shape
dist = np.zeros((N, N))
for i, j in combinations(range(N), 2):
xi = X[i]
xj = X[j]
from utensor_cgen.backend.graph_lower import TensorAllocationPlanner
from utensor_cgen.frontend.tensorflow import GraphDefParser
parser = GraphDefParser(config={})
planner = TensorAllocationPlanner(config={})
ugraph = parser.parse('tests/deep_mlp/simple_mnist.pb', output_nodes=['y_pred'])
planner.apply(ugraph)
plan = ugraph.attributes[planner.KWARGS_NAMESCOPE].plan
total_size = ugraph.attributes[planner.KWARGS_NAMESCOPE].total_size
from ortools.sat.python import cp_model
model = cp_model.CpModel()
nonoverlap_map = {
'w:0': [],
'x:0': ['w:0'],
'y:0': ['x:0', 'w:0'],
'z:0': ['x:0', 'w:0', 'y:0'],
'u:0': ['w:0', 'z:0'],
}
from ortools.sat.python import cp_model
model = cp_model.CpModel()
model.NewIntVar # declare a variable of type int
model.NewBoolVar # declare a variable of type bool
model.NewIntervalVar # declare an inclusive interval [a, b]
model.Add # add constraint, such as x < 1
model.AddNoOverlap # add constraint for non overlapping intervals
# and more...
@dboyliao
dboyliao / ortools_example.py
Last active March 12, 2020 14:48
Simple ortools example for solving constraint optimization with CP solver
from ortools.sat.python import cp_model
# setup a model which represents the constraint optimization problem
model = cp_model.CpModel()
# declare variables
# x and y are two integer with range of 0 to 2
x = model.NewIntVar(0, 2, 'x')
y = model.NewIntVar(0, 2, 'y')
# add constraint: x+y <= 1
model.Add(x + y <= 1)
@dboyliao
dboyliao / pytorch_lagrange_multi.py
Last active January 29, 2023 15:48
Simple Example: Solving Lagrange Multiplier with PyTorch
import torch
x = torch.tensor(0, requires_grad=True, dtype=torch.float64)
y = torch.tensor(0, requires_grad=True, dtype=torch.float64)
l = torch.tensor(0, requires_grad=True, dtype=torch.float64)
lr = 0.1
# min x^2+y^2 s.t x+y = 1
for i in range(100):
L = x**2 + y**2 + l*(1-x-y)