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 |
|---|---|---|---|---|---|
Next we will need a specialized tokenizer for this model. This one will try to use the [spaCy](https://spacy.io/) and [ftfy](https://pypi.org/project/ftfy/) libraries if they are installed, or else it will fall back to BERT's `BasicTokenizer` followed by Byte-Pair Encoding (which should be fine for most use cases). | from transformers import OpenAIGPTTokenizer
tokenizer = OpenAIGPTTokenizer.from_pretrained("openai-gpt") | _____no_output_____ | Apache-2.0 | 16_nlp_with_rnns_and_attention.ipynb | otamilocintra/ml2gh |
Now let's use the tokenizer to tokenize and encode the prompt text: | prompt_text = "This royal throne of kings, this sceptred isle"
encoded_prompt = tokenizer.encode(prompt_text,
add_special_tokens=False,
return_tensors="tf")
encoded_prompt | _____no_output_____ | Apache-2.0 | 16_nlp_with_rnns_and_attention.ipynb | otamilocintra/ml2gh |
Easy! Next, let's use the model to generate text after the prompt. We will generate 5 different sentences, each starting with the prompt text, followed by 40 additional tokens. For an explanation of what all the hyperparameters do, make sure to check out this great [blog post](https://huggingface.co/blog/how-to-generat... | num_sequences = 5
length = 40
generated_sequences = model.generate(
input_ids=encoded_prompt,
do_sample=True,
max_length=length + len(encoded_prompt[0]),
temperature=1.0,
top_k=0,
top_p=0.9,
repetition_penalty=1.0,
num_return_sequences=num_sequences,
)
generated_sequences | _____no_output_____ | Apache-2.0 | 16_nlp_with_rnns_and_attention.ipynb | otamilocintra/ml2gh |
Now let's decode the generated sequences and print them: | for sequence in generated_sequences:
text = tokenizer.decode(sequence, clean_up_tokenization_spaces=True)
print(text)
print("-" * 80) | this royal throne of kings, this sceptred isle. even if someone had given them permission, even if it were required, they would never have been allowed to live through the hell they've survived.'
'they couldn't have known that.
--------------------------------------------------------------------------------
this royal ... | Apache-2.0 | 16_nlp_with_rnns_and_attention.ipynb | otamilocintra/ml2gh |
Notebook to verify the calculations of our simulator Importing required libraries | # importaing standard libraries
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from scipy.signal import freqs,periodogram,cheby1
import numpy as np
# import quantum libraries
import qutip
from itertools import product
from numpy import array, kron
from qmldataset import pauli_operators, create_custo... | 2021-09-26 16:34:01.309496: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0
| MIT | simulation/verification.ipynb | rajibchakravorty/QDataSet |
Step 1: Create a simulatorWe supply the parameters and create a simulator. Here we will create a 1-qubit experiment with Control on X-Axis, Type 1 noise on Z-Axis | dimension = 2
evolution_time = 1
num_time_steps = 1024
omega = 12
dynamic_operators = [0.5*pauli_operators[1]]
static_operators = [0.5*pauli_operators[3]*omega]
noise_operators = [0.5*pauli_operators[3]]
measurement_operators = pauli_operators[1:]
initial_states = [
np.array([[0.5, 0.5], [0.5, 0.5]]), np.array([[0.... | 2021-09-26 16:34:05.687838: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set
2021-09-26 16:34:05.689143: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcuda.so.1
2021-09-26 16:34:05.737996: I tensorflow/st... | MIT | simulation/verification.ipynb | rajibchakravorty/QDataSet |
Now we run a single experimentThe experiment will produce a result by simulating `num_realizations` number of noise realizations. | experiment_result = run_experiment(simulator=simulator_with_distortion) | 2021-09-26 16:34:09.738690: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:116] None of the MLIR optimization passes are enabled (registered 2)
2021-09-26 16:34:09.761987: I tensorflow/core/platform/profile_utils/cpu_utils.cc:112] CPU Frequency: 3094175000 Hz
2021-09-26 16:34:13.227801: I tensorflow/stream_... | MIT | simulation/verification.ipynb | rajibchakravorty/QDataSet |
Once run, let us read the experiment outcome | # plot the pulse
plt.figure()
num_controls = len(experiment_result["sim_parameters"]["dynamic_operators"])
for idx in range(num_controls):
plt.subplot(num_controls , 1, idx+1 )
plt.plot(experiment_result["time_range"], experiment_result["pulses"][:,0,idx], label="undistorted")
plt.plot(experiment_result["ti... | [[-20.345783 0.12233578 0.1 ]
[ 58.95591 0.27380085 0.1 ]
[ 38.14025 0.4457677 0.1 ]
[ 29.669308 0.61551726 0.1 ]
[-74.14498 0.7660476 0.1 ]]
| MIT | simulation/verification.ipynb | rajibchakravorty/QDataSet |
Display the distortion if exists | if distortion:
# display distortion filter if exists
distortion = cheby1(4,0.1,2*np.pi*20, analog=True)
# evaluate frequency response of the filter
w, Hw = freqs(distortion[0], distortion[1])
plt.figure(figsize=[15,4])
plt.subplot(1,2,1)
plt.semilogx(w, 20*np.log(np.abs(Hw)))
plt.xlabel(... | _____no_output_____ | MIT | simulation/verification.ipynb | rajibchakravorty/QDataSet |
Display the noise | # display noise if exists
for idx_profile,profile in enumerate(experiment_result["sim_parameters"]["noise_profile"]):
if profile in ['Type 2','Type 3','Type 4'] or (profile=='Type 6' and p==0):
# estimate the correlation matrix of the noise
correlation = 0
for k in range(experiment_result[... | _____no_output_____ | MIT | simulation/verification.ipynb | rajibchakravorty/QDataSet |
Comparing the output with `qutip`Hint: They should be same !! | # load initial states, measurement operators, and control Hamilotonian
initial_states = [qutip.Qobj(state) for state in experiment_result["sim_parameters"]["initial_states"] ]
measurements = [qutip.Qobj(op) for op in experiment_result["sim_parameters"]["measurement_operators"] ]
H0 = [ [qutip.Qobj(op), np.ones((le... | _____no_output_____ | MIT | simulation/verification.ipynb | rajibchakravorty/QDataSet |
Continuación clase método de la transformada inversa | # Librería de optimización
from scipy import optimize
from scipy.stats import beta
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# %matplotlib notebook
%matplotlib inline | _____no_output_____ | MIT | TEMA-2/Clase10_MetodoAceptacionRechazo.ipynb | AndresHdzJmz/SPF-2021-I |
Función para crear histograma de distribuciones discretas | def Gen_distr_discreta(p_acum: 'P.Acumulada de la distribución a generar',
indices: 'valores reales a generar aleatoriamente',
N: 'cantidad de números aleatorios a generar'):
U =np.random.rand(N)
# Diccionario de valores aleatorios
rand2reales = {i: idx for... | _____no_output_____ | MIT | TEMA-2/Clase10_MetodoAceptacionRechazo.ipynb | AndresHdzJmz/SPF-2021-I |
Ejemplo binomial: La distribución binomial modela el número de éxitos de n ensayos independientes donde hay una probabilidad p de éxito en cada ensayo.Generar una variable aletoria binomial con parámetros $n=10$ y $p=0.7$. Recordar que$$X\sim binomial(n,p) \longrightarrow p_i=P(X=i)=\frac{n!}{i!(n-i)!}p^i(1-p)^{n-i},\... | # Función que calcula la probabilidad acumulada optimizada
def P_acum_Binomial_o(n,p):
Pr = np.zeros(n)
Pr[0] = (1-p)**n
def pr(i):
nonlocal Pr
c = p/(1-p)
Pr[i+1]=(c*(n-i)/(i+1))*Pr[i]
# Lleno el vector Pr usando compresión de listas
[pr(i) for i in range(n-1)]
... | _____no_output_____ | MIT | TEMA-2/Clase10_MetodoAceptacionRechazo.ipynb | AndresHdzJmz/SPF-2021-I |
Explore el funcionamiento del siguiente comando | list(set(d_binomial)) | _____no_output_____ | MIT | TEMA-2/Clase10_MetodoAceptacionRechazo.ipynb | AndresHdzJmz/SPF-2021-I |
> TareaSeguir un procedimiento similar al mostrado cuando se generó una distribución binomial, pero en esta caso genere un código que genere variables aletorias Poisson cuya función de distribución de probabilidad esta dada por:>$$P(k,\lambda)=\frac{e^{-\lambda}(\lambda)^k}{k!}$$ > Demuestre matemáticamente que > $... | # Función de aceptación y rechazo usando for
def Acep_rechazo2(R2:'Variables distruidas U~U(0,1)',
R1:'Variables distribuidas como g(x)',
f:'función objetivo a generar',
t:'función que mayora a f'):
# R1 = np.random.rand(N)
f_x = f(R1)
t_x = t(R1)
condi... | _____no_output_____ | MIT | TEMA-2/Clase10_MetodoAceptacionRechazo.ipynb | AndresHdzJmz/SPF-2021-I |
b). Caso general: $\alpha,\beta>0$ | # Parámetros de la función beta
a =10; b=3
N = 500 # número de puntos
# Función objetivo
f = lambda x: beta.pdf(x,a,b)
x = np.arange(0,1,0.01)
plt.plot(x,f(x),'k')
# Encuentro el máximo de la función f
c = float(f(optimize.fmin(lambda x:-f(x),0,disp=False)))
print('El máximo de la función es:',c)
t = lambda x: c*np.o... | El máximo de la función es: 3.5848168690361635
| MIT | TEMA-2/Clase10_MetodoAceptacionRechazo.ipynb | AndresHdzJmz/SPF-2021-I |
Tarea 6Partiendo que se desea generar variables aleatorias para la siguiente función de densidad$$f(x)=30(x^2-2x^3+x^4)$$Responda los siguientes literales:1. Usar como función que mayora a $f(x)$ a $t(x)=a \sin(\pi x)$ donde a es el máximo de la función $f(x)$ y graficarlas en una misma gráfica, para validar que en re... | import numpy as np
import matplotlib.pyplot as plt
| _____no_output_____ | MIT | TEMA-2/Clase10_MetodoAceptacionRechazo.ipynb | AndresHdzJmz/SPF-2021-I |
xdata로 상관계수가 높은 column을 넣어서 Ridge- elasticnet으로 상관계수가 높은 feature를 넣어 모델생성 | from sklearn.metrics import mean_squared_error
# 필요 패키지 로드
#from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_absolute_error
# y값인 q1-q5가 결측인 2020년 데이터 제거
a = df[0:-82]
a
# 경찰서와 연도 데이터 제거
a.drop(columns... | _____no_output_____ | MIT | 2.Model_code/Linear/ridge_grid_search.ipynb | PpangPpang93/Main_project_police |
q1 절도폭력 | # 그리드 서치 후 최고 성능의 모델을 ridge1에 저장
grid_search.fit(xtrain1, ytrain1)
ridge1 = grid_search.best_estimator_
# MAE 출력
y_pred1 = ridge1.predict(xtest1)
mean_absolute_error(ytest1, y_pred1)
# 결과
print('alpha =', ridge1.alpha)
print(ridge1.coef_) # Ridge 회귀분석으로 나온 weghit값
print('가장 강한 양의 상관관계: ',a_1.columns[ridge1.coef_.arg... | alpha = 10.0
[ 0.1858718 0.35944705 -0.18654878 -0.88752003 0.12550527 -0.00879849
0.23483285 -0.25640454 0.46469126 0.50380436 0.85031836 -0.29439753
-0.17669475 0.36080588 0.12274043 -0.78509441 -0.35994638 0.30965558
0.10691769 0.51217057 -0.14159903 0.05857899 0.07225416 -0.33213259
-0.30612817 -0... | MIT | 2.Model_code/Linear/ridge_grid_search.ipynb | PpangPpang93/Main_project_police |
q2 강도살인 | # 그리드 서치 후 최고 성능의 모델을 ela2에 저장
grid_search.fit(xtrain2, ytrain2)
ridge2 = grid_search.best_estimator_
# MAE 출력
y_pred2 = ridge2.predict(xtest2)
mean_absolute_error(ytest2, y_pred2)
# 결과
print('alpha =', ridge2.alpha)
print(ridge2.coef_) # Ridge 회귀분석으로 나온 weghit값
print('가장 강한 양의 상관관계: ',a_2.columns[ridge2.coef_.argma... | alpha = 4.566000000000001
[ 0.0860792 0.4554509 -0.42882456 -1.39474717 -0.04082773 0.67245513
0.44065367 -0.35757788 0.36512942 1.13101206 1.47174792 -0.50713043
-0.21119051 0.64726755 0.26600496 -1.10801628 -0.61302412 0.37013122
-0.29569089 0.61392221 -0.10098044 0.05371732 0.21285102 -0.44627423
-... | MIT | 2.Model_code/Linear/ridge_grid_search.ipynb | PpangPpang93/Main_project_police |
q3 교통안전 | # 그리드 서치 후 최고 성능의 모델을 lasso3에 저장
grid_search.fit(xtrain3, ytrain3)
ridge3 = grid_search.best_estimator_
ridge3 = Ridge(alpha = 23)
ridge3.fit(xtrain3, ytrain3)
# MAE 출력
y_pred3 = ridge3.predict(xtest3)
mean_absolute_error(ytest3, y_pred3)
# 결과
print('alpha =', ridge3.alpha)
print(ridge3.coef_) # Ridge 회귀분석으로 나온 wegh... | alpha = 23
[ 0.60462781 -0.01836216 0.33480332 0.07597766 0.05094331 -0.01801049
0.12955529 -0.03098228 -0.02389251 0.32231312 0.36155864 -0.06357061
-0.17338605 0.10758736 -0.13071408 -0.23385295 -0.16651811 0.02234594
0.22738254 0.10056028 -0.08911714 -0.08948507 0.10180638 -0.05404081
0.32308556 -0.0... | MIT | 2.Model_code/Linear/ridge_grid_search.ipynb | PpangPpang93/Main_project_police |
q4 법질서 준수도 | # 그리드 서치 후 최고 성능의 모델을 lasso4에 저장
grid_search.fit(xtrain4, ytrain4)
ridge4 = grid_search.best_estimator_
# MAE 출력
y_pred4 = ridge4.predict(xtest4)
mean_absolute_error(ytest4, y_pred4)
# 결과
print('alpha =', ridge4.alpha)
print(ridge4.coef_) # Ridge 회귀분석으로 나온 weghit값
print('가장 강한 양의 상관관계: ',a_4.columns[ridge4.coef_.arg... | alpha = 10.0
[ 0.08422014 0.47496439 0.14834264 -0.31512474 0.90924745 0.72152184
-0.16558919 -0.19975831 -0.11015924 0.08660646 0.65342416 -0.33030785
-0.23131614 0.15442808 -0.02441021 -0.79282277 -0.16042672 0.17084599
0.28093741 0.34898235 -0.48400998 0.13322148 -0.25607675 -0.2081495
0.36480096 -0.... | MIT | 2.Model_code/Linear/ridge_grid_search.ipynb | PpangPpang93/Main_project_police |
q5 전반적 안전도 | # 그리드 서치 후 최고 성능의 모델을 lasso4에 저장
grid_search.fit(xtrain5, ytrain5)
ridge5 = grid_search.best_estimator_
ridge5 = Ridge(alpha = 6.25)
ridge5.fit(xtrain5, ytrain5)
# MAE 출력
y_pred5 = ridge5.predict(xtest5)
mean_absolute_error(ytest5, y_pred5)
# 결과
print('alpha =', ridge5.alpha)
print(ridge5.coef_) # Ridge 회귀분석으로 나온 we... | alpha = 6.25
[ 0.06421938 0.4187727 0.01456397 -0.98143189 0.27599427 0.34433021
0.25962214 -0.1884639 0.36799516 0.6268941 0.78630458 -0.33307267
-0.33674456 0.32468536 -0.07203347 -0.87313847 -0.42267696 0.30238462
0.04100536 0.52735428 -0.07934469 -0.02891441 0.096653 -0.20399747
0.23988935 -0... | MIT | 2.Model_code/Linear/ridge_grid_search.ipynb | PpangPpang93/Main_project_police |
Optional: Dropout**Note**: This exercise is optional and using dropout is not required to pass beyond the linear regime of the scoring function for your fully connected network.Dropout [1] is a technique for regularizing neural networks by randomly setting some features to zero during the forward pass. In this exercis... | # As usual, a bit of setup
import time
import numpy as np
import matplotlib.pyplot as plt
from exercise_code.classifiers.fc_net import *
from exercise_code.data_utils import get_CIFAR10_data
from exercise_code.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
from exercise_code.solver import... | _____no_output_____ | RSA-MD | exercise_2/3_Dropout-optional.ipynb | nazmicancalik/i2dl |
Dropout forward passIn the file `exercise_code/layers.py`, implement the forward pass for dropout. Since dropout behaves differently during training and testing, make sure to implement the operation for both modes.Once you have done so, run the cell below to test your implementation. | x = np.random.randn(500, 500) + 10
for p in [0.3, 0.6, 0.75]:
out, _ = dropout_forward(x, {'mode': 'train', 'p': p})
out_test, _ = dropout_forward(x, {'mode': 'test', 'p': p})
print('Running tests with p = ', p)
print('Mean of input: ', x.mean())
print('Mean of train-time output: ', out.mean())
... | _____no_output_____ | RSA-MD | exercise_2/3_Dropout-optional.ipynb | nazmicancalik/i2dl |
Dropout backward passIn the file `exercise_code/layers.py`, implement the backward pass for dropout. After doing so, run the following cell to numerically gradient-check your implementation. | x = np.random.randn(10, 10) + 10
dout = np.random.randn(*x.shape)
dropout_param = {'mode': 'train', 'p': 0.8, 'seed': 123}
out, cache = dropout_forward(x, dropout_param)
dx = dropout_backward(dout, cache)
dx_num = eval_numerical_gradient_array(lambda xx: dropout_forward(xx, dropout_param)[0], x, dout)
print('dx relat... | _____no_output_____ | RSA-MD | exercise_2/3_Dropout-optional.ipynb | nazmicancalik/i2dl |
Fully-connected nets with DropoutIn the file `exercise_code/classifiers/fc_net.py`, modify your implementation to use dropout. Specificially, if the constructor the the net receives a nonzero value for the `dropout` parameter, then the net should add dropout immediately after every ReLU nonlinearity. After doing so, r... | N, D, H1, H2, C = 2, 15, 20, 30, 10
X = np.random.randn(N, D)
y = np.random.randint(C, size=(N,))
for dropout in [0, 0.25, 0.5]:
print('Running check with dropout = ', dropout)
model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C,
weight_scale=5e-2, dtype=np.float64,
... | _____no_output_____ | RSA-MD | exercise_2/3_Dropout-optional.ipynb | nazmicancalik/i2dl |
Regularization experimentAs an experiment, we will train a pair of two-layer networks on 500 training examples: one will use no dropout, and one will use a dropout probability of 0.75. We will then visualize the training and validation accuracies of the two networks over time. | # Train two identical nets, one with dropout and one without
num_train = 500
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
solvers = {}
dropout_choices = [0, 0.75]
for dropout in dropout_choices:
model = Ful... | _____no_output_____ | RSA-MD | exercise_2/3_Dropout-optional.ipynb | nazmicancalik/i2dl |
QDA | load("PCA.rda")
load("DP.rda")
suppressMessages(library(caret))
set.seed(201703)
options(warn=-1)
# QDA
pca_qda_s = train(response~., data = pca_train, method = "qda", trControl = trainControl(method = "LOOCV"))
pca_qda_te = predict(pca_qda_s, data.frame(pca_test_s))
pca_qda_ac = mean(pca_qda_te == golub_test_r)
pca_qd... | _____no_output_____ | MIT | ReproducingMLpipelines/Paper6/ModelQDAPCA.ipynb | CompareML/AIM-Manuscript |
!pwd | /content
| MIT | Udacity Course.ipynb | jtkrohm/jt | |
print("JT") | JT
| MIT | Udacity Course.ipynb | jtkrohm/jt | |
Dependencies | from openvaccine_scripts import *
import warnings, json
from sklearn.model_selection import KFold, StratifiedKFold
import tensorflow.keras.layers as L
import tensorflow.keras.backend as K
from tensorflow.keras import optimizers, losses, Model
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
SEE... | _____no_output_____ | MIT | Model backlog/Models/41-openvaccine-weighted-samples.ipynb | dimitreOliveira/COVID-19-Vaccine-Degradation-Prediction |
Model parameters | config = {
"BATCH_SIZE": 64,
"EPOCHS": 120,
"LEARNING_RATE": 1e-3,
"ES_PATIENCE": 10,
"N_FOLDS": 5,
"N_USED_FOLDS": 5,
"PB_SEQ_LEN": 107,
"PV_SEQ_LEN": 130,
}
with open('config.json', 'w') as json_file:
json.dump(json.loads(json.dumps(config)), json_file)
config | _____no_output_____ | MIT | Model backlog/Models/41-openvaccine-weighted-samples.ipynb | dimitreOliveira/COVID-19-Vaccine-Degradation-Prediction |
Load data | database_base_path = '/kaggle/input/stanford-covid-vaccine/'
train = pd.read_json(database_base_path + 'train.json', lines=True)
test = pd.read_json(database_base_path + 'test.json', lines=True)
print('Train samples: %d' % len(train))
display(train.head())
print(f'Test samples: {len(test)}')
display(test.head()) | Train samples: 2400
| MIT | Model backlog/Models/41-openvaccine-weighted-samples.ipynb | dimitreOliveira/COVID-19-Vaccine-Degradation-Prediction |
Auxiliary functions | def get_dataset(x, y=None, sample_weights=None, labeled=True, shuffled=True, batch_size=32, buffer_size=-1, seed=0):
input_map = {'inputs_seq': x['sequence'],
'inputs_struct': x['structure'],
'inputs_loop': x['predicted_loop_type'],
'inputs_bpps_max': x['bpps_ma... | _____no_output_____ | MIT | Model backlog/Models/41-openvaccine-weighted-samples.ipynb | dimitreOliveira/COVID-19-Vaccine-Degradation-Prediction |
Model | def model_fn(hidden_dim=384, dropout=.5, pred_len=68, n_outputs=5):
inputs_seq = L.Input(shape=(None, 1), name='inputs_seq')
inputs_struct = L.Input(shape=(None, 1), name='inputs_struct')
inputs_loop = L.Input(shape=(None, 1), name='inputs_loop')
inputs_bpps_max = L.Input(shape=(None, 1), name='... | Model: "functional_1"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
i... | MIT | Model backlog/Models/41-openvaccine-weighted-samples.ipynb | dimitreOliveira/COVID-19-Vaccine-Degradation-Prediction |
Pre-process | # Add bpps as features
bpps_max = []
bpps_sum = []
bpps_mean = []
bpps_scaled = []
bpps_nb_mean = 0.077522 # mean of bpps_nb across all training data
bpps_nb_std = 0.08914 # std of bpps_nb across all training data
for row in train.itertuples():
probability = np.load(f'{database_base_path}/bpps/{row.id}.npy')
... | _____no_output_____ | MIT | Model backlog/Models/41-openvaccine-weighted-samples.ipynb | dimitreOliveira/COVID-19-Vaccine-Degradation-Prediction |
Training | AUTO = tf.data.experimental.AUTOTUNE
skf = KFold(n_splits=config['N_USED_FOLDS'], shuffle=True, random_state=SEED)
history_list = []
oof = train[['id', 'SN_filter', 'signal_to_noise'] + pred_cols].copy()
oof_preds = np.zeros((len(train), 68, len(pred_cols)))
test_public_preds = np.zeros((len(public_test), config['PB_S... |
FOLD: 1
Epoch 1/120
30/30 - 7s - loss: 3.5876 - output_react_loss: 0.4014 - output_bg_ph_loss: 0.5248 - output_ph_loss: 0.5226 - output_mg_c_loss: 0.4188 - output_c_loss: 0.3750 - val_loss: 2.3896 - val_output_react_loss: 0.2423 - val_output_bg_ph_loss: 0.3301 - val_output_ph_loss: 0.3582 - val_output_mg_c_loss: 0.302... | MIT | Model backlog/Models/41-openvaccine-weighted-samples.ipynb | dimitreOliveira/COVID-19-Vaccine-Degradation-Prediction |
Model loss graph | for fold, history in enumerate(history_list):
print(f'\nFOLD: {fold+1}')
print(f"Train {np.array(history['loss']).min():.5f} Validation {np.array(history['val_loss']).min():.5f}")
plot_metrics_agg(history_list) |
FOLD: 1
Train 1.05189 Validation 1.37240
FOLD: 2
Train 1.07609 Validation 1.38107
FOLD: 3
Train 1.05777 Validation 1.33757
FOLD: 4
Train 1.02478 Validation 1.38429
FOLD: 5
Train 0.91044 Validation 1.34764
| MIT | Model backlog/Models/41-openvaccine-weighted-samples.ipynb | dimitreOliveira/COVID-19-Vaccine-Degradation-Prediction |
Post-processing | # Assign preds to OOF set
for idx, col in enumerate(pred_cols):
val = oof_preds[:, :, idx]
oof = oof.assign(**{f'{col}_pred': list(val)})
oof.to_csv('oof.csv', index=False)
oof_preds_dict = {}
for col in pred_cols:
oof_preds_dict[col] = oof_preds[:, :, idx]
# Assign values to test set
preds_ls = []
... | _____no_output_____ | MIT | Model backlog/Models/41-openvaccine-weighted-samples.ipynb | dimitreOliveira/COVID-19-Vaccine-Degradation-Prediction |
Model evaluation | y_true_dict = get_targets_dict(train, pred_cols, train.index)
y_true = np.array([y_true_dict[col] for col in pred_cols]).transpose((1, 2, 0, 3)).reshape(oof_preds.shape)
display(evaluate_model(train, y_true, oof_preds, pred_cols)) | _____no_output_____ | MIT | Model backlog/Models/41-openvaccine-weighted-samples.ipynb | dimitreOliveira/COVID-19-Vaccine-Degradation-Prediction |
Visualize test predictions | submission = pd.read_csv(database_base_path + 'sample_submission.csv')
submission = submission[['id_seqpos']].merge(preds_df, on=['id_seqpos']) | _____no_output_____ | MIT | Model backlog/Models/41-openvaccine-weighted-samples.ipynb | dimitreOliveira/COVID-19-Vaccine-Degradation-Prediction |
Test set predictions | display(submission.head(10))
display(submission.describe())
submission.to_csv('submission.csv', index=False) | _____no_output_____ | MIT | Model backlog/Models/41-openvaccine-weighted-samples.ipynb | dimitreOliveira/COVID-19-Vaccine-Degradation-Prediction |
Inspecting trained model | seed = 600
system = 'chaotic-rnn'
if os.path.exists('./synth_data/%s_%s'%(system, seed)):
data_dict = read_data('./synth_data/%s_%s'%(system, seed))
else:
from synthetic_data import generate_chaotic_rnn_data
param_dict = yaml.load(open('./synth_data/%s_params.yaml'%system, 'r'), Loader=yaml.FullLoader)
... | _____no_output_____ | MIT | deprecated/.ipynb_checkpoints/lfads_demo-checkpoint.ipynb | lyprince/hierarchical_lfads |
Analyze a large dataset with Google BigQuery**Learning Objectives**1. Access an ecommerce dataset1. Look at the dataset metadata1. Remove duplicate entries1. Write and execute queries Introduction BigQuery is Google's fully managed, NoOps, low cost analytics database. With BigQuery you can query terabytes and terabyte... | import os
import pandas as pd
PROJECT = "<YOUR PROJECT>" #TODO Replace with your project id
os.environ["PROJECT"] = PROJECT
pd.options.display.max_columns = 50 | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/how_google_does_ml/bigquery/solution/analyze_with_bigquery_solution.ipynb | Glairly/introduction_to_tensorflow |
Explore eCommerce data and identify duplicate recordsScenario: You were provided with Google Analytics logs for an eCommerce website in a BigQuery dataset. The data analyst team created a new BigQuery table of all the raw eCommerce visitor session data. This data tracks user interactions, location, device types, tim... | %%bigquery --project $PROJECT
#standardsql
SELECT *
EXCEPT
(table_catalog, table_schema, is_generated, generation_expression, is_stored,
is_updatable, is_hidden, is_system_defined, is_partitioning_column, clustering_ordinal_position)
FROM `data-to-insights.ecommerce.INFORMATION_SCHEMA.COLUMNS`
WHERE tab... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/how_google_does_ml/bigquery/solution/analyze_with_bigquery_solution.ipynb | Glairly/introduction_to_tensorflow |
Next examine how many rows are in the table. TODO 1 | %%bigquery --project $PROJECT
#standardSQL
SELECT count(*)
FROM `data-to-insights.ecommerce.all_sessions_raw` | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/how_google_does_ml/bigquery/solution/analyze_with_bigquery_solution.ipynb | Glairly/introduction_to_tensorflow |
Now take a quick at few rows of data in the table. | %%bigquery --project $PROJECT
#standardSQL
SELECT *
FROM `data-to-insights.ecommerce.all_sessions_raw`
LIMIT 7 | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/how_google_does_ml/bigquery/solution/analyze_with_bigquery_solution.ipynb | Glairly/introduction_to_tensorflow |
Identify duplicate rowsSeeing a sample amount of data may give you greater intuition for what is included in the dataset. But since the table is quite large, a preview is not likely to render meaningful results. As you scan and scroll through the sample rows you see there is no singular field that uniquely identifies... | %%bigquery --project $PROJECT
#standardSQL
SELECT count(*) AS num_duplicate_rows,
*
FROM `data-to-insights.ecommerce.all_sessions_raw`
GROUP BY fullvisitorid,
channelgrouping,
time,
country,
city,
totaltransactionrevenue,
transactions,
... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/how_google_does_ml/bigquery/solution/analyze_with_bigquery_solution.ipynb | Glairly/introduction_to_tensorflow |
As you can see there are quite a few "duplicate" records (615) when analyzed with these parameters.In your own datasets, even if you have a unique key, it is still beneficial to confirm the uniqueness of the rows with COUNT, GROUP BY, and HAVING before you begin your analysis. Analyze the new all_sessions tableIn this... | %%bigquery --project $PROJECT
#standardSQL
SELECT fullvisitorid, # the unique visitor ID
visitid, # a visitor can have multiple visits
date, # session date stored as string YYYYMMDD
time, # time of the individual site hit (can be 0 or more)
v2productname, # not unique since a product ca... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/how_google_does_ml/bigquery/solution/analyze_with_bigquery_solution.ipynb | Glairly/introduction_to_tensorflow |
The query returns zero records indicating no duplicates exist. Write basic SQL against the eCommerce data (TODO 4)In this section, you query for insights on the ecommerce dataset.A good first path of analysis is to find the total unique visitorsThe query below determines the total views by counting product_views and t... | %%bigquery --project $PROJECT
#standardSQL
SELECT count(*) AS product_views,
count(DISTINCT fullvisitorid) AS unique_visitors
FROM `data-to-insights.ecommerce.all_sessions`; | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/how_google_does_ml/bigquery/solution/analyze_with_bigquery_solution.ipynb | Glairly/introduction_to_tensorflow |
The next query shows total unique visitors(fullVisitorID) by the referring site (channelGrouping): | %%bigquery --project $PROJECT
#standardSQL
SELECT count(DISTINCT fullvisitorid) AS unique_visitors,
channelgrouping
FROM `data-to-insights.ecommerce.all_sessions`
GROUP BY 2
ORDER BY 2 DESC; | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/how_google_does_ml/bigquery/solution/analyze_with_bigquery_solution.ipynb | Glairly/introduction_to_tensorflow |
To find deeper insights in the data, the next query lists the five products with the most views (product_views) from unique visitors. The query counts number of times a product (v2ProductName) was viewed (product_views), puts the list in descending order, and lists the top 5 entries: | %%bigquery --project $PROJECT
#standardSQL
SELECT count(*) AS product_views,
( v2productname ) AS ProductName
FROM `data-to-insights.ecommerce.all_sessions`
WHERE type = 'PAGE'
GROUP BY v2productname
ORDER BY product_views DESC
LIMIT 5; | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/how_google_does_ml/bigquery/solution/analyze_with_bigquery_solution.ipynb | Glairly/introduction_to_tensorflow |
Now expand your previous query to include the total number of distinct products ordered and the total number of total units ordered (productQuantity): | %%bigquery --project $PROJECT
#standardSQL
SELECT count(*) AS product_views,
count(productquantity) AS orders,
sum(productquantity) AS quantity_product_ordered,
v2productname
FROM `data-to-insights.ecommerce.all_sessions`
WHERE type = 'PAGE'
GROUP BY v2productname
ORDER ... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/how_google_does_ml/bigquery/solution/analyze_with_bigquery_solution.ipynb | Glairly/introduction_to_tensorflow |
Lastly, expand the query to include the average amount of product per order (total number of units ordered/total number of orders, or `SUM(productQuantity)/COUNT(productQuantity)`). | %%bigquery --project $PROJECT
#standardSQL
SELECT count(*) AS product_views,
count(productquantity) AS orders,
sum(productquantity) AS quantity_product_ordered,
sum(productquantity) / Count(productquantity) AS a... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/how_google_does_ml/bigquery/solution/analyze_with_bigquery_solution.ipynb | Glairly/introduction_to_tensorflow |
download the dataset from https://www.ncdc.noaa.gov/cag/global/time-series Data wrangling Normalize the column name :change the `value` to `Surface Temperature in Africa` in each dataframe | Africa1 <- read_csv(file = "Africa.csv")
Africa <- Africa1 %>% rename("SurfaceTemperature" = "Value")
Africa2 <- Africa %>% rename("Surface Temperature in Africa" = "SurfaceTemperature")
North_America1 <- read_csv(file = "North America.csv")
North_America <- North_America1 %>% rename("SurfaceTemperature" = "Value")
Nor... | _____no_output_____ | Apache-2.0 | Climate.ipynb | Deyang-Li/tidy-beauty |
Join together! | climate_df <- Africa2 %>%
full_join(North_America2) %>%
full_join(South_America2) %>%
full_join(Europe2) %>%
full_join(Asia2) %>%
full_join(Oceania2) | Joining, by = "Year"
Joining, by = "Year"
Joining, by = "Year"
Joining, by = "Year"
Joining, by = "Year"
| Apache-2.0 | Climate.ipynb | Deyang-Li/tidy-beauty |
check about the types of the columns, the missing values, and output a quick summary of the dataset. | glimpse(climate_df)
summary(climate_df)
climate_df %>%
skim() %>%
kable()
write_csv(climate_df,"Climate.csv") | _____no_output_____ | Apache-2.0 | Climate.ipynb | Deyang-Li/tidy-beauty |
Data analysis choose the data from 1950 to 2018 for ploting | Africa$pos = Africa$SurfaceTemperature >= 0
Africa_climate_plot <- Africa %>%
filter( Year >= 1950) %>%
ggplot(aes(
x = Year,
y = SurfaceTemperature,
fill = pos)) +
labs(title = "Time Series of Surface Temperature Anomalies in Africa") +
scale_x_continuous(breaks=seq(1950, 2020, ... | _____no_output_____ | Apache-2.0 | Climate.ipynb | Deyang-Li/tidy-beauty |
Put all plots together | library(ggpubr)
general_plot <- ggarrange(Africa_climate_plot, Asia_climate_plot,
Europe_climate_plot, South_America_climate_plot,
North_America_climate_plot, Oceania_climate_plot, ncol = 2, nrow = 3)
general_plot
ggsave(general_plot,filename = "Climate general plot.jpg",width ... | _____no_output_____ | Apache-2.0 | Climate.ipynb | Deyang-Li/tidy-beauty |
For some reason the mixed layer depth coordinate indices are displaced by +1 in relation to the ECCO data stored on Pangeo. The coordinates need to be matched for future calculations. | mxldepth.coords['i'] = coords['i']
mxldepth.coords['j'] = coords['j'] | _____no_output_____ | BSD-3-Clause | ecco_LPsstvarbudget_load.ipynb | cpatrizio88/pangeo_binder_example |
Calculate climatological mean mixed layer depth. We will be using this later to mask grid points outside of the mixed layer. | mxldepth_clim=mxldepth.mean(dim='time').load()
#mxldepth_clim=mxldepth.mean(dim='time').persist() | _____no_output_____ | BSD-3-Clause | ecco_LPsstvarbudget_load.ipynb | cpatrizio88/pangeo_binder_example |
Make a mask of points outside the ocean mixed layer: | mxlpoints = np.abs(coords['Z']) <= mxldepth_clim
# Flag for low-pass filtering
lowpass=True
# Filter requirements
order = 5
fs = 1 # sample rate, (cycles per month)
Tn = 12*3.
cutoff = 1/Tn # desired cutoff frequency of the filter (cycles per month)
# Face numbers to analyze
# 0: Southern Ocean (Atlantic)
# 1: S... | _____no_output_____ | BSD-3-Clause | ecco_LPsstvarbudget_load.ipynb | cpatrizio88/pangeo_binder_example |
The temperature variance budget is clearly balanced! Let's take a look at the contribution due to each term. | T_var_adv = fac*cov_adv
T_var_dif = fac*cov_dif
T_var_forc = fac*cov_forc
vmin=-1.0
vmax=1.0
sstmax=1.6
if lowpass:
sstmax=0.5
vmin=-0.5
vmax=0.5 | _____no_output_____ | BSD-3-Clause | ecco_LPsstvarbudget_load.ipynb | cpatrizio88/pangeo_binder_example |
Contributions to temperature variance from advection, diffusion and surface forcing | k=0
mapper(T_var_sum.isel(k=k), bnds=bnds, cmap='cubehelix_r', vmin=0,vmax=sstmax)
plt.title(r'temperature variance (K$^2$)')
plt.savefig(fout + 'Tvar_sum.png')
mapper(T_var_adv.isel(k=k), bnds=bnds, cmap='RdBu_r', vmin=vmin,vmax=vmax)
plt.title(r'advective contribution (K$^2$)')
plt.savefig(fout + 'Tvar_adv.png')
mapp... | _____no_output_____ | BSD-3-Clause | ecco_LPsstvarbudget_load.ipynb | cpatrizio88/pangeo_binder_example |
Contributions to ocean mixed layer temperature variance from advection, diffusion and surface forcing | mxlpoints = mxlpoints.isel(face=facen)
delz = drF*hFacC
delz=delz.where(mxlpoints)
delz_sum = delz.sum(dim='k')
mxlpoints
weights = delz/delz_sum
T_var_mxl = (weights*T_var).where(mxlpoints).sum(dim='k')
T_var_adv_mxl = (weights*T_var_adv).where(mxlpoints).sum(dim='k')
T_var_dif_mxl = (weights*T_var_dif).where(mxlpoint... | _____no_output_____ | BSD-3-Clause | ecco_LPsstvarbudget_load.ipynb | cpatrizio88/pangeo_binder_example |
speakers = os.listdir('./speaker_spectrograms/')speaker_pred = dict()for speaker in speakers: spects = np.load('./speaker_spectrograms/' + speaker) spects = spects.reshape(spects.shape+(1,)) pred = model.predict(spects) pred = np.argmax(pred, axis=-1) pred_labels = classes[pred] speaker_pred[speaker.s... | speaker_pred = pickle.load(open('./per_speaker_pred.pkl', 'rb'))
speaker_gt = pickle.load(open('./per_speaker_gt.pkl', 'rb'))
per_speaker = dict()
for speaker in os.listdir('./speaker_spectrograms/'):
speaker = speaker.split('.')[0]
pred = np.array(speaker_pred[speaker])
gt = np.array(speaker_gt[speaker])
... | _____no_output_____ | Apache-2.0 | Speaker_predictions.ipynb | aakaashjois/Dense-Recurrent-Net-For-Speech-Command-Classification |
Tweepy streamer Find Top tweeting user: - Find User who is tweeting a lot. - Find top 50 across the world. Since this is streaming application, we will use python logging module to log. [Further read.](https://www.webcodegeeks.com/python/python-logging-example/) | import logging # python logging module
# basic format for logging
logFormat = "%(asctime)s - [%(levelname)s] (%(funcName)s:%(lineno)d) %(message)s"
# logs will be stored in tweepy.log
logging.basicConfig(filename='tweepytopuser.log', level=logging.INFO,
format=logFormat, datefmt="%Y-%m-%d %H:%M:%S... | _____no_output_____ | Apache-2.0 | Dalon_4_RTD_MiniPro_Tweepy_Q5.ipynb | intellect82/venkateswarlu_SVAP_Asmt_R3 |
Authentication and AuthorisationCreate an app in twitter [here](https://apps.twitter.com/). Copy the necessary keys and access tokens, which will be used here in our code. The authorization is done using Oauth, An open protocol to allow secure authorization in a simple and standard method from web, mobile and desktop ... | import tweepy # importing all the modules required
import socket # will be used to create sockets
import json # manipulate json
from httplib import IncompleteRead
# Keep these tokens secret, as anyone can have full access to your
# twitter account, using these tokens
consumerKey = "#"
consumerSecret = "#"
acces... | _____no_output_____ | Apache-2.0 | Dalon_4_RTD_MiniPro_Tweepy_Q5.ipynb | intellect82/venkateswarlu_SVAP_Asmt_R3 |
Post this step, we will have full access to twitter api's | # Performing the authentication and authorization, post this step
# we will have full access to twitter api's
def connectToTwitter():
"""Connect to twitter."""
try:
auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)
api = tweep... | _____no_output_____ | Apache-2.0 | Dalon_4_RTD_MiniPro_Tweepy_Q5.ipynb | intellect82/venkateswarlu_SVAP_Asmt_R3 |
Streaming with tweepyThe Twitter streaming API is used to download twitter messages in real time. We use streaming api instead of rest api because, the REST api is used to pull data from twitter but the streaming api pushes messages to a persistent session. This allows the streaming api to download more data in real t... | # Tweet listner class which subclasses from tweepy.StreamListener
class TweetListner(tweepy.StreamListener):
"""Twitter stream listner"""
def __init__(self, csocket):
self.clientSocket = csocket
def dataProcessing(self, data):
"""Process the data, before sending to spark stream... | _____no_output_____ | Apache-2.0 | Dalon_4_RTD_MiniPro_Tweepy_Q5.ipynb | intellect82/venkateswarlu_SVAP_Asmt_R3 |
Drawbacks of twitter streaming APIThe major drawback of the Streaming API is that Twitter’s Steaming API provides only a sample of tweets that are occurring. The actual percentage of total tweets users receive with Twitter’s Streaming API varies heavily based on the criteria users request and the current traffic. Stud... | if __name__ == "__main__":
try:
api, auth = connectToTwitter() # connecting to twitter
# Global information is available by using 1 as the WOEID
# woeid = getWOEIDForTrendsAvailable(api, "Worldwide") # get the woeid of the worldwide
host = "localhost"
port = 8600
... | _____no_output_____ | Apache-2.0 | Dalon_4_RTD_MiniPro_Tweepy_Q5.ipynb | intellect82/venkateswarlu_SVAP_Asmt_R3 |
Analizando información de IMDB con KerasYa aprendiste cómo se construye una red neuronal. ¡Ahora es tu turno! En este reto, vas a construir una red neuronal que logra predecir si hay un sentimiento positivo o negativo en un review. | import numpy as np
import keras
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.preprocessing.text import Tokenizer
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(42) | _____no_output_____ | MIT | 2.IMDB.ipynb | Krax7/master-data-ai |
Paso 1. Cargar la información | # IMDB ya es un dataset que es parte de Keras, así que lo tenemos fácil!
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=1000)
print(x_train.shape)
print(x_test.shape) | _____no_output_____ | MIT | 2.IMDB.ipynb | Krax7/master-data-ai |
Paso 2. Comprender la informaciónEsta vez la información ya esta preprocesada, por lo cuál es mucho más fácil trabajar con ella. Todas las palabras han sido transformadas a números, y cada review es un vector con las palabras que contine. El output es el sentimiento, donde 1 es un sentimiento positivo y 0 un sentimien... | print(x_train[0])
print(y_train[0]) | _____no_output_____ | MIT | 2.IMDB.ipynb | Krax7/master-data-ai |
Paso 3. Modificar la información para la red neuronal One-hot encodingTenemos un vector con números, pero queremos convertirlo en muchos vectores con valor 0 ó 1. Por ejemplo, si el vector preprocesado contiene el número 14, entonces el vector procesado, en la entrada 14, será 1. Haremos lo mismo para la salida. Estam... | # One-hot encoding the output into vector mode, each of length 1000
tokenizer = Tokenizer(num_words=1000)
x_train = tokenizer.sequences_to_matrix(x_train, mode='binary')
x_test = tokenizer.sequences_to_matrix(x_test, mode='binary')
print(x_train[0])
# One-hot encoding the output
num_classes = 2
y_train = keras.utils.to... | _____no_output_____ | MIT | 2.IMDB.ipynb | Krax7/master-data-ai |
Paso 4. Construimos Arquitectura del ModeloConstruye un modelo secuencial. Siéntete libre de explorar y experimentar. | ## TODO: Construye un modelo secuencial
## TODO: Compila el modelo con un optimizador y una función de pérdida | _____no_output_____ | MIT | 2.IMDB.ipynb | Krax7/master-data-ai |
Paso 5. Entrenamos el modelo | ## TODO: Corre el modelo. Experimenta con diferentes tamaños de batch y número de epochs.
# Usa verbose=2 para ver cómo va progresando el modelo | _____no_output_____ | MIT | 2.IMDB.ipynb | Krax7/master-data-ai |
Paso 6. Evaluamos el modelo¿Crees poder llegar a más de 80%? ¿Qué tal arriba de 85%? | score = model.evaluate(x_test, y_test, verbose=0)
print("Accuracy: ", score[1]) | _____no_output_____ | MIT | 2.IMDB.ipynb | Krax7/master-data-ai |
SOLUCIONES No las veas antes de intentar tú primero Ya intentaste tú primero? Intenta primero | ## TODO: Construye un modelo secuencial
model = Sequential()
model.add(Dense(512, activation='relu', input_dim=1000))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.summary()
## TODO: Compila el modelo con un optimizador y una función de pérdida
model.compile(loss='categorical_crosse... | _____no_output_____ | MIT | 2.IMDB.ipynb | Krax7/master-data-ai |
Learn with us: www.zerotodeeplearning.comCopyright © 2021: Zero to Deep Learning ® Catalit LLC. | # 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 the L... | _____no_output_____ | Apache-2.0 | notebooks/Pre-trained_Models.ipynb | zuhairah87/ztdl-masterclasses |
Pre-trained Models | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
import os
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# sports_images_path = tf.keras.utils.get_file(
# 'sports_images',
# 'https://archive.org/download/ztdl_sports_images... | _____no_output_____ | Apache-2.0 | notebooks/Pre-trained_Models.ipynb | zuhairah87/ztdl-masterclasses |
Pre-trained modelLet's use a Resnet50 model to classify the images without any training. | from PIL import Image
from io import BytesIO
from IPython.display import HTML
import base64
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.applications.resnet50 import preprocess_input as preprocess_input_resnet50
from tensorflow.keras.applications.resnet50 import decode_predictions a... | _____no_output_____ | Apache-2.0 | notebooks/Pre-trained_Models.ipynb | zuhairah87/ztdl-masterclasses |
Stochastic examplesThis example is designed to show how to use the stochatic optimizationalgorithms for descrete and semicontinous measures from the POT library. | # Author: Kilian Fatras <kilian.fatras@gmail.com>
#
# License: MIT License
import matplotlib.pylab as pl
import numpy as np
import ot
import ot.plot | _____no_output_____ | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
COMPUTE TRANSPORTATION MATRIX FOR SEMI-DUAL PROBLEM | print("------------SEMI-DUAL PROBLEM------------") | ------------SEMI-DUAL PROBLEM------------
| MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
DISCRETE CASESample two discrete measures for the discrete case---------------------------------------------Define 2 discrete measures a and b, the points where are defined the sourceand the target measures and finally the cost matrix c. | n_source = 7
n_target = 4
reg = 1
numItermax = 1000
a = ot.utils.unif(n_source)
b = ot.utils.unif(n_target)
rng = np.random.RandomState(0)
X_source = rng.randn(n_source, 2)
Y_target = rng.randn(n_target, 2)
M = ot.dist(X_source, Y_target) | _____no_output_____ | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
Call the "SAG" method to find the transportation matrix in the discrete case---------------------------------------------Define the method "SAG", call ot.solve_semi_dual_entropic and plot theresults. | method = "SAG"
sag_pi = ot.stochastic.solve_semi_dual_entropic(a, b, M, reg, method,
numItermax)
print(sag_pi) | [[2.55553509e-02 9.96395660e-02 1.76579142e-02 4.31178196e-06]
[1.21640234e-01 1.25357448e-02 1.30225078e-03 7.37891338e-03]
[3.56123975e-03 7.61451746e-02 6.31505947e-02 1.33831456e-07]
[2.61515202e-02 3.34246014e-02 8.28734709e-02 4.07550428e-04]
[9.85500870e-03 7.52288517e-04 1.08262628e-02 1.21423583e-01]
[2.1... | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
SEMICONTINOUS CASESample one general measure a, one discrete measures b for the semicontinouscase---------------------------------------------Define one general measure a, one discrete measures b, the points whereare defined the source and the target measures and finally the cost matrix c. | n_source = 7
n_target = 4
reg = 1
numItermax = 1000
log = True
a = ot.utils.unif(n_source)
b = ot.utils.unif(n_target)
rng = np.random.RandomState(0)
X_source = rng.randn(n_source, 2)
Y_target = rng.randn(n_target, 2)
M = ot.dist(X_source, Y_target) | _____no_output_____ | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
Call the "ASGD" method to find the transportation matrix in the semicontinouscase---------------------------------------------Define the method "ASGD", call ot.solve_semi_dual_entropic and plot theresults. | method = "ASGD"
asgd_pi, log_asgd = ot.stochastic.solve_semi_dual_entropic(a, b, M, reg, method,
numItermax, log=log)
print(log_asgd['alpha'], log_asgd['beta'])
print(asgd_pi) | [3.75309361 7.63288278 3.76418767 2.53747778 1.70389504 3.53981297
2.67663944] [-2.49164966 -2.25281897 -0.77666675 5.52113539]
[[2.19699465e-02 1.03185982e-01 1.76983379e-02 2.87611188e-06]
[1.20688044e-01 1.49823131e-02 1.50635578e-03 5.68043045e-03]
[3.01194583e-03 7.75764779e-02 6.22686313e-02 8.78225379e-08]
... | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
Compare the results with the Sinkhorn algorithm---------------------------------------------Call the Sinkhorn algorithm from POT | sinkhorn_pi = ot.sinkhorn(a, b, M, reg)
print(sinkhorn_pi) | [[2.55535622e-02 9.96413843e-02 1.76578860e-02 4.31043335e-06]
[1.21640742e-01 1.25369034e-02 1.30234529e-03 7.37715259e-03]
[3.56096458e-03 7.61460101e-02 6.31500344e-02 1.33788624e-07]
[2.61499607e-02 3.34255577e-02 8.28741973e-02 4.07427179e-04]
[9.85698720e-03 7.52505948e-04 1.08291770e-02 1.21418473e-01]
[2.1... | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
PLOT TRANSPORTATION MATRIX Plot SAG results---------------- | pl.figure(4, figsize=(5, 5))
ot.plot.plot1D_mat(a, b, sag_pi, 'semi-dual : OT matrix SAG')
pl.show() | _____no_output_____ | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
Plot ASGD results----------------- | pl.figure(4, figsize=(5, 5))
ot.plot.plot1D_mat(a, b, asgd_pi, 'semi-dual : OT matrix ASGD')
pl.show() | _____no_output_____ | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
Plot Sinkhorn results--------------------- | pl.figure(4, figsize=(5, 5))
ot.plot.plot1D_mat(a, b, sinkhorn_pi, 'OT matrix Sinkhorn')
pl.show() | _____no_output_____ | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
COMPUTE TRANSPORTATION MATRIX FOR DUAL PROBLEM | print("------------DUAL PROBLEM------------") | ------------DUAL PROBLEM------------
| MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
SEMICONTINOUS CASESample one general measure a, one discrete measures b for the semicontinouscase---------------------------------------------Define one general measure a, one discrete measures b, the points whereare defined the source and the target measures and finally the cost matrix c. | n_source = 7
n_target = 4
reg = 1
numItermax = 100000
lr = 0.1
batch_size = 3
log = True
a = ot.utils.unif(n_source)
b = ot.utils.unif(n_target)
rng = np.random.RandomState(0)
X_source = rng.randn(n_source, 2)
Y_target = rng.randn(n_target, 2)
M = ot.dist(X_source, Y_target) | _____no_output_____ | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
Call the "SGD" dual method to find the transportation matrix in thesemicontinous case---------------------------------------------Call ot.solve_dual_entropic and plot the results. | sgd_dual_pi, log_sgd = ot.stochastic.solve_dual_entropic(a, b, M, reg,
batch_size, numItermax,
lr, log=log)
print(log_sgd['alpha'], log_sgd['beta'])
print(sgd_dual_pi) | [ 1.67648902 5.3770004 1.70385554 0.4276547 -0.77206786 1.0474898
0.54202203] [-0.23723788 -0.20259434 1.30855788 8.06179985]
[[2.62451875e-02 1.00499531e-01 1.78515577e-02 4.57450829e-06]
[1.20510690e-01 1.21972758e-02 1.27002374e-03 7.55197481e-03]
[3.65708350e-03 7.67963231e-02 6.38381061e-02 1.41974930e... | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
Compare the results with the Sinkhorn algorithm---------------------------------------------Call the Sinkhorn algorithm from POT | sinkhorn_pi = ot.sinkhorn(a, b, M, reg)
print(sinkhorn_pi) | [[2.55535622e-02 9.96413843e-02 1.76578860e-02 4.31043335e-06]
[1.21640742e-01 1.25369034e-02 1.30234529e-03 7.37715259e-03]
[3.56096458e-03 7.61460101e-02 6.31500344e-02 1.33788624e-07]
[2.61499607e-02 3.34255577e-02 8.28741973e-02 4.07427179e-04]
[9.85698720e-03 7.52505948e-04 1.08291770e-02 1.21418473e-01]
[2.1... | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
Plot SGD results----------------- | pl.figure(4, figsize=(5, 5))
ot.plot.plot1D_mat(a, b, sgd_dual_pi, 'dual : OT matrix SGD')
pl.show() | _____no_output_____ | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
Plot Sinkhorn results--------------------- | pl.figure(4, figsize=(5, 5))
ot.plot.plot1D_mat(a, b, sinkhorn_pi, 'OT matrix Sinkhorn')
pl.show() | _____no_output_____ | MIT | notebooks/plot_stochastic.ipynb | vfdev-5/POT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.