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 |
|---|---|---|---|---|---|
PinSage Code PinSage Layers | import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
import dgl.nn.pytorch as dglnn
import dgl.function as fn
def disable_grad(module):
for param in module.parameters():
param.requires_grad = False
def _init_input_modules(g, ntype, textset, hidden_dims):
# We initialize the li... | _____no_output_____ | MIT | 2021/pinsage_movielens_robert_output_disabled.ipynb | harvard-visionlab/psy1406 |
PinSage Sampler | import numpy as np
import dgl
import torch
from torch.utils.data import IterableDataset, DataLoader
def compact_and_copy(frontier, seeds):
block = dgl.to_block(frontier, seeds)
for col, data in frontier.edata.items():
if col == dgl.EID:
continue
block.edata[col] = data[block.edata[d... | _____no_output_____ | MIT | 2021/pinsage_movielens_robert_output_disabled.ipynb | harvard-visionlab/psy1406 |
PinSage Evaluation | import numpy as np
import torch
import pickle
import dgl
import argparse
def prec(recommendations, ground_truth):
n_users, n_items = ground_truth.shape
K = recommendations.shape[1]
user_idx = np.repeat(np.arange(n_users), K)
item_idx = recommendations.flatten()
relevance = ground_truth[user_idx, it... | _____no_output_____ | MIT | 2021/pinsage_movielens_robert_output_disabled.ipynb | harvard-visionlab/psy1406 |
PinSage Training | import pickle
import argparse
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torchtext
import dgl
import tqdm
import madgrad
from fastprogress.fastprogress import master_bar, progress_bar
# import layers
# import sampler as sampler_module
# import evaluation
cl... | _____no_output_____ | MIT | 2021/pinsage_movielens_robert_output_disabled.ipynb | harvard-visionlab/psy1406 |
Check model with dataChoose different datasets to see how the model automatically adjusts to fit the data in the graph. | import torch
from types import SimpleNamespace
args = SimpleNamespace()
# args.dataset_path = '/content/data.pkl'
# args.dataset_path = '/content/ml_1m_plot_data.pkl'
# args.dataset_path = '/content/ml_1m_backdrop_swin.pkl'
# args.dataset_path = '/content/ml_1m_imdb_longest.pkl'
args.dataset_path = '/content/ml_1m_onl... | _____no_output_____ | MIT | 2021/pinsage_movielens_robert_output_disabled.ipynb | harvard-visionlab/psy1406 |
PinSage Train on Implicit Task template, don't use/edit this one, it's just for reference | from types import SimpleNamespace
args = SimpleNamespace()
args.dataset_path = '/content/data.pkl'
# args.dataset_path = '/content/ml_1m_only_id.pkl'
args.random_walk_length = 2
args.random_walk_restart_prob = .5
args.num_random_walks = 1
args.num_neighbors = 3
args.num_layers = 2
args.hidden_dims = 16
args.batch_... | _____no_output_____ | MIT | 2021/pinsage_movielens_robert_output_disabled.ipynb | harvard-visionlab/psy1406 |
baseline model, movie id only | from types import SimpleNamespace
args = SimpleNamespace()
args.dataset_path = '/content/ml_1m_only_id.pkl'
args.random_walk_length = 2
args.random_walk_restart_prob = .5
args.num_random_walks = 1
args.num_neighbors = 3
args.num_layers = 2
args.hidden_dims = 32 # 16
args.batch_size = 256 # 32
args.device = 'cuda:0... | _____no_output_____ | MIT | 2021/pinsage_movielens_robert_output_disabled.ipynb | harvard-visionlab/psy1406 |
possible variationsYou can try different datasets (i.e., change the name of the data file being used to load the graph - the PinSage model automatically adapts to the data in the Graph):- [ ] ml_1m_only_id.pkl (this is our baseline)- [ ] ml_1m_imdb_plot.pkl(embedding of short plot descriptions)- [ ] ml_1m_imdb_full_pl... | from types import SimpleNamespace
# Edit the Dataset path
args = SimpleNamespace()
args.dataset_path = '/content/ml_1m_only_id.pkl'
args.random_walk_length = 2
args.random_walk_restart_prob = .5
args.num_random_walks = 1
args.num_neighbors = 3
args.num_layers = 2
args.hidden_dims = 32 # 16
args.batch_size = 256 # ... | _____no_output_____ | MIT | 2021/pinsage_movielens_robert_output_disabled.ipynb | harvard-visionlab/psy1406 |
Summary & ConclusionsBreifly write up a summary of what you did, what you found, and what you think it means.Then share this notebook (you're edited copy) with me (grez72@gmail.com) to submit your final project. | _____no_output_____ | MIT | 2021/pinsage_movielens_robert_output_disabled.ipynb | harvard-visionlab/psy1406 | |
Geocodio tells you the likely accuracy of the lat/long it's provided with an accuracy score. Some of the scores do not have high accuracy scores, which is worth mentioning. For now, we'll see if any mapping errors actually occur. If they do, I'll go back and engineer a solution. | #We have 239 cities, so we want to make sure there's 239 rows.
df.shape | _____no_output_____ | Apache-2.0 | EDA.ipynb | mattymecks/nlchp-mapping-project |
Because I'm only missing five values, I'm going to manually find their lat/lon coordinates and then add them in. I'll do this here because I want them mapped in all future data. | # Manual updating of relevent values
new_data = [(40.0874759, -108.8048292, 'CO3', 'CO'), (39.446649, -106.03757, 'CO2', 'CO'),
(28.022243, -81.732857, 'FL9', 'FL'), (39.9689532, -82.9376804, 'OH3', 'OH'),
(39.103119, -84.512016, 'OH1', 'OH')]
indexes = (63, 85, 98, 172, 191)
for i in rang... | _____no_output_____ | Apache-2.0 | EDA.ipynb | mattymecks/nlchp-mapping-project |
Much better. The campaign wants to keep track of the status of the anti-panhandling statutes/ordinances in each city, and they want to be able to update those values to reflect varying degrees of success as the campaign goes on. I'm going to create a 'status' value for each city set it's default to "active." Then I'm g... | # Adding in a "status" column
df['status'] = 0
# Creating a conditional column explaining ordinance status
d_text = {0: 'Ordinance Active - With No Response',
1: 'Ordinance Active - With Response Indicating No Immediate Repeal',
2: 'Ordinance Active - With Committment To Review',
3: ... | _____no_output_____ | Apache-2.0 | EDA.ipynb | mattymecks/nlchp-mapping-project |
Now I'm going to persist my changes. I'll make updates periodically, but I'll use a seperate notebook for that so that I don't have to continously repeat this project. | df.to_csv('cleaned_data.csv', mode ='w+') | _____no_output_____ | Apache-2.0 | EDA.ipynb | mattymecks/nlchp-mapping-project |
Overfitting demo Criando um conjunto de dados baseado em uma função senoidal | import math
import random
import numpy as np
import pandas as pd
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge
from sklearn.linear_model import RidgeCV
from sklearn.linear_model im... | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Vamos considerar um conjunto de dados sintéticos de 30 pontos amostrados de uma função senoidal $y = \sin(4x)$: | def f(x):
return np.sin(np.multiply(4,x)) | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Abaixo criamos valores aleatéorios para $x$ no intervalo [0,1) | random.seed(98103)
n = 30 # quantidade de valores gerados
x = np.array([random.random() for _ in range(n)]) #em cada iteração gera um valor aleatório entre 0 e 1
x=np.sort(x) # ordena os valores em ordem crescente
#transforma o array em uma matrix com uma n linhas e 1 coluna (vetor coluna)
X = x[:,np.newaxis] | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Calcula $y$ como uma função de $x$. $y$ é chamada variável independente pois depende de $x$ | Y = f(x) | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Adiciona ruído Gaussiano aleatório à $y$ | random.seed(1)
#ruído é amostrado de uma distribuição normal com média 0 e desvio padrão 1/3
e = np.array([random.gauss(0,1.0/3.0) for i in range(n)])
Y = Y + e | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Funções auxiliares Função para plotar os dados (scatter plot) | def plot_data(X,Y):
plt.plot(X,Y,'k.')
plt.xlabel('X')
plt.ylabel('Y')
plt.axis([0,1,-1.5,2]) | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Função para imprimir coeficientes | def print_coefficients(model):
# Retorna o grau do polinômio
deg = len(model.steps[1][1].coef_)-1
# Obtém os parâmetros estimados
w = list(model.steps[1][1].coef_) #model.steps é usado pois o modelo é calculado usando make_pipile do scikit learn
# Numpy tem uma função para imprimir o polinômio m... | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Função para calcular uma regressão polinomial para qualquer grau usando scikit learn. | def polynomial_regression(X,Y,deg):
model = make_pipeline(PolynomialFeatures(deg),LinearRegression())
model.fit(X,Y)
return model | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Função para plotar o modelo por meio de suas predições | def print_poly_predictions(X,Y, model):
plot_data(X,Y)
x_plot = np.array([i/200.0 for i in range(200)])
X_plot = x_plot[:,np.newaxis]
y_pred = model.predict(X_plot)
plt.plot(x_plot,y_pred,'g-')
plt.axis([0,1,-1.5,2])
def plot_residuals_vs_fit(X,Y, model):
# plot_data(X,Y)
# x_plot = np.arr... | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Função geradora | plot_data(X,Y)
x_plot = np.array([i/200.0 for i in range(200)])
y_plot = f(x_plot)
plt.plot(x_plot,y_plot,color='cornflowerblue',linewidth=2) | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Regressão polinomial de diferentes graus | model = polynomial_regression(X,Y,16)
print_poly_predictions(X,Y,model) | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Mostrando o modelo e coeficientes. | print_coefficients(model) | Polinômio estimado para grau 16:
16 15 14 13
3.337e+08 x - 2.226e+09 x + 6.62e+09 x - 1.156e+10 x
12 11 10 9 8
+ 1.309e+10 x - 1e+10 x + 5.14e+09 x - 1.657e+09 x + 2.258e+08 x
7 6 ... | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Regressão Ridge A regressão ridge se propõe a evitar o overfitting adicionando um custo ao RSS (dos mínimos quadrados) que depende da norma L2 dos coeficientes $\|w\|$ (ou seja da magnitude dos coeficientes). O resultado é a penalização de ajustes com coeficientes muito grandes. A força dessa penalidade é controlada... | def polynomial_ridge_regression(X,Y, deg, l2_penalty):
model = make_pipeline(PolynomialFeatures(deg),Ridge(alpha=l2_penalty))
model.fit(X,Y)
return model | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Ridge com grau 16 usando uma penalidade *muito* pequena | model = polynomial_ridge_regression(X,Y,deg=16,l2_penalty=1e-14)
print_coefficients(model)
print_poly_predictions(X,Y,model) | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Ridge com grau 16 usando uma penalidade *muito* grande | model = polynomial_ridge_regression(X,Y, deg=16, l2_penalty=100)
print_coefficients(model)
print_poly_predictions(X,Y,model) | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Sequência de ajustes para uma sequência crescente de valores de lambda | for l2_penalty in [1e-10, 1e-8, 1e-6, 1e-3, 1, 1e1, 1e2]:
model = polynomial_ridge_regression(X,Y, deg=16, l2_penalty=l2_penalty)
print('lambda = %.2e' % l2_penalty)
print_coefficients(model)
print('\n')
plt.figure()
print_poly_predictions(X,Y,model)
plt.title('Ridge, lambda = %.2e' % l2_pen... | lambda = 1.00e-10
Polinômio estimado para grau 16:
16 15 14 13 12 11 10
7567 x - 7803 x - 6900 x + 714.5 x + 6541 x + 5802 x - 498.1 x
9 8 7 6 5 4 3
- 6056 x - 4252 x + 3439 x + 4893 x - 4281 x + 769.9 x + 100... | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Usando validação cruzada para encontrar o melhor lembda para Regressão Ridge A função abaixo calcula os rmses (root mean squared error) para um certo modelo considerando todos os k folds (parâmetro cv na função cross_val_score do scikit learn). | from sklearn.model_selection import cross_val_score
def rmse_cv(model):
rmse = np.sqrt(-cross_val_score(model,X,Y,scoring="neg_mean_squared_error",cv=10))
return (rmse) | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Cria um modelo de regressão ridge | model_ridge = Ridge() | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Plota resultados (médias de rmse) para cada valor de alpha (ou lambda) | l2_penalties = [0.001,0.01,0.1,0.3,0.5,1,3,5,10,15,20,40,60,80,100]
cv_ridge = [rmse_cv(Ridge(alpha=l2_penalty)).mean()
for l2_penalty in l2_penalties]
cv_ridge = pd.Series(cv_ridge,index=l2_penalties)
cv_ridge.plot(title="Lambda vs Erro de Validação")
plt.xlabel("l2_penalty")
plt.ylabel("rmse")
best_l2_pe... | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Regressão Lasso A regressão Lasso, ao mesmo tempo, encolhe a magnitude dos coeficientes para evitar o overfitting e realiza implicitamente seleção de característcas igualando alguns atributos a zero (para lambdas, aqui chamados "L1_penalty", suficientemente grandes). Em particular, o Lasso adiciona ao RSS o custo $\|w... | def polynomial_lasso_regression(X, Y, deg, l1_penalty):
model = make_pipeline(PolynomialFeatures(deg),Lasso(alpha=l1_penalty,max_iter=10000))
# X = data['X'][:,np.newaxis] #transformando em matrix para LinearRegression
model.fit(X,Y)
return model | _____no_output_____ | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
Explore a solução lasso solution como uma função de diferentes fatores de penalidade Nos referimos ao fator de penalidade do lasso como "l1_penalty" | for l1_penalty in [0.0001, 0.001, 0.01, 0.1, 10]:
model = polynomial_lasso_regression(X, Y,deg=16, l1_penalty=l1_penalty)
print ('l1_penalty = %e' % l1_penalty)
w = list(model.steps[1][1].coef_)
print ('número de não zeros = %d' % np.count_nonzero(w))
print_coefficients(model)
print ('\n')
p... | l1_penalty = 1.000000e-04
número de não zeros = 5
Polinômio estimado para grau 16:
11 10 4 2
1.626 x + 1.074 x - 7.667 x + 4.545 x - 0.4504 x + 0.4478
l1_penalty = 1.000000e-03
número de não zeros = 3
Polinômio estimado para grau 16:
5 4
-0.181 x - 2.886 x + 1.373 x + ... | MIT | regressao_linear/Overfitting_Demo_Ridge.ipynb | luizcz/aprendizado_maquina |
BTC - Gender BiasFinder | import pandas as pd
import numpy as np
import math
import time
base_dir = "../../data/biasfinder/gender/"
df = pd.read_csv(base_dir + "test.csv", header=None, sep="\t", names=["label", "mutant", "template", "original", "gender", "template_id"])
df.drop_duplicates()
def read_txt(fpath):
pred = []
file = open(fpa... | _____no_output_____ | Apache-2.0 | codes/gender/BTC.ipynb | yangzhou6666/BiasHeal |
Use Groupby to Group the text by Template | gb = df.groupby("template_id")
gb.count()
len(gb.size())
df
id = 0
df.iloc[id]["mutant"]
df.iloc[id]["original"]
df.iloc[id]["template"] | _____no_output_____ | Apache-2.0 | codes/gender/BTC.ipynb | yangzhou6666/BiasHeal |
Get DF template only | df
dft = df.iloc[:,[2,3,5]]
dft = dft.drop_duplicates()
dft
# ## template
dft = dft.sort_values(by=["template_id"])
dft = dft.reset_index(drop=True)
dft
## mutant
df = df.reset_index(drop=True)
df
dft | _____no_output_____ | Apache-2.0 | codes/gender/BTC.ipynb | yangzhou6666/BiasHeal |
Get Number of Discordant Pairs for Each TemplateThere is a memory limitation that make us can't directly produce +- 240M pairs. Fortunately, the number of discordant pairs for each template can be calculate theoritically without crossing th data to get +- 240M pairs. This will solve the memory issue.For each template,... | gb = df.groupby("template_id")
gb.count() | _____no_output_____ | Apache-2.0 | codes/gender/BTC.ipynb | yangzhou6666/BiasHeal |
Data crossing | import time
start = time.time()
identifier = "gender"
mutant_example = []
mutant_prediction_stat = []
key = []
for i in range(len(gb.size())) :
# for i in range(10) :
data = gb.get_group(i)
dc = data.groupby(identifier)
me = {} # mutant example
mp = {} # mutant prediction
key = []
for k, v in... | _____no_output_____ | Apache-2.0 | codes/gender/BTC.ipynb | yangzhou6666/BiasHeal |
Number of Bias-Uncovering Test Case | int(dft["btc"].sum()) | _____no_output_____ | Apache-2.0 | codes/gender/BTC.ipynb | yangzhou6666/BiasHeal |
BTC Rate | dft["btc"].sum() / dft["possible_pair"].sum() | _____no_output_____ | Apache-2.0 | codes/gender/BTC.ipynb | yangzhou6666/BiasHeal |
Get Data that Have number of BTC more than one | d = dft[dft["btc"] > 0]
d | _____no_output_____ | Apache-2.0 | codes/gender/BTC.ipynb | yangzhou6666/BiasHeal |
Sort Data based on the number of BTC | d = d.sort_values(["btc", "template"], ascending=False)
d = d.reset_index(drop=True)
d | _____no_output_____ | Apache-2.0 | codes/gender/BTC.ipynb | yangzhou6666/BiasHeal |
Get Data BTC for train and test | df
template_that_produce_btc = d["template_id"].tolist()
# template_that_produce_btc
start = time.time()
mutant_text_1 = []
mutant_text_2 = []
prediction_1 = []
prediction_2 = []
identifier_1 = []
identifier_2 = []
template = []
original = []
label = []
for i in template_that_produce_btc: # only processing from templa... | _____no_output_____ | Apache-2.0 | codes/gender/BTC.ipynb | yangzhou6666/BiasHeal |
Balanced Data for Training | df_0 = unique_data[unique_data["label"] == 0]
df_1 = unique_data[unique_data["label"] == 1]
print(len(df_0))
print(len(df_1))
df_1 = df_1.sample(len(df_0), replace=True)
df_oversampled = pd.concat([df_0, df_1], axis=0)
df_oversampled
data_dir = base_dir + "unique/balanced/"
if not os.path.exists(data_dir) :
os.mak... | _____no_output_____ | Apache-2.0 | codes/gender/BTC.ipynb | yangzhou6666/BiasHeal |
Live Human Pose Estimation with OpenVINOThis notebook demonstrates live pose estimation with OpenVINO. We use the OpenPose model [human-pose-estimation-0001](https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/intel/human-pose-estimation-0001) from [Open Model Zoo](https://github.com/openvinotoolkit/o... | import sys
import collections
import os
import time
import cv2
import numpy as np
from IPython import display
from numpy.lib.stride_tricks import as_strided
from openvino import inference_engine as ie
from decoder import OpenPoseDecoder
sys.path.append("../utils")
import notebook_utils as utils | _____no_output_____ | Apache-2.0 | notebooks/402-pose-estimation-webcam/402-pose-estimation.ipynb | scalers-ai/openvino_notebooks |
The model Download the modelWe use `omz_downloader`, which is a command line tool from the `openvino-dev` package. `omz_downloader` automatically creates a directory structure and downloads the selected model.If you want to download another model, please change the model name and precision. *Note: This will require a ... | # directory where model will be downloaded
base_model_dir = "model"
# model name as named in Open Model Zoo
model_name = "human-pose-estimation-0001"
# selected precision (FP32, FP16, FP16-INT8)
precision = "FP16-INT8"
model_path = f"model/intel/{model_name}/{precision}/{model_name}.xml"
model_weights_path = f"model/... | _____no_output_____ | Apache-2.0 | notebooks/402-pose-estimation-webcam/402-pose-estimation.ipynb | scalers-ai/openvino_notebooks |
Load the modelDownloaded models are located in a fixed structure, which indicates vendor, model name and precision.Only a few lines of code are required to run the model. First, we create an Inference Engine object. Then we read the network architecture and model weights from the .bin and .xml files to load onto the d... | # initialize inference engine
ie_core = ie.IECore()
# read the network and corresponding weights from file
net = ie_core.read_network(model=model_path, weights=model_weights_path)
# load the model on the CPU (you can use GPU or MYRIAD as well)
exec_net = ie_core.load_network(net, "CPU")
# get input and output names of... | _____no_output_____ | Apache-2.0 | notebooks/402-pose-estimation-webcam/402-pose-estimation.ipynb | scalers-ai/openvino_notebooks |
Input key is the name of the input node and output keys contain names of output nodes of the network. In the case of the OpenPose Model, we have one input and two outputs: pafs and keypoints heatmap. | input_key, output_keys | _____no_output_____ | Apache-2.0 | notebooks/402-pose-estimation-webcam/402-pose-estimation.ipynb | scalers-ai/openvino_notebooks |
Processing OpenPoseDecoderWe need a decoder to transform the raw results from the neural network into pose estimations. This magic happens inside Open Pose Decoder, which is provided in the [Open Model Zoo](https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/openvino/model_zoo/model_api/m... | decoder = OpenPoseDecoder() | _____no_output_____ | Apache-2.0 | notebooks/402-pose-estimation-webcam/402-pose-estimation.ipynb | scalers-ai/openvino_notebooks |
Process ResultsA bunch of useful functions to transform results into poses.First, we will pool the heatmap. Since pooling is not available in numpy, we use a simple method to do it directly with numpy. Then, we use non-maximum suppression to get the keypoints from the heatmap. After that, we decode poses using the dec... | # 2d pooling in numpy (from: htt11ps://stackoverflow.com/a/54966908/1624463)
def pool2d(A, kernel_size, stride, padding, pool_mode="max"):
"""
2D Pooling
Parameters:
A: input 2D array
kernel_size: int, the size of the window
stride: int, the stride of the window
padding: int... | _____no_output_____ | Apache-2.0 | notebooks/402-pose-estimation-webcam/402-pose-estimation.ipynb | scalers-ai/openvino_notebooks |
Draw Pose OverlaysDraw pose overlays on the image to visualize estimated poses. Joints are drawn as circles and limbs are drawn as lines. The code is based on the [Human Pose Estimation Demo](https://github.com/openvinotoolkit/open_model_zoo/tree/master/demos/human_pose_estimation_demo/python) from Open Model Zoo. | colors = ((255, 0, 0), (255, 0, 255), (170, 0, 255), (255, 0, 85), (255, 0, 170), (85, 255, 0),
(255, 170, 0), (0, 255, 0), (255, 255, 0), (0, 255, 85), (170, 255, 0), (0, 85, 255),
(0, 255, 170), (0, 0, 255), (0, 255, 255), (85, 0, 255), (0, 170, 255))
default_skeleton = ((15, 13), (13, 11), (16, ... | _____no_output_____ | Apache-2.0 | notebooks/402-pose-estimation-webcam/402-pose-estimation.ipynb | scalers-ai/openvino_notebooks |
Main Processing FunctionRun pose estimation on the specified source. Either a webcam or a video file. | # main processing function to run pose estimation
def run_pose_estimation(source=0, flip=False, use_popup=False, skip_first_frames=0):
player = None
try:
# create video player to play with target fps
player = utils.VideoPlayer(source, flip=flip, fps=30, skip_first_frames=skip_first_frames)
... | _____no_output_____ | Apache-2.0 | notebooks/402-pose-estimation-webcam/402-pose-estimation.ipynb | scalers-ai/openvino_notebooks |
Run Run Live Pose EstimationRun using a webcam as the video input. By default, the primary webcam is set with `source=0`. If you have multiple webcams, each one will be assigned a consecutive number starting at 0. Set `flip=True` when using a front-facing camera. Some web browsers, especially Mozilla Firefox, may caus... | run_pose_estimation(source=0, flip=True, use_popup=False) | _____no_output_____ | Apache-2.0 | notebooks/402-pose-estimation-webcam/402-pose-estimation.ipynb | scalers-ai/openvino_notebooks |
Run Pose Estimation on a Video FileIf you don't have a webcam, you can still run this demo with a video file. Any format supported by OpenCV will work (see: https://docs.opencv.org/4.5.1/dd/d43/tutorial_py_video_display.html). You can skip first N frames to fast forward video. | video_file = "https://github.com/intel-iot-devkit/sample-videos/blob/master/store-aisle-detection.mp4?raw=true"
run_pose_estimation(video_file, flip=False, use_popup=False, skip_first_frames=500) | _____no_output_____ | Apache-2.0 | notebooks/402-pose-estimation-webcam/402-pose-estimation.ipynb | scalers-ai/openvino_notebooks |
Awesome basics that you can't live without when using Scitkit-learn | import sklearn | _____no_output_____ | MIT | notebooks/Untitled.ipynb | eleijonmarck/analytics-workflow-showcase |
All the methods within the scikit that you might want to explore and import when applicable | (sklearn.__dict__)['__all__'] | _____no_output_____ | MIT | notebooks/Untitled.ipynb | eleijonmarck/analytics-workflow-showcase |
2017 French presidential elections My aim was to highlight differences between Emmanuel Macron and Marine Le Pen, the two candidates who went to the second round of the 2017 French presidential elections.I have downloaded transcripts of the speeches that the two candidates performed from the 1st of January 2017 to the... | import os
import numpy as np
import nltk
from nltk.corpus import stopwords
import string
import re
import copy
from string import digits
## Load data
listFiles = os.listdir("~/Presidentielles2017/Data") | _____no_output_____ | MIT | 2017-French-presidential-elections.ipynb | AurelieDaviaud/2017-French-presidential-elections |
Preprocess the speeches First, have to preprocess the speeches to keep only important words. So we have to clean up irregularities (i.e. change to lowercase and remove punctuation) and to remove stop words. We have to prepare a list of French stopwords (as comprehensive as possible, by combining several existing lists... | ## Prepare stop words
stopw = open("stopwords-fr1.txt", "r").read()
months = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"]
n = re.compile('\n')
stopw = n.sub(' ', stopw)
stopw = nltk.word_tokenize(stopw)
stopw = stopw + stopwords.words('french'... | _____no_output_____ | MIT | 2017-French-presidential-elections.ipynb | AurelieDaviaud/2017-French-presidential-elections |
Some transcripts of Le Pen's speeches are actually subtitles. So, we also have to remove the timestamp and any backest that usually include sound effect. Moreover, transcripts of Le Pen's and Macron's speeches do not have the same format. So we are going to use two different functions to process the documents. Functio... | def cleanLP(str, subtitle=False):
timestamp = re.compile('^\d+\n?.*\n?', re.MULTILINE) # finds line numbers and the line after them (which usually houses timestamps)
brackets = re.compile('\[[^]]*\]\n?|\([^)]*\)\n?|<[^>]*>\n?|\{[^}]*\}\n?') # finds brackets and anything in between them (sound effects... | _____no_output_____ | MIT | 2017-French-presidential-elections.ipynb | AurelieDaviaud/2017-French-presidential-elections |
Function to preprocess speeches of Macron | def cleanMac(str):
brackets = re.compile('\[[^]]*\]\n?|\([^)]*\)\n?|<[^>]*>\n?|\{[^}]*\}\n?') # finds brackets and anything in between them (sound effects)
opensubs = re.compile('.*str.*\n?|.*subs.*\n?', re.IGNORECASE) # finds the opensubtitles signature
urls = re.compile('www.*\s\n?|[... | _____no_output_____ | MIT | 2017-French-presidential-elections.ipynb | AurelieDaviaud/2017-French-presidential-elections |
Preprocess the speeches | tokenMacTot = []
tokenLPTot = []
for file in listFiles:
str = open(file, "r").read()
if "MACRON" in file:
tokenMac = cleanMac(str)
tokenMacTot = tokenMacTot + tokenMac
if "Le Pen" in file:
if "Subtitle" in file:
tokenLP = cleanLP(str, subtitle=True)
tokenLP... | _____no_output_____ | MIT | 2017-French-presidential-elections.ipynb | AurelieDaviaud/2017-French-presidential-elections |
Store the tokens | tokens_mac_file = open('tokens_mac.txt', 'w')
for item in tokenMacTot:
tokens_mac_file.write("%s\n" % item)
tokens_LP_file = open('tokens_LP.txt', 'w')
for item in tokenLPTot:
tokens_LP_file.write("%s\n" % item) | _____no_output_____ | MIT | 2017-French-presidential-elections.ipynb | AurelieDaviaud/2017-French-presidential-elections |
Analyse the data Let's see whether the number of words used by each candidate is similar. | # Macron
tokenMacUni = set(tokenMacTot)
len(tokenMacUni)
# Le Pen
tokenLPUni = set(tokenLPTot)
len(tokenLPUni) | _____no_output_____ | MIT | 2017-French-presidential-elections.ipynb | AurelieDaviaud/2017-French-presidential-elections |
Macron seems to have a vocabulary that is a bit less varied than Le Pen. Count words Now, we have to compute the frequency of each word for each candidate to create the word clouds. | from collections import Counter
# Macron
n = re.compile('\n')
tokenMacTot = open("tokens_mac.txt", "r").read()
tokenMacTot = n.sub(' ', tokenMacTot)
tokenMacTot = nltk.word_tokenize(tokenMacTot)
mac = Counter(tokenMacTot)
mac_most = mac.most_common(n=100)
# Le Pen
tokenLPTot = open("tokens_LP.txt", "r").read()
toke... | _____no_output_____ | MIT | 2017-French-presidential-elections.ipynb | AurelieDaviaud/2017-French-presidential-elections |
Create word clouds | import wordcloud
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from PIL import Image
import matplotlib.pyplot as plt
str_mac = open("tokens_mac.txt", "r").read()
str_lp = open("tokens_LP.txt", "r").read()
## Generate word clouds
mac = WordCloud(background_color="white", collocations= False, font_path... | _____no_output_____ | MIT | 2017-French-presidential-elections.ipynb | AurelieDaviaud/2017-French-presidential-elections |
The two candidates seem to use frequently the same words: France/français/française, Europe/européen/européenne, pays/nation/république, sécurité, monde, économie/économique, territoire... Well... that's not very surprising in a presidential election...This kind of word cloud may not be the best strategy to highlight t... | ## Generate mask (load and format image) (NB: background must be transparent)
# Macron
mac_im = Image.open("F:/Boulot/00-DataScience/Portfolio/Presidentielles2017/macronNB.png")
mac_mask = Image.new("RGB", mac_im.size, (255,255,255))
mac_mask.paste(mac_im, mac_im)
mac_mask = np.array(mac_mask)
# Le Pen
lp_im = Image.... | _____no_output_____ | MIT | 2017-French-presidential-elections.ipynb | AurelieDaviaud/2017-French-presidential-elections |
Now, let's see whether we can color the words using the colors of the French flag: blue, white and red. | import random
def BBR_color_func(word, font_size, position, orientation, random_state=None,
**kwargs):
return "%s" % random.choice(["hsl(240, 100%, 25%)", "hsl(0, 0%, 100%)", "hsl(0, 100%, 50%)"])
## Generate mask (load and format image) (NB: background must be transparent)
# Macron
mac_im = Im... | _____no_output_____ | MIT | 2017-French-presidential-elections.ipynb | AurelieDaviaud/2017-French-presidential-elections |
Task1 | from math import exp
INF = 10
EPS = 1e-8
ITERATIONS_NUM = 1000
class Differentiable:
def __init__(self, derivatives):
self.derivatives = derivatives
def __call__(self, x):
return self.derivatives[0](x)
def grad(self):
if (len(self.derivatives) == 1):
raise Exception("no d... | bisec: 1.414213553071022
newton: 1.414213562373095
| MIT | beliakov-artem/HW1.ipynb | Malkovsky/co-mkn-hw-2021 |
Task2 | def get_roots(p):
if (p.get_degree() == 1):
return [-p.coefs[0] / p.coefs[1]]
a = [-INF]
a += get_roots(p.grad())
a.append(INF)
roots = []
for i in range(len(a) - 1):
roots.append(bisec(p, a[i], a[i + 1]))
return roots
def get_polynom_by_roots(roots):
coefs = [0] * ... | _____no_output_____ | MIT | beliakov-artem/HW1.ipynb | Malkovsky/co-mkn-hw-2021 |
Понятно, что этот код не работает в самой общей постановке задачи. Как минимум он всегда возвращает столько корней, какой степени полином. Он совершенно не работает в сценарии, когда у нас есть кратные корни. Да и у производной могут быть кратные корни, но мне очень не хотелось разбирать все эти случаи. Так что вот так... | def get_differentiable(a, b, c, d):
def f(x):
return exp(a * x) + exp(- b * x) + c * ((x - d) ** 2)
def f_grad(x):
return a * exp(a * x) - b * exp(- b * x) + 2 * c * (x - d)
def f_grad2(x):
return (a ** 2) * exp(a * x) + (b ** 2) * exp(- b * x) + 2 * c
return Diff... | bisec: 0.49007306806743145
newton: 0.4900730684805478
ternary: 0.49007306428116904
| MIT | beliakov-artem/HW1.ipynb | Malkovsky/co-mkn-hw-2021 |
필요한 필수 새팅 작업 | !ls
!pip install -r drive/'My Drive'/'KoGPT2-FineTuning_pre'/requirements.txt
import os
import sys
sys.path.append('drive/My Drive/KoGPT2-FineTuning_pre')
logs_base_dir = "runs"
from jupyter_main_auto import main
ctx= 'cuda'
cachedir='~/kogpt2/'
load_path = './gdrive/My Drive/KoGPT2-FineTuning_pre/checkpoint/KoGPT2_che... | _____no_output_____ | Apache-2.0 | Colab.ipynb | andrewlaikhT/KoGPT2 |
모델 학습 시작 | # 저장 잘 되는지 테스트
drive.mount('/content/gdrive')
f = open(save_path+ 'KoGPT2_checkpoint_' + str(142) + '.tar', 'w')
f.write("가자")
f.close()
main(load_path = load_path, data_file_path = data_file_path, save_path = './gdrive/My Drive/KoGPT2-FineTuning_pre/checkpoint/', summary_url = './gdrive/My Drive/KoGPT2-FineTuning_pre... | _____no_output_____ | Apache-2.0 | Colab.ipynb | andrewlaikhT/KoGPT2 |
Decision trees and random forests | import numpy as np
import pandas as pd
from sklearn import model_selection as ms, tree, ensemble
%matplotlib inline
WHITES_URL = 'http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv' | _____no_output_____ | CC-BY-4.0 | 12_decision_trees_and_random_forests/notebooks/02_solutions.ipynb | JoseHJBlanco/ga-data-science |
Read in the Wine Quality dataset. | whites = pd.read_csv(WHITES_URL, sep=';') | _____no_output_____ | CC-BY-4.0 | 12_decision_trees_and_random_forests/notebooks/02_solutions.ipynb | JoseHJBlanco/ga-data-science |
Train a decision tree for 'quality' limiting the depth to 3, and the minimum number of samples per leaf to 50. | X = whites.drop('quality', axis=1)
y = whites.quality
tree1 = tree.DecisionTreeRegressor(max_depth=2, min_samples_leaf=50)
tree1.fit(X, y) | _____no_output_____ | CC-BY-4.0 | 12_decision_trees_and_random_forests/notebooks/02_solutions.ipynb | JoseHJBlanco/ga-data-science |
Export the tree for plotting. | tree.export_graphviz(tree1, 'tree1.dot', feature_names=X.columns) | _____no_output_____ | CC-BY-4.0 | 12_decision_trees_and_random_forests/notebooks/02_solutions.ipynb | JoseHJBlanco/ga-data-science |
Define folds for cross-validation. | ten_fold_cv = ms.KFold(n_splits=10, shuffle=True) | _____no_output_____ | CC-BY-4.0 | 12_decision_trees_and_random_forests/notebooks/02_solutions.ipynb | JoseHJBlanco/ga-data-science |
Compute average MSE across folds. | mses = ms.cross_val_score(tree.DecisionTreeRegressor(max_depth=2, min_samples_leaf=50),
X, y, scoring='neg_mean_squared_error', cv=ten_fold_cv)
np.mean(-mses) | _____no_output_____ | CC-BY-4.0 | 12_decision_trees_and_random_forests/notebooks/02_solutions.ipynb | JoseHJBlanco/ga-data-science |
Train a random forest with 20 decision trees. | rf1 = ensemble.RandomForestRegressor(n_estimators=20)
rf1.fit(X, y) | _____no_output_____ | CC-BY-4.0 | 12_decision_trees_and_random_forests/notebooks/02_solutions.ipynb | JoseHJBlanco/ga-data-science |
Investigate importances of predictors. | rf1.feature_importances_ | _____no_output_____ | CC-BY-4.0 | 12_decision_trees_and_random_forests/notebooks/02_solutions.ipynb | JoseHJBlanco/ga-data-science |
Evaluate performance through cross-validation. | mses = ms.cross_val_score(ensemble.RandomForestRegressor(n_estimators=20),
X, y, scoring='neg_mean_squared_error', cv=ten_fold_cv)
np.mean(-mses) | _____no_output_____ | CC-BY-4.0 | 12_decision_trees_and_random_forests/notebooks/02_solutions.ipynb | JoseHJBlanco/ga-data-science |
What happens when you increase the number of trees to 50? | mses = ms.cross_val_score(ensemble.RandomForestRegressor(n_estimators=50),
X, y, scoring='neg_mean_squared_error', cv=ten_fold_cv)
np.mean(-mses) | _____no_output_____ | CC-BY-4.0 | 12_decision_trees_and_random_forests/notebooks/02_solutions.ipynb | JoseHJBlanco/ga-data-science |
NormalizationUse what you've learned to normalize case in the following text and remove punctuation! | text = "The first time you see The Second Renaissance it may look boring. Look at it at least twice and definitely watch part 2. It will change your view of the matrix. Are the human people the ones who started the war ? Is AI a bad thing ?"
print(text) | The first time you see The Second Renaissance it may look boring. Look at it at least twice and definitely watch part 2. It will change your view of the matrix. Are the human people the ones who started the war ? Is AI a bad thing ?
| MIT | Text Processing/normalization_practice.ipynb | maitreytalware/Natural-Language-Processing-Pipelines |
Case Normalization | # Convert to lowercase
text = text.lower()
print(text) | the first time you see the second renaissance it may look boring. look at it at least twice and definitely watch part 2. it will change your view of the matrix. are the human people the ones who started the war ? is ai a bad thing ?
| MIT | Text Processing/normalization_practice.ipynb | maitreytalware/Natural-Language-Processing-Pipelines |
Punctuation RemovalUse the `re` library to remove punctuation with a regular expression (regex). Feel free to refer back to the video or Google to get your regular expression. You can learn more about regex [here](https://docs.python.org/3/howto/regex.html). | # Remove punctuation characters
import re
text = re.sub(r"[^a-zA-Z0-9]"," ",text)
print(text) | the first time you see the second renaissance it may look boring look at it at least twice and definitely watch part 2 it will change your view of the matrix are the human people the ones who started the war is ai a bad thing
| MIT | Text Processing/normalization_practice.ipynb | maitreytalware/Natural-Language-Processing-Pipelines |
End of distribution Imputation ==> Feature-Engine What is Feature-EngineFeature-Engine is an open source python package that I created at the back of this course. - Feature-Engine includes all the feature engineering techniques described in the course- Feature-Engine works like to Scikit-learn, so it is easy to learn-... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# to split the datasets
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
# from feature-engine
from feature_engine import missing_data_imputers as mdi
# let's load the dataset with a selected group of var... | _____no_output_____ | BSD-3-Clause | notebooks/feature-engineering/Section-04-Missing-Data-Imputation/04.18-End-Tail-Imputation-Feature-Engine.ipynb | sophiabrandt/udemy-feature-engineering |
All the predictor variables contain missing data. | # let's separate into training and testing set
# first drop the target from the feature list
cols_to_use.remove('SalePrice')
X_train, X_test, y_train, y_test = train_test_split(data[cols_to_use],
data['SalePrice'],
... | _____no_output_____ | BSD-3-Clause | notebooks/feature-engineering/Section-04-Missing-Data-Imputation/04.18-End-Tail-Imputation-Feature-Engine.ipynb | sophiabrandt/udemy-feature-engineering |
Feature-Engine captures the numerical variables automatically | # we call the imputer from feature-engine
# we specify whether we want to find the values using
# the gaussian approximation or the inter-quantal range
# proximity rule.
# in addition we need to specify if we want the values placed at
# the left or right tail
imputer = mdi.EndTailImputer(distribution='gaussian', ta... | _____no_output_____ | BSD-3-Clause | notebooks/feature-engineering/Section-04-Missing-Data-Imputation/04.18-End-Tail-Imputation-Feature-Engine.ipynb | sophiabrandt/udemy-feature-engineering |
Feature-engine allows you to specify variable groups easily | # let's do it imputation but this time
# and let's do it over 2 of the 3 numerival variables
# let's also select the proximity rule on the left tail
imputer = mdi.EndTailImputer(distribution='skewed', tail='left',
variables=['LotFrontage', 'MasVnrArea'])
imputer.fit(X_train)
# now the im... | _____no_output_____ | BSD-3-Clause | notebooks/feature-engineering/Section-04-Missing-Data-Imputation/04.18-End-Tail-Imputation-Feature-Engine.ipynb | sophiabrandt/udemy-feature-engineering |
Feature-engine can be used with the Scikit-learn pipeline | # let's look at the distributions to determine the
# end tail value selection method
X_train.hist() | _____no_output_____ | BSD-3-Clause | notebooks/feature-engineering/Section-04-Missing-Data-Imputation/04.18-End-Tail-Imputation-Feature-Engine.ipynb | sophiabrandt/udemy-feature-engineering |
All variables are skewed. For this demo, I will use the proximity rule for GarageYrBlt and MasVnrArea, and the Gaussian approximation for LotFrontage. | pipe = Pipeline([
('imputer_skewed', mdi.EndTailImputer(distribution='skewed', tail='right',
variables=['GarageYrBlt', 'MasVnrArea'])),
('imputer_gaussian', mdi.EndTailImputer(distribution='gaussian', tail='right',
variables=... | _____no_output_____ | BSD-3-Clause | notebooks/feature-engineering/Section-04-Missing-Data-Imputation/04.18-End-Tail-Imputation-Feature-Engine.ipynb | sophiabrandt/udemy-feature-engineering |
[NumPyro](https://github.com/pyro-ppl/numpyro) is probabilistic programming language built on top of JAX. It is very similar to [Pyro](https://pyro.ai/), which is built on top of PyTorch, but [tends to be faster](https://stackoverflow.com/questions/61846620/numpyro-vs-pyro-why-is-former-100x-faster-and-when-should-i-u... | # Standard Python libraries
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import time
#import numpy as np
#np.set_printoptions(precision=3)
import glob
import matplotlib.pyplot as plt
import PIL
import imageio
from IPython import display
%matplotlib inline
import sklear... | jax version 0.2.7
jax backend gpu
| MIT | notebooks/numpyro_intro.ipynb | khanshehjad/pyprobml |
Distributions | import numpyro
import numpyro.distributions as dist
from numpyro.diagnostics import hpdi
from numpyro.distributions.transforms import AffineTransform
from numpyro.infer import MCMC, NUTS, Predictive
rng_key = random.PRNGKey(0)
rng_key, rng_key_ = random.split(rng_key) | _____no_output_____ | MIT | notebooks/numpyro_intro.ipynb | khanshehjad/pyprobml |
1d Gaussian | # 2 independent 1d gaussians (ie 1 diagonal Gaussian)
mu = 1.5
sigma = 2
d = dist.Normal(mu, sigma)
dir(d)
rng_key, rng_key_ = random.split(rng_key)
nsamples = 1000
ys = d.sample(rng_key_, (nsamples,))
print(ys.shape)
mu_hat = np.mean(ys,0)
print(mu_hat)
sigma_hat = np.std(ys, 0)
print(sigma_hat) | (1000,)
1.5070927
2.0493808
| MIT | notebooks/numpyro_intro.ipynb | khanshehjad/pyprobml |
Multivariate Gaussian | mu = np.array([-1, 1])
sigma = np.array([1, 2])
Sigma = np.diag(sigma)
d2 = dist.MultivariateNormal(mu, Sigma)
#rng_key, rng_key_ = random.split(rng_key)
nsamples = 1000
ys = d2.sample(rng_key_, (nsamples,))
print(ys.shape)
mu_hat = np.mean(ys,0)
print(mu_hat)
Sigma_hat = np.cov(ys, rowvar=False) #jax.np.cov not implem... | (1000, 2)
[-1.0127413 1.0091063]
[[ 0.9770031 -0.00533966]
[-0.00533966 1.9718108 ]]
| MIT | notebooks/numpyro_intro.ipynb | khanshehjad/pyprobml |
Shape semanticsNumpyro, [Pyro](https://pyro.ai/examples/tensor_shapes.html) and [TFP](https://www.tensorflow.org/probability/examples/Understanding_TensorFlow_Distributions_Shapes) all distinguish between 'event shape' and 'batch shape'.For a D-dimensional Gaussian, the event shape is (D,), and the batch shapewill be ... | d2 = dist.MultivariateNormal(mu, Sigma)
print(f'event shape {d2.event_shape}, batch shape {d2.batch_shape}')
nsamples = 3
ys2 = d2.sample(rng_key_, (nsamples,))
print('samples, shape {}'.format(ys2.shape))
print(ys2)
# 2 independent 1d gaussians (same as one 2d diagonal Gaussian)
d3 = dist.Normal(mu, np.diag(Sigma))
... | -2.6185904
[-1.35307 -1.6120898]
| MIT | notebooks/numpyro_intro.ipynb | khanshehjad/pyprobml |
We can turn a set of independent distributions into a single productdistribution using the [Independent class](http://num.pyro.ai/en/stable/distributions.htmlindependent) | d4 = dist.Independent(d3, 1) # treat the first batch dimension as an event dimensions
print(d4.event_shape)
print(d4.batch_shape)
print(d4.log_prob(y)) | (2,)
()
-2.96516
| MIT | notebooks/numpyro_intro.ipynb | khanshehjad/pyprobml |
Posterior inference with MCMC Example: 1d Gaussian with unknown mean.We use the simple example from the [Pyro intro](https://pyro.ai/examples/intro_part_ii.htmlA-Simple-Example). The goal is to infer the weight $\theta$ of an object, given noisy measurements $y$. We assume the following model:$$\begin{align}\theta &\... | mu = 8.5; tau = 1.0; sigma = 0.75; y = 9.5
m = (sigma**2 * mu + tau**2 * y)/(sigma**2 + tau**2)
s2 = (sigma**2 * tau**2)/(sigma**2 + tau**2)
s = np.sqrt(s2)
print(m)
print(s)
def model(prior_mean, prior_sd, obs_sd, measurement=None):
theta = numpyro.sample("theta", dist.Normal(prior_mean, prior_sd))
return nump... | _____no_output_____ | MIT | notebooks/numpyro_intro.ipynb | khanshehjad/pyprobml |
Interactive Example 1. Run GaMMA in terminal or use QuakeFlow APINote: Please only use the QuakeFlow API for debugging and testing on small datasets. Do not run large jobs using the QuakeFlow API. The computational cost can be high for us.```bashuvicorn --app-dir=gamma app:app --reload --port 8001``` | import requests
import json
import pandas as pd
import os
# GAMMA_API_URL = "http://127.0.0.1:8001"
GAMMA_API_URL = "http://gamma.quakeflow.com" | _____no_output_____ | MIT | docs/example_interactive.ipynb | wayneweiqiang/GMMA |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.