markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Hacer variables dummies
n=-10 final=general.MWh.tail(-n) onlyMWh=pd.DataFrame(general.MWh) general['Month'] = general.index.month general['Weekday_Name'] = general.index.weekday_name dates=general.index dummies = pd.get_dummies(general['Weekday_Name']).astype(int) dummies2 = pd.get_dummies(general['Month']).astype(int) Dum=pd.DataFrame(dummie...
_____no_output_____
MIT
Efecto Arima en final.ipynb
ramirezdiana/Forecast-with-fourier
Observar descomposición
part=general.MWh.tail(100) result=seasonal_decompose(part, model='multiplicative') fig = result.seasonal.plot(figsize=(20,5))
_____no_output_____
MIT
Efecto Arima en final.ipynb
ramirezdiana/Forecast-with-fourier
Al ver la decomposición, se puede ver por la forma que fourier debe estblecerse en senos y cosenos absolutos, para que se parezca a la estacionalidad de la serie. Se agrega a las variables dummies esta estacionalidad semanal, que parece ser fundamental en los datos Detectar efecto de las variables dummies
t=np.arange(1,len(onlyMWh)+1) Tiempo=pd.DataFrame(t) Tiempo["one"]=np.ones(len(onlyMWh)) Tiempo['sen']=np.abs(np.sin(((2*np.pi)/14)*t)) Tiempo['cos']=np.abs(np.cos(((2*np.pi)/14)*t)) Combinacion=kronecker(Dum,Tiempo) model = LinearRegression() prediction=regresion_linear(Combinacion[:n],general.MWh.values[:n]) plt.figu...
_____no_output_____
MIT
Efecto Arima en final.ipynb
ramirezdiana/Forecast-with-fourier
Obtener error de datos con variables dummies vs datos reales
Tabla=pd.DataFrame(columns=['regresion','datos','resta']) Tabla["regresion"]=prediction Tabla["datos"]=onlyMWh.MWh.values[:n] Tabla["resta"]=Tabla.datos-Tabla.regresion plt.plot(Tabla.resta) plt.show()
_____no_output_____
MIT
Efecto Arima en final.ipynb
ramirezdiana/Forecast-with-fourier
Establecer las frecuencias que se debe considerar en la serie de fourier
f, Pxx_den = signal.periodogram(Tabla.resta, 1) plt.plot(1/f, Pxx_den) plt.xlabel('periodo') plt.ylabel('PSD') plt.show() top_50_periods = {} # get indices for 3 highest Pxx values top50_freq_indices = np.flip(np.argsort(Pxx_den), 0)[2:12] freqs = f[top50_freq_indices] power = Pxx_den[top50_freq_indices] periods = 1 /...
power periods 0 8.749328e+09 1911.333333 1 5.225123e+09 45.507937 2 4.883263e+09 819.142857 3 4.626260e+09 1146.800000 4 4.413181e+09 36.522293 5 4.324008e+09 955.666667 6 4.069662e+09 573.400000 7 4.064267e+09 521.272727 8 3.968931e+09 61.000000 9 3.914966e+09 91.015873
MIT
Efecto Arima en final.ipynb
ramirezdiana/Forecast-with-fourier
Hacer la regresión del efecto cruzado de variables dummies y senos/cosenos absolutos de frecuencia de error
sencos = pd.DataFrame() sencos["t"]=np.arange(1,len(onlyMWh)+1) for i in matrix.periods: sencos["{}_sen".format(i)] = np.abs(np.sin(((2*np.pi)/i)*t)) sencos["{}_cos".format(i)] = np.abs(np.cos(((2*np.pi)/i)*t)) sencos["unos"] = 1 sencos['sen']=np.abs(np.sin(((2*np.pi)/14)*t)) sencos['cos']=np.abs(np.c...
_____no_output_____
MIT
Efecto Arima en final.ipynb
ramirezdiana/Forecast-with-fourier
MAPE de la regresion
plt.figure(figsize=(10,5)) plt.plot(onlyMWh.MWh[0:n].values,label ="Datos") plt.plot(prediction,label="Predicción") plt.ylabel("demanda en MWh") plt.xlabel("días") plt.legend() plt.show() #%%obtener mape de regresión comp=comparacion(onlyMWh.MWh.values[:n],prediction) MAPE=comp.error.mean() print("MAPE = ",round(MAPE,4...
_____no_output_____
MIT
Efecto Arima en final.ipynb
ramirezdiana/Forecast-with-fourier
Graficar residuales de la regresión
Tabla=pd.DataFrame(columns=['regresion','datos','resta']) Tabla["regresion"]=prediction Tabla["datos"]=onlyMWh.MWh[0:n].values Tabla["resta"]=Tabla.datos-Tabla.regresion plt.plot(Tabla.resta) plt.show() plt.hist(Tabla["resta"],bins=50) plt.show() resta=pd.DataFrame(Tabla["resta"]) from statsmodels.tsa.arima_model impor...
_____no_output_____
MIT
Efecto Arima en final.ipynb
ramirezdiana/Forecast-with-fourier
Gráfica de manera dinámica
extra=results.predict(len(onlyMWh.MWh[0:n]),len(onlyMWh.MWh[0:n])-n) extra=extra.iloc[1:] from sklearn.linear_model import Lasso Combinaciontest=kronecker(Dum_test,sencos_test) #Initializing the Lasso Regressor with Normalization Factor as True lasso_reg = Lasso(normalize=True) #Fitting the Training data to the Lasso r...
_____no_output_____
MIT
Efecto Arima en final.ipynb
ramirezdiana/Forecast-with-fourier
todo para pronóstico
comp_pronostico=comparacion(final,y_pred_lass+extra.values) #comp_pronostico=comparacion(final,hubpredict+extra.values) MAPE=comp_pronostico.error.mean() plt.figure(figsize=(10,5)) plt.plot(final,label="Real") plt.plot(comp_pronostico.prediccion,label="Pronóstico") plt.ylabel("demanda en MWh") plt.xlabel("días") plt.le...
_____no_output_____
MIT
Efecto Arima en final.ipynb
ramirezdiana/Forecast-with-fourier
МАДМО Физтех-Школа Прикладной математики и информатики МФТИ Лаборатория нейронных сетей и глубокого обучения (DeepHackLab) Домашнее задание необходимо загрузить в общий репозиторий с именной папкой Домашнее задание 1 Основы Python и пакет NumPy---
import numpy as np import random import scipy.stats as sps
_____no_output_____
MIT
Students/Tunitskaya/Hometask_1(1).ipynb
Alken1/Sberbank_ML
Задача 1В первой задаче вам предлагается перемножить две квадратные матрицы двумя способами -- без использования пакета ***numpy*** и с ним.
# Для генерации матриц используем фукнцию random -- она используется для генерации случайных объектов # функция sample создает случайную выборку. В качестве аргумента ей передается кортеж (i,j), здесь i -- число строк, # j -- число столбцов. a = np.random.sample((1000,1000)) b = np.random.sample((1000,1000)) # выведит...
Wall time: 46.8 ms
MIT
Students/Tunitskaya/Hometask_1(1).ipynb
Alken1/Sberbank_ML
Задача 2Напишите функцию, которая по данной последовательности $\{A_i\}_{i=1}^n$ строит последовательность $S_n$, где $S_k = \frac{A_1 + ... + A_k}{k}$. Аналогично -- с помощью библиотеки **NumPy** и без нее. Сравните скорость, объясните результат.
# функция, решающая задачу с помощью NumPy def sec_av(A): return np.cumsum(A)/list(range(1,len(A)+1)) pass # функция без NumPy def stupid_sec_av(A): S = [0 for i in range(len(A))] S[0] = A[0] for i in range(len(A)-1): S[i+1] = A[i+1] + S[i] numb = list(range(1,len(A)+1))...
Wall time: 1.39 s Wall time: 10.7 s
MIT
Students/Tunitskaya/Hometask_1(1).ipynb
Alken1/Sberbank_ML
Задача 3Пусть задан некоторый массив $X$. Надо построить новый массив, где все элементы с нечетными индексами требуется заменить на число $a$ (если оно не указано, то на 1). Все элементы с четными индексами исходного массива нужно возвести в куб и записать в обратном порядке относительно позиций этих элементов. Массив...
# функция, решающая задачу с помощью NumPy def transformation(X, a = 1): X[1::2] = a X[::2] **= 3 X[::2] = X[::2][::-1] return X # функция, решающая задачу без NumPy def stupid_transformation(X): t_odd = [] t_ev = [] t_ev_inv = [] Y = [] t_odd = int(round...
Wall time: 172 ms
MIT
Students/Tunitskaya/Hometask_1(1).ipynb
Alken1/Sberbank_ML
Почему методы ***numpy*** оказываются эффективнее?
# Написаны на C
_____no_output_____
MIT
Students/Tunitskaya/Hometask_1(1).ipynb
Alken1/Sberbank_ML
Дополнительные задачи Дополнительные задачи подразумевают, что Вы самостоятельно разберётесь в некоторых функциях ***numpy***, чтобы их сделать. Эти задачи не являются обязательными, но могут повлиять на Ваш рейтинг в лучшую сторону (точные правила учёта доп. задач будут оглашены позже). Задача 4* Дана функция двух ...
from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline def f(x, y): '''Функция двух переменных''' return np.sin(x) * np.cos(y) def draw_f(grid_x, grid_y): '''Функция отрисовки функции f(x, y)''' fig = plt.figure(figsize=(10, 8)) ax = Axes3D(fig) ax.plot...
_____no_output_____
MIT
Students/Tunitskaya/Hometask_1(1).ipynb
Alken1/Sberbank_ML
Задача 5* Выберите любую картинку и загрузите ее в папку с кодом. При загрузке её размерность равна 3: **(w, h, num_channels)**, где **w** - ширина картинки в пикселях, **h** - высота картинки в пикселях, **num_channels** - количество каналов *(R, G, B, alpha)*.Вам нужно "развернуть" картинку в одномерный массив разме...
from matplotlib import pyplot as plt %matplotlib inline path_to_image = './image.png' image_array = plt.imread(path_to_image) plt.imshow(image_array); flat_image_array = = image_array.flatten() print(len(flat_image_array))
_____no_output_____
MIT
Students/Tunitskaya/Hometask_1(1).ipynb
Alken1/Sberbank_ML
Colab-pytorch-image-classification Original repo: [bentrevett/pytorch-image-classification](https://github.com/bentrevett/pytorch-image-classification) [SqueezeNet code](https://github.com/pytorch/vision/blob/master/torchvision/models/squeezenet.py): [pytorch/vision](https://github.com/pytorch/vision) My fork: [styl...
!nvidia-smi
_____no_output_____
MIT
9_SqueezeNet.ipynb
styler00dollar/Colab-image-classification
DATASET CREATION
#@title Mount Google Drive from google.colab import drive drive.mount('/content/drive') print('Google Drive connected.') # copy data somehow !mkdir '/content/classification' !mkdir '/content/classification/images' !cp "/content/drive/MyDrive/classification_v2.7z" "/content/classification/images/classification.7z"...
_____no_output_____
MIT
9_SqueezeNet.ipynb
styler00dollar/Colab-image-classification
CALC MEANS & STDS
#@title print means and stds import torch import torchvision.transforms as transforms import torchvision.datasets as datasets from tqdm import tqdm train_data = datasets.ImageFolder(root = train_dir, transform = transforms.ToTensor()) means = torch.zeros(3) stds = torch.zeros(3) for...
_____no_output_____
MIT
9_SqueezeNet.ipynb
styler00dollar/Colab-image-classification
TRAIN
#@title import, seed, transforms, dataloader, functions, plot, model, parameter %cd /content/ from tqdm import tqdm import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler from torch.optim.lr_scheduler import _LRScheduler import torc...
_____no_output_____
MIT
9_SqueezeNet.ipynb
styler00dollar/Colab-image-classification
TESTING
#@title Calc test loss model.load_state_dict(torch.load('best-validation-accuracy.pt')) print("best-validation-accuracy.pt") test_loss, test_acc_1, test_acc_5 = evaluate(model, test_iterator, criterion, device) print("-----------------------------") model.load_state_dict(torch.load('best-validation-loss.pt')) print("be...
_____no_output_____
MIT
9_SqueezeNet.ipynb
styler00dollar/Colab-image-classification
From Variables to Classes A short Introduction Python - as any programming language - has many extensions and libraries at its disposal. Basically, there are libraries for everything. But what are **libraries**? Basically, **libraries** are a collection of methods (_small pieces of code where you put sth in and g...
x = 4.2 print(type(x)) y = 'Hello World!' print(type(y)) z = True print(type(z))
<class 'float'> <class 'str'> <class 'bool'>
MIT
00_Variables_to_Classes.ipynb
darius74/geothermics
We can use operations (normal arithmetic operations) to use variables for getting results we want. With numbers, you can add, substract, multiply, divide, basically taking the values from the memory assigned to the variable name and performing calculations. Let's have a look at operations with numbers and strings. We...
n1 = 7 n2 = 42 s1 = 'Looking good, ' s2 = 'you are.' first_sum = n1 + n2 print(first_sum) first_conc = s1 + s2 print(first_conc)
49 Looking good, you are.
MIT
00_Variables_to_Classes.ipynb
darius74/geothermics
Variables can be more than just a number. If you think of an Excel-Spreadsheet, a variable can be the content of a single cell, or multiple cells can be combined in one variable (e.g. one column of an Excel table). So let's create a list -_a collection of variables_ - from `x`, `n1`, and `n2`. Lists in python are creat...
first_list = [x, n1, n2] second_sum = first_list[0] + first_list[1] + first_list[2] print('manual sum {}'.format(second_sum)) # This can also be done with a function print('sum function {}'.format(sum(first_list)))
manual sum 53.2 sum function 53.2
MIT
00_Variables_to_Classes.ipynb
darius74/geothermics
Functions The `sum()` method we used above is a **function**. Functions (later we will call them methods) are pieces of code, which take an input, perform some kind of operation, and (_optionally_) return an output. In Python, functions are written like: ```pythondef func(input): """ Description of the funct...
def sumup(inp): """ input: inp - list/array with floating point or integer numbers return: sumd - scalar value of the summed up list """ val = 0 for i in inp: val = val + i return val # let's compare the implemented standard sum function with the new sumup function sum1 = sum(first_...
the sum of the array is: 5050
MIT
00_Variables_to_Classes.ipynb
darius74/geothermics
As we see above, functions are quite practical and save a lot of time. Further, they help structuring your code. Some functions are directly available in python without any libraries or other external software. In the example above however, you might have noticed, that we `import`ed a library called `numpy`. In those ...
# here we just create the data for clustering from sklearn.datasets.samples_generator import make_blobs import matplotlib.pyplot as plt %matplotlib inline X, y = make_blobs(n_samples=100, centers=3, cluster_std= 0.5, random_state=0) plt.scatter(X[:,0], X[:,1], s=70) # now we create an instance of the...
_____no_output_____
MIT
00_Variables_to_Classes.ipynb
darius74/geothermics
Implementing LSH algorithm 0. Dataset 0.1 Import 20-news dataset
newsgroup_dataset = datasets.fetch_20newsgroups(data_home='./dataset/', subset='train', remove=('headers', 'footers', 'quotes'), download_if_missing=True) raw_documents = newsgroup_dataset['data'][:] len(raw_documents) raw_documents[0]
_____no_output_____
MIT
AI506/hw1/hw1-20194331/hw1_problem.ipynb
sungnyun/AI-assignments
0.2 Preprocess the documents
K = 5 # number of word tokens to shinlge def preprocess(documents): processed_words = defaultdict(list) cnt = 0 for doc in documents: # first, filter out some uncesseary symbols like punctuations doc = re.sub('\/|\-|\'|\@|\%|\$|\#|\,|\(|\)|\}|\"|\{|\?|\.|\!|\;|\:', '', doc) ...
_____no_output_____
MIT
AI506/hw1/hw1-20194331/hw1_problem.ipynb
sungnyun/AI-assignments
1. Shingling
######################################################################################################################## # Programming 1 [15pt] # # In this section, you will implement the shingling algorithm to convert the ...
_____no_output_____
MIT
AI506/hw1/hw1-20194331/hw1_problem.ipynb
sungnyun/AI-assignments
1.1 Get Shingles from the documents
def get_shingles(documents): ###################################################################################### # Programming 1.1 [10pt] # # Implement 'get_shingles' function to get 1-singles from the preprocessed documents # # You shoul...
1.0299334526062012
MIT
AI506/hw1/hw1-20194331/hw1_problem.ipynb
sungnyun/AI-assignments
1.2 Build document to shingles dictionary
def build_doc_to_shingle_dictionary(documents, shingles): ################################################################################################################################ # Programming 1.2 [5pt] ...
Test passed
MIT
AI506/hw1/hw1-20194331/hw1_problem.ipynb
sungnyun/AI-assignments
2. Min-Hashing
############################################################################################################################ # Programming 2 [25pt] # # In this section, you will implement the min-hashing algorithm to co...
_____no_output_____
MIT
AI506/hw1/hw1-20194331/hw1_problem.ipynb
sungnyun/AI-assignments
2.1 Generate Prime numbers for Universal Hashing
def is_prime(n): for i in range(2,int(np.sqrt(n))+1): if not n % i: return False return True def generate_prime_numbers(M, N): # this function generate the M prime numbers where each prime number is greater than N primes = [] cnt = 0 n = N + 1 while cnt < M: ...
_____no_output_____
MIT
AI506/hw1/hw1-20194331/hw1_problem.ipynb
sungnyun/AI-assignments
2.2 Jaccard Similarity
def jaccard_similarity(s1, s2): ################################################################################## # Programming 2.2 [5pt] # # Implement the jaccard similarity algorithm to get the similarity of tw...
Test passed
MIT
AI506/hw1/hw1-20194331/hw1_problem.ipynb
sungnyun/AI-assignments
2.3 Min Hash
M = 100 # Number of Hash functions to use N = len(shingles) # First we will create M universal hashing functions # You can also modify or implement your own hash functions for implementing min_hash function class Hash(): def __init__(self, M, N): self.M = M self.N = N self.p = generate_p...
100%|██████████| 10000/10000 [00:04<00:00, 2437.12it/s]
MIT
AI506/hw1/hw1-20194331/hw1_problem.ipynb
sungnyun/AI-assignments
2.4 Qualitive Analysis
print('Document 3542') print(documents[3542]) print('-------------') print('Document 8033') print(documents[8033]) print('-------------') print('true jaccard similarity:' ,jaccard_similarity(set(doc_to_shingles[3542]), set(doc_to_shingles[8033]))) print('approx jaccard similarity:',sum(np.equal(signatures[:,3542], si...
Document 3542 i have one complaint for the cameramen doing the jerseypitt series show the shots not the hits on more than one occassion the camera zoomed in on a check along the boards while the puck was in the slot they panned back to show the rebound maybe moms camera people were a little more experienced -----------...
MIT
AI506/hw1/hw1-20194331/hw1_problem.ipynb
sungnyun/AI-assignments
3. Locality Sensitive Hashing
######################################################################################################################## # Programming 3 [35pt] # # In this section, you will implement the Min-Hash based Locality Sensitive H...
_____no_output_____
MIT
AI506/hw1/hw1-20194331/hw1_problem.ipynb
sungnyun/AI-assignments
3.1 Min-Hash based LSH
def lsh(signatures, b, r): ######################################################################################################### # Programming 3.1 [20pt] # # Implement the min-hash based LSH algorithm to find the candidate ...
b=10 # of candidate pairs = 162 0th sample pair: (1658, 5780) Jaccard similarity: 0.8108108108108109 ------------- from paynecrldeccom andrew payne messageid organization dec cambridge research lab date tue apr gmt does anyone know if a source for the modem chips as used in the baycom and my pmp modems ideally somethin...
MIT
AI506/hw1/hw1-20194331/hw1_problem.ipynb
sungnyun/AI-assignments
3.2 Compute the precision, recall, and F1-score
# Compute the number of condition positives, which is the number of every document pair whose Jaccard similarity is greater than or equal to the threshold s = 0.8 # similarity threshold for checking condition positives numConditionPositives = 151 # This is the computed result when s=0.8, but I gave it to you to save ...
-----Test results----- [Test 1.1 (1)]: Passed [Test 1.1 (2)]: Passed [Test 1.2]: Passed [Test 2.1]: Passed [Test 2.2]: Passed ----------------------
MIT
AI506/hw1/hw1-20194331/hw1_problem.ipynb
sungnyun/AI-assignments
Plotting functions
from recnn.preprocessing import sequentialize_by_pt def load_tf(filename_train, preprocess=None, n_events_train=-1): # Make training data print("Loading training data...") fd = open(filename_train, "rb") X, y = pickle.load(fd) fd.close() y = np.array(y) if n_events_train > 0: ...
_____no_output_____
BSD-3-Clause
notebooks/04-jet-study.ipynb
glouppe/recnn
Count parameters
def count(params): def _count(thing): if isinstance(thing, list): c = 0 for stuff in thing: c += _count(stuff) return c elif isinstance(thing, np.ndarray): return np.prod(thing.shape) c = 0 for k, v in params.items(): ...
('Simple =', 10081) ('Gated =', 50361)
BSD-3-Clause
notebooks/04-jet-study.ipynb
glouppe/recnn
Embedding visualization
prefix_train = "antikt-kt" prefix_test = prefix_train tf = load_tf("../data/w-vs-qcd/final/%s-train.pickle" % prefix_train) X, y, w = load_test(tf, "../data/w-vs-qcd/final/%s-test.pickle" % prefix_test) fd = open("../models/jet-study-2/model-w-s-antikt-kt-1.pickle", "rb") params = pickle.load(fd) fd.close() Xt = grnn_...
_____no_output_____
BSD-3-Clause
notebooks/04-jet-study.ipynb
glouppe/recnn
Generate all ROCs
for pattern, gated in [ # Simple ## Particles ("antikt-kt", False), ("antikt-cambridge", False), ("antikt-antikt", False), ("antikt-random", False), ("antikt-seqpt", False), ("antikt-seqpt-reversed", False), ## Towers ("antikt-kt-delphes", ...
_____no_output_____
BSD-3-Clause
notebooks/04-jet-study.ipynb
glouppe/recnn
Table
for pattern, gated, label in [ # Simple ## Particles ("antikt-kt", False, "RNN $k_t$"), ("antikt-cambridge", False, "RNN C/A"), ("antikt-antikt", False, "RNN anti-$k_t$"), ("antikt-random", False, "RNN random"), ("antikt-seqpt", False, "RNN asc-$p_T$"), ("...
particles & RNN $k_t$ & 0.9178 $\pm$ 0.0008 & 67.0 $\pm$ 2.6 \\ towers & RNN $k_t$ & 0.8801 $\pm$ 0.0012 & 24.1 $\pm$ 0.6 \\ towers & RNN $k_t$ & 0.8332 $\pm$ 0.0029 & 12.6 $\pm$ 0.4 \\ particles & RNN $k_t$ (gated) & 0.918...
BSD-3-Clause
notebooks/04-jet-study.ipynb
glouppe/recnn
Plots
# Simple vs gated for pattern, gated, label, color in [ ("antikt-kt", False, "RNN $k_t$ (simple)", "r"), ("antikt-kt", True, "RNN $k_t$ (gated)", "b") ]: fd = open("../models/jet-study-2/rocs/rocs-%s-%s.pickle" % ("s" if not gated else "g", pattern), "rb") r, f, t = pickle.load(fd) ...
particles ROC AUC=0.9195+-0.00 1/FPR@TPR=0.5=74.34+-2.40 towers ROC AUC=0.8822+-0.00 1/FPR@TPR=0.5=25.41+-0.36 images ROC AUC=0.8277+-0.00 1/FPR@TPR=0.5=12.36+-0.30
BSD-3-Clause
notebooks/04-jet-study.ipynb
glouppe/recnn
Trimming
for pattern_train, pattern_test, gated in [ ("antikt-kt", "antikt-kt", False), ("antikt-kt", "antikt-kt-trimmed", False), ("antikt-kt-trimmed", "antikt-kt-trimmed", False), ("antikt-kt-trimmed", "antikt-kt", False), ]: r, f, t = build_rocs(pattern_train, pattern_test, pattern_tra...
$k_t$ on $k_t$ ROC AUC=0.9185+-0.00 1/FPR@TPR=0.5=68.32+-1.80 $k_t$ on $k_t$-trimmed ROC AUC=0.8952+-0.00 1/FPR@TPR=0.5=28.70+-1.30 $k_t$-trimmed on $k_t$-trimmed ROC AUC=0.9034+-0.00 1/FPR@TPR=0.5=33.05+-1.85 $k_t$-trimmed on $k_t$ ROC AUC=0.8893+-0.01 1/FPR@TPR=0.5=36.78+-5.88
BSD-3-Clause
notebooks/04-jet-study.ipynb
glouppe/recnn
Colinear splits
from functools import partial from recnn.preprocessing import sequentialize_by_pt preprocess_seqpt = partial(sequentialize_by_pt, reverse=False) preprocess_seqpt_rev = partial(sequentialize_by_pt, reverse=True) for pattern_train, pattern_test, gated, preprocess in [ # kt ("antikt-kt", "antikt-kt-colin...
$k_t$ colinear1 & 0.9183 $\pm$ 0.0006 & 68.7 $\pm$ 2.0 \\ $k_t$ colinear10 & 0.9174 $\pm$ 0.0006 & 67.5 $\pm$ 2.6 \\ $k_t$ colinear1-max & 0.9184 $\pm$ 0.0006 & 68.5 $\pm$ 2.8 \\ $k_t$ colinear10-max & 0.9159 $\pm$ 0.0009 & 65.7 $\pm$ 2.7 \\ asc-$p_T$...
BSD-3-Clause
notebooks/04-jet-study.ipynb
glouppe/recnn
Soft particles
from functools import partial from recnn.preprocessing import sequentialize_by_pt preprocess_seqpt = partial(sequentialize_by_pt, reverse=False) preprocess_seqpt_rev = partial(sequentialize_by_pt, reverse=True) for pattern_train, pattern_test, gated, preprocess in [ ("antikt-kt", "antikt-kt-soft", False, None...
$k_t$ soft & 0.9179 $\pm$ 0.0006 & 68.2 $\pm$ 2.3 \\ asc-$p_T$ soft & 0.9121 $\pm$ 0.0032 & 51.3 $\pm$ 6.0 \\ desc-$p_T$ soft & 0.9188 $\pm$ 0.0009 & 70.2 $\pm$ 3.7 \\
BSD-3-Clause
notebooks/04-jet-study.ipynb
glouppe/recnn
Learning curve
for pattern, gated, n_events in [ # ("antikt-kt", False, 6000), # ("antikt-seqpt-reversed", False, 6000), ("antikt-kt", True, 6000), ("antikt-seqpt-reversed", True, 6000), # ("antikt-kt", False, 15000), # ("antikt-seqpt-reversed", False, 15000), ("antikt-kt", True...
$k_t$ 100k ROC AUC=0.9195+-0.00 1/FPR@TPR=0.5=74.34+-2.40 $k_t$ 10k ROC AUC=0.9042+-0.00 1/FPR@TPR=0.5=46.42+-5.09 $k_t$ 1k ROC AUC=0.8726+-0.01 1/FPR@TPR=0.5=22.63+-2.97 desc-$p_T$ 100k ROC AUC=0.9212+-0.00 1/FPR@TPR=0.5=83.27+-3.08 ...
BSD-3-Clause
notebooks/04-jet-study.ipynb
glouppe/recnn
Tau21
import h5py f = h5py.File("../data/w-vs-qcd/h5/w_100000_j1p0_sj0p30_delphes_jets_images.h5", "r")["auxvars"] tau1 = f["tau_1"] tau2 = f["tau_2"] tau21 = np.true_divide(tau2, tau1) pt = f["pt_trimmed"] mass = f["mass_trimmed"] mask = (f["mass_trimmed"] < 110) & (f["mass_trimmed"] > 50) & (f["pt_trimmed"] < 300) & (f["pt...
tau21+mass ROC AUC=0.8207+-0.00 1/FPR@TPR=0.5=11.06+-0.00
BSD-3-Clause
notebooks/04-jet-study.ipynb
glouppe/recnn
RandomizedSearchCV
big_param_grid = { 'C' : np.arange(0, 10, 0.01), 'tol': np.arange(0, 0.001, 1e-5), } big_param_grid # Create the RandomizedSearch estimator along with a parameter object containing the values to adjust from sklearn.model_selection import RandomizedSearchCV random_clf = RandomizedSearchCV(model, big_param_grid, ...
precision recall f1-score support blue 0.83 1.00 0.91 10 red 1.00 0.87 0.93 15 accuracy 0.92 25 macro avg 0.92 0.93 0.92 25 weighted avg 0.93 0.92 0.92 ...
ADSL
01-Lesson-Plans/19-Supervised-Machine-Learning/1/Extra-Activities/01-Ins_Hyperparameters/Solved/Ins_Hyperparameters.ipynb
anirudhmungre/sneaky-lessons
AveragePooling3D **[pooling.AveragePooling3D.0] input 4x4x4x2, pool_size=(2, 2, 2), strides=None, padding='valid', data_format='channels_last'**
data_in_shape = (4, 4, 4, 2) L = AveragePooling3D(pool_size=(2, 2, 2), strides=None, padding='valid', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(290) data_in...
in shape: (4, 4, 4, 2) in: [-0.453175, -0.475078, 0.486234, -0.949643, -0.349099, -0.837108, 0.933439, 0.167853, -0.995191, 0.459466, -0.788337, -0.120985, 0.06215, 0.138625, -0.102201, 0.976605, -0.591051, -0.592066, 0.469334, -0.435067, 0.621416, 0.817698, 0.790015, 0.485862, 0.469679, -0.611443, 0.582845, -0.503885...
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
**[pooling.AveragePooling3D.1] input 4x4x4x2, pool_size=(2, 2, 2), strides=(1, 1, 1), padding='valid', data_format='channels_last'**
data_in_shape = (4, 4, 4, 2) L = AveragePooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='valid', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(291) da...
in shape: (4, 4, 4, 2) in: [-0.803361, 0.348731, 0.30124, -0.168638, 0.516406, -0.258765, 0.297839, 0.993235, 0.958465, -0.273175, -0.704992, 0.261477, -0.301255, 0.263104, 0.678631, -0.644936, -0.029034, -0.320266, 0.307733, -0.479016, 0.608177, 0.034951, 0.456908, -0.929353, 0.594982, -0.243058, -0.524918, 0.455339,...
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
**[pooling.AveragePooling3D.2] input 4x5x2x3, pool_size=(2, 2, 2), strides=(2, 1, 1), padding='valid', data_format='channels_last'**
data_in_shape = (4, 5, 2, 3) L = AveragePooling3D(pool_size=(2, 2, 2), strides=(2, 1, 1), padding='valid', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(282) da...
in shape: (4, 5, 2, 3) in: [-0.263147, -0.216555, -0.75766, -0.396007, 0.85243, 0.98415, -0.230197, -0.979579, 0.117628, -0.66833, 0.714058, -0.907302, -0.574249, 0.299573, 0.101165, 0.655872, -0.104788, 0.242064, -0.409262, -0.124059, 0.105687, -0.969325, -0.167941, 0.382377, 0.710487, 0.793042, 0.180663, -0.80231, 0...
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
**[pooling.AveragePooling3D.3] input 4x4x4x2, pool_size=(3, 3, 3), strides=None, padding='valid', data_format='channels_last'**
data_in_shape = (4, 4, 4, 2) L = AveragePooling3D(pool_size=(3, 3, 3), strides=None, padding='valid', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(283) data_in...
in shape: (4, 4, 4, 2) in: [0.19483, -0.346754, 0.281648, -0.656271, 0.588328, 0.864284, -0.661556, 0.344578, 0.534692, 0.187914, -0.172976, 0.100575, 0.287857, 0.151936, 0.679748, 0.137527, 0.726773, -0.503042, -0.902524, -0.895315, 0.870645, 0.792427, -0.102238, -0.748643, -0.048728, -0.025835, 0.358631, 0.804295, -...
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
**[pooling.AveragePooling3D.4] input 4x4x4x2, pool_size=(3, 3, 3), strides=(3, 3, 3), padding='valid', data_format='channels_last'**
data_in_shape = (4, 4, 4, 2) L = AveragePooling3D(pool_size=(3, 3, 3), strides=(3, 3, 3), padding='valid', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(284) da...
in shape: (4, 4, 4, 2) in: [0.691755, -0.79282, -0.953135, 0.756956, -0.736874, 0.171061, -0.801845, 0.588236, -0.884749, 0.06721, -0.585121, -0.546211, -0.605281, -0.998989, 0.309413, -0.260604, -0.123585, 0.168908, -0.179496, 0.657412, -0.973664, 0.146258, -0.851615, -0.320588, 0.375102, -0.048494, 0.822789, 0.06357...
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
**[pooling.AveragePooling3D.5] input 4x4x4x2, pool_size=(2, 2, 2), strides=None, padding='same', data_format='channels_last'**
data_in_shape = (4, 4, 4, 2) L = AveragePooling3D(pool_size=(2, 2, 2), strides=None, padding='same', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(285) data_in ...
in shape: (4, 4, 4, 2) in: [-0.495196, -0.886872, 0.220815, 0.126844, 0.168234, -0.640849, 0.457897, -0.375014, 0.001134, -0.486501, -0.819617, -0.468351, 0.15859, 0.39238, -0.590545, -0.402922, 0.821619, -0.208255, -0.512219, -0.586151, -0.365648, -0.195611, -0.280978, -0.08818, -0.449229, 0.169082, 0.075074, -0.7197...
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
**[pooling.AveragePooling3D.6] input 4x4x4x2, pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same', data_format='channels_last'**
data_in_shape = (4, 4, 4, 2) L = AveragePooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(286) dat...
in shape: (4, 4, 4, 2) in: [-0.709952, -0.532913, -0.169956, -0.391538, 0.729034, -0.2004, -0.67324, -0.973672, 0.879975, -0.981827, -0.4828, -0.887985, 0.843364, 0.710745, -0.260613, 0.20082, 0.309563, 0.721671, -0.967848, -0.976471, -0.13058, 0.052684, 0.666494, -0.319759, -0.060338, 0.359151, -0.795562, 0.70488, 0....
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
**[pooling.AveragePooling3D.7] input 4x5x4x2, pool_size=(2, 2, 2), strides=(1, 2, 1), padding='same', data_format='channels_last'**
data_in_shape = (4, 5, 4, 2) L = AveragePooling3D(pool_size=(2, 2, 2), strides=(1, 2, 1), padding='same', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(287) dat...
in shape: (4, 5, 4, 2) in: [-0.71103, 0.421506, 0.752321, 0.542455, -0.557162, -0.963774, 0.910303, -0.933284, 0.67521, 0.588709, -0.782848, -0.108964, -0.767069, 0.338318, -0.660374, -0.967294, -0.501079, -0.917532, -0.087991, -0.160473, 0.520493, 0.612007, -0.955448, -0.809749, -0.627003, 0.494441, 0.985405, 0.99813...
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
**[pooling.AveragePooling3D.8] input 4x4x4x2, pool_size=(3, 3, 3), strides=None, padding='same', data_format='channels_last'**
data_in_shape = (4, 4, 4, 2) L = AveragePooling3D(pool_size=(3, 3, 3), strides=None, padding='same', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(288) data_in ...
in shape: (4, 4, 4, 2) in: [0.106539, 0.430065, 0.625063, -0.956042, 0.681684, 0.345995, -0.589061, 0.186737, 0.535452, -0.125905, -0.396262, -0.44893, 0.39021, 0.253402, -0.238515, 0.337141, 0.178107, 0.244331, -0.93179, -0.081267, 0.895223, 0.820023, 0.365435, -0.738456, 0.893031, -0.787916, -0.518813, 0.661518, -0....
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
**[pooling.AveragePooling3D.9] input 4x4x4x2, pool_size=(3, 3, 3), strides=(3, 3, 3), padding='same', data_format='channels_last'**
data_in_shape = (4, 4, 4, 2) L = AveragePooling3D(pool_size=(3, 3, 3), strides=(3, 3, 3), padding='same', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(289) dat...
in shape: (4, 4, 4, 2) in: [0.454263, 0.047178, -0.644362, 0.432654, 0.776147, -0.088086, -0.16527, -0.152361, -0.723283, 0.119471, -0.020663, 0.230897, 0.249349, -0.825224, 0.809245, 0.37136, 0.649976, 0.690981, -0.5766, 0.750394, -0.777363, -0.359006, 0.398419, -0.851015, -0.479232, -0.924962, -0.898893, 0.135445, 0...
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
**[pooling.AveragePooling3D.10] input 2x3x3x4, pool_size=(3, 3, 3), strides=(2, 2, 2), padding='valid', data_format='channels_first'**
data_in_shape = (2, 3, 3, 4) L = AveragePooling3D(pool_size=(3, 3, 3), strides=(2, 2, 2), padding='valid', data_format='channels_first') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(290) d...
in shape: (2, 3, 3, 4) in: [-0.453175, -0.475078, 0.486234, -0.949643, -0.349099, -0.837108, 0.933439, 0.167853, -0.995191, 0.459466, -0.788337, -0.120985, 0.06215, 0.138625, -0.102201, 0.976605, -0.591051, -0.592066, 0.469334, -0.435067, 0.621416, 0.817698, 0.790015, 0.485862, 0.469679, -0.611443, 0.582845, -0.503885...
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
**[pooling.AveragePooling3D.11] input 2x3x3x4, pool_size=(3, 3, 3), strides=(1, 1, 1), padding='same', data_format='channels_first'**
data_in_shape = (2, 3, 3, 4) L = AveragePooling3D(pool_size=(3, 3, 3), strides=(1, 1, 1), padding='same', data_format='channels_first') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(291) da...
in shape: (2, 3, 3, 4) in: [-0.803361, 0.348731, 0.30124, -0.168638, 0.516406, -0.258765, 0.297839, 0.993235, 0.958465, -0.273175, -0.704992, 0.261477, -0.301255, 0.263104, 0.678631, -0.644936, -0.029034, -0.320266, 0.307733, -0.479016, 0.608177, 0.034951, 0.456908, -0.929353, 0.594982, -0.243058, -0.524918, 0.455339,...
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
**[pooling.AveragePooling3D.12] input 3x4x4x3, pool_size=(2, 2, 2), strides=None, padding='valid', data_format='channels_first'**
data_in_shape = (3, 4, 4, 3) L = AveragePooling3D(pool_size=(2, 2, 2), strides=None, padding='valid', data_format='channels_first') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(292) data_i...
in shape: (3, 4, 4, 3) in: [-0.497409, -0.250345, 0.196124, -0.044334, -0.324906, 0.560065, 0.220435, -0.167776, -0.923771, 0.77337, -0.862909, -0.584756, -0.70451, 0.870272, 0.841773, -0.312016, 0.599915, 0.073955, 0.944336, -0.4175, 0.865698, 0.609184, 0.033839, -0.72494, -0.239473, 0.514968, -0.318523, -0.244443, 0...
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
export for Keras.js tests
print(json.dumps(DATA))
{"pooling.AveragePooling3D.0": {"input": {"data": [-0.453175, -0.475078, 0.486234, -0.949643, -0.349099, -0.837108, 0.933439, 0.167853, -0.995191, 0.459466, -0.788337, -0.120985, 0.06215, 0.138625, -0.102201, 0.976605, -0.591051, -0.592066, 0.469334, -0.435067, 0.621416, 0.817698, 0.790015, 0.485862, 0.469679, -0.61144...
MIT
notebooks/layers/pooling/AveragePooling3D.ipynb
GTDev87/tpt-hackathon
Debugging strategiesIn this notebook, we'll talk about what happens when you get an error message (it will happen often!) and some steps you can take to resolve them.Run the code in the next cell.
x = 10 if x > 20 print(f'{x} is greater than 20!')
_____no_output_____
MIT
reference/Debugging strategies.ipynb
ireapps/cfj-2018
The "traceback" message shows you a couple of useful things:- What line the error is on: `line 3`- The class of error: `SyntaxError` (v common)- Exactly _where_ the error occured -- see where the `^` symbol is pointing?What's the problem? GooglingIf it's not immediately clear what's wrong -- if you're not even sure wha...
staff = [ {'name': 'Fran', 'years_of_service': 2, 'job': 'Reporter'}, {'name': 'Graham', 'years_of_service': 7, 'job': 'Reporter'}, {'name': 'Pat', 'years_of_service': 4, 'job': 'Web Producer'}, {'name': 'John', 'years_of_service': '26', 'job': 'Managing Editor'}, {'name': 'Sue', 'years_of_service':...
_____no_output_____
MIT
reference/Debugging strategies.ipynb
ireapps/cfj-2018
We didn't get an exception, but something is _clearly_ wrong with John's bonus. What's going on?Maybe you spot the error already. If not, we might Google something like ["python multiply numbers repeating"](https://www.google.com/search?q=python+multiply+numbers+repeating) -- which leads us to [this StackOverflow answe...
for person in staff: name = person['name'] bonus = person['years_of_service'] * 50 print(name, type(person['years_of_service'])) print(f'{name} is getting a bonus of {bonus}')
_____no_output_____
MIT
reference/Debugging strategies.ipynb
ireapps/cfj-2018
Aha! John's value for `years_of_service` has been stored as a string, not an integer. Let's fix that by using the [`int()`](https://docs.python.org/3/library/functions.htmlint) function to coerce the value to an integer.
for person in staff: name = person['name'] bonus = int(person['years_of_service']) ** 2 print(f'{name} is getting a bonus of {bonus}')
_____no_output_____
MIT
reference/Debugging strategies.ipynb
ireapps/cfj-2018
Winner winner, chicken dinner.Here are some more debugging exercises for you to work through. See if you can figure out what's wrong and fix them.
print(Hello, Pittsburgh!) desk = { 'wood': 'fir', 'color': 'black', 'height_in': 36, 'width_in': 48, 'length_in': 68 } print(desk['drawer_count']) students = ['Kelly', 'Larry', 'José', 'Frank', 'Sarah', 'Sue'] for student in students: if student = 'Kelly': print('It's Kelly!') elif stu...
_____no_output_____
MIT
reference/Debugging strategies.ipynb
ireapps/cfj-2018
Make the Dataset
CA_x, CA_y = [], [] KS_x, KS_y = [], [] MT_x, MT_y = [], [] TX_x, TX_y = [], [] OH_x, OH_y = [], [] states = {"CA" : [CA_x, CA_y, "Roi_1"], "KS" : [KS_x, KS_y, "Roi_2"], "MT" : [MT_x, MT_y, "Roi_3"], "TX" : [TX_x, TX_y, "Roi_4"], "OH" : [OH_x, OH_y, "Roi_5"]}
_____no_output_____
MIT
Notebooks/GCN_cuda_Implement_speed.ipynb
oqbrady/Sentinel2_Traffic
Load into RAM
master_df = pd.read_csv("Sentinel2_Traffic/Traffic_Data/5_state_traffic.csv") master_df = master_df.set_index("Unnamed: 0") CA_x, CA_y = [], [] KS_x, KS_y = [], [] MT_x, MT_y = [], [] TX_x, TX_y = [], [] OH_x, OH_y = [], [] states = {"Cali" : [CA_x, CA_y, "Roi_1"], "KS" : [KS_x, KS_y, "Roi_2"], "MT" :...
_____no_output_____
MIT
Notebooks/GCN_cuda_Implement_speed.ipynb
oqbrady/Sentinel2_Traffic
Train the Model
# X = dataset[:][0] # y = dataset[:][1] print(dataset.state[0:37]) print(dataset.state[37:64]) print(dataset.state[64:88]) print(dataset.state[88:119]) print(dataset.state[119:124]) from dgl.dataloading import GraphDataLoader from torch.utils.data.sampler import SubsetRandomSampler from torch.utils.data import DataLoad...
_____no_output_____
MIT
Notebooks/GCN_cuda_Implement_speed.ipynb
oqbrady/Sentinel2_Traffic
Bi directional GRU encoder
class EncoderRNN(nn.Module): def __init__(self, hidden_size, embedding, n_layers=1, dropout=0): super(EncoderRNN, self).__init__() self.n_layers = n_layers self.hidden_size = hidden_size self.embedding = embedding self.gru = nn.GRU(hidden_size, hidden_size, n_layers, ...
_____no_output_____
Apache-2.0
ChatBot.ipynb
DEK11/Chatbot-RNN
Attention module
class Attn(torch.nn.Module): def __init__(self, method, hidden_size): super(Attn, self).__init__() self.method = method if self.method not in ['dot', 'general', 'concat']: raise ValueError(self.method, "is not an appropriate attention method.") self.hidden_size = hidden_s...
> Hi Bot: hi . > How are you? Bot: i m fine . > Are you in love? Bot: i m not . > What are you thinking? Bot: i m thinking of a little . > Do you watch movies? Bot: sure . > which is your favourite? Bot: the big one . > Okay, bye now! Bot: okay . > q
Apache-2.0
ChatBot.ipynb
DEK11/Chatbot-RNN
When can we start watching?---Henry Rachootin - December 2018MIT License: https://opensource.org/licenses/MIT---BitTorrent allows people to download movies without staying strictly within the confines of the law, but because of the peer to peer nature of the download, the file will not download sequentially. The VLC p...
# Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' import numpy as np from scipy.stats import poisson from math import ceil,exp,floor from thinkbayes2 impor...
_____no_output_____
MIT
examples/.ipynb_checkpoints/Greedy pirates-checkpoint.ipynb
sportsracer48/ThinkBayes2
First we will just define some values.Let's define $T$ to be the runtime of the movie in seconds and $N$ to be the number of 4 MB pieces in the movie. From these, we can define $t_p$, the runtime of a single 4 MB piece as $\frac{T}{N}$.
T = 149*60 #movie runtime in seconds N = ceil(12.91*1000/4) #number of 4MB pieces in the whole movie t_p = T/N #runtime of a single 4MB piece print(f"The runtime of a single piece is {t_p:.2f} seconds")
The runtime of a single piece is 2.77 seconds
MIT
examples/.ipynb_checkpoints/Greedy pirates-checkpoint.ipynb
sportsracer48/ThinkBayes2
Let's now consider where we are going with this calculation. When watching the movie, we need to have the next piece every 2.77 seconds. If we assume that each piece is equally likely to be downloaded, we can define a function $P_p(t)$ which tells us the probability of having a specific piece after $t$ seconds, and tha...
#wireshark dump data = pd.read_csv('torrent pieces.csv') #this finds the piece packets data = data[data.Info=="Piece[Malformed Packet]"] #extract the time each piece arrived at times = np.array(data.Time) #dump the initial times, they don't represent the long term behavior times = times[45:] interTimes = np.diff...
_____no_output_____
MIT
examples/.ipynb_checkpoints/Greedy pirates-checkpoint.ipynb
sportsracer48/ThinkBayes2
And we can implement all the functions we defined above:
def P_n(n,t,lam): """probability of having exactly n pieces at time t for rate lambda""" return poisson.pmf(n,lam*t) def P_p(t,n_0,lam): """probability of having a specific piece at time t for rate lambda""" #all the numbers of pieces there could be ns = np.array(range(n_0,N+1)) #the pro...
_____no_output_____
MIT
examples/.ipynb_checkpoints/Greedy pirates-checkpoint.ipynb
sportsracer48/ThinkBayes2
With those done, we can make our final $P(t,x)$ function, which will give us the probability of getting to time $t$ if we start at $x$ percent downloaded with our derived distribution for $\lambda$.
def PWatch(t,x): """Probability of getting to time t with initial download percentage x""" #intial piece number approximation n0 = floor(x*N/100) Ptot = 0 #law of total probability for l,p in lam.Items(): Ptot += p*P(t,n0,l) return Ptot
_____no_output_____
MIT
examples/.ipynb_checkpoints/Greedy pirates-checkpoint.ipynb
sportsracer48/ThinkBayes2
Unfortunately that function is prohibitively slow. We can speed it up quite a lot by improving our $P_p$ function to be less accurate but much faster. We will approximate it by$$P_p(t)=\frac{\min(\lambda t+n_0,N)}{N}$$which is just assuming that we get one piece every $\lambda$ seconds. This ignores the uncertanty of t...
def P_p_fast(t,n_0,lam): return min(lam*t+n_0,N)/N testLam = lam.Mean() ts = np.linspace(0,4000) ps = np.array([P_p(t,0,testLam) for t in ts]) psFast = np.array([P_p_fast(t,0,testLam) for t in ts]) thinkplot.plot(ts,ps,label='Correct') thinkplot.plot(ts,psFast,label='Fast') thinkplot.decorate(title='Probability of...
_____no_output_____
MIT
examples/.ipynb_checkpoints/Greedy pirates-checkpoint.ipynb
sportsracer48/ThinkBayes2
From the graph we can see that this is an ok approximation.With that done, we can start making graphs and answering the original question.
P_p = P_p_fast #use the fast function from now on ts = np.linspace(0,500) xs = [50,90,95,99] for x in xs: ps = [PWatch(t,x) for t in ts] thinkplot.plot(ts,ps,label=f'start at {x}%') thinkplot.decorate(title='Probability of getting to different times in the movie', xlabel='Time (s)', ...
_____no_output_____
MIT
examples/.ipynb_checkpoints/Greedy pirates-checkpoint.ipynb
sportsracer48/ThinkBayes2
That graph is zoomed in near the start of the movie, but here's what it looks like over the whole runtime:
ts = np.linspace(0,T) xs = [50,90,95,99] for x in xs: ps = [PWatch(t,x) for t in ts] thinkplot.plot(ts,ps,label=f'start at {x}%') thinkplot.decorate(title='Probability of getting to different times in the movie', xlabel='Time (s)', ylabel='Probability')
_____no_output_____
MIT
examples/.ipynb_checkpoints/Greedy pirates-checkpoint.ipynb
sportsracer48/ThinkBayes2
So we can see there is a definite falling off period, and after that we will probably finish the movie. With that in mind, we can ask what the probability of finishing the movie will be for different starting percentages.
xs = np.linspace(0,100) ps = [PWatch(T,x) for x in xs] thinkplot.plot(xs,ps) thinkplot.decorate(title='Probability of finishing movie', xlabel='Starting percent downloaded', ylabel='Probability of finishing movie')
_____no_output_____
MIT
examples/.ipynb_checkpoints/Greedy pirates-checkpoint.ipynb
sportsracer48/ThinkBayes2
Here's the nonzero portion of that graph:
xs = np.linspace(90,100) ps = [PWatch(T,x) for x in xs] thinkplot.plot(xs,ps) thinkplot.decorate(title='Probability of finishing movie', xlabel='Starting percent downloaded', ylabel='Probability of finishing movie')
_____no_output_____
MIT
examples/.ipynb_checkpoints/Greedy pirates-checkpoint.ipynb
sportsracer48/ThinkBayes2
Notebook para o PAN - Atribuição Autoral - 2018
%matplotlib inline #python basic libs from __future__ import print_function from tempfile import mkdtemp from shutil import rmtree import os; from os.path import join as pathjoin; import re; import glob; import json; import codecs; from collections import defaultdict; import pprint; from pprint import pprint from t...
Darwin-17.5.0-x86_64-i386-64bit NumPy 1.14.2 SciPy 1.0.1 Scikit-Learn 0.19.1 seaborn 0.8.1
Apache-2.0
2018/PAN_AA_2018-char-simplified.ipynb
jeleandro/PANAA2018
paths configuration
baseDir = '/Users/joseeleandrocustodio/Dropbox/mestrado/02 - Pesquisa/code'; inputDir= pathjoin(baseDir,'pan18aa'); outputDir= pathjoin(baseDir,'out',"oficial"); if not os.path.exists(outputDir): os.mkdir(outputDir);
_____no_output_____
Apache-2.0
2018/PAN_AA_2018-char-simplified.ipynb
jeleandro/PANAA2018
loading the dataset
def readCollectionsOfProblems(path): # Reading information about the collection infocollection = path+os.sep+'collection-info.json' with open(infocollection, 'r') as f: problems = [ { 'problem': attrib['problem-name'], 'language': attrib['language'], ...
_____no_output_____
Apache-2.0
2018/PAN_AA_2018-char-simplified.ipynb
jeleandro/PANAA2018
examinando o parametro min_df isoladamente
def runML(problem): print ("\nProblem: %s, language: %s, " %(problem['problem'],problem['language'])) train_docs, train_labels, _ = zip(*problem['candidates']) problem['training_docs_size'] = len(train_docs); test_docs, _, test_filename = zip(*problem['unknown']) pipeline = Pipeline([...
_____no_output_____
Apache-2.0
2018/PAN_AA_2018-char-simplified.ipynb
jeleandro/PANAA2018
analisando os demais parametros
def runML(problem): print ("\nProblem: %s, language: %s, " %(problem['problem'],problem['language'])) train_docs, train_labels, _ = zip(*problem['candidates']) problem['training_docs_size'] = len(train_docs); test_docs, _, test_filename = zip(*problem['unknown']) pipeline = Pipeline([...
\begin{table}[h] \centering \caption{Medida F1 para os parâmetros } \begin{tabular}{llllrrrr} \toprule & & & ngram\_range & (2, 3) & (2, 4) & (2, 5) & (3, 5) \\ problem & language & sublinear\_tf & norm & & & & \\ \midrule 1 & inglesa & False & l1 & 0.680 & 0.787 & 0.804 & 0.803 \\ & & & l2 & 0.670 & 0.760 & 0.715 & ...
Apache-2.0
2018/PAN_AA_2018-char-simplified.ipynb
jeleandro/PANAA2018
Example usageTo use `webtoon_data` in a project:
import webtoon_data print(webtoon_data.__version__)
_____no_output_____
MIT
docs/example.ipynb
ekimz/webtoons_data
Copyright 2018 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
site/en/2/tutorials/keras/save_and_restore_models.ipynb
allenlavoie/docs
Save and restore models View on TensorFlow.org Run in Google Colab View source on GitHub Model progress can be saved during—and after—training. This means a model can resume where it left off and avoid long training times. Saving also means you can share your model and others can recreate your wo...
!pip install h5py pyyaml
_____no_output_____
Apache-2.0
site/en/2/tutorials/keras/save_and_restore_models.ipynb
allenlavoie/docs
Get an example datasetWe'll use the [MNIST dataset](http://yann.lecun.com/exdb/mnist/) to train our model to demonstrate saving weights. To speed up these demonstration runs, only use the first 1000 examples:
from __future__ import absolute_import, division, print_function import os !pip install tf-nightly-2.0-preview import tensorflow as tf keras = tf.keras tf.__version__ (train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data() train_labels = train_labels[:1000] test_labels = test_...
_____no_output_____
Apache-2.0
site/en/2/tutorials/keras/save_and_restore_models.ipynb
allenlavoie/docs
Define a model Let's build a simple model we'll use to demonstrate saving and loading weights.
# Returns a short sequential model def create_model(): model = tf.keras.models.Sequential([ keras.layers.Dense(512, activation=tf.keras.activations.relu, input_shape=(784,)), keras.layers.Dropout(0.2), keras.layers.Dense(10, activation=tf.keras.activations.softmax) ]) model.compile(optimizer='adam'...
_____no_output_____
Apache-2.0
site/en/2/tutorials/keras/save_and_restore_models.ipynb
allenlavoie/docs
Save checkpoints during training The primary use case is to automatically save checkpoints *during* and at *the end* of training. This way you can use a trained model without having to retrain it, or pick-up training where you left of—in case the training process was interrupted.`tf.keras.callbacks.ModelCheckpoint` is...
checkpoint_path = "training_1/cp.ckpt" checkpoint_dir = os.path.dirname(checkpoint_path) # Create checkpoint callback cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, save_weights_only=True, verbose=1) ...
_____no_output_____
Apache-2.0
site/en/2/tutorials/keras/save_and_restore_models.ipynb
allenlavoie/docs
This creates a single collection of TensorFlow checkpoint files that are updated at the end of each epoch:
!ls {checkpoint_dir}
_____no_output_____
Apache-2.0
site/en/2/tutorials/keras/save_and_restore_models.ipynb
allenlavoie/docs
Create a new, untrained model. When restoring a model from only weights, you must have a model with the same architecture as the original model. Since it's the same model architecture, we can share weights despite that it's a different *instance* of the model.Now rebuild a fresh, untrained model, and evaluate it on the...
model = create_model() loss, acc = model.evaluate(test_images, test_labels) print("Untrained model, accuracy: {:5.2f}%".format(100*acc))
_____no_output_____
Apache-2.0
site/en/2/tutorials/keras/save_and_restore_models.ipynb
allenlavoie/docs
Then load the weights from the checkpoint, and re-evaluate:
model.load_weights(checkpoint_path) loss,acc = model.evaluate(test_images, test_labels) print("Restored model, accuracy: {:5.2f}%".format(100*acc))
_____no_output_____
Apache-2.0
site/en/2/tutorials/keras/save_and_restore_models.ipynb
allenlavoie/docs