Skip to content

Instantly share code, notes, and snippets.

View phil8192's full-sized avatar
🦇

Phil Stubbings phil8192

🦇
View GitHub Profile
# desired matrix:
# 1 1
# 1 2
# 1 3
# 2 1
# 2 2
# 2 3
# 2 4
# 3 1
# 3 2
def sample(x):
"""
1
2 3
4 5 6 7
=
4 2 6 1 3 5 7
>>> list(sample(['a', 'b', 'c', 'd', 'e', 'f', 'g']))
[('d', 1), ('b', 2), ('f', 2), ('a', 3), ('c', 3), ('e', 3), ('g', 3)]
"""
@phil8192
phil8192 / waterflow.R
Created November 2, 2018 19:10
R solution to twitter waterflow problem
# 1 line
function(x) sum(head(tail(pmin(cummax(x),rev(cummax(rev(x))))-x,-1),-1))
# or with fancy ascii visualisation!
#
# > water(x)
# $water
# [1] 10
#
# $vis
@phil8192
phil8192 / wapply.R
Last active April 11, 2019 19:59
roll apply with window of indices
wapply <- function(x, window=1:10, fun=mean) {
res <- rep(NA, length(x))
names(res) <- names(x)
i <- max(window) + 1
while(i <= length(x)) {
res[i] <- fun(x[i - window])
i <- i + 1
# convert
# 7, 7, 6, 5, 5, 3, 3, 2, 0, 0 ->
# 1 1 2 3 3 4 4 5 NA NA
x <- c(7,7,6,5,5,3,3,2,0,0)
ifelse(x,cumsum(c(1,abs(sign(diff(x))))),NA)
# [1] 1 1 2 3 3 4 4 5 NA NA
library(homomorpheR)
key.pair <- PaillierKeyPair$new(modulusBits=1024)
encrypt <- function(x) key.pair$pubkey$encrypt(x)
decrypt <- decrypt <- function(x) key.pair$getPrivateKey()$decrypt(x)
"%+%" <- function(a, b) key.pair$pubkey$add(a, b)
20 == decrypt(encrypt(1) %+% encrypt(19)) # TRUE
def set_weights(intercept, coef, classes, model=linear_model.SGDClassifier()):
model.intercept_ = intercept
model.coef_ = coef
model.classes_ = classes
return model
def batches(X, y, batch_size, randomise):
rows = X.shape[0]
i = np.arange(rows)
if randomise:
np.random.shuffle(i)
splits = rows / batch_size
for x_batch, y_batch in zip(np.array_split(X[i, ], splits),
np.array_split(y[i], splits)):
yield x_batch, y_batch
def batch_update(model, X, y, classes, batch_size, randomise):
if batch_size is None:
batch_size = X.shape[0]
for x_batch, y_batch in batches(X, y, batch_size, randomise):
model.partial_fit(x_batch, y_batch, classes)
return model.intercept_, model.coef_
def batch_train(model, X, y, classes, epochs, batch_size, randomise):
for _ in range(0, epochs):
batch_update(model, X, y, classes, batch_size, randomise)