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 |
|---|---|---|---|---|---|
Skeletonize | import numpy as np
import cv2
from imutils import resize
from imutils.contours import sort_contours
from skimage.morphology import skeletonize as skl
# path = 'test_img/cat.png'
# path = "test_img/place.png"
# path = "test_img/cts.png"
path = "test_img/"+image_name
# path = 'test_img/reverse.png'
img = cv2.imread(pat... | _____no_output_____ | MIT | Notebooks/.ipynb_checkpoints/Character Segmentation Model -checkpoint.ipynb | swapnilmarathe007/Handwriting-Recognition |
Turn to transpose | trnspse_img = np.transpose(skel_img)
plt.imshow(trnspse_img) | _____no_output_____ | MIT | Notebooks/.ipynb_checkpoints/Character Segmentation Model -checkpoint.ipynb | swapnilmarathe007/Handwriting-Recognition |
Calculate the median of the word | up = []
down = []
for val in trnspse_img:
temp = []
for i , value in enumerate(val):
if(value>0):
temp.append(i)
try:
up.append(temp[0])
down.append(temp[-1])
except :
pass
up_avg = sum(up)//len(up)
print (up_avg)
down_avg = sum(down) // len(down)
print ... | _____no_output_____ | MIT | Notebooks/.ipynb_checkpoints/Character Segmentation Model -checkpoint.ipynb | swapnilmarathe007/Handwriting-Recognition |
Draw line in median in copy | copy_of_original[median] = [255] * len(copy_of_original[median])
plt.imshow(copy_of_original)
# Transpose look of median drawn image
plt.imshow(np.transpose(copy_of_original))
# checking from down till median for single 255 and sum of that val == 255
sp_list = [] # Segmentation Points
for i , val in enumerate(trnspse... | [193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 274, 276, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 384, 385, 386, 387,... | MIT | Notebooks/.ipynb_checkpoints/Character Segmentation Model -checkpoint.ipynb | swapnilmarathe007/Handwriting-Recognition |
To find Consecutive elements | def consecutive(data, stepsize=1):
return np.split(data, np.where(np.diff(data) != stepsize)[0]+1)
res_list = consecutive(sp_list)
# from Top
res_list_t = consecutive(sp_list_t)
for lst in res_list:
print (lst)
#from Top
for lst in res_list_t:
print (lst)
avg_of_blocks = []
#from top
avg_of_blocks_t = []
fo... | [85, 279, 353]
| MIT | Notebooks/.ipynb_checkpoints/Character Segmentation Model -checkpoint.ipynb | swapnilmarathe007/Handwriting-Recognition |
This is a new way of hacking | combine_copy = skel_img.copy()
plt.imshow(combine_copy)
new_combined_list = [] + new_avg_block
for val in new_avg_block_t:
for i , vl in enumerate(new_avg_block):
try:
if(val-vl > 80 and new_avg_block[i+1]-val > 80):
new_combined_list.append(val)
break
exc... | _____no_output_____ | MIT | Notebooks/.ipynb_checkpoints/Character Segmentation Model -checkpoint.ipynb | swapnilmarathe007/Handwriting-Recognition |
Tried but not working | transpose_of_copy = np.transpose(copy_of_original)
#for top
transpose_of_copy_t = np.transpose(copy_of_original)
plt.imshow(transpose_of_copy)
plt.imshow(transpose_of_copy_t)
# for val in avg_of_blocks:
# transpose_of_copy[val] = [255] * len(transpose_of_copy[val])
for val in new_avg_block:
transpose_of_copy[va... | 61
131
105
| MIT | Notebooks/.ipynb_checkpoints/Character Segmentation Model -checkpoint.ipynb | swapnilmarathe007/Handwriting-Recognition |
两种降维的途径:投影$(projection)$和流形学习$(Manifold\ Learning)$ 三种降维的技术:$PCA, Kernel\ PCA, LLE$ | # 2D
import numpy as np
p = 0
for it in range(100001):
x1, y1 = np.random.ranf(), np.random.ranf()
x2, y2 = np.random.ranf(), np.random.ranf()
p += np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
print(1.0 * p / 100000)
# 3D
p = 0
for it in range(100001):
x1, y1, z1 = np.random.ranf(), np.random.ranf(), np.ran... | 1.1286641926694834
| MIT | handson-ml/8_Dimensionality Reduction.ipynb | Luoyayu/Machine-Learning |
由上述计算可知,当维数增加时,hypercube中两点距离变大,当维数为1e6时,avg_dis=408.25,可知在高维空间内数据点间隔较大,分布非常稀疏, 这意味着遇到的new instace 也可能距离所有的train instances很远, 从而导致预测相比低维空间不可靠, 通常表现为overfitting, 因为模型做了很强的外推。一种直观的解决方法是增大数据密度然而显然这是不切实际的。 Main Approaches for Dimensionality Reduction Projection 投影法投影法基于这样的事实:虽然数据是多维度的,但是数据之间强关联性或者某类特征为常量,这样产生的数据集就很有可能仅... | from sklearn.datasets import make_swiss_roll
import matplotlib.pylab as plt
from mpl_toolkits.mplot3d import Axes3D
X, t = make_swiss_roll(n_samples=1000, noise=0.2, random_state=42)
axes = [-11.5, 14, -2, 23, -12, 15]
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X[:, 0], X... | _____no_output_____ | MIT | handson-ml/8_Dimensionality Reduction.ipynb | Luoyayu/Machine-Learning |
我们应该把瑞士卷拉开展平在2D上,而不是直接拍平 | plt.figure(figsize=(18, 6))
plt.subplot(121)
plt.scatter(X[:, 0], X[:, 1], c=t, cmap=plt.cm.hot)
plt.axis('off')
plt.subplot(122)
plt.scatter(t, X[:,1], c=t, cmap=plt.cm.hot)
plt.axis('off')
plt.show() | _____no_output_____ | MIT | handson-ml/8_Dimensionality Reduction.ipynb | Luoyayu/Machine-Learning |
Manifold Learning 所谓流形是指d维的超平面在更高的n维空间被bent,twist, 比如上面的右图其在作为2D平面在3D空间被roll后形成了3D瑞士卷 PCA Principal Component Analysis | np.random.seed(4)
m = 60
w1, w2 = 0.1, 0.3
noise = 0.1
angles = np.random.rand(m) * 3 * np.pi / 2 - 0.5
X = np.empty((m, 3))
X[:, 0] = np.cos(angles) + np.sin(angles)/2 + noise * np.random.randn(m) / 2
X[:, 1] = np.sin(angles) * 0.7 + noise * np.random.randn(m) / 2
X[:, 2] = X[:, 0] * w1 + X[:, 1] * w2 + noise * np.ra... | _____no_output_____ | MIT | handson-ml/8_Dimensionality Reduction.ipynb | Luoyayu/Machine-Learning |
Principal Component(PCs) | # 使用SVD(奇异值分解)求主成分PCs
import numpy as np
X_centered = X - X.mean(axis=0)
U, s, V = np.linalg.svd(X_centered)
c1 = V[:, 0]
c2 = V[:, 1]
c1, c2 # PCs
c1.dot(c2) # 正交
W2 = V.T[:, :2]
X2D = X_centered.dot(W2)
from sklearn.decomposition import PCA
pca = PCA(n_components = 2)
X2D = pca.fit_transform(X) # automatic centering
... | [0.84248607 0.14631839]
| MIT | handson-ml/8_Dimensionality Reduction.ipynb | Luoyayu/Machine-Learning |
Choose the Right Number of Dimensions | # 假设我们要求降维后的数据保存95%的信息
pca = PCA()
pca.fit(X)
cumsum = np.cumsum(pca.explained_variance_ratio_) # 前缀和cumsum
d = np.argmax(cumsum >= 0.95) + 1
print(d, cumsum[d-1])
pca = PCA(n_components=d) # or n_components = 0.95 | 2 0.988804464429311
| MIT | handson-ml/8_Dimensionality Reduction.ipynb | Luoyayu/Machine-Learning |
PCA for Compression | from sklearn.datasets import fetch_mldata
from sklearn.model_selection import train_test_split
import matplotlib
mnist = fetch_mldata("mnist original")
X = mnist['data']
y = mnist['target']
X_train, X_test, y_train, y_test = train_test_split(X, y)
def plot_digit(flat, size=28):
img = flat.reshape(size, size)
p... | _____no_output_____ | MIT | handson-ml/8_Dimensionality Reduction.ipynb | Luoyayu/Machine-Learning |
Incremental PCA | %matplotlib notebook
from sklearn.decomposition import IncrementalPCA
import numpy as np
n_batchs = 100
inc_pac = path = IncrementalPCA(n_components=169)
for X_batch in np.array_split(X_train, n_batchs):
inc_pac.partial_fit(X_batch)
X_mnist_reduced = inc_pac.fit_transform(X_train)
X_mnist_recoverd = inc_pac.inverse... | _____no_output_____ | MIT | handson-ml/8_Dimensionality Reduction.ipynb | Luoyayu/Machine-Learning |
[Module 1.2] 세이지 메이커 로컬 모드 및 스크립트 모드로 훈련본 워크샵의 모든 노트북은 **conda_tensorflow2_p36** 를 사용합니다.이 노트북은 아래와 같은 작업을 합니다.- 1. 기본 환경 세팅 - 2. 노트북에서 세이지 메이커 스크립트 모드 스타일로 코드 변경- 3. 세이지 메이커 스크립트 모드 스타일로 코드 실행 (실제로 세이지 메이커 사용 안함)- 4. 세이지 메이커 로컬 모드로 훈련- 5. 세이지 메이커의 호스트 모드로 훈련- 6. 모델 아티펙트 경로 저장 참고:- 이 페이지를 보시면 Cifar10 데이터 설명 및 기본 모델 훈련... | %load_ext autoreload
%autoreload 2
import sagemaker
sagemaker_session = sagemaker.Session()
bucket = sagemaker_session.default_bucket()
prefix = "sagemaker/DEMO-pytorch-cnn-cifar10"
role = sagemaker.get_execution_role()
import tensorflow as tf
print("tensorflow version: ", tf.__version__)
%store -r train_dir
%store... | _____no_output_____ | MIT | code/phase0/1.2.Train_Keras_Local_Script_Mode.ipynb | gonsoomoon-ml/SageMaker-Tensorflow-Step-By-Step |
2. 노트북에서 세이지 메이커 스크립트 모드 스타일로 코드 변경- 이 페이지를 보시면 기본 코드를 세이지 메이커 스크립트 모드로 변경하는 내용이 있습니다. - [Train a Keras Sequential Model (TensorFlow 2.0)](https://github.com/daekeun-ml/tensorflow-in-sagemaker-workshop/blob/master/0_Running_TensorFlow_In_SageMaker_tf2.ipynb)- 아래의 ` !pygmentize src/cifar10_keras_sm_tf2.py` 의 주석을 제거하... | # !pygmentize src/cifar10_keras_sm_tf2.py | _____no_output_____ | MIT | code/phase0/1.2.Train_Keras_Local_Script_Mode.ipynb | gonsoomoon-ml/SageMaker-Tensorflow-Step-By-Step |
3. 세이지 메이커 스크립트 모드 스타일로 코드 실행 (실제로 세이지 메이커 사용 안함)테스트를 위해 위와 동일한 명령(command)으로 새 스크립트를 실행하고, 예상대로 실행되는지 확인합니다. SageMaker TensorFlow API 호출 시에 환경 변수들은 자동으로 넘겨기지만, 로컬 주피터 노트북에서 테스트 시에는 수동으로 환경 변수들을 지정해야 합니다. (아래 예제 코드를 참조해 주세요.)```python%env SM_MODEL_DIR=./logs``` | print("train_dir: ", train_dir)
print("validation_dir: ", validation_dir)
print("eval_dir: ", eval_dir)
%%time
!mkdir -p logs
# Number of GPUs on this machine
%env SM_NUM_GPUS=1
# Where to save the model
%env SM_MODEL_DIR=./logs
!python src/cifar10_keras_sm_tf2.py --model_dir ./logs \
... | env: SM_NUM_GPUS=1
env: SM_MODEL_DIR=./logs
args:
Namespace(batch_size=128, epochs=1, eval='data/cifar10/eval', learning_rate=0.001, model_dir='./logs', model_output_dir='./logs', momentum=0.9, optimizer='adam', train='data/cifar10/train', validation='data/cifar10/validation', weight_decay=0.0002)
312/312 [==========... | MIT | code/phase0/1.2.Train_Keras_Local_Script_Mode.ipynb | gonsoomoon-ml/SageMaker-Tensorflow-Step-By-Step |
4. 세이지 메이커 로컬 모드로 훈련본격적으로 학습을 시작하기 전에 로컬 모드를 사용하여 디버깅을 먼저 수행합니다. 로컬 모드는 학습 인스턴스를 생성하는 과정이 없이 로컬 인스턴스로 컨테이너를 가져온 후 곧바로 학습을 수행하기 때문에 코드를 보다 신속히 검증할 수 있습니다.Amazon SageMaker Python SDK의 로컬 모드는 TensorFlow 또는 MXNet estimator서 단일 인자값을 변경하여 CPU (단일 및 다중 인스턴스) 및 GPU (단일 인스턴스) SageMaker 학습 작업을 에뮬레이션(enumlate)할 수 있습니다. 로컬 모드 학습을... | !wget -q https://raw.githubusercontent.com/aws-samples/amazon-sagemaker-script-mode/master/local_mode_setup.sh
!wget -q https://raw.githubusercontent.com/aws-samples/amazon-sagemaker-script-mode/master/daemon.json
!/bin/bash ./local_mode_setup.sh | nvidia-docker2 already installed. We are good to go!
SageMaker instance route table setup is ok. We are good to go.
SageMaker instance routing for Docker is ok. We are good to go!
| MIT | code/phase0/1.2.Train_Keras_Local_Script_Mode.ipynb | gonsoomoon-ml/SageMaker-Tensorflow-Step-By-Step |
로컬 모드로 훈련 실행- 아래의 두 라인이 로컬모드로 훈련을 지시 합니다.```python instance_type=instance_type, local_gpu or local 지정 session = sagemaker.LocalSession(), 로컬 세션을 사용합니다.``` 로컬의 GPU, CPU 여부로 instance_type 결정 | import os
import subprocess
instance_type = "local_gpu" # GPU 사용을 가정 합니다. CPU 사용시에 'local' 로 정의 합니다.
print("Instance type = " + instance_type) | Instance type = local_gpu
| MIT | code/phase0/1.2.Train_Keras_Local_Script_Mode.ipynb | gonsoomoon-ml/SageMaker-Tensorflow-Step-By-Step |
학습 작업을 시작하기 위해 `estimator.fit() ` 호출 시, Amazon ECR에서 Amazon SageMaker TensorFlow 컨테이너를 로컬 노트북 인스턴스로 다운로드합니다.`sagemaker.tensorflow` 클래스를 사용하여 SageMaker Python SDK의 Tensorflow Estimator 인스턴스를 생성합니다.인자값으로 하이퍼파라메터와 다양한 설정들을 변경할 수 있습니다.자세한 내용은 [documentation](https://sagemaker.readthedocs.io/en/stable/using_tf.htmltraining-... | from sagemaker.tensorflow import TensorFlow
estimator = TensorFlow(base_job_name='cifar10',
entry_point='cifar10_keras_sm_tf2.py',
source_dir='src',
role=role,
framework_version='2.4.1',
py_version='py37',... | Creating roqiryt46i-algo-1-jt4ft ...
Creating roqiryt46i-algo-1-jt4ft ... done
Attaching to roqiryt46i-algo-1-jt4ft
[36mroqiryt46i-algo-1-jt4ft |[0m 2021-10-11 09:57:34.729714: W tensorflow/core/profiler/internal/smprofiler_timeline.cc:460] Initializing the SageMaker Profiler.
[36mroqiryt46i-algo-1-jt4ft |[0m 2021... | MIT | code/phase0/1.2.Train_Keras_Local_Script_Mode.ipynb | gonsoomoon-ml/SageMaker-Tensorflow-Step-By-Step |
ECR 로 부터 로컬에 다운로드된 도커 이미지 확인 | ! docker image ls | REPOSITORY TAG IMAGE ID CREATED SIZE
763104351884.dkr.ecr.us-east-1.amazonaws.com/tensorflow-training 2.4.1-gpu-py37 8467bc1c5070 5 months ago 8.91GB
| MIT | code/phase0/1.2.Train_Keras_Local_Script_Mode.ipynb | gonsoomoon-ml/SageMaker-Tensorflow-Step-By-Step |
5. 세이지 메이커의 호스트 모드로 훈련 데이터 세트를 S3에 업로드- 로컬에 저장되어 있는 데이터를 S3 로 업로드하여 사용합니다. | dataset_location = sagemaker_session.upload_data(path=data_dir, key_prefix='data/DEMO-cifar10')
display(dataset_location)
from sagemaker.tensorflow import TensorFlow
estimator = TensorFlow(base_job_name='cifar10',
entry_point='cifar10_keras_sm_tf2.py',
source_dir='src',
... | train_instance_type has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
train_instance_count has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
train_instance_type has been renamed in sagemaker>=2.
See: https://sagema... | MIT | code/phase0/1.2.Train_Keras_Local_Script_Mode.ipynb | gonsoomoon-ml/SageMaker-Tensorflow-Step-By-Step |
SageMaker Host Mode 로 훈련- `cifar10_estimator.fit(inputs, wait=False)` - 입력 데이터를 inputs로서 S3 의 경로를 제공합니다. - wait=False 로 지정해서 async 모드로 훈련을 실행합니다. - 실행 경과는 아래의 cifar10_estimator.logs() 에서 확인 합니다. | %%time
estimator.fit({'train':'{}/train'.format(dataset_location),
'validation':'{}/validation'.format(dataset_location),
'eval':'{}/eval'.format(dataset_location)}, wait=False)
estimator.logs() | 2021-10-11 10:10:06 Starting - Starting the training job...
2021-10-11 10:10:29 Starting - Launching requested ML instancesProfilerReport-1633947005: InProgress
............
2021-10-11 10:12:29 Starting - Preparing the instances for training.........
2021-10-11 10:14:02 Downloading - Downloading input data
2021-10-11 1... | MIT | code/phase0/1.2.Train_Keras_Local_Script_Mode.ipynb | gonsoomoon-ml/SageMaker-Tensorflow-Step-By-Step |
6. 모델 아티펙트 저장- S3 에 저장된 모델 아티펙트를 저장하여 추론시 사용합니다. | keras_script_artifact_path = estimator.model_data
print("script_artifact_path: ", keras_script_artifact_path)
%store keras_script_artifact_path | script_artifact_path: s3://sagemaker-us-east-1-227612457811/cifar10-2021-10-11-10-10-05-339/output/model.tar.gz
Stored 'keras_script_artifact_path' (str)
| MIT | code/phase0/1.2.Train_Keras_Local_Script_Mode.ipynb | gonsoomoon-ml/SageMaker-Tensorflow-Step-By-Step |
Add model: translation attention ecoder-decocer over the b4 dataset | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchtext import data
import pandas as pd
import unicodedata
import string
import re
import random
import copy
from contra_qa.plots.functions import simple_step_plot, plot_confusion_matrix
import matplotlib.pyplot as plt
device... | _____no_output_____ | MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
Preparing data | df2 = pd.read_csv("data/boolean5_train.csv")
df2_test = pd.read_csv("data/boolean5_test.csv")
df2["text"] = df2["sentence1"] + df2["sentence2"]
df2_test["text"] = df2_test["sentence1"] + df2_test["sentence2"]
all_sentences = list(df2.text.values) + list(df2_test.text.values)
df2train = df2.iloc[:8500]
df2valid = d... | Read 8500 sentence pairs
Trimmed to 8500 sentence pairs
Counting words...
Counted words:
eng_enc 773
eng_dec 772
Read 1500 sentence pairs
Trimmed to 1500 sentence pairs
Counting words...
Counted words:
eng_enc 701
eng_dec 700
| MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
sentences 2 tensors | def indexesFromSentence(lang, sentence):
return [lang.word2index[word] for word in sentence.split(' ')]
def tensorFromSentence(lang, sentence):
indexes = indexesFromSentence(lang, sentence)
indexes.append(EOS_token)
return torch.tensor(indexes, dtype=torch.long, device=device).view(-1, 1)
def tensorsFro... | _____no_output_____ | MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
models | class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size):
super(EncoderRNN, self).__init__()
self.hidden_size = hidden_size
self.embedding = nn.Embedding(input_size, hidden_size)
self.gru = nn.GRU(hidden_size, hidden_size)
def forward(self, input, hidden):
... | _____no_output_____ | MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
translating | def translate(encoder,
decoder,
sentence,
max_length=MAX_LENGTH):
with torch.no_grad():
input_tensor = tensorFromSentence(input_lang, sentence)
input_length = input_tensor.size()[0]
encoder_hidden = encoder.initHidden()
encoder_outputs = tor... | _____no_output_____ | MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
translation of a trained model: and A | for t in training_pairs_A[0:3]:
print("input_sentence : " + t[0])
neural_translation = translate(encoderA,
decoderA,
t[0],
max_length=MAX_LENGTH)
print("neural translation : " + neural_translation)
r... | input_sentence : jeffery created a silly and vast work of art
neural translation : brenda created a blue work of art <EOS>
reference translation : jeffery created a silly work of art <EOS>
blue score = 0.41
input_sentence : hilda created a zealous and better work of art
neural translation : brenda created a pitiful wo... | MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
translation of a trained model: and B | for t in training_pairs_B[0:3]:
print("input_sentence : " + t[0])
neural_translation = translate(encoderB,
decoderB,
t[0],
max_length=MAX_LENGTH)
print("neural translation : " + neural_translation)
r... | input_sentence : jeffery created a silly and vast work of art
neural translation : marion created a vast work of art <EOS>
reference translation : jeffery created a vast work of art <EOS>
blue score = 0.84
input_sentence : hilda created a zealous and better work of art
neural translation : marion created a better work... | MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
Defining the And modelmodel inner working:- $s_1$ is the first sentence (e.g., 'penny is thankful and naomi is alive')- $s_2$ is the second sentence (e.g., 'penny is not alive')- $h_A = dec_{A}(enc_{A}(s_1, \vec{0}))$- $h_B = dec_{B}(enc_{B}(s_1, \vec{0}))$- $h_{inf} = \sigma (W[h_A ;h_B] + b)$- $e = enc_{A}(s_2, h_{i... | class AndModel(nn.Module):
def __init__(self,
encoderA,
decoderA,
encoderB,
decoderB,
hidden_size,
output_size,
max_length,
input_lang,
target_lang,
... | _____no_output_____ | MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
Test encoding decoding | for ex in training_pairs_B[0:3]:
print("===========")
ex = ex[0]
print("s1:\n")
print(ex)
print()
ex_A = addmodel.sen2vec(ex,
addmodel.encoderA,
addmodel.decoderA,
is_tensor=False,
out_tensor=False)
... | ('jeffery created a silly and vast work of art', 'jeffery didn t create a silly work of art', 1)
(tensor([[ 2],
[ 3],
[ 4],
[ 5],
[ 6],
[ 7],
[ 8],
[ 9],
[10],
[ 1]]), tensor([[ 2],
[11],
[12],
[13],
[ 4],
[ ... | MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
Prediction BEFORE training | n_iters = 100
training_pairs_little = [random.choice(train_triples_t) for i in range(n_iters)]
predictions = []
labels = []
for i in range(n_iters):
s1, s2, label = training_pairs_little[i]
pred = addmodel.predict(s1, s2)
label = label.item()
pred = pred.item()
predictions.append(pred)
labels.a... | _____no_output_____ | MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
Training functions | def CEtrain(s1_tensor,
s2_tensor,
label,
model,
optimizer,
criterion):
model.train()
optimizer.zero_grad()
logits = model(s1_tensor, s2_tensor)
loss = criterion(logits, label)
loss.backward()
optimizer.step()
return loss | _____no_output_____ | MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
Test CEtrain | CE = nn.CrossEntropyLoss()
addmodel_opt = torch.optim.SGD(addmodel.parameters(), lr= 0.3)
loss = CEtrain(s1_tensor=example_t[0],
s2_tensor=example_t[1],
label=example_t[2],
model=addmodel,
optimizer=addmodel_opt,
criterion=CE)
assert type(loss.... | _____no_output_____ | MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
Little example of training | epochs = 10
learning_rate = 0.1
CE = nn.CrossEntropyLoss()
encoderA = EncoderRNN(eng_enc_v_size, hidden_size)
decoderA = AttnDecoderRNN(hidden_size, eng_dec_v_size)
encoderA.load_state_dict(torch.load("b5_encoder1_att.pkl"))
decoderA.load_state_dict(torch.load("b5_decoder1_att.pkl"))
encoderB = EncoderRNN(eng_enc_v_s... | epoch 1/10 0m 59s mean loss = 1.36
epoch 2/10 0m 58s mean loss = 0.87
epoch 3/10 1m 2s mean loss = 0.85
epoch 4/10 0m 59s mean loss = 0.82
epoch 5/10 0m 54s mean loss = 0.80
epoch 6/10 0m 53s mean loss = 0.78
epoch 7/10 0m 50s mean loss = 0.77
epoch 8/10 0m 59s mean loss = 0.77
epoch 9/10 0m 53s mean loss = 0.76
epoch ... | MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
Prediction AFTER training | n_iters = 100
training_pairs_little = [random.choice(train_triples_t) for i in range(n_iters)]
predictions = []
labels = []
for i in range(n_iters):
s1, s2, label = training_pairs_little[i]
pred = addmodel.predict(s1, s2)
label = label.item()
pred = pred.item()
predictions.append(pred)
labels.a... | _____no_output_____ | MIT | lab/notebooks_phase2/AddModel_simpleB_b5.ipynb | felipessalvatore/ContraQA |
 Ingeniería de características Suavizado de series de tiempo [Julio Waissman Vilanova](julio.waissman@unison.mx)Vamos a ver diferentes tipos y formas de suavisar curvas. Para esto, vamos a utilizar como serie de tiempo la serie de casos confirmados por... | import pandas as pd
import statsmodels.api as sm
import plotly.graph_objects as go
import plotly.express as px
confirmados = pd.read_csv(
"Casosdiarios.csv",
engine="python",
parse_dates=['Fecha']
)[['Fecha', 'CASOS']] \
.groupby("Fecha") \
.sum() \
.diff() + 1
fig = px.scatter(
confirm... | _____no_output_____ | MIT | suavizado/suavizado.ipynb | mcd-unison/ing-caracteristicas-2020 |
Suavizado por medias movilesEl suavizado por media movil utiliza una ventana de tiempo en los datos para suavizar. La ventana de tiempo debe de tener sentido para los datos, pero se puede jugar con ella. Para esto se usa el método `rolling` el cual se puede usar con otros tipos de funciones. | confirmados["ma 3"] = confirmados.CASOS.rolling(window=3, center=True).mean()
confirmados["ma 7"] = confirmados.CASOS.rolling(window=7, center=True).mean()
confirmados["ma 14"] = confirmados.CASOS.rolling(window=14, center=True).mean()
fig = go.Figure(
).add_scatter(
x=confirmados.index,
y=confirmados["CASOS"]... | _____no_output_____ | MIT | suavizado/suavizado.ipynb | mcd-unison/ing-caracteristicas-2020 |
Medianas moviles exponenciales | confirmados["mm 3"] = confirmados.CASOS.rolling(window=3, center=True).median()
confirmados["mm 7"] = confirmados.CASOS.rolling(window=7, center=True).median()
confirmados["mm 14"] = confirmados.CASOS.rolling(window=14, center=True).median()
fig = go.Figure(
).add_scatter(
x=confirmados.index,
y=confirmados["C... | _____no_output_____ | MIT | suavizado/suavizado.ipynb | mcd-unison/ing-caracteristicas-2020 |
Medias moviles exponenciales | confirmados["ewm 3"] = confirmados.CASOS.ewm(span=3).mean()
confirmados["ewm 7"] = confirmados.CASOS.ewm(span=7).mean()
confirmados["ewm 14"] = confirmados.CASOS.ewm(span=14).mean()
fig = go.Figure(
).add_scatter(
x=confirmados.index,
y=confirmados["CASOS"],
mode='markers',
name="Real"
).add_scatter(
... | _____no_output_____ | MIT | suavizado/suavizado.ipynb | mcd-unison/ing-caracteristicas-2020 |
LOWESS | lowess = sm.nonparametric.lowess
l1 = lowess(confirmados.CASOS, confirmados.index, frac=1/5)
l2 = lowess(confirmados.CASOS, confirmados.index, frac=1/10)
l3 = lowess(confirmados.CASOS, confirmados.index, frac=1/20)
fig = go.Figure(
).add_scatter(
x=confirmados.index,
y=confirmados["CASOS"],
mode='markers'... | _____no_output_____ | MIT | suavizado/suavizado.ipynb | mcd-unison/ing-caracteristicas-2020 |
Casting as a date type | %%read_sql
SELECT date::date
FROM wnv_train
LIMIT 10 | Query started at 02:52:58 PM EDT; Query executed in 0.00 m | MIT | src/solutions/feature_engineering_solutions.ipynb | crawles/data-science-training |
Extracting year, month, and day from a date | input_table = 'wnv_train'
output_table = 'wnv_train_ts'
%%read_sql
DROP TABLE if EXISTS {output_table};
CREATE TABLE {output_table}
AS
WITH wnv_train_dates AS (
SELECT date::date date_ts, *
FROM {input_table}
)
SELECT extract(year from date_ts)::int AS yea... | Query started at 02:52:59 PM EDT; Query executed in 0.00 m | MIT | src/solutions/feature_engineering_solutions.ipynb | crawles/data-science-training |
Aggregate to Trap, Species, Level We are asked to predict for a given day, trap, and species, predict the presence of West Nile Virus in mosquitoes. | input_table = 'wnv_train_ts'
output_table = 'wnv_train_agg'
%%read_sql
DROP TABLE IF EXISTS {output_table};
CREATE TABLE {output_table}
AS
SELECT date_ts,year,month,day,day_of_year,trap,latitude,longitude,species,
SUM(NumMosquitos)::int total_num_mosquitos,
MAX(WnvPresent) wnv_present
FROM {input_table}
G... | Query started at 02:53:00 PM EDT; Query executed in 0.00 m | MIT | src/solutions/feature_engineering_solutions.ipynb | crawles/data-science-training |
Categorical Variable Enconding | input_table = 'wnv_train_agg'
output_table = 'wnv_train_agg_dummy'
df = %read_sql SELECT species FROM {input_table}
import re
species = ['CULEX PIPIENS/RESTUANS',
'CULEX RESTUANS',
'CULEX PIPIENS',
'CULEX TERRITANS',
'CULEX SALINARIUS',
'CULEX TARSALIS',
'CULEX ERRATICUS']
def _clean_dummy_val( cval):
"""Fo... | Query started at 02:54:09 PM EDT; Query executed in 0.00 m | MIT | src/solutions/feature_engineering_solutions.ipynb | crawles/data-science-training |
Weather Data Data Cleansing and Missing ValuesNeed to remove whitespace and replace characters with empty | input_table = 'wnv_weather'
output_table = 'wnv_trimmed'
df = %read_sql SELECT * FROM wnv_weather
df.dtypes | Query started at 03:08:37 PM EDT; Query executed in 0.00 m | MIT | src/solutions/feature_engineering_solutions.ipynb | crawles/data-science-training |
Trim White Space | %%read_sql
DROP TABLE IF EXISTS {output_table};
CREATE TEMP TABLE {output_table}
AS
SELECT *,
trim(avgspeed) avgspeed_trimmed,
trim(preciptotal) preciptotal_trimmed,
/* trim(tmin) tmin_trimmed, */
trim(tavg) tavg_trimmed
/* trim(tmax) tmax_trimmed */
FROM {input_table}
%read_sql SELEC... | _____no_output_____ | MIT | src/solutions/feature_engineering_solutions.ipynb | crawles/data-science-training |
Replacing Missing Variables | input_table = 'wnv_trimmed'
output_table = 'wnv_weather_clean'
%%read_sql
DROP TABLE IF EXISTS {output_table};
CREATE TABLE {output_table}
AS
SELECT date,
CAST(regexp_replace(avgspeed_trimmed, '^[^\d.]+$', '0') AS float) AS avgspeed,
CAST(regexp_replace(preciptotal_trimmed, '^[^\d.]+$', '0') AS float) AS... | Query started at 03:15:26 PM EDT; Query executed in 0.00 mQuery started at 03:15:26 PM EDT; Query executed in 0.00 m | MIT | src/solutions/feature_engineering_solutions.ipynb | crawles/data-science-training |
Create weather date features (same as for station data)This analysis is the same as used for the station data so we have filled it in. | input_table = 'wnv_weather_clean'
output_table = 'wnv_weather_ts'
%%read_sql
DROP TABLE if EXISTS {output_table};
CREATE TABLE {output_table}
AS
WITH wnv_weather_dates AS (
SELECT date::date date_ts, *
FROM {input_table}
)
SELECT extract(yea... | Query started at 03:15:30 PM EDT; Query executed in 0.00 m | MIT | src/solutions/feature_engineering_solutions.ipynb | crawles/data-science-training |
Compute Weather Averages | input_table = 'wnv_weather_ts'
output_table = 'wnv_weather_rolling'
%%read_sql
DROP TABLE IF EXISTS {output_table};
CREATE TABLE {output_table}
AS
SELECT date_ts,
avg(avgspeed) OVER (ORDER BY date_ts RANGE BETWEEN 7 PRECEDING AND CURRENT ROW),
avg(preciptotal) OVER (ORDER BY date_ts RANGE BETWEEN 7 PRECED... | Query started at 03:52:39 PM Eastern Daylight Time
Query executed in 0.00 m
| MIT | src/solutions/feature_engineering_solutions.ipynb | crawles/data-science-training |
Putting it All Together: Join weather data and mosquito station data | station_table = 'wnv_train_agg_dummy'
weather_table = 'wnv_weather_rolling'
output_table = 'wnv_features'
df = %read_sql SELECT * FROM {station_table} LIMIT 10
df.columns.tolist()
%%read_sql
DROP TABLE IF EXISTS {output_table};
CREATE TABLE {output_table}
AS
SELECT row_number() OVER () as id, *
FROM {station_table}
INN... | 1
| MIT | src/solutions/feature_engineering_solutions.ipynb | crawles/data-science-training |
(FCD)= 1.5 Definición de función, continuidad y derivada ```{admonition} Notas para contenedor de docker:Comando de docker para ejecución de la nota de forma local:nota: cambiar `` por la ruta de directorio que se desea mapear a `/datos` dentro del contenedor de docker y `` por la versión más actualizada que se presen... | import sympy | _____no_output_____ | Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
**Límite de $\frac{\cos(x+h) - \cos(x)}{h}$ para $h \rightarrow 0$:** | x, h = sympy.symbols("x, h")
quotient = (sympy.cos(x+h) - sympy.cos(x))/h
sympy.pprint(sympy.limit(quotient, h, 0)) | -sin(x)
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
Lo anterior corresponde a la **derivada de $\cos(x)$**: | x = sympy.Symbol('x')
sympy.pprint(sympy.cos(x).diff(x)) | -sin(x)
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
**Si queremos evaluar la derivada podemos usar:** | sympy.pprint(sympy.cos(x).diff(x).subs(x,sympy.pi/2))
sympy.pprint(sympy.Derivative(sympy.cos(x), x))
sympy.pprint(sympy.Derivative(sympy.cos(x), x).doit_numerically(sympy.pi/2)) | -1.00000000000000
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
Caso $f: \mathbb{R}^n \rightarrow \mathbb{R}^m$ ```{admonition} Definición$f$ es diferenciable en $x \in \text{intdom}f$ si existe una matriz $Df(x) \in \mathbb{R}^{m\times n}$ tal que:$$\displaystyle \lim_{z \rightarrow x, z \neq x} \frac{||f(z)-f(x)-Df(x)(z-x)||_2}{||z-x||_2} = 0, z \in \text{dom}f$$en este caso $Df... | x1, x2 = sympy.symbols("x1, x2") | _____no_output_____ | Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
**Definimos funciones $f_1, f_2$ que son componentes del vector $f(x)$**. | f1 = x1*x2 + x2**2
sympy.pprint(f1)
f2 = x1**2 + x2**2 + 2*x1*x2
sympy.pprint(f2) | 2 2
x₁ + 2⋅x₁⋅x₂ + x₂
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
**Derivadas parciales:** Para $f_1(x) = x_1x_2 + x_2^2$: ```{margin}**Derivada parcial de $f_1$ respecto a $x_1$.**``` | df1_x1 = f1.diff(x1)
sympy.pprint(df1_x1) | x₂
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin}**Derivada parcial de $f_1$ respecto a $x_2$.**``` | df1_x2 = f1.diff(x2)
sympy.pprint(df1_x2) | x₁ + 2⋅x₂
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
Para $f_2(x) = x_1^2 + 2x_1 x_2 + x_2^2$: ```{margin}**Derivada parcial de $f_2$ respecto a $x_1$.**``` | df2_x1 = f2.diff(x1)
sympy.pprint(df2_x1) | 2⋅x₁ + 2⋅x₂
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin}**Derivada parcial de $f_2$ respecto a $x_2$.**``` | df2_x2 = f2.diff(x2)
sympy.pprint(df2_x2) | 2⋅x₁ + 2⋅x₂
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
**Entonces la derivada es:** $$Df(x) = \left [\begin{array}{cc}x_2 & x_1+2x_2\\2x_1 + 2x_2 & 2x_1+2x_2\end{array}\right ]$$ **Otra opción más fácil es utilizando [Matrices](https://docs.sympy.org/latest/tutorial/matrices.html):** | f = sympy.Matrix([f1, f2])
sympy.pprint(f) | ⎡ 2 ⎤
⎢ x₁⋅x₂ + x₂ ⎥
⎢ ⎥
⎢ 2 2⎥
⎣x₁ + 2⋅x₁⋅x₂ + x₂ ⎦
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin} **Jacobiana de $f$**``` | sympy.pprint(f.jacobian([x1, x2])) | ⎡ x₂ x₁ + 2⋅x₂ ⎤
⎢ ⎥
⎣2⋅x₁ + 2⋅x₂ 2⋅x₁ + 2⋅x₂⎦
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
**Para evaluar por ejemplo en $(x_1, x_2)^T = (0, 1)^T$:** | d = f.jacobian([x1, x2])
sympy.pprint(d.subs([(x1, 0), (x2, 1)])) | ⎡1 2⎤
⎢ ⎥
⎣2 2⎦
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
Regla de la cadena ```{admonition} DefiniciónSi $f:\mathbb{R}^n \rightarrow \mathbb{R}^m$ es diferenciable en $x\in \text{intdom}f$ y $g:\mathbb{R}^m \rightarrow \mathbb{R}^p$ es diferenciable en $f(x)\in \text{intdom}g$, se define la composición $h:\mathbb{R}^n \rightarrow \mathbb{R}^p$ por $h(z) = g(f(z))$, la cual ... | x = sympy.Symbol('x')
f = sympy.cos(x)
sympy.pprint(f)
g = sympy.sin(x)
sympy.pprint(g)
h = g.subs(x, f)
sympy.pprint(h)
sympy.pprint(h.diff(x)) | -sin(x)⋅cos(cos(x))
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
**Otras formas para calcular la derivada de la composición $h$:** | g = sympy.sin
h = g(f)
sympy.pprint(h.diff(x))
h = sympy.sin(f)
sympy.pprint(h.diff(x)) | -sin(x)⋅cos(cos(x))
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
Ejemplo$f(x) = x_1 + \frac{1}{x_2}, g(x) = e^x$ por lo que $h(x) = e^{x_1 + \frac{1}{x_2}}$. Calcular la derivada de $h$. | x1, x2 = sympy.symbols("x1, x2")
f = x1 + 1/x2
sympy.pprint(f)
g = sympy.exp
sympy.pprint(g)
h = g(f)
sympy.pprint(h) | 1
x₁ + ──
x₂
ℯ
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin}**Derivada parcial de $h$ respecto a $x_1$.**``` | sympy.pprint(h.diff(x1)) | 1
x₁ + ──
x₂
ℯ
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin}**Derivada parcial de $h$ respecto a $x_2$.**``` | sympy.pprint(h.diff(x2)) | 1
x₁ + ──
x₂
-ℯ
──────────
2
x₂
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
**Otra forma para calcular el gradiente de $h$ (derivada de $h$) es utilizando [how-to-get-the-gradient-and-hessian-sympy](https://stackoverflow.com/questions/39558515/how-to-get-the-gradient-and-hessian-sympy):** | from sympy.tensor.array import derive_by_array
sympy.pprint(derive_by_array(h, (x1, x2))) | ⎡ 1 ⎤
⎢ 1 x₁ + ── ⎥
⎢ x₁ + ── x₂ ⎥
⎢ x₂ -ℯ ⎥
⎢ℯ ──────────⎥
⎢ 2 ⎥
⎣ x₂ ⎦
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
(CP1)= Caso particularSean:* $f: \mathbb{R}^n \rightarrow \mathbb{R}^m$, $f(x) = Ax +b$ con $A \in \mathbb{R}^{m\times n},b \in \mathbb{R}^m$,* $g:\mathbb{R}^m \rightarrow \mathbb{R}^p$, * $h: \mathbb{R}^n \rightarrow \mathbb{R}^p$, $h(x)=g(f(x))=g(Ax+b)$ con $\text{dom}h=\{z \in \mathbb{R}^n | Az+b \in \text{dom}g\}$... | x1, x2 = sympy.symbols("x1, x2")
f = x1**2 + x2**2
sympy.pprint(f)
t = sympy.Symbol('t')
v1, v2 = sympy.symbols("v1, v2")
new_args_for_f_function = {"x1": x1+t*v1, "x2": x2 + t*v2}
g = f.subs(new_args_for_f_function)
sympy.pprint(g) | 2 2
(t⋅v₁ + x₁) + (t⋅v₂ + x₂)
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin} **Derivada de $g$ respecto a $t$: $Dg(t)=\nabla f(x+tv)^T v$.**``` | sympy.pprint(g.diff(t)) | 2⋅v₁⋅(t⋅v₁ + x₁) + 2⋅v₂⋅(t⋅v₂ + x₂)
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
**Segunda opción para calcular la derivada utilizando vectores:** | x = sympy.Matrix([x1, x2])
sympy.pprint(x)
v = sympy.Matrix([v1, v2])
new_arg_f_function = x+t*v
sympy.pprint(new_arg_f_function)
mapping_for_g_function = {"x1": new_arg_f_function[0],
"x2": new_arg_f_function[1]}
g = f.subs(mapping_for_g_function)
sympy.pprint(g) | 2 2
(t⋅v₁ + x₁) + (t⋅v₂ + x₂)
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin} **Derivada de $g$ respecto a $t$: $Dg(t)=\nabla f(x+tv)^T v$.**``` | sympy.pprint(g.diff(t)) | 2⋅v₁⋅(t⋅v₁ + x₁) + 2⋅v₂⋅(t⋅v₂ + x₂)
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
**Tercera opción definiendo a la función $f$ a partir de $x$ symbol Matrix:** | sympy.pprint(x)
f = x[0]**2 + x[1]**2
sympy.pprint(f)
sympy.pprint(new_arg_f_function)
g = f.subs({"x1": new_arg_f_function[0],
"x2": new_arg_f_function[1]})
sympy.pprint(g) | 2 2
(t⋅v₁ + x₁) + (t⋅v₂ + x₂)
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin} **Derivada de $g$ respecto a $t$: $Dg(t)=\nabla f(x+tv)^T v$.**``` | sympy.pprint(g.diff(t)) | 2⋅v₁⋅(t⋅v₁ + x₁) + 2⋅v₂⋅(t⋅v₂ + x₂)
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
**En lo siguiente se utiliza [derive-by_array](https://docs.sympy.org/latest/modules/tensor/array.htmlderivatives-by-array), [how-to-get-the-gradient-and-hessian-sympy](https://stackoverflow.com/questions/39558515/how-to-get-the-gradient-and-hessian-sympy) para mostrar cómo se puede hacer un producto punto con SymPy** | sympy.pprint(derive_by_array(f, x))
sympy.pprint(derive_by_array(f, x).subs({"x1": new_arg_f_function[0],
"x2": new_arg_f_function[1]}))
gradient_f_new_arg = derive_by_array(f, x).subs({"x1": new_arg_f_function[0],
"x2": new_arg... | ⎡v₁⎤
⎢ ⎥
⎣v₂⎦
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin} **Derivada de $g$ respecto a $t$: $Dg(t)=\nabla f(x+tv)^T v = v^T \nabla f(x + tv)$.**``` | sympy.pprint(v.dot(gradient_f_new_arg)) | v₁⋅(2⋅t⋅v₁ + 2⋅x₁) + v₂⋅(2⋅t⋅v₂ + 2⋅x₂)
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
(EJ2)= EjemploSi $h: \mathbb{R}^n \rightarrow \mathbb{R}$ dada por $h(x) = \log \left( \displaystyle \sum_{i=1}^m \exp(a_i^Tx+b_i) \right)$ con $x\in \mathbb{R}^n,a_i\in \mathbb{R}^n \forall i=1,\dots,m$ y $b_i \in \mathbb{R} \forall i=1,\dots,m$ entonces: $$Dh(x)=\left(\displaystyle \sum_{i=1}^m\exp(a_i^Tx+b_i) \righ... | m = sympy.Symbol('m')
n = sympy.Symbol('n') | _____no_output_____ | Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin} Ver [indexed](https://docs.sympy.org/latest/modules/tensor/indexed.html)``` | y = sympy.IndexedBase('y')
i = sympy.Symbol('i') #for index of sum
g = sympy.log(sympy.Sum(sympy.exp(y[i]), (i, 1, m))) | _____no_output_____ | Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin} **Esta función es la que queremos derivar.**``` | sympy.pprint(g) | ⎛ m ⎞
⎜ ___ ⎟
⎜ ╲ ⎟
⎜ ╲ y[i]⎟
log⎜ ╱ ℯ ⎟
⎜ ╱ ⎟
⎜ ‾‾‾ ⎟
⎝i = 1 ⎠
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
**Para un caso de $m=3$ en la función $g$ se tiene:** | y1, y2, y3 = sympy.symbols("y1, y2, y3")
g_m_3 = sympy.log(sympy.exp(y1) + sympy.exp(y2) + sympy.exp(y3))
sympy.pprint(g_m_3) | ⎛ y₁ y₂ y₃⎞
log⎝ℯ + ℯ + ℯ ⎠
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin} Ver [derive-by_array](https://docs.sympy.org/latest/modules/tensor/array.htmlderivatives-by-array)``` | dg_m_3 = derive_by_array(g_m_3, [y1, y2, y3]) | _____no_output_____ | Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin} **Derivada de $g$ respecto a $y_1, y_2, y_3$.** ``` | sympy.pprint(dg_m_3) | ⎡ y₁ y₂ y₃ ⎤
⎢ ℯ ℯ ℯ ⎥
⎢─────────────── ─────────────── ───────────────⎥
⎢ y₁ y₂ y₃ y₁ y₂ y₃ y₁ y₂ y₃⎥
⎣ℯ + ℯ + ℯ ℯ + ℯ + ℯ ℯ + ℯ + ℯ ⎦
| Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin} Ver [Kronecker delta](https://en.wikipedia.org/wiki/Kronecker_delta)``` | sympy.pprint(derive_by_array(g, [y[1], y[2], y[3]])) | ⎡ m m m ⎤
⎢ ____ ____ ____ ⎥
⎢ ╲ ╲ ╲ ⎥
⎢ ╲ ╲ ╲ ⎥
⎢ ╲ y[i] ╲ y[i] ╲ y[i] ⎥
⎢ ╱ ℯ ⋅δ ╱ ℯ ⋅δ ╱ ℯ ... | Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
**Para la composición $h(x) = g(f(x))$ se utilizan las siguientes celdas:** ```{margin} Ver [indexed](https://docs.sympy.org/latest/modules/tensor/indexed.html)``` | A = sympy.IndexedBase('A')
x = sympy.IndexedBase('x')
j = sympy.Symbol('j')
b = sympy.IndexedBase('b')
#we want something like:
sympy.pprint(sympy.exp(sympy.Sum(A[i, j]*x[j], (j, 1, n)) + b[i]))
#better if we split each step:
arg_sum = A[i, j]*x[j]
sympy.pprint(arg_sum)
arg_exp = sympy.Sum(arg_sum, (j, 1, n)) + b[i]
sy... | ⎛ m ⎞
⎜_______ ⎟
⎜╲ ⎟
⎜ ╲ ⎟
⎜ ╲ n ⎟
⎜ ╲ ___ ⎟
⎜ ╲ ╲ ⎟
⎜ ╲ ╲ ⎟
... | Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin} **Derivada de $h$ respecto a $x_1$.**``` | sympy.pprint(h.diff(x[1])) | m
________
╲
╲ n
╲ ___
╲ ╲ ... | Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{margin} Ver [Kronecker delta](https://en.wikipedia.org/wiki/Kronecker_delta)``` | sympy.pprint(derive_by_array(h, [x[1]])) #we can use also: derive_by_array(h, [x[1], x[2], x[3]] | ⎡ m ⎤
⎢________ ⎥
⎢╲ ⎥
⎢ ╲ n ⎥
⎢ ╲ ___ ⎥
⎢ ╲ ╲ ... | Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
```{admonition} Pregunta:class: tip¿Se puede resolver este ejercicio con [Matrix Symbol](https://docs.sympy.org/latest/modules/matrices/expressions.html)?``` ```{admonition} Ejercicio:class: tipVerificar que lo obtenido con SymPy es igual a lo desarrollado en "papel" al inicio del {ref}`Ejemplo ```` Segunda derivada d... | eps = 1-3*(4/3-1)
print("{:0.16e}".format(eps))
eps_sympy = 1-3*(sympy.Rational(4,3)-1)
print("{:0.16e}".format(float(eps_sympy))) | _____no_output_____ | Apache-2.0 | libro_optimizacion/temas/I.computo_cientifico/1.5/Definicion_de_funcion_continuidad_derivada.ipynb | vserranoc/analisis-numerico-computo-cientifico |
doit> _The use of `doit` is an implementation detail, and is subject to change!_Under the hood, the [CLI](./cli.ipynb) is powered by [doit](https://github.com/pydoit/doit), a lightweight task engine in python comparable to `make`. Using Tasks with the API | import os, pathlib, tempfile, shutil, atexit, hashlib, pandas
from IPython.display import *
from IPython import get_ipython # needed for `jupyter_execute` because magics?
import IPython
if "TMP_DIR" not in globals():
TMP_DIR = pathlib.Path(tempfile.mkdtemp(prefix="_my_lite_dir_"))
def clean():
shutil.rm... | /tmp/_my_lite_dir_pskl3egv
| BSD-3-Clause | docs/doit.ipynb | marimeireles/jupyterlite |
The `LiteManager` collects all the tasks from _Addons_, and can optionally accept a `task_prefix` in case you need to integrate with existing tasks. | from jupyterlite.manager import LiteManager
manager = LiteManager(
task_prefix="lite_"
)
manager.initialize()
manager.doit_run("lite_status") | lite_static:jupyter-lite.json
. lite_pre_status:lite_static:jupyter-lite.json
tarball: jupyterlite-app-0.1.0-alpha.5.tgz 18MB
output: /tmp/_my_lite_dir_pskl3egv/_output
lite dir: /tmp/_my_lite_dir_pskl3egv
apps: ('lab', 'retro')
lite_archive:archive
lite_contents:contents
lite_lite:jupyter-lite.... | BSD-3-Clause | docs/doit.ipynb | marimeireles/jupyterlite |
Custom Tasks and `%doit``doit` offers an IPython [magic](https://ipython.readthedocs.io/en/stable/interactive/magics.html), enabled with an extension. This can be combined to create highly reactive build tools for creating very custom sites. | %reload_ext doit | _____no_output_____ | BSD-3-Clause | docs/doit.ipynb | marimeireles/jupyterlite |
It works against the `__main__` namespace, which won't have anything by default. | %doit list | _____no_output_____ | BSD-3-Clause | docs/doit.ipynb | marimeireles/jupyterlite |
All the JupyterLite tasks can be added by updating `__main__` via `globals` | globals().update(manager._doit_tasks) | _____no_output_____ | BSD-3-Clause | docs/doit.ipynb | marimeireles/jupyterlite |
Now when a new task is created, it can reference other tasks and targets. | def task_hello():
return dict(
actions=[lambda: print("HELLO!")],
task_dep=["lite_post_status"]
)
%doit -v2 hello | lite_static:jupyter-lite.json
. lite_pre_status:lite_static:jupyter-lite.json
tarball: jupyterlite-app-0.1.0-alpha.5.tgz 18MB
output: /tmp/_my_lite_dir_pskl3egv/_output
lite dir: /tmp/_my_lite_dir_pskl3egv
apps: ('lab', 'retro')
. hello
HELLO!
| BSD-3-Clause | docs/doit.ipynb | marimeireles/jupyterlite |
Instrument Pricing Analytics - Volatility Surfaces InitialisationFirst thing I need to do is import my libraries and then run my scripts to define my helper functions. As you will note I am importing the Refinitiv Data Platform library which will be my main interface to the Platform - as well as few of the most commo... | import pandas as pd
import requests
import numpy as np
import json
import refinitiv.dataplatform as rdp
%run -i c:/Refinitiv/credentials.ipynb
%run ./plotting_helper.ipynb | _____no_output_____ | Apache-2.0 | Vol Surfaces Webinar.ipynb | Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves |
Connect to the Refintiv Data PlatformI am using my helper functions to establish a connection the Platform by requesting a session and opening it. | session = rdp.PlatformSession(
get_app_key(),
rdp.GrantPassword(
username = get_rdp_login(),
password = get_rdp_password()
)
)
session.open() | _____no_output_____ | Apache-2.0 | Vol Surfaces Webinar.ipynb | Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.