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
Exercise 1. Get a better fit to the data (create a better model & fit it) - try using different optimizers in scipy.optimize
arr = np.arange(100) arr[10:50] arr[slice(10,50)]
_____no_output_____
BSD-3-Clause
notebooks/MarchApril2016_TutorialSession/Notebook - March 18 - Part 1.ipynb
ESO-python/ESOPythonTutorials
Cloning the pyprobml repo
!git clone https://github.com/probml/pyprobml %cd pyprobml/scripts
_____no_output_____
MIT
notebooks/figures/chapter16_figures.ipynb
kzymgch/pyprobml
Installing required software (This may take few minutes)
!apt-get install octave -qq > /dev/null !apt-get install liboctave-dev -qq > /dev/null %%capture %load_ext autoreload %autoreload 2 DISCLAIMER = 'WARNING : Editing in VM - changes lost after reboot!!' from google.colab import files def interactive_script(script, i=True): if i: s = open(script).read() if no...
_____no_output_____
MIT
notebooks/figures/chapter16_figures.ipynb
kzymgch/pyprobml
Figure 16.1: (a) Illustration of a $K$-nearest neighbors classifier in 2d for $K=5$. The nearest neighbors of test point $\mathbf x $ have labels $\ 1, 1, 1, 0, 0\ $, so we predict $p(y=1|\mathbf x , \mathcal D ) = 3/5$. (b) Illustration of the Voronoi tesselation induced by 1-NN. Adapted from Figure 4.13 of [...
interactive_script("knn_voronoi_plot.py")
_____no_output_____
MIT
notebooks/figures/chapter16_figures.ipynb
kzymgch/pyprobml
Figure 16.2: Decision boundaries induced by a KNN classifier. (a) $K=1$. (b) $K=2$. (c) $K=5$. (d) Train and test error vs $K$. Figure(s) generated by [knn_classify_demo.py](https://github.com/probml/pyprobml/blob/master/scripts/knn_classify_demo.py)
interactive_script("knn_classify_demo.py")
_____no_output_____
MIT
notebooks/figures/chapter16_figures.ipynb
kzymgch/pyprobml
Figure 16.3: Illustration of the curse of dimensionality. (a) We embed a small cube of side $s$ inside a larger unit cube. (b) We plot the edge length of a cube needed to cover a given volume of the unit cube as a function of the number of dimensions. Adapted from Figure 2.6 from [HTF09] . Figure(s) generated by ...
interactive_script("curse_dimensionality.py")
_____no_output_____
MIT
notebooks/figures/chapter16_figures.ipynb
kzymgch/pyprobml
Figure 16.4: Illustration of latent coincidence analysis (LCA) as a directed graphical model. The inputs $\mathbf x , \mathbf x ' \in \mathbb R ^D$ are mapped into Gaussian latent variables $\mathbf z , \mathbf z ' \in \mathbb R ^L$ via a linear mapping $\mathbf W $. If the two latent points coincide (withi...
show_image("/content/pyprobml/notebooks/figures/images/LCA-PGM.png")
_____no_output_____
MIT
notebooks/figures/chapter16_figures.ipynb
kzymgch/pyprobml
Figure 16.5: Networks for deep metric learning. (a) Siamese network. (b) Triplet network. From Figure 5 of [MH19] . Used with kind permission of Mahmut Kaya. .
show_image("/content/pyprobml/notebooks/figures/images/siameseNet.png") show_image("/content/pyprobml/notebooks/figures/images/tripletNet.png")
_____no_output_____
MIT
notebooks/figures/chapter16_figures.ipynb
kzymgch/pyprobml
Figure 16.6: Speeding up triplet loss minimization. (a) Illustration of hard vs easy negatives. Here $a$ is the anchor point, $p$ is a positive point, and $n_i$ are negative points. Adapted from Figure 4 of [MH19] . (b) Standard triplet loss would take $8 \times 3 \times 4 = 96$ calculations, whereas using a proxy...
show_image("/content/pyprobml/notebooks/figures/images/hard-negative-mining.png") show_image("/content/pyprobml/notebooks/figures/images/tripletBound.png")
_____no_output_____
MIT
notebooks/figures/chapter16_figures.ipynb
kzymgch/pyprobml
Figure 16.7: Adding spherical embedding constraint to a deep metric learning method. Used with kind permission of Dingyi Zhang.
show_image("/content/pyprobml/notebooks/figures/images/SEC.png")
_____no_output_____
MIT
notebooks/figures/chapter16_figures.ipynb
kzymgch/pyprobml
Figure 16.8: A comparison of some popular normalized kernels. Figure(s) generated by [smoothingKernelPlot.m](https://github.com/probml/pmtk3/blob/master/demos/smoothingKernelPlot.m)
!octave -W smoothingKernelPlot.m >> _
_____no_output_____
MIT
notebooks/figures/chapter16_figures.ipynb
kzymgch/pyprobml
Figure 16.9: A nonparametric (Parzen) density estimator in 1d estimated from 6 data points, denoted by x. Top row: uniform kernel. Bottom row: Gaussian kernel. Left column: bandwidth parameter $h=1$. Right column: bandwidth parameter $h=2$. Adapted from http://en.wikipedia.org/wiki/Kernel_density_estimation . F...
interactive_script("parzen_window_demo2.py")
_____no_output_____
MIT
notebooks/figures/chapter16_figures.ipynb
kzymgch/pyprobml
Figure 16.10: An example of kernel regression in 1d using a Gaussian kernel. Figure(s) generated by [kernelRegressionDemo.m](https://github.com/probml/pmtk3/blob/master/demos/kernelRegressionDemo.m)
!octave -W kernelRegressionDemo.m >> _
_____no_output_____
MIT
notebooks/figures/chapter16_figures.ipynb
kzymgch/pyprobml
Подключаем необходимые библиотеки
import os import datetime import numpy as np import pandas as pd from sqlalchemy import create_engine
_____no_output_____
MIT
project1_sql/scripts/requests.ipynb
mikhailbadin/ds_couse_homeworks
Настраиваем подключение к БД
engine = create_engine("postgresql://postgres:@{}:{}".format(os.environ["POSGRES_HOST"], os.environ['POSGRES_PORT']))
_____no_output_____
MIT
project1_sql/scripts/requests.ipynb
mikhailbadin/ds_couse_homeworks
Запрос 2: Подсчитать общее количест получателей
emailreceivers = pd.read_sql("select * from emailreceivers", engine) req2_result = emailreceivers["personid"].drop_duplicates().count() print(req2_result) pd.DataFrame( [req2_result], columns=['count']).to_csv(os.environ['PANDAS_EXPORT_FOLDER'] + 'req2.csv')
418
MIT
project1_sql/scripts/requests.ipynb
mikhailbadin/ds_couse_homeworks
Запрос 3: Подсчитать количество отправленных писем за 2012
emails = pd.read_sql("select * from emails", engine) req3_result = emails[ (emails["metadatadatesent"] >= np.datetime64('2012-01-01')) & (emails["metadatadatesent"] < np.datetime64('2013-01-01')) ]["id"].count() print(req3_result) pd.DataFrame( [req3_result], columns=['emails']).to_csv(os.environ['PAND...
1500
MIT
project1_sql/scripts/requests.ipynb
mikhailbadin/ds_couse_homeworks
Запрос 5:Вывести список писем в следующем формате:Отправитель письма, получатель письма, тема письма,и отсортированы по теме письма.
emails = pd.read_sql("select * from emails", engine) req5_df = emails[ ["metadatafrom", "metadatato", "metadatasubject"] ].sort_values(by=["metadatasubject"]) print(req5_df.head()) req5_df.head().to_csv(os.environ['PANDAS_EXPORT_FOLDER'] + 'req5.csv')
metadatafrom metadatato metadatasubject 35711 Mills, Cheryl D H - MORE WHEN WE SPEAK 3951 Mills, Cheryl D H - MORE WHEN WE SPEAK 1528 hrod17@clintonemail.com millscd@state.gov - MORE WHEN WE SPEAK 17504 hrod17@clintonemail.c...
MIT
project1_sql/scripts/requests.ipynb
mikhailbadin/ds_couse_homeworks
Запрос 6:Вывести среднюю длинну сообщения
emails = pd.read_sql("select * from emails", engine) req6_result = emails["extractedbodytext"].str.len().mean() print(req6_result) pd.DataFrame( [req6_result], columns=['avg']).to_csv(os.environ['PANDAS_EXPORT_FOLDER'] + 'req6.csv')
533.1624147137348
MIT
project1_sql/scripts/requests.ipynb
mikhailbadin/ds_couse_homeworks
Запрос 7:Вывести количество писем, в которых содержится подстрока UNCLASSIFIED
emails = pd.read_sql("select * from emails", engine) req7_result = emails[ emails["extractedbodytext"].str.contains("UNCLASSIFIED") == True ]["extractedbodytext"].count() print(req7_result) pd.DataFrame( [req7_result], columns=['text']).to_csv(os.environ['PANDAS_EXPORT_FOLDER'] + 'req7.csv')
78
MIT
project1_sql/scripts/requests.ipynb
mikhailbadin/ds_couse_homeworks
20 Jan
import pandas as pd import numpy as np tips = pd.read_csv("/Users/amitkumarsahu/Desktop/pandas/tips.csv") tips tips.pivot_table(index=["day", "smoker"]) tips["tip_pct"]=tips["tip"]*100/tips["total_bill"] tips[:6] tips.pivot_table(["tip_pct", "size"], index=["time", "day"], columns="smoker")
_____no_output_____
CC-BY-3.0
Pivot_table and crosstab.ipynb
priyankakushi/machine-learning
21 Jan
tips.pivot_table(["tip_pct", "size"], index=["time", "day"], columns="smoker", margins=True) tips.pivot_table("tip", index=["time", "smoker"], columns="day", aggfunc=len, margins=True) tips.pivot_table("tip_pct", index=["time", "size", "smoker"], columns="day", aggfunc="mean", fill_value=0) from io impo...
_____no_output_____
CC-BY-3.0
Pivot_table and crosstab.ipynb
priyankakushi/machine-learning
OverviewAnother data type that we haven't discussed yet is the list. Lists store values for us, and we can access these values using indices, or by knowing where an element is located to access it. Questions- How can I store multiple values? Objectives- Explain why programs need collections of values.- Write programs...
pressures = [0.273, 0.275, 0.277, 0.276] print(pressures[0]) print("pressures", pressures) print("length:", len(pressures))
pressures [0.273, 0.275, 0.277, 0.276] length: 4
MIT
lessonNotebooks/1.11 Lists.ipynb
crowegian/SummerFellowsDBMIWorkshopMaterials
Use an item’s index to fetch it from a list.
print("Zeroth item:", pressures[0]) print("fourth item:", pressures[3])
Zeroth item: 0.273 fourth item: 0.276
MIT
lessonNotebooks/1.11 Lists.ipynb
crowegian/SummerFellowsDBMIWorkshopMaterials
Lists’ values can be replaced by assigning to them.
print(pressures) pressures[0] = 0.265 print("current pressures", pressures)
current pressures [0.265, 0.275, 0.277, 0.276]
MIT
lessonNotebooks/1.11 Lists.ipynb
crowegian/SummerFellowsDBMIWorkshopMaterials
Appending items to a list lengthens it.
primes = [2, 3, 5] print("current primes", primes) primes.append(7) primes.append(9) print("primes has become", primes) primes = primes.append(13) print(primes) teen_primes = [11, 13, 17, 19] middle_aged_primes = [37, 41, 43, 47] print("primes is currently", primes) primes.extend(teen_primes) print("primes is now", pri...
primes is currently [2, 3, 5, 7, 9] primes is now [2, 3, 5, 7, 9, 11, 13, 17, 19]
MIT
lessonNotebooks/1.11 Lists.ipynb
crowegian/SummerFellowsDBMIWorkshopMaterials
Use del to remove items from a list entirely.
primes = [2, 3, 5, 7, 9] print("current primes", primes) del primes[2] print("primes now", primes)
current primes [2, 3, 5, 7, 9] primes now [2, 3, 7, 9]
MIT
lessonNotebooks/1.11 Lists.ipynb
crowegian/SummerFellowsDBMIWorkshopMaterials
Lists may contain values of different types.
goals = [1, "create lists.", 2, "extract items from lists", 3, "modify lists"] goals
_____no_output_____
MIT
lessonNotebooks/1.11 Lists.ipynb
crowegian/SummerFellowsDBMIWorkshopMaterials
Character strings can be indexed like lists.
element = "carbon" print(element[0])
c
MIT
lessonNotebooks/1.11 Lists.ipynb
crowegian/SummerFellowsDBMIWorkshopMaterials
Character strings are immutable.
print(element) element[0] = "C" print(element)
carbon
MIT
lessonNotebooks/1.11 Lists.ipynb
crowegian/SummerFellowsDBMIWorkshopMaterials
Indexing beyond the end of the collection is an error.
print("99th element of element is:", element[99]) primes = [2, 3, 7, 9] primes.remove(7) primes del primes[0] primes
_____no_output_____
MIT
lessonNotebooks/1.11 Lists.ipynb
crowegian/SummerFellowsDBMIWorkshopMaterials
Inference and ValidationNow that you have a trained network, you can use it for making predictions. This is typically called **inference**, a term borrowed from statistics. However, neural networks have a tendency to perform *too well* on the training data and aren't able to generalize to data that hasn't been seen be...
import torch from torchvision import datasets, transforms # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) # Download and load the training data trainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_d...
_____no_output_____
Apache-2.0
01_introduction/5_Inference_and_Validation.ipynb
thearonn/dtu_mlops
Here I'll create a model like normal, using the same one from my solution for part 4.
from torch import nn, optim import torch.nn.functional as F class Classifier(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 256) self.fc2 = nn.Linear(256, 128) self.fc3 = nn.Linear(128, 64) self.fc4 = nn.Linear(64, 10) def forward(s...
_____no_output_____
Apache-2.0
01_introduction/5_Inference_and_Validation.ipynb
thearonn/dtu_mlops
The goal of validation is to measure the model's performance on data that isn't part of the training set. Performance here is up to the developer to define though. Typically this is just accuracy, the percentage of classes the network predicted correctly. Other options are [precision and recall](https://en.wikipedia.or...
model = Classifier() images, labels = next(iter(testloader)) # Get the class probabilities ps = torch.exp(model(images)) # Make sure the shape is appropriate, we should get 10 class probabilities for 64 examples print(ps.shape)
torch.Size([64, 10])
Apache-2.0
01_introduction/5_Inference_and_Validation.ipynb
thearonn/dtu_mlops
With the probabilities, we can get the most likely class using the `ps.topk` method. This returns the $k$ highest values. Since we just want the most likely class, we can use `ps.topk(1)`. This returns a tuple of the top-$k$ values and the top-$k$ indices. If the highest value is the fifth element, we'll get back 4 as ...
top_p, top_class = ps.topk(1, dim=1) # Look at the most likely classes for the first 10 examples print(top_class[:10,:])
tensor([[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]])
Apache-2.0
01_introduction/5_Inference_and_Validation.ipynb
thearonn/dtu_mlops
Now we can check if the predicted classes match the labels. This is simple to do by equating `top_class` and `labels`, but we have to be careful of the shapes. Here `top_class` is a 2D tensor with shape `(64, 1)` while `labels` is 1D with shape `(64)`. To get the equality to work out the way we want, `top_class` and `l...
equals = top_class == labels.view(*top_class.shape) #print(equals)
_____no_output_____
Apache-2.0
01_introduction/5_Inference_and_Validation.ipynb
thearonn/dtu_mlops
Now we need to calculate the percentage of correct predictions. `equals` has binary values, either 0 or 1. This means that if we just sum up all the values and divide by the number of values, we get the percentage of correct predictions. This is the same operation as taking the mean, so we can get the accuracy with a c...
accuracy = torch.mean(equals.type(torch.FloatTensor)) print(f'Accuracy: {accuracy.item()*100}%')
Accuracy: 10.9375%
Apache-2.0
01_introduction/5_Inference_and_Validation.ipynb
thearonn/dtu_mlops
The network is untrained so it's making random guesses and we should see an accuracy around 10%. Now let's train our network and include our validation pass so we can measure how well the network is performing on the test set. Since we're not updating our parameters in the validation pass, we can speed up our code by t...
model = Classifier() criterion = nn.NLLLoss() optimizer = optim.Adam(model.parameters(), lr=0.003) epochs = 30 steps = 0 train_losses, test_losses = [], [] for e in range(epochs): running_loss = 0 for images, labels in trainloader: optimizer.zero_grad() log_ps = model(images)...
racy: 82.8125% Accuracy: 85.9375% Accuracy: 75.0% Accuracy: 90.625% Accuracy: 89.0625% Accuracy: 93.75% Accuracy: 82.8125% Accuracy: 79.6875% Accuracy: 79.6875% Accuracy: 82.8125% Accuracy: 89.0625% Accuracy: 87.5% Accuracy: 90.625% Accuracy: 85.9375% Accuracy: 89.0625% Accuracy: 84.375% Accuracy: 92.1875% Accuracy: 82...
Apache-2.0
01_introduction/5_Inference_and_Validation.ipynb
thearonn/dtu_mlops
OverfittingIf we look at the training and validation losses as we train the network, we can see a phenomenon known as overfitting.The network learns the training set better and better, resulting in lower training losses. However, it starts having problems generalizing to data outside the training set leading to the va...
from torch import nn, optim import torch.nn.functional as F class Classifier2(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 256) self.fc2 = nn.Linear(256, 128) self.fc3 = nn.Linear(128, 64) self.fc4 = nn.Linear(64, 10) self.dropout = n...
_____no_output_____
Apache-2.0
01_introduction/5_Inference_and_Validation.ipynb
thearonn/dtu_mlops
InferenceNow that the model is trained, we can use it for inference. We've done this before, but now we need to remember to set the model in inference mode with `model.eval()`. You'll also want to turn off autograd with the `torch.no_grad()` context.
# Import helper module (should be in the repo) import helper # Test out your network! model.eval() dataiter = iter(testloader) images, labels = dataiter.next() img = images[0] # Convert 2D image to 1D vector img = img.view(1, 784) # Calculate the class probabilities (softmax) for img with torch.no_grad(): outpu...
_____no_output_____
Apache-2.0
01_introduction/5_Inference_and_Validation.ipynb
thearonn/dtu_mlops
TimeEval shared parameter optimization result analysis
# Automatically reload packages: %load_ext autoreload %autoreload 2 # imports import json import warnings import pandas as pd import numpy as np import scipy as sp import plotly.offline as py import plotly.graph_objects as go import plotly.figure_factory as ff import plotly.express as px from plotly.subplots import mak...
_____no_output_____
MIT
notebooks/TimeEval shared param optimization analysis 2.ipynb
HPI-Information-Systems/TimeEval
ConfigurationTarget parameters that were optimized in this run (per algorithm):
algo_param_mapping = { "HBOS": ["n_bins"], "MultiHMM": ["n_bins"], "MTAD-GAT": ["context_window_size", "mag_window_size", "score_window_size"], "PST": ["n_bins"] }
_____no_output_____
MIT
notebooks/TimeEval shared param optimization analysis 2.ipynb
HPI-Information-Systems/TimeEval
Define data and results folder:
# constants and configuration data_path = Path("../../data") / "test-cases" result_root_path = Path("../timeeval_experiments/results") experiment_result_folder = "2021-10-04_shared-optim2" # build paths result_paths = [d for d in result_root_path.iterdir() if d.is_dir()] print("Available result directories:") display(...
Available result directories:
MIT
notebooks/TimeEval shared param optimization analysis 2.ipynb
HPI-Information-Systems/TimeEval
Load results and dataset metadata:
def extract_hyper_params(param_names): def extract(value): params = json.loads(value) result = None for name in param_names: try: value = params[name] result = pd.Series([name, value], index=["optim_param_name", "optim_param_value"]) ...
Reading results from /home/sebastian/Documents/Projects/akita/timeeval/timeeval_experiments/results/2021-10-04_shared-optim2
MIT
notebooks/TimeEval shared param optimization analysis 2.ipynb
HPI-Information-Systems/TimeEval
Define plotting functions:
def load_scores_df(algorithm_name, dataset_id, optim_params, repetition=1): params_id = df.loc[(df["algorithm"] == algorithm_name) & (df["collection"] == dataset_id[0]) & (df["dataset"] == dataset_id[1]) & (df["optim_param_name"] == optim_params[0]) & (df["optim_param_value"] == optim_params[1]), "hyper_params_id"]...
_____no_output_____
MIT
notebooks/TimeEval shared param optimization analysis 2.ipynb
HPI-Information-Systems/TimeEval
Analyze TimeEval results
df[["algorithm", "dataset_name", "status", "AVERAGE_PRECISION", "PR_AUC", "RANGE_PR_AUC", "ROC_AUC", "execute_main_time", "optim_param_name", "optim_param_value"]]
_____no_output_____
MIT
notebooks/TimeEval shared param optimization analysis 2.ipynb
HPI-Information-Systems/TimeEval
--- Errors
df_error_counts = df.pivot_table(index=["algo_training_type", "algorithm"], columns=["status"], values="repetition", aggfunc="count") df_error_counts = df_error_counts.fillna(value=0).astype(np.int64)
_____no_output_____
MIT
notebooks/TimeEval shared param optimization analysis 2.ipynb
HPI-Information-Systems/TimeEval
Aggregation of errors per algorithm grouped by algorithm training type
for tpe in ["SEMI_SUPERVISED", "SUPERVISED", "UNSUPERVISED"]: if tpe in df_error_counts.index: print(tpe) display(df_error_counts.loc[tpe])
SEMI_SUPERVISED
MIT
notebooks/TimeEval shared param optimization analysis 2.ipynb
HPI-Information-Systems/TimeEval
Slow algorithmsAlgorithms, for which more than 50% of all executions ran into the timeout.
df_error_counts[df_error_counts["Status.TIMEOUT"] > (df_error_counts["Status.ERROR"] + df_error_counts["Status.OK"])]
_____no_output_____
MIT
notebooks/TimeEval shared param optimization analysis 2.ipynb
HPI-Information-Systems/TimeEval
Broken algorithmsAlgorithms, which failed for at least 50% of the executions.
error_threshold = 0.5 df_error_counts[df_error_counts["Status.ERROR"] > error_threshold*( df_error_counts["Status.TIMEOUT"] + df_error_counts["Status.ERROR"] + df_error_counts["Status.OK"] )]
_____no_output_____
MIT
notebooks/TimeEval shared param optimization analysis 2.ipynb
HPI-Information-Systems/TimeEval
Detail errors
algo_list = ["MTAD-GAT", "MultiHMM"] error_list = ["OOM", "Segfault", "ZeroDivisionError", "IncompatibleParameterConfig", "WrongDBNState", "SyntaxError", "other"] errors = pd.DataFrame(0, index=error_list, columns=algo_list, dtype=np.int_) for algo in algo_list: df_tmp = df[(df["algorithm"] == algo) & (df["status"...
_____no_output_____
MIT
notebooks/TimeEval shared param optimization analysis 2.ipynb
HPI-Information-Systems/TimeEval
--- Parameter assessment
sort_by = ("ROC_AUC", "mean") metric_agg_type = ["mean", "median"] time_agg_type = "mean" aggs = { "AVERAGE_PRECISION": metric_agg_type, "RANGE_PR_AUC": metric_agg_type, "PR_AUC": metric_agg_type, "ROC_AUC": metric_agg_type, "train_main_time": time_agg_type, "execute_main_time": time_agg_type, ...
_____no_output_____
MIT
notebooks/TimeEval shared param optimization analysis 2.ipynb
HPI-Information-Systems/TimeEval
Selected parameters- HBOS: `n_bins=20` (more is better)- MultiHMM: `n_bins=5` (8 is slightly better, but takes way longer. The scores are very bad anyway!)- MTAD-GAT: `context_window_size=30,mag_window_size=40,score_window_size=52` (very slow)- PST: `n_bins=5` (less is better)> **Note**>> MTAD-GAT is very slow! Exclud...
plot_scores([("MultiHMM", "n_bins", 5), ("MultiHMM", "n_bins", 8)], "sinus-type-mean") plot_scores([("MTAD-GAT", "context_window_size", 30), ("MTAD-GAT", "context_window_size", 40)], "sinus-type-mean")
_____no_output_____
MIT
notebooks/TimeEval shared param optimization analysis 2.ipynb
HPI-Information-Systems/TimeEval
Tacotron 2 inference code Edit the variables **checkpoint_path** and **text** to match yours and run the entire code to generate plots of mel outputs, alignments and audio synthesis from the generated mel-spectrogram using Griffin-Lim. Import libraries and setup matplotlib
import matplotlib %matplotlib inline import matplotlib.pylab as plt import IPython.display as ipd import sys sys.path.append('waveglow/') import numpy as np import torch from hparams import create_hparams from model import Tacotron2 from layers import TacotronSTFT, STFT from audio_processing import griffin_lim from...
_____no_output_____
BSD-3-Clause
inference.ipynb
ncantrell/tacotron2
Setup hparams
hparams = create_hparams() hparams.sampling_rate = 22050
WARNING: The TensorFlow contrib module will not be included in TensorFlow 2.0. For more information, please see: * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md * https://github.com/tensorflow/addons If you depend on functionality not listed there, please file an issue.
BSD-3-Clause
inference.ipynb
ncantrell/tacotron2
Load model from checkpoint
checkpoint_path = "tacotron2_statedict.pt" model = load_model(hparams) model.load_state_dict(torch.load(checkpoint_path)['state_dict']) _ = model.cuda().eval().half()
_____no_output_____
BSD-3-Clause
inference.ipynb
ncantrell/tacotron2
Load WaveGlow for mel2audio synthesis and denoiser
waveglow_path = 'waveglow_256channels.pt' waveglow = torch.load(waveglow_path)['model'] waveglow.cuda().eval().half() for m in waveglow.modules(): if 'Conv' in str(type(m)): setattr(m, 'padding_mode', 'zeros') for k in waveglow.convinv: k.float() denoiser = Denoiser(waveglow)
/home/kabakov/VOICE/venv/lib/python3.6/site-packages/torch/serialization.py:454: SourceChangeWarning: source code of class 'torch.nn.modules.conv.ConvTranspose1d' has changed. you can retrieve the original source code by accessing the object's source attribute or set `torch.nn.Module.dump_patches = True` and use the pa...
BSD-3-Clause
inference.ipynb
ncantrell/tacotron2
Prepare text input
#%%timeit 77.9 µs ± 237 ns text = "Waveglow is really awesome!" sequence = np.array(text_to_sequence(text, ['english_cleaners']))[None, :] sequence = torch.autograd.Variable( torch.from_numpy(sequence)).cuda().long()
_____no_output_____
BSD-3-Clause
inference.ipynb
ncantrell/tacotron2
Decode text input and plot results
#%%timeit 240 ms ± 9.72 ms mel_outputs, mel_outputs_postnet, _, alignments = model.inference(sequence) plot_data((mel_outputs.float().data.cpu().numpy()[0], mel_outputs_postnet.float().data.cpu().numpy()[0], alignments.float().data.cpu().numpy()[0].T))
_____no_output_____
BSD-3-Clause
inference.ipynb
ncantrell/tacotron2
Synthesize audio from spectrogram using WaveGlow
#%%timeit 193 ms ± 4.87 ms with torch.no_grad(): audio = waveglow.infer(mel_outputs_postnet, sigma=0.666) ipd.Audio(audio[0].data.cpu().numpy(), rate=hparams.sampling_rate)
waveglow/glow.py:162: RuntimeWarning: nn.functional.tanh is deprecated. Use torch.tanh instead. torch.IntTensor([self.n_channels])) waveglow/glow.py:162: RuntimeWarning: nn.functional.sigmoid is deprecated. Use torch.sigmoid instead. torch.IntTensor([self.n_channels]))
BSD-3-Clause
inference.ipynb
ncantrell/tacotron2
(Optional) Remove WaveGlow bias
audio_denoised = denoiser(audio, strength=0.01)[:, 0] ipd.Audio(audio_denoised.cpu().numpy(), rate=hparams.sampling_rate)
_____no_output_____
BSD-3-Clause
inference.ipynb
ncantrell/tacotron2
Save result as wav
import librosa # save librosa.output.write_wav('./out.wav', audio[0].data.cpu().numpy().astype(np.float32), 22050) # check y, sr = librosa.load('out.wav') ipd.Audio(y, rate=sr)
_____no_output_____
BSD-3-Clause
inference.ipynb
ncantrell/tacotron2
Table of Contents1&nbsp;&nbsp;label identity hairstyle2&nbsp;&nbsp;Prepare hairstyle images3&nbsp;&nbsp;prepare hairstyle manifest
from query.models import Video, FaceIdentity, Identity from esper.widget import * from esper.prelude import collect, esper_widget import pickle import os import random get_ipython().magic('matplotlib inline') get_ipython().magic('reload_ext autoreload') get_ipython().magic('autoreload 2')
_____no_output_____
Apache-2.0
app/notebooks/hairstyle.ipynb
scanner-research/esper-tv
label identity hairstyle
identity_hair_dict = {} identities = Identity.objects.all() identity_list = [(i.id, i.name) for i in identities] identity_list.sort() # 154 hair_color_3 = {0: 'black', 1: 'white', 2: 'blond'} hair_color_5 = {0: 'black', 1: 'white', 2: 'blond', 3: 'brown', 4: 'gray'} hair_length = {0: 'long', 1: 'medium', 2: 'short', 3:...
_____no_output_____
Apache-2.0
app/notebooks/hairstyle.ipynb
scanner-research/esper-tv
Prepare hairstyle images
faceIdentities = FaceIdentity.objects \ .filter(identity__name='melania trump') \ .filter(probability__gt=0.9) \ .select_related('face__frame__video') faceIdentities_sampled = random.sample(list(faceIdentities), 1000) print("Load %d face identities" % len(faceIdentities_sampled)) identity_grouped = collect(...
_____no_output_____
Apache-2.0
app/notebooks/hairstyle.ipynb
scanner-research/esper-tv
prepare hairstyle manifest
img_list = os.listdir('/app/result/clothing/images/') len(img_list) group_by_identity = {} for name in img_list: iid = int(name.split('_')[0]) if iid not in group_by_identity: group_by_identity[iid] = [] else: group_by_identity[iid].append(name) identity_label = [id for id, img_list in group...
_____no_output_____
Apache-2.0
app/notebooks/hairstyle.ipynb
scanner-research/esper-tv
loading dataset
data = pd.read_csv("student-data.csv") data.head() data.shape type(data)
_____no_output_____
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
Exploratory data analysis
import matplotlib.pyplot as plt import seaborn as sns a = data.plot() data.info() data.isnull().sum() a = sns.heatmap(data.isnull(),cmap='Blues') a = sns.heatmap(data.isnull(),cmap='Blues',yticklabels=False)
_____no_output_____
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
this indicates that we have no any null values in the dataset
a = sns.heatmap(data.isna(),yticklabels=False)
_____no_output_____
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
this heatmap indicates that we have no any 'NA' values in the dataset
sns.set(style='darkgrid') sns.countplot(data=data,x='reason')
_____no_output_____
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
This indicates the count for choosing school of various reasons.A count plot can be thought of as a histogram across a categorical, instead of quantitative, variable.
data.head(7)
_____no_output_____
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
calculating total passed students
passed = data.loc[data.passed == 'yes'] passed.shape tot_passed=passed.shape[0] print('total passed students is: {} '.format(tot_passed))
total passed students is: 265
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
calculating total failed students
failed = data.loc[data.passed == 'no'] print('total failed students is: {}'.format(failed.shape[0]))
total failed students is: 130
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
Feature Engineering
data.head()
_____no_output_____
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
To identity feature and target variable lets first do some feature engineering stuff!
data.columns data.columns[-1]
_____no_output_____
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
Here 'passed' is our target variable. Since in this system we need to develop the model that will predict the likelihood that a given student will pass, quantifying whether an intervention is necessary.
target = data.columns[-1] data.columns[:-1] #initially taking all columns as our feature variables feature = list(data.columns[:-1]) data[target].head() data[feature].head()
_____no_output_____
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
Now taking feature and target data in seperate dataframe
featuredata = data[feature] targetdata = data[target]
_____no_output_____
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
Now we need to convert several non-numeric columns like 'internet' into numerical form for the model to process
def preprocess_features(X): output = pd.DataFrame(index = X.index) for col, col_data in X.iteritems(): if col_data.dtype == object: col_data = col_data.replace(['yes', 'no'], [1, 0]) if col_data.dtype == object: col_data = pd.get_dummies(col_data, prefix = col) ...
_____no_output_____
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
MODEL IMPLEMENTATION Decision tree
from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split model=DecisionTreeClassifier() X_train, X_test, y_train, y_test = train_test_split(featuredata, targetdata, test_size=0.33, random_state=6) model.fit(X_train,y_train) from sklearn.metrics import accuracy_score predictio...
_____no_output_____
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
K-Nearest Neighbours
from sklearn.neighbors import KNeighborsClassifier new_classifier = KNeighborsClassifier(n_neighbors=7) new_classifier.fit(X_train,y_train) predictions2 = new_classifier.predict(X_test) accuracy_score(y_test,predictions2)*100
_____no_output_____
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
SVM
from sklearn import svm clf = svm.SVC(random_state=6) clf.fit(featuredata,targetdata) clf.score(featuredata,targetdata) predictions3= clf.predict(X_test) accuracy_score(y_test,predictions3)*100
_____no_output_____
MIT
020_NIRMAL.ipynb
NirmalSilwal/Machine-Learning
k-means clustering
import warnings warnings.filterwarnings('ignore') %matplotlib inline import scipy as sc import scipy.stats as stats from scipy.spatial.distance import euclidean import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.colors as mcolors plt.style.use('fivethirtyeight') plt.rcParams['fo...
_____no_output_____
MIT
codici/kmeans.ipynb
tvml/ml2122
1. Install DependenciesFirst install the libraries needed to execute recipes, this only needs to be done once, then click play.
!pip install git+https://github.com/google/starthinker
_____no_output_____
Apache-2.0
colabs/smartsheet_to_bigquery.ipynb
fivestones-apac/starthinker
2. Get Cloud Project IDTo run this recipe [requires a Google Cloud Project](https://github.com/google/starthinker/blob/master/tutorials/cloud_project.md), this only needs to be done once, then click play.
CLOUD_PROJECT = 'PASTE PROJECT ID HERE' print("Cloud Project Set To: %s" % CLOUD_PROJECT)
_____no_output_____
Apache-2.0
colabs/smartsheet_to_bigquery.ipynb
fivestones-apac/starthinker
3. Get Client CredentialsTo read and write to various endpoints requires [downloading client credentials](https://github.com/google/starthinker/blob/master/tutorials/cloud_client_installed.md), this only needs to be done once, then click play.
CLIENT_CREDENTIALS = 'PASTE CREDENTIALS HERE' print("Client Credentials Set To: %s" % CLIENT_CREDENTIALS)
_____no_output_____
Apache-2.0
colabs/smartsheet_to_bigquery.ipynb
fivestones-apac/starthinker
4. Enter SmartSheet Sheet To BigQuery ParametersMove sheet data into a BigQuery table. 1. Specify SmartSheet token. 1. Locate the ID of a sheet by viewing its properties. 1. Provide a BigQuery dataset ( must exist ) and table to write the data into. 1. StarThinker will automatically map the correct schema.Modify the va...
FIELDS = { 'auth_read': 'user', # Credentials used for reading data. 'auth_write': 'service', # Credentials used for writing data. 'token': '', # Retrieve from SmartSheet account settings. 'sheet': '', # Retrieve from sheet properties. 'dataset': '', # Existing BigQuery dataset. 'table': '', # Table t...
_____no_output_____
Apache-2.0
colabs/smartsheet_to_bigquery.ipynb
fivestones-apac/starthinker
5. Execute SmartSheet Sheet To BigQueryThis does NOT need to be modified unless you are changing the recipe, click play.
from starthinker.util.project import project from starthinker.script.parse import json_set_fields USER_CREDENTIALS = '/content/user.json' TASKS = [ { 'smartsheet': { 'auth': 'user', 'token': {'field': {'name': 'token','kind': 'string','order': 2,'default': '','description': 'Retrieve from SmartSheet...
_____no_output_____
Apache-2.0
colabs/smartsheet_to_bigquery.ipynb
fivestones-apac/starthinker
TD: prédiction du vote 2016 aux Etats-Unis par arbres de décisions et méthodes ensemblistesLa séance d'aujourd'hui porte sur la prévision du vote en 2016 aux États-Unis. Précisément, les données d'un recensement sont fournies avec diverses informations par comté à travers les États-Unis. L'objectif est de construire ...
%matplotlib inline from pylab import * import numpy as np import os import random import matplotlib.pyplot as plt
_____no_output_____
MIT
MI203-td2_tree_and_forest.ipynb
NataliaDiaz/colab
Accès aux données* Elles sont disponibles: https://github.com/stepherbin/teaching/tree/master/ENSTA/TD2* Charger le fichier the combined_data.csv sur votre drive puis monter le depuis colab
USE_COLAB = True UPLOAD_OUTPUTS = False if USE_COLAB: # mount the google drive from google.colab import drive drive.mount('/content/drive', force_remount=True) # download data on GoogleDrive data_dir = "/content/drive/My Drive/teaching/ENSTA/TD_tree/" else: data_dir = "data/" import pandas as pd...
_____no_output_____
MIT
MI203-td2_tree_and_forest.ipynb
NataliaDiaz/colab
Analyse préliminaire des donnéesLes données sont organisées en champs:* fips = code du comté à 5 chiffres, le premier ou les deux premiers chiffres indiquent l'état.* votes = nombre de votants* etc..Regarder leur structure, quantité, nature.Où se trouvent les informations pour former les ensembles d'apprentissage et d...
# Exemples de moyens d'accéder aux caractéristiques des données print(census_data.shape ) print(census_data.columns.values) print(census_data['fips']) print(census_data.head(3)) iattr = 10 attrname = census_data.columns[iattr] print("Mean of {} is {:.1f}".format(attrname,np.array(census_data[attrname]).mean())) ####...
_____no_output_____
MIT
MI203-td2_tree_and_forest.ipynb
NataliaDiaz/colab
La classe à prédire ('Democrat') n'est décrite que par un seul attribut binaire.Calculer la répartition des couleurs politiques (quel est a priori la probabilité qu'un comté soit démocrate vs. républicain)
######################### ## METTRE VOTRE CODE ICI ######################### print("La probabilité qu'un comté soit démocrate est de {:.2f}%%".format(100*proba_dem))
La probabilité qu'un comté soit démocrate est de 15.45%%
MIT
MI203-td2_tree_and_forest.ipynb
NataliaDiaz/colab
Préparation du chantier d'apprentissageOn va préparer les ensembles d'apprentissage et de test. Pour éviter des problèmes de format de données, on choisit une liste d'attributs utiles dans la liste "feature_cols" ci dessous.L'ensemble de test sera constitué des comtés d'un seul état.Info: https://scikit-learn.org/stab...
## Sous ensembles d'attributs informatifs pour la suite feature_cols = ['BLACK_FEMALE_rate', 'BLACK_MALE_rate', 'Percent of adults with a bachelor\'s degree or higher, 2011-2015', 'ASIAN_MALE_rate', 'ASIAN_FEMALE_rate', '25-29_rate', ...
BLACK_FEMALE_rate BLACK_MALE_rate ... Protestant Denomination Zoroastrian 0 0.067586 0.062079 ... 0 0 1 0.067586 0.062079 ... 0 0 [2 rows x 49 columns] 598 0 599 0 Name: Democrat, dtype: int64
MIT
MI203-td2_tree_and_forest.ipynb
NataliaDiaz/colab
Apprentissage d'un arbre de décisionOn utilisera la bibliothèque scikit learn * Construire l'arbre sur les données d'entrainement* Prédire le vote sur les comtés de test* Calculer l'erreur et la matrice de confusionFaire varier certains paramètres (profondeur max, pureté, critère...) et visualisez leur influence.Info:...
from sklearn import tree ######################### ## METTRE VOTRE CODE ICI #########################
_____no_output_____
MIT
MI203-td2_tree_and_forest.ipynb
NataliaDiaz/colab
Les instructions suivantes permettent de visualiser l'arbre.Interpréter le contenu de la représentation.
import graphviz dot_data = tree.export_graphviz(clf, out_file=None) graph = graphviz.Source(dot_data) dot_data = tree.export_graphviz(clf, out_file=None, feature_names=X_train.columns.values, class_names=["R","D"], filled=True, rounded=True, ...
Predictions per county in state #34 are [0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 1 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 ...
MIT
MI203-td2_tree_and_forest.ipynb
NataliaDiaz/colab
--- BaggingL'objectif de cette partie est de construire **à la main** une approche de bagging.Le principe de l'approche est de:* Apprendre et collecter plusieurs arbres sur des échantillonnages aléatoires des données d'apprentissage* Agréger les prédictions par vote * Evaluer: Les prédictions agrégées* Comparer avec le...
from sklearn.model_selection import train_test_split # Données d'apprentissage: X_train, y_train, idx_train # Données de test: X_test, y_test, idx_test # Les étapes de conception du prédicteur (apprentissage) sont les suivantes: # - Construction des sous-ensembles de données # - Apprentissage d'un arbre # - Agré...
Taux de bonne prédiction = 76.32% 0.6837740384615385
MIT
MI203-td2_tree_and_forest.ipynb
NataliaDiaz/colab
Osnabrück University - Machine Learning (Summer Term 2018) - Prof. Dr.-Ing. G. Heidemann, Ulf Krumnack Exercise Sheet 08 IntroductionThis week's sheet should be solved and handed in before the end of **Sunday, June 3, 2018**. If you need help (and Google and other resources were not enough), feel free to contact your...
import numpy as np # Activation function σ. # We use scipy's builtin because it fixes some NaN problems for us. # sigmoid = lambda x: 1 / (1 + np.exp(-x)) from scipy.special import expit as sigmoid class Perceptron: """Single neuron handling its own weights and bias.""" def __init__(self, dim_in, act_func=s...
_____no_output_____
MIT
sheet_08/sheet_08_machine-learning_solution.ipynb
ArielMant0/ml2018
PerceptronLayerA `PerceptronLayer` is a combination of multiple `Perceptron` instances. It mainly is concerened with passing input and delta values to its individual neurons. There is no math to be done here! InitializationWhen initializing a `PerceptronLayer` (like this: `layer = PerceptronLayer(5, 3)`), the `__init_...
class PerceptronLayer: """Layer of multiple neurons. Attributes: perceptrons (list): List of perceptron instances in the layer. """ def __init__(self, dim_in, dim_out, act_func=sigmoid): """Initialize the layer as a list of individual neurons. A layer contains as many neuro...
_____no_output_____
MIT
sheet_08/sheet_08_machine-learning_solution.ipynb
ArielMant0/ml2018
MultilayerPerceptron Forward-Propagation / ActivationPropagate the input value $x$ through each layer of the network, employing the output of the previous layer as input to the next layer. Back-Propagation / AdaptationThis is the most complex step of the whole task. Split into three separate parts:1. ***Forward propag...
class MultilayerPerceptron: """Network of perceptrons, also a set of multiple perceptron layers. Attributes: layers (list): List of perceptron layers in the network. """ def __init__(self, *layers): """Initialize a new network, madeup of individual PerceptronLayers. Args: ...
_____no_output_____
MIT
sheet_08/sheet_08_machine-learning_solution.ipynb
ArielMant0/ml2018
Classification Problem DefinitionBefore we start, we need a problem to solve. In the following cell we first generate some three dimensional data (= $\text{input_dim}$) between 0 and 1 and label all data according to a binary classification: If the data is close to the center (radius < 2.5), it belongs to one class, ...
def uniform(a, b, n=1): """Returns n floats uniformly distributed between a and b.""" return (b - a) * np.random.random_sample(n) + a n = 1000 radius = 5 r = np.append(uniform(0, radius * .5, n // 2), uniform(radius * .7, radius, n // 2)) angle = uniform(0, 2 * np.pi, n) x = r * np.sin(angle) + ...
_____no_output_____
MIT
sheet_08/sheet_08_machine-learning_solution.ipynb
ArielMant0/ml2018
Model DesignThe following cell already contains a simple model with a single layer. Play around with some different configurations!
MLP = MultilayerPerceptron( PerceptronLayer(2, 1), ) # Adapt this MLP ### BEGIN SOLUTION MLP = MultilayerPerceptron( PerceptronLayer(2, 4), PerceptronLayer(4, 2), PerceptronLayer(2, 1), ) ### END SOLUTION
_____no_output_____
MIT
sheet_08/sheet_08_machine-learning_solution.ipynb
ArielMant0/ml2018