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
Don't forget the validation set!And note that you can use the check_accuracy function to evaluate on either the test set or the validation set, by passing either **loader_test** or **loader_val** as the second argument to check_accuracy. You should not touch the test set until you have finished your architecture and hyperparameter tuning, and only run the test set once at the end to report a final value. Train a _great_ model on CIFAR-10!Now it's your job to experiment with architectures, hyperparameters, loss functions, and optimizers to train a model that achieves **>=70%** accuracy on the CIFAR-10 **validation** set. You can use the check_accuracy and train functions from above. Things you should try:- **Filter size**: Above we used 7x7; this makes pretty pictures but smaller filters may be more efficient- **Number of filters**: Above we used 32 filters. Do more or fewer do better?- **Pooling vs Strided Convolution**: Do you use max pooling or just stride convolutions?- **Batch normalization**: Try adding spatial batch normalization after convolution layers and vanilla batch normalization after affine layers. Do your networks train faster?- **Network architecture**: The network above has two layers of trainable parameters. Can you do better with a deep network? Good architectures to try include: - [conv-relu-pool]xN -> [affine]xM -> [softmax or SVM] - [conv-relu-conv-relu-pool]xN -> [affine]xM -> [softmax or SVM] - [batchnorm-relu-conv]xN -> [affine]xM -> [softmax or SVM]- **Global Average Pooling**: Instead of flattening and then having multiple affine layers, perform convolutions until your image gets small (7x7 or so) and then perform an average pooling operation to get to a 1x1 image picture (1, 1 , Filter), which is then reshaped into a (Filter) vector. This is used in [Google's Inception Network](https://arxiv.org/abs/1512.00567) (See Table 1 for their architecture).- **Regularization**: Add l2 weight regularization, or perhaps use Dropout. Tips for trainingFor each network architecture that you try, you should tune the learning rate and regularization strength. When doing this there are a couple important things to keep in mind:- If the parameters are working well, you should see improvement within a few hundred iterations- Remember the coarse-to-fine approach for hyperparameter tuning: start by testing a large range of hyperparameters for just a few training iterations to find the combinations of parameters that are working at all.- Once you have found some sets of parameters that seem to work, search more finely around these parameters. You may need to train for more epochs.- You should use the validation set for hyperparameter search, and save your test set for evaluating your architecture on the best parameters as selected by the validation set. Going above and beyondIf you are feeling adventurous there are many other features you can implement to try and improve your performance. You are **not required** to implement any of these; however they would be good things to try for extra credit.- Alternative update steps: For the assignment we implemented SGD+momentum, RMSprop, and Adam; you could try alternatives like AdaGrad or AdaDelta.- Alternative activation functions such as leaky ReLU, parametric ReLU, ELU, or MaxOut.- Model ensembles- Data augmentation- New Architectures - [ResNets](https://arxiv.org/abs/1512.03385) where the input from the previous layer is added to the output. - [DenseNets](https://arxiv.org/abs/1608.06993) where inputs into previous layers are concatenated together. - [This blog has an in-depth overview](https://chatbotslife.com/resnets-highwaynets-and-densenets-oh-my-9bb15918ee32)If you do decide to implement something extra, clearly describe it in the "Extra Credit Description" cell below. What we expectAt the very least, you should be able to train a ConvNet that gets at least 70% accuracy on the validation set. This is just a lower bound - if you are careful it should be possible to get accuracies much higher than that! Extra credit points will be awarded for particularly high-scoring models or unique approaches.You should use the space below to experiment and train your network. Have fun and happy training!
import time import hyperopt.pyll from hyperopt import fmin, tpe, hp, STATUS_OK, Trials from hyperopt.pyll import scope @scope.define_pure def L1_shift(a): return [a + 5] @scope.define_pure def L2_shift(a): return [a + 5] @scope.define_pure def L2_L3_shift(a, b): return [a + 5, b + 5] @scope.define_pure def W1_shift(a): return [a + 256] @scope.define_pure def W2_shift(a): return [a + 64]
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
Base ModelAfter 20 rounds of hyperparameters optimization we were able to get a 60% validation accuracy. parameters_zero = {'L1': [6], 'S': [3], 'W1': [651], 'loss': 0.6},
# Train your model here, and make sure the output of this cell is the accuracy of your best model on the # train, val, and test sets. Here's some code to get you started. The output of this cell should be the training # and validation accuracy on your best model (measured by validation accuracy). def model_zero(L1, W1, S, C = 10): n_Conv2d = out_dim(32, S, 0, 1) n_MaxPool2d = out_dim(n_Conv2d, 2, 0, 2) n_Flatten = L1*n_MaxPool2d**2 return nn.Sequential( # You fill this in! nn.Conv2d(3, L1, kernel_size=S, stride=1), nn.ReLU(inplace=True), nn.BatchNorm2d(L1), nn.MaxPool2d(2, stride=2), Flatten(), # see above for explanation nn.Linear(n_Flatten, W1), # affine layer nn.ReLU(inplace=True), nn.Linear(W1, C) # affine layer ) search_space_zero = { 'L1': L1_shift(hp.randint('L1', 20)), 'W1': W1_shift(hp.randint('W1', 2048)), 'S': hp.choice('S', [3, 5, 7]) } def loss_zero(x): print(x) model = model_zero(x['L1'][0], x['W1'][0], x['S']).type(dtype) loss_fn = nn.CrossEntropyLoss() optimizer = optim.RMSprop(model.parameters(), lr=1e-3) train(model, loss_fn, optimizer, num_epochs=20, verbose=False) return -check_accuracy(model, loader_val, verbose=False) def objective_zero(x): return { 'loss': loss_zero(x), 'status': STATUS_OK, # -- store other results 'eval_time': time.time() } trials_zero = Trials() best_zero = fmin(objective_zero, space=search_space_zero, algo=tpe.suggest, max_evals=20, trials=trials_zero) def extract_zero(x): return { 'loss': -x['result']['loss'], 'L1': list(map(lambda v: v+5, x['misc']['vals']['L1'])), 'W1': list(map(lambda v: v+256, x['misc']['vals']['W1'])), 'S': list(map(lambda v: 3 if v == 0 else 5 if v == 1 else 7,x['misc']['vals']['S'])) } res_zero = list(map(extract_zero, trials_zero)) [{'L1': [9], 'S': [5], 'W1': [1870], 'loss': 0.584}, {'L1': [8], 'S': [7], 'W1': [649], 'loss': 0.568}, {'L1': [16], 'S': [5], 'W1': [614], 'loss': 0.55}, {'L1': [18], 'S': [7], 'W1': [1773], 'loss': 0.513}, {'L1': [21], 'S': [3], 'W1': [1664], 'loss': 0.616}, {'L1': [6], 'S': [3], 'W1': [651], 'loss': 0.6}, {'L1': [5], 'S': [3], 'W1': [750], 'loss': 0.587}, {'L1': [17], 'S': [3], 'W1': [2189], 'loss': 0.623}, {'L1': [14], 'S': [7], 'W1': [2240], 'loss': 0.553}, {'L1': [5], 'S': [5], 'W1': [1008], 'loss': 0.533}, {'L1': [22], 'S': [5], 'W1': [1498], 'loss': 0.609}, {'L1': [15], 'S': [3], 'W1': [2065], 'loss': 0.581}, {'L1': [11], 'S': [7], 'W1': [1174], 'loss': 0.557}, {'L1': [9], 'S': [7], 'W1': [923], 'loss': 0.566}, {'L1': [15], 'S': [7], 'W1': [2022], 'loss': 0.59}, {'L1': [6], 'S': [5], 'W1': [969], 'loss': 0.587}, {'L1': [9], 'S': [3], 'W1': [1193], 'loss': 0.514}, {'L1': [16], 'S': [5], 'W1': [2252], 'loss': 0.627}, {'L1': [12], 'S': [5], 'W1': [1821], 'loss': 0.611}, {'L1': [9], 'S': [7], 'W1': [279], 'loss': 0.53}]
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
[conv-relu-pool]xN -> [affine]xM -> [softmax or SVM]66.5% validation accuracy with: {'L1': [16], 'L2': [8], 'W1': [464], 'W2': [], 'loss': 0.665}
def model_one(conv_relu_pool_depths, affine_depths, C = 10): from functools import reduce from collections import OrderedDict Conv2d_K = 3 Conv2d_S = 1 MaxPool2d_K = 2 MaxPool2d_S = 2 # 15, 4500; 6, 720 conv_relu_pool_sizes = [ lambda N: out_dim(N, Conv2d_K, 0, Conv2d_S), lambda N: out_dim(N, MaxPool2d_K, 0, MaxPool2d_S) ] * len(conv_relu_pool_depths) n_to_Flatten = reduce(lambda value, f: f(value), conv_relu_pool_sizes, 32) n_Flatten = conv_relu_pool_depths[-1]*n_to_Flatten**2 def conv_relu_pool_layers_ctr(): for i, (L0, L1) in enumerate(zip([3] + conv_relu_pool_depths[:-1], conv_relu_pool_depths)): yield 'conv2d_%s'%i, nn.Conv2d(L0, L1, kernel_size=Conv2d_K, stride=Conv2d_S) yield 'relu_%s'%i, nn.ReLU(inplace=True) yield 'pool_%s'%i, nn.MaxPool2d(MaxPool2d_K, stride=MaxPool2d_S) def affine_layers_ctr(): for i, (W0, W1) in enumerate(zip([n_Flatten] + affine_depths[:-1], affine_depths)): yield 'affine_linear_%s'%i, nn.Linear(W0, W1) yield 'affine_relu_%s'%i, nn.ReLU(inplace=True) layers = list(conv_relu_pool_layers_ctr()) + [tuple(('flatten', Flatten()))] + list(affine_layers_ctr()) + [tuple(('to_classes', nn.Linear(affine_depths[-1], C)))] return nn.Sequential(OrderedDict(layers)) search_space_one = { 'conv_relu_pool_layers': L1_shift(hp.randint('L1', 20)) + hp.choice('conv_relu_pool_depths', [ list(), L2_shift(hp.randint('L2', 20)) ]), 'affine_layers': W1_shift(hp.randint('W1', 2048)) + hp.choice('affine_depths', [ list(), W2_shift(hp.randint('W2', 256)) ]) } def loss_one(x): print(x) model = model_one(list(x['conv_relu_pool_layers']), list(x['affine_layers'])).type(dtype) loss_fn = nn.CrossEntropyLoss() optimizer = optim.RMSprop(model.parameters(), lr=1e-3) train(model, loss_fn, optimizer, num_epochs=20, verbose=True) return -check_accuracy(model, loader_val, verbose=True) def objective_one(x): return { 'loss': loss_one(x), 'status': STATUS_OK, # -- store other results 'eval_time': time.time() } trials_one = Trials() best_one = fmin(objective_one, space=search_space_one, algo=tpe.suggest, max_evals=20, trials=trials_one) def extract_one(x): return { 'loss': -x['result']['loss'], 'L1': list(map(lambda x: x+5, x['misc']['vals']['L1'])), 'L2': list(map(lambda x: x+5, x['misc']['vals']['L2'])), 'W1': list(map(lambda x: x+256, x['misc']['vals']['W1'])), 'W2': list(map(lambda x: x+64, x['misc']['vals']['W2'])) } res_one = list(map(extract_one, trials_one)) [{'L1': [18], 'L2': [], 'W1': [950], 'W2': [], 'loss': 0.614}, {'L1': [7], 'L2': [], 'W1': [2072], 'W2': [168], 'loss': 0.586}, {'L1': [21], 'L2': [20], 'W1': [840], 'W2': [], 'loss': 0.653}, {'L1': [16], 'L2': [8], 'W1': [464], 'W2': [], 'loss': 0.665}, {'L1': [17], 'L2': [], 'W1': [2011], 'W2': [316], 'loss': 0.619}, {'L1': [24], 'L2': [], 'W1': [1908], 'W2': [174], 'loss': 0.644}, {'L1': [14], 'L2': [8], 'W1': [2196], 'W2': [], 'loss': 0.604}, {'L1': [15], 'L2': [10], 'W1': [1806], 'W2': [], 'loss': 0.607}, {'L1': [20], 'L2': [], 'W1': [1820], 'W2': [], 'loss': 0.643}, {'L1': [11], 'L2': [], 'W1': [1431], 'W2': [247], 'loss': 0.62}, {'L1': [9], 'L2': [5], 'W1': [2238], 'W2': [], 'loss': 0.548}, {'L1': [7], 'L2': [], 'W1': [1655], 'W2': [], 'loss': 0.6}, {'L1': [12], 'L2': [], 'W1': [2241], 'W2': [], 'loss': 0.612}, {'L1': [20], 'L2': [9], 'W1': [1818], 'W2': [], 'loss': 0.589}, {'L1': [22], 'L2': [], 'W1': [934], 'W2': [], 'loss': 0.636}, {'L1': [24], 'L2': [13], 'W1': [667], 'W2': [210], 'loss': 0.64}, {'L1': [18], 'L2': [], 'W1': [455], 'W2': [278], 'loss': 0.62}, {'L1': [9], 'L2': [], 'W1': [967], 'W2': [], 'loss': 0.594}, {'L1': [13], 'L2': [], 'W1': [1033], 'W2': [], 'loss': 0.63}, {'L1': [19], 'L2': [24], 'W1': [573], 'W2': [], 'loss': 0.647}]
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
[batchnorm-relu-conv]xN -> [affine]xM -> [softmax or SVM]64.9% validation accuracy with: {'L1': [20], 'L2': [21], 'L2_1': [], 'L3_1': [], 'W1': [487], 'W2': [], 'loss': 0.649}
def model_three(batchnorm_conv_relu_depths, affine_depths, C = 10): from functools import reduce from collections import OrderedDict Conv2d_K = 3 Conv2d_S = 1 batchnorm_conv_relu_sizes = [ lambda N: out_dim(N, Conv2d_K, 0, Conv2d_S) ] * len(batchnorm_conv_relu_depths) n_to_Flatten = reduce(lambda value, f: f(value), batchnorm_conv_relu_sizes, 32) n_Flatten = batchnorm_conv_relu_depths[-1]*n_to_Flatten**2 def batchnorm_conv_relu_layers_ctr(): for i, (L0, L1) in enumerate(zip([3] + batchnorm_conv_relu_depths[:-1], batchnorm_conv_relu_depths)): yield 'batchnorm2d_%s'%i, nn.BatchNorm2d(L0) yield 'conv2d_%s'%i, nn.Conv2d(L0, L1, kernel_size=Conv2d_K, stride=Conv2d_S) yield 'relu_%s'%i, nn.ReLU(inplace=True) def affine_layers_ctr(): for i, (W0, W1) in enumerate(zip([n_Flatten] + affine_depths[:-1], affine_depths)): yield 'affine_linear_%s'%i, nn.Linear(W0, W1) yield 'affine_relu_%s'%i, nn.ReLU(inplace=True) layers = list(batchnorm_conv_relu_layers_ctr()) + [tuple(('flatten', Flatten()))] + list(affine_layers_ctr()) + [tuple(('to_classes', nn.Linear(affine_depths[-1], C)))] return nn.Sequential(OrderedDict(layers)) search_space_three = { 'batchnorm2d_conv_relu_layers': L1_shift(hp.randint('L1', 20)) + hp.choice('batchnorm2d_conv_relu_L2', [ list(), L2_shift(hp.randint('L2', 20)) ]) + hp.choice('batchnorm2d_conv_relu_L3', [ list(), L2_shift(hp.randint('L3', 20)) ]), 'affine_layers': W1_shift(hp.randint('W1', 2048)) + hp.choice('affine_depths', [ list(), W2_shift(hp.randint('W2', 256)) ]) } def loss_three(x): print(x) model = model_three(list(x['batchnorm2d_conv_relu_layers']), list(x['affine_layers'])).type(dtype) loss_fn = nn.CrossEntropyLoss() optimizer = optim.RMSprop(model.parameters(), lr=1e-3) train(model, loss_fn, optimizer, num_epochs=20, verbose=False) return -check_accuracy(model, loader_val, verbose=False) def objective_three(x): return { 'loss': loss_three(x), 'status': STATUS_OK, # -- store other results 'eval_time': time.time() } trials_three = Trials() best_three = fmin(objective_three, space=search_space_three, algo=tpe.suggest, max_evals=20, trials=trials_three) def extract_three(x): val = x['misc']['vals'] return { 'loss': -x['result']['loss'], 'L1': list(map(lambda x: x+5, val['L1'])), 'L2': list(map(lambda x: x+5, val.get('L2', []))), 'L2_1': list(map(lambda x: x+5, val.get('L2_1', []))), 'L3_1': list(map(lambda x: x+5, val.get('L3_1', []))), 'W1': list(map(lambda x: x+256, val['W1'])), 'W2': list(map(lambda x: x+64, val.get('W2', []))) } res_three = list(map(extract_three, trials_three)) [{'L1': [24], 'L2': [], 'L2_1': [], 'L3_1': [], 'W1': [975], 'W2': [], 'loss': 0.603}, {'L1': [13], 'L2': [], 'L2_1': [], 'L3_1': [], 'W1': [1873], 'W2': [222], 'loss': 0.613}, {'L1': [9], 'L2': [10], 'L2_1': [], 'L3_1': [], 'W1': [2180], 'W2': [161], 'loss': 0.616}, {'L1': [14], 'L2': [], 'L2_1': [], 'L3_1': [], 'W1': [1241], 'W2': [295], 'loss': 0.622}, {'L1': [11], 'L2': [8], 'L2_1': [], 'L3_1': [], 'W1': [1138], 'W2': [74], 'loss': 0.6}, {'L1': [20], 'L2': [10], 'L2_1': [], 'L3_1': [], 'W1': [1968], 'W2': [261], 'loss': 0.618}, {'L1': [15], 'L2': [], 'L2_1': [], 'L3_1': [], 'W1': [803], 'W2': [], 'loss': 0.614}, {'L1': [24], 'L2': [], 'L2_1': [], 'L3_1': [], 'W1': [1607], 'W2': [], 'loss': 0.594}, {'L1': [24], 'L2': [], 'L2_1': [], 'L3_1': [], 'W1': [1132], 'W2': [], 'loss': 0.596}, {'L1': [10], 'L2': [], 'L2_1': [], 'L3_1': [], 'W1': [1500], 'W2': [302], 'loss': 0.584}, {'L1': [9], 'L2': [22], 'L2_1': [], 'L3_1': [], 'W1': [2272], 'W2': [], 'loss': 0.559}, {'L1': [15], 'L2': [18], 'L2_1': [], 'L3_1': [], 'W1': [1224], 'W2': [], 'loss': 0.614}, {'L1': [23], 'L2': [], 'L2_1': [], 'L3_1': [], 'W1': [1120], 'W2': [], 'loss': 0.621}, {'L1': [22], 'L2': [11], 'L2_1': [], 'L3_1': [], 'W1': [1398], 'W2': [], 'loss': 0.573}, {'L1': [13], 'L2': [], 'L2_1': [], 'L3_1': [], 'W1': [1214], 'W2': [283], 'loss': 0.61}, {'L1': [24], 'L2': [7], 'L2_1': [], 'L3_1': [], 'W1': [302], 'W2': [], 'loss': 0.559}, {'L1': [20], 'L2': [21], 'L2_1': [], 'L3_1': [], 'W1': [487], 'W2': [], 'loss': 0.649}, {'L1': [22], 'L2': [22], 'L2_1': [], 'L3_1': [], 'W1': [1007], 'W2': [], 'loss': 0.641}, {'L1': [15], 'L2': [18], 'L2_1': [], 'L3_1': [], 'W1': [509], 'W2': [168], 'loss': 0.61}, {'L1': [12], 'L2': [], 'L2_1': [], 'L3_1': [], 'W1': [1424], 'W2': [], 'loss': 0.583}]
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
Describe what you did In the cell below you should write an explanation of what you did, any additional features that you implemented, and any visualizations or graphs that you make in the process of training and evaluating your network. DNN with architectures 0, 1 and 3 were implemented and trained on data. Hyperparameter optimization was performed.The best model found was the [conv-relu-pool]xN -> [affine]xM -> [softmax] with parameters: {'L1': 16, 'L2': 8, 'W1': 464} which got an accuracy of 0.665. Test set -- run this only onceNow that we've gotten a result we're happy with, we test our final model on the test set (which you should store in best_model). This would be the score we would achieve on a competition. Think about how this compares to your validation set accuracy.
best_model = None check_accuracy(best_model, loader_test)
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
Introduction to Python
#Python Indention if 5>2: print("five is greater than two!") x = 1 # This is a single variable with single value x,y = 1,2 # these are two variables with two different values x,y,z= 1,2,3 print(x) print(y) print(z) x,y="four",2 x y x
_____no_output_____
Apache-2.0
Demo1.ipynb
RoyMillamis/Roy-Millamis-BSCpE-1-2
Casting
b = int(4) b c= float(4) c
_____no_output_____
Apache-2.0
Demo1.ipynb
RoyMillamis/Roy-Millamis-BSCpE-1-2
Type Function
x=5 y= "John" # This is a type of string h= "ana" H='Ana' print(type(x)) print(type(y)) print(h) print(H)
<class 'int'> <class 'str'> ana Ana
Apache-2.0
Demo1.ipynb
RoyMillamis/Roy-Millamis-BSCpE-1-2
One Value to Multiple Variables
x = y = z = 'four' print(x) print(y) print(z) x = "enjoying" print("Python Programming is" " " + x) x = 11 y = 12 z = 13 print(x+y+z) x+=3 #This is the same as x = +3 print(x) y+=5 print(y) x<y and x!=x # pag isang lang yung true false na x>y or not y==z # kahit isa lang yung true, true paden not(print(x>y)) #Identity operations print (x is y) print (x is not z)
False True
Apache-2.0
Demo1.ipynb
RoyMillamis/Roy-Millamis-BSCpE-1-2
Programación lineal> La programación lineal es el campo de la optimización matemática dedicado a maximizar o minimizar (optimizar) funciones lineales, denominada función objetivo, de tal forma que las variables de dicha función estén sujetas a una serie de restricciones expresadas mediante un sistema de ecuaciones o inecuaciones también lineales.**Referencias:**- https://es.wikipedia.org/wiki/Programaci%C3%B3n_lineal- https://docs.scipy.org/doc/scipy-0.18.1/reference/optimize.html 1. Apuntes históricos- 1826: Joseph Fourier anticipa la programación lineal. Carl Friedrich Gauss resuelve ecuaciones lineales por eliminación "gaussiana".- 1902: Gyula Farkas concibe un método para resolver sistemas de inecuaciones.- Es hasta la Segunda Guerra Mundial que se plantea la programación lineal como un modelo matemático para planificar gastos y retornos, de modo que se reduzcan costos de guerra y aumentar pérdidas del enemigo. Secreto hasta 1947 (posguerra).- 1947: George Dantzig publica el algoritmo simplex y John von Neumann desarrolló la teoría de la dualidad. Se sabe que Leonid Kantoróvich también formuló la teoría en forma independiente.- Fue usado por muchas industrias en la planificación diaria.**Hasta acá, tiempos exponenciales de solución. Lo siguiente, tiempo polinomial.**- 1979: Leonid Khachiyan, diseñó el llamado Algoritmo del elipsoide, a través del cual demostró que el problema de la programación lineal es resoluble de manera eficiente, es decir, en tiempo polinomial.- 1984: Narendra Karmarkar introduce el método del punto interior para resolver problemas de programación lineal.**Mencionar complejidad computacional.** 2. MotivaciónYa la clase pasada habíamos mencionado que cuando se quería optimizar una función de varias variables con restricciones, se podía aplicar siempre el método de Multiplicadores de Lagrange. Sin embargo, este método es computacionalmente muy complejo conforme crece el número de variables.Por tanto, cuando la función a optimizar y las restricciones son de caracter lineal, los métodos de solución que se pueden desarrollar son computacionalmente eficientes, por lo que es útil realizar la distinción. 3. Problemas de programación lineal 3.1. Ejemplo básicoUna compañía produce dos productos ($X_1$ y $X_2$) usando dos máquinas ($A$ y $B$). Cada unidad de $X_1$ que se produce requiere 50 minutos en la máquina $A$ y 30 minutos en la máquina $B$. Cada unidad de $X_2$ que se produce requiere 24 minutos en la máquina $A$ y 33 minutos en la máquina $B$.Al comienzo de la semana hay 30 unidades de $X_1$ y 90 unidades de $X_2$ en inventario. El tiempo de uso disponible de la máquina $A$ es de 40 horas y el de la máquina $B$ es de 35 horas.La demanda para $X_1$ en la semana actual es de 75 unidades y de $X_2$ es de 95 unidades. La política de la compañía es maximizar la suma combinada de unidades de $X_1$ e $X_2$ en inventario al finalizar la semana.Formular el problema de decidir cuánto hacer de cada producto en la semana como un problema de programación lineal. SoluciónSean:- $x_1$ la cantidad de unidades de $X_1$ a ser producidas en la semana, y- $x_2$ la cantidad de unidades de $X_2$ a ser producidas en la semana.Notar que lo que se quiere es maximizar $x_1+x_2$.Restricciones:1. El tiempo de uso disponible de la máquina $A$ es de 40 horas: $50x_1+24x_2\leq 40(60)\Rightarrow 50x_1+24x_2\leq 2400$.2. El tiempo de uso disponible de la máquina $B$ es de 35 horas: $30x_1+33x_2\leq 35(60)\Rightarrow 30x_1+33x_2\leq 2100$.3. La demanda para $X_1$ en la semana actual es de 75 unidades: $x_1+30\geq 75\Rightarrow x_1\geq 45\Rightarrow -x_1\leq -45$.4. La demanda para $X_2$ en la semana actual es de 95 unidades: $x_2+90\geq 95\Rightarrow x_2\geq 5\Rightarrow -x_2\leq -5$.Finalmente, el problema puede ser expresado en la forma explicada como:\begin{equation}\begin{array}{ll}\min_{x_1,x_2} & -x_1-x_2 \\\text{s. a. } & 50x_1+24x_2\leq 2400 \\ & 30x_1+33x_2\leq 2100 \\ & -x_1\leq -45 \\ & -x_2\leq -5,\end{array}\end{equation}o, eqivalentemente \begin{equation}\begin{array}{ll}\min_{\boldsymbol{x}} & \boldsymbol{c}^T\boldsymbol{x} \\\text{s. a. } & \boldsymbol{A}_{eq}\boldsymbol{x}=\boldsymbol{b}_{eq} \\ & \boldsymbol{A}\boldsymbol{x}\leq\boldsymbol{b},\end{array}\end{equation}con- $\boldsymbol{c}=\left[-1 \quad -1\right]^T$,- $\boldsymbol{A}=\left[\begin{array}{cc}50 & 24 \\ 30 & 33\\ -1 & 0\\ 0 & -1\end{array}\right]$, y- $\boldsymbol{b}=\left[2400\quad 2100\quad -45\quad -5\right]^T$.Preferiremos, en adelante, la notación vectorial/matricial. 3.2. En generalDe acuerdo a lo descrito anteriormente, un problema de programación lineal puede escribirse en la siguiente forma:\begin{equation}\begin{array}{ll}\min_{x_1,\dots,x_n} & c_1x_1+\dots+c_nx_n \\\text{s. a. } & a^{eq}_{j,1}x_1+\dots+a^{eq}_{j,n}x_n=b^{eq}_j \text{ para } 1\leq j\leq m_1 \\ & a_{k,1}x_1+\dots+a_{k,n}x_n\leq b_k \text{ para } 1\leq k\leq m_2,\end{array}\end{equation}donde:- $x_i$ para $i=1,\dots,n$ son las incógnitas o variables de decisión,- $c_i$ para $i=1,\dots,n$ son los coeficientes de la función a optimizar,- $a^{eq}_{j,i}$ para $j=1,\dots,m_1$ e $i=1,\dots,n$, son los coeficientes de la restricción de igualdad,- $a_{k,i}$ para $k=1,\dots,m_2$ e $i=1,\dots,n$, son los coeficientes de la restricción de desigualdad,- $b^{eq}_j$ para $j=1,\dots,m_1$ son valores conocidos que deben ser respetados estrictamente, y- $b_k$ para $k=1,\dots,m_2$ son valores conocidos que no deben ser superados.Equivalentemente, el problema puede escribirse como\begin{equation}\begin{array}{ll}\min_{\boldsymbol{x}} & \boldsymbol{c}^T\boldsymbol{x} \\\text{s. a. } & \boldsymbol{A}_{eq}\boldsymbol{x}=\boldsymbol{b}_{eq} \\ & \boldsymbol{A}\boldsymbol{x}\leq\boldsymbol{b},\end{array}\end{equation}donde:- $\boldsymbol{x}=\left[x_1\quad\dots\quad x_n\right]^T$,- $\boldsymbol{c}=\left[c_1\quad\dots\quad c_n\right]^T$,- $\boldsymbol{A}_{eq}=\left[\begin{array}{ccc}a^{eq}_{1,1} & \dots & a^{eq}_{1,n}\\ \vdots & \ddots & \vdots\\ a^{eq}_{m_1,1} & \dots & a^{eq}_{m_1,n}\end{array}\right]$,- $\boldsymbol{A}=\left[\begin{array}{ccc}a_{1,1} & \dots & a_{1,n}\\ \vdots & \ddots & \vdots\\ a_{m_2,1} & \dots & a_{m_2,n}\end{array}\right]$,- $\boldsymbol{b}_{eq}=\left[b^{eq}_1\quad\dots\quad b^{eq}_{m_1}\right]^T$, y- $\boldsymbol{b}=\left[b_1\quad\dots\quad b_{m_2}\right]^T$.**Nota:** el problema $\max_{\boldsymbol{x}}\boldsymbol{g}(\boldsymbol{x})$ es equivalente a $\min_{\boldsymbol{x}}-\boldsymbol{g}(\boldsymbol{x})$. Bueno, y una vez planteado, ¿cómo se resuelve el problema? Este problema está sencillo pues solo es en dos variables. La solución gráfica es válida.
import matplotlib.pyplot as plt %matplotlib inline import numpy as np def res1(x1): return (2400-50*x1)/24 def res2(x1): return (2100-30*x1)/33 x1 = np.linspace(40, 50) r1 = res1(x1) r2 = res2(x1) plt.figure(figsize = (8,6)) plt.plot(x1, res1(x1), 'b--', label = 'res1') plt.plot(x1, res2(x1), 'r--', label = 'res2') plt.plot([45, 45], [0, 25], 'k', label = 'res3') plt.plot([40, 50], [5, 5], 'm', label = 'res4') plt.fill_between(np.array([45.0, 45.6]), res1(np.array([45.0, 45.6])), 5*np.ones(2)) plt.text(44,4,'$(45,5)$',fontsize=10) plt.text(45.1,6.35,'$(45,6.25)$',fontsize=10) plt.text(45.6,4,'$(45.6,5)$',fontsize=10) plt.legend(loc = 'best') plt.xlabel('$x_1$') plt.ylabel('$x_2$') plt.axis([44, 46, 4, 7]) plt.show()
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
**Actividad.** Mónica hace aretes y cadenitas de joyería. Es tan buena, que todo lo que hace lo vende.Le toma 30 minutos hacer un par de aretes y una hora hacer una cadenita, y como Mónica también es estudihambre, solo dispone de 10 horas a la semana para hacer las joyas. Por otra parte, el material que compra solo le alcanza para hacer 15 unidades (el par de aretes cuenta como unidad) de joyas por semana.La utilidad que le deja la venta de las joyas es \$15 en cada par de aretes y \$20 en cada cadenita.¿Cuántos pares de aretes y cuántas cadenitas debería hacer Mónica para maximizar su utilidad?Formular el problema en la forma explicada y obtener la solución gráfica (puede ser a mano).**Diez minutos: quien primero lo haga, pasará a explicarlo al tablero y le subiré la nota de alguna tarea a 100. Debe salir a explicar el problema en el pizarrón.** 5. ¿Cómo se resuelve en python? 5.1 Librería `SciPy``SciPy` es un softwar de código abierto basado en `Python` para matemáticas, ciencia e ingeniería. En particular, los siguientes son algunos de los paquetes básicos:- `NumPy`- **Librería `SciPy`**- `SymPy`- `matplotlib`- `pandas`La **Librería `SciPy`** es uno de los paquetes principales y provee varias rutinas numéricas eficientes. Entre ellas, para integración numérica y optimización.En esta clase, y en lo que resta del módulo, estaremos utilizando el módulo `optimize` de la librería `SciPy`.**Importémoslo**
# Importar el módulo optimize de la librería scipy import scipy.optimize as opt
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
El módulo `optimize` que acabamos de importar contiene varias funciones para optimización y búsqueda de raices ($f(x)=0$). Entre ellas se encuentra la función `linprog`
# Función linprog del módulo optimize help(opt.linprog)
Help on function linprog in module scipy.optimize._linprog: linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None, method='simplex', callback=None, options=None) Minimize a linear objective function subject to linear equality and inequality constraints. Linear Programming is intended to solve the following problem form:: Minimize: c^T * x Subject to: A_ub * x <= b_ub A_eq * x == b_eq Parameters ---------- c : array_like Coefficients of the linear objective function to be minimized. A_ub : array_like, optional 2-D array which, when matrix-multiplied by ``x``, gives the values of the upper-bound inequality constraints at ``x``. b_ub : array_like, optional 1-D array of values representing the upper-bound of each inequality constraint (row) in ``A_ub``. A_eq : array_like, optional 2-D array which, when matrix-multiplied by ``x``, gives the values of the equality constraints at ``x``. b_eq : array_like, optional 1-D array of values representing the RHS of each equality constraint (row) in ``A_eq``. bounds : sequence, optional ``(min, max)`` pairs for each element in ``x``, defining the bounds on that parameter. Use None for one of ``min`` or ``max`` when there is no bound in that direction. By default bounds are ``(0, None)`` (non-negative) If a sequence containing a single tuple is provided, then ``min`` and ``max`` will be applied to all variables in the problem. method : str, optional Type of solver. :ref:`'simplex' <optimize.linprog-simplex>` and :ref:`'interior-point' <optimize.linprog-interior-point>` are supported. callback : callable, optional (simplex only) If a callback function is provide, it will be called within each iteration of the simplex algorithm. The callback must have the signature ``callback(xk, **kwargs)`` where ``xk`` is the current solution vector and ``kwargs`` is a dictionary containing the following:: "tableau" : The current Simplex algorithm tableau "nit" : The current iteration. "pivot" : The pivot (row, column) used for the next iteration. "phase" : Whether the algorithm is in Phase 1 or Phase 2. "basis" : The indices of the columns of the basic variables. options : dict, optional A dictionary of solver options. All methods accept the following generic options: maxiter : int Maximum number of iterations to perform. disp : bool Set to True to print convergence messages. For method-specific options, see :func:`show_options('linprog')`. Returns ------- A `scipy.optimize.OptimizeResult` consisting of the following fields: x : ndarray The independent variable vector which optimizes the linear programming problem. fun : float Value of the objective function. slack : ndarray The values of the slack variables. Each slack variable corresponds to an inequality constraint. If the slack is zero, then the corresponding constraint is active. success : bool Returns True if the algorithm succeeded in finding an optimal solution. status : int An integer representing the exit status of the optimization:: 0 : Optimization terminated successfully 1 : Iteration limit reached 2 : Problem appears to be infeasible 3 : Problem appears to be unbounded nit : int The number of iterations performed. message : str A string descriptor of the exit status of the optimization. See Also -------- show_options : Additional options accepted by the solvers Notes ----- This section describes the available solvers that can be selected by the 'method' parameter. The default method is :ref:`Simplex <optimize.linprog-simplex>`. :ref:`Interior point <optimize.linprog-interior-point>` is also available. Method *simplex* uses the simplex algorithm (as it relates to linear programming, NOT the Nelder-Mead simplex) [1]_, [2]_. This algorithm should be reasonably reliable and fast for small problems. .. versionadded:: 0.15.0 Method *interior-point* uses the primal-dual path following algorithm as outlined in [4]_. This algorithm is intended to provide a faster and more reliable alternative to *simplex*, especially for large, sparse problems. Note, however, that the solution returned may be slightly less accurate than that of the simplex method and may not correspond with a vertex of the polytope defined by the constraints. References ---------- .. [1] Dantzig, George B., Linear programming and extensions. Rand Corporation Research Study Princeton Univ. Press, Princeton, NJ, 1963 .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to Mathematical Programming", McGraw-Hill, Chapter 4. .. [3] Bland, Robert G. New finite pivoting rules for the simplex method. Mathematics of Operations Research (2), 1977: pp. 103-107. .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point optimizer for linear programming: an implementation of the homogeneous algorithm." High performance optimization. Springer US, 2000. 197-232. .. [5] Andersen, Erling D. "Finding all linearly dependent rows in large-scale linear programming." Optimization Methods and Software 6.3 (1995): 219-227. .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear Programming based on Newton's Method." Unpublished Course Notes, March 2004. Available 2/25/2017 at https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf .. [7] Fourer, Robert. "Solving Linear Programs by Interior-Point Methods." Unpublished Course Notes, August 26, 2005. Available 2/25/2017 at http://www.4er.org/CourseNotes/Book%20B/B-III.pdf .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear programming." Mathematical Programming 71.2 (1995): 221-245. .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear programming." Athena Scientific 1 (1997): 997. .. [10] Andersen, Erling D., et al. Implementation of interior point methods for large scale linear programming. HEC/Universite de Geneve, 1996. Examples -------- Consider the following problem: Minimize: f = -1*x[0] + 4*x[1] Subject to: -3*x[0] + 1*x[1] <= 6 1*x[0] + 2*x[1] <= 4 x[1] >= -3 where: -inf <= x[0] <= inf This problem deviates from the standard linear programming problem. In standard form, linear programming problems assume the variables x are non-negative. Since the variables don't have standard bounds where 0 <= x <= inf, the bounds of the variables must be explicitly set. There are two upper-bound constraints, which can be expressed as dot(A_ub, x) <= b_ub The input for this problem is as follows: >>> c = [-1, 4] >>> A = [[-3, 1], [1, 2]] >>> b = [6, 4] >>> x0_bounds = (None, None) >>> x1_bounds = (-3, None) >>> from scipy.optimize import linprog >>> res = linprog(c, A_ub=A, b_ub=b, bounds=(x0_bounds, x1_bounds), ... options={"disp": True}) Optimization terminated successfully. Current function value: -22.000000 Iterations: 1 >>> print(res) fun: -22.0 message: 'Optimization terminated successfully.' nit: 1 slack: array([39., 0.]) status: 0 success: True x: array([10., -3.]) Note the actual objective value is 11.428571. In this case we minimized the negative of the objective function.
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
la cual resuelve problemas como los que aprendimos a plantear. 5.2 Solución del ejemplo básico con linprogYa hicimos la solución gráfica. Contrastemos con la solución que nos da `linprog`...
# Importar numpy para crear las matrices import numpy as np # Crear las matrices para resolver el problema c = np.array([-1, -1]) A = np.array([[50, 24], [30, 33], [-1, 0], [0, -1]]) b = np.array([2400, 2100, -45, -5]) b # Resolver utilizando linprog resultado = opt.linprog(c, A_ub=A, b_ub=b) # Mostrar el resultado resultado # Extraer el vector solución resultado.x
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
**Conclusión**- Para maximizar el inventario conjunto de cantidad de productos X1 y X2, se deben producir 45 unidades de X1 y 6.25 unidades de X2.- Con esa producción, el inventario conjunto al finalizar la semana es de 1.25 unidades. **Otra forma:** poner las cotas de las variables a parte
# Escribir matrices y cotas c = np.array([-1, -1]) A = np.array([[50, 24], [30, 33]]) b = np.array([2400, 2100]) x1_bound = (45, None) x2_bound = (5, None) # Resolver resultado2 = opt.linprog(c, A_ub=A, b_ub=b, bounds=(x1_bound,x2_bound)) # Mostrar el resultado resultado2
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
**Actividad.** Resolver el ejemplo de Mónica y sus tiliches con `linprog`
# Resolver acá c = np.array([-15, -20]) A = np.array([[1, 2], [1, 1]]) b = np.array([20, 15]) resultado_monica = opt.linprog(c, A_ub=A, b_ub=b) resultado_monica
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
6. Problema de transporte 1- **Referencia**: https://es.wikipedia.org/wiki/Programaci%C3%B3n_linealEste es un caso curioso, con solo 6 variables (un caso real de problema de transporte puede tener fácilmente más de 1.000 variables) en el cual se aprecia la utilidad de este procedimiento de cálculo.Existen tres minas de carbón cuya producción diaria es:- la mina "a" produce 40 toneladas de carbón por día;- la mina "b" produce 40 t/día; y,- la mina "c" produce 20 t/día.En la zona hay dos centrales termoeléctricas que consumen:- la central "d" consume 40 t/día de carbón; y,- la central "e" consume 60 t/día.Los costos de mercado, de transporte por tonelada son:- de "a" a "d" = 2 monedas;- de "a" a "e" = 11 monedas;- de "b" a "d" = 12 monedas;- de "b" a "e" = 24 monedas;- de "c" a "d" = 13 monedas; y,- de "c" a "e" = 18 monedas.Si se preguntase a los pobladores de la zona cómo organizar el transporte, tal vez la mayoría opinaría que debe aprovecharse el precio ofrecido por el transportista que va de "a" a "d", porque es más conveniente que los otros, debido a que es el de más bajo precio.En este caso, el costo total del transporte es:- transporte de 40 t de "a" a "d" = 80 monedas;- transporte de 20 t de "c" a "e" = 360 monedas; y,- transporte de 40 t de "b" a "e" = 960 monedas, Para un total 1.400 monedas.Sin embargo, formulando el problema para ser resuelto por la programación lineal con- $x_1$ toneladas transportadas de la mina "a" a la central "d"- $x_2$ toneladas transportadas de la mina "a" a la central "e"- $x_3$ toneladas transportadas de la mina "b" a la central "d"- $x_4$ toneladas transportadas de la mina "b" a la central "e"- $x_5$ toneladas transportadas de la mina "c" a la central "d"- $x_6$ toneladas transportadas de la mina "c" a la central "e"se tienen las siguientes ecuaciones:Restricciones de la producción:- $x_1 + x_2 \leq 40$- $x_3 + x_4 \leq 40$- $x_5 + x_6 \leq 20$Restricciones del consumo:- $x_1 + x_3 + x_5 \geq 40$- $x_2 + x_4 + x_6 \geq 60$La función objetivo será:$$\min_{x_1,\dots,x_6}2x_1 + 11x_2 + 12x_3 + 24x_4 + 13x_5 + 18x_6$$Resolver con `linprog`
# Matrices y cotas c = np.array([2, 11, 12, 24, 13, 18]) A = np.array([[1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1], [-1, 0, -1, 0, -1, 0], [0, -1, 0, -1, 0, -1]]) b = np.array([40, 40, 20, -40, -60]) # Resolver resultado_transporte = opt.linprog(c, A_ub=A, b_ub=b) # Mostrar resultado resultado_transporte
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
**Conclusión**- La estrategia de menor costo es llevar 40 toneladas de la mina "a" a la central "e", 40 toneladas de la mina "b" a la central "d" y 20 toneladas de la mina "c" a la central "e". El costo total de esta estrategia de transporte es 1280 monedas. 7. Optimización de inversión en bonos**Referencia:**
from IPython.display import YouTubeVideo YouTubeVideo('gukxBus8lOs')
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
El objetivo de este problema es determinar la mejor estrategia de inversión, dados diferentes tipos de bono, la máxima cantidad que puede ser invertida en cada bono, el porcentaje de retorno y los años de madurez. También hay una cantidad fija de dinero disponible ($\$750,000$). Por lo menos la mitad de este dinero debe ser invertido en bonos con 10 años o más para la madurez. Se puede invertir un máximo del $25\%$ de esta cantidad en cada bono. Finalmente, hay otra restricción que no permite usar más de $35\%$ en bonos de alto riesgo.Existen seis (6) opciones de inversión con las letras correspondientes $A_i$1. $A_1$:(Tasa de retorno=$8.65\%$; Años para la madurez=11, Riesgo=Bajo)1. $A_2$:(Tasa de retorno=$9.50\%$; Años para la madurez=10, Riesgo=Alto)1. $A_3$:(Tasa de retorno=$10.00\%$; Años para la madurez=6, Riesgo=Alto)1. $A_4$:(Tasa de retorno=$8.75\%$; Años para la madurez=10, Riesgo=Bajo)1. $A_5$:(Tasa de retorno=$9.25\%$; Años para la madurez=7, Riesgo=Alto)1. $A_6$:(Tasa de retorno=$9.00\%$; Años para la madurez=13, Riesgo=Bajo)Lo que se quiere entonces es maximizar el retorno que deja la inversión.Este problema puede ser resuelto con programación lineal. Formalmente, puede ser descrito como:$$\max_{A_1,A_2,...,A_6}\sum^{6}_{i=1} A_iR_i,$$donde $A_i$ representa la cantidad invertida en la opción, y $R_i$ representa la tasa de retorno respectiva. Plantear restricciones...
# Matrices y cotas # Resolver # Mostrar resultado
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
Recordar que en el problema minimizamos $-\sum^{6}_{i=1} A_iR_i$. El rendimiento obtenido es entonces: **Conclusión**- 8. Tarea 1. Diseño de la Dieta ÓptimaSe quiere producir comida para gatos de la manera más barata, no obstante se debe también asegurar que se cumplan los datos requeridos de analisis nutricional. Por lo que se quiere variar la cantidad de cada ingrediente para cumplir con los estandares nutricionales. Los requisitos que se tienen es que en 100 gramos, se deben tener por lo menos 8 gramos de proteína y 6 gramos de grasa. Así mismo, no se debe tener más de 2 gramos de fibra y 0.4 gramos de sal. Los datos nutricionales se pueden obtener de la siguiente tabla:Ingrediente|Proteína|Grasa|Fibra|Sal:----|----Pollo| 10.0%|08.0%|00.1%|00.2%Carne| 20.0%|10.0%|00.5%|00.5%Cordero|15.0%|11.0%|00.5%|00.7%Arroz| 00.0%|01.0%|10.0%|00.2%Trigo| 04.0%|01.0%|15.0%|00.8%Gel| 00.0%|00.0%|00.0%|00.0%Los costos de cada producto son:Ingrediente|Costo por gramo:----|----Pollo|$\$$0.013Carne|$\$$0.008Cordero|$\$$0.010Arroz|$\$$0.002Trigo|$\$$0.005Gel|$\$$0.001 Lo que se busca optimizar en este caso es la cantidad de productos que se debe utilizar en la comida de gato, para simplificar la notación se van a nombrar las siguientes variables: $x_1:$ Gramos de pollo $x_2:$ Gramos de carne $x_3:$ Gramos de cordero $x_4:$ Gramos de arroz $x_5:$ Gramos de trigo $x_6:$ Gramos de gel Con los datos, se puede plantear la función objetivo, está dada por la siguiente expresión:$$\min 0.013 x_1 + 0.008 x_2 + 0.010 x_3 + 0.002 x_4 + 0.005 x_5 + 0.001 x_6$$Las restricciones estarían dadas por el siguiente conjunto de ecuaciones:$x_1+x_2+x_3+x_4+x_5+x_6=100$ $(10.0 x_1+ 20.0 x_2+ 15.0 x_3+ 00.0 x_4+ 04.0 x_5+ 00.0 x_6)/100 \geq 8.0$ $(08.0 x_1+ 10.0 x_2+ 11.0 x_3+ 01.0 x_4+ 01.0 x_5+ 00.0 x_6)/100 \geq 6.0$ $(00.1 x_1+ 00.5 x_2+ 00.5 x_3+ 10.0 x_4+ 15.0 x_5+ 00.0 x_6)/100 \leq 2.0$ $(00.2 x_1+ 00.5 x_2+ 00.7 x_3+ 00.2 x_4+ 00.8 x_5+ 00.0 x_6)/100 \leq 0.4$ La primer condición asegura que la cantidad de productos que se usará cumple con los 100 gramos. Las siguientes sólo siguen los lineamientos planteados para cumplir con los requisitos nutrimentales. 2. Otro problema de transporteReferencia: https://relopezbriega.github.io/blog/2017/01/18/problemas-de-optimizacion-con-python/Supongamos que tenemos que enviar cajas de cervezas de 2 cervecerías (Modelo y Cuauhtémoc Moctezuma) a 5 bares de acuerdo al siguiente gráfico:Asimismo, supongamos que nuestro gerente financiero nos informa que el costo de transporte por caja de cada ruta se conforma de acuerdo a la siguiente tabla:
import pandas as pd info = pd.DataFrame({'Bar1': [2, 3], 'Bar2': [4, 1], 'Bar3': [5, 3], 'Bar4': [2, 2], 'Bar5': [1, 3]}, index = ['CerveceriaA', 'CerveceriaB']) info
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
NYSE & BlurrIn this guide we will train a machine learning model that predicts closing price of a stock based on historical data. We will transform time-series stock data into features to train this model. PrerequisitesIt's recommended to have a basic understanding of how Blurr works. Following [tutorials 1](http://productml-blurr.readthedocs.io/en/latest/Streaming%20BTS%20Tutorial/) and [2](http://productml-blurr.readthedocs.io/en/latest/Window%20BTS%20Tutorial/) should provide enough background context. PreparationLet's start by installing `Blurr` and other required dependencies (using requirements.txt):
import sys print("installing blurr and other required dependencies...") !{sys.executable} -m pip install blurr --quiet !{sys.executable} -m pip install -r requirements.txt --quiet print("done.")
installing blurr and other required dependencies... done.
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
The DatasetThis walkthrough is based on [New York Stock Exchange Data](https://www.kaggle.com/dgawlik/nyse/data) made available for [Kaggle challenges](https://www.kaggle.com/dgawlik/nyse).Let's start by downloading and having a peek at the available data:
!wget http://demo.productml.com/data/nyse-input-data.json.zip !unzip -o nyse-input-data.json.zip -d . import pandas as pd stocks = pd.read_json("./nyse-input-data.json", lines=True) stocks.head()
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
This dataset contains data for each market day.Our **goal is to predict closing price** of a stock for any given day based on historical data. In order to do that, we need to transform our original data source into **features** that can be used for training.We'll calculate **moving averages** and other aggregate data for different **time windows**: one, three and seven days. Blurr TemplatesWe perform initial aggregations of our data by day with [nyse-streaming-bts.yml](./nyse-streaming-bts.yml). Features are then computed using [nyse-window-bts.yml](./nyse-window-bts.yml) for each stock per day.
!cat 'nyse-streaming-bts.yml'
Type: Blurr:Transform:Streaming Version: '2018-03-01' Description: New York Store Exchange Transformations Name: nyse Import: - { Module: dateutil.parser, Identifiers: [ parse ]} Identity: source.symbol Time: parse(source.datetime) Stores: - Type: Blurr:Store:Memory Name: memory Aggregates: - Type: Blurr:Aggregate:Block Name: stats Store: memory Split: time.date() != stats.latest_tradetime.date() When: source.symbol in ['AAPL', 'MSFT', 'GOOG', 'FB'] Fields: - Name: close Type: float Value: source.price - Name: high Type: float Value: source.price When: source.price >= stats.high - Name: low Type: float Value: source.price When: (stats.low == 0 or source.price < stats.low) - Name: volatility Type: float Value: (float(stats.high) / float(stats.low)) - 1 When: stats.low > 0 - Name: volume Type: float Value: stats.volume + source.volume - Name: latest_tradetime Type: datetime Value: time
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
**Streaming BTS**We're predicting values for tech companies only (Apple, Facebook, Microsoft, Google):```yamlWhen: source.symbol in ['AAPL', 'MSFT', 'GOOG', 'FB']```Each record in the original dataset represents a single stock transaction. By setting `Split: str(time.date()) != stats.date` we'll create a new aggregate for each day per stock.
!cat 'nyse-window-bts.yml'
Type: Blurr:Transform:Window Version: '2018-03-01' Name: moving_averages SourceBTS: nyse Anchor: Condition: nyse.stats.volatility < 0.04 Aggregates: - Type: Blurr:Aggregate:Window Name: close WindowType: count WindowValue: 1 Source: nyse.stats Fields: - Name: value Type: float Value: anchor.close # the anchor object represents the record that matches the anchor condition - Type: Blurr:Aggregate:Window Name: last WindowType: count WindowValue: -1 Source: nyse.stats Fields: - Name: close Type: float Value: source.close[0] - Name: volume Type: float Value: source.volume[0] - Name: volatility Type: float Value: source.volatility[0] - Type: Blurr:Aggregate:Window Name: last_3 WindowType: count WindowValue: -3 Source: nyse.stats Fields: - Name: close_avg Type: float Value: sum(source.close) / len(source.close) - Name: volume_avg Type: float Value: sum(source.volume) / len(source.volume) - Name: volatility_avg Type: float Value: sum(source.volatility) / len(source.volatility) - Name: max_volatility Type: float Value: max(source.volatility) - Name: min_volatility Type: float Value: min(source.volatility) - Type: Blurr:Aggregate:Window Name: last_7 WindowType: count WindowValue: -7 Source: nyse.stats Fields: - Name: close_avg Type: float Value: sum(source.close) / len(source.close) - Name: volume_avg Type: float Value: sum(source.volume) / len(source.volume) - Name: volatility_avg Type: float Value: sum(source.volatility) / len(source.volatility) - Name: max_volatility Type: float Value: max(source.volatility) - Name: min_volatility Type: float Value: min(source.volatility)
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
**Window BTS**We'll use a very rough criteria to remove outliers: our model will only work when closing price changes less than a 4%:```yamlAnchor: Condition: nyse.stats.volatility < 0.04```We're using [moving averages](https://www.investopedia.com/terms/m/movingaverage.asp) to generate features based on historical data about a stock:```yaml- Type: Blurr:Aggregate:Window Name: last_7 WindowType: count WindowValue: -7 Source: nyse.stats Fields: - Name: close_avg Type: float Value: sum(source.close) / len(source.close)``` Transforming Data
from blurr_util import print_head, validate, transform validate('nyse-streaming-bts.yml') validate('nyse-window-bts.yml')
Running syntax validation on nyse-streaming-bts.yml Document is valid Running syntax validation on nyse-window-bts.yml Document is valid
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Let's run our Streaming BTS for informational purposes only, so we can preview the result of the transformation:
transform(log_files=["./nyse-input-data.json"], stream_bts='./nyse-streaming-bts.yml', output_file="./nyse-streaming-bts-out.log") print_head("./nyse-streaming-bts-out.log") transform(log_files=["./nyse-input-data.json"], stream_bts='./nyse-streaming-bts.yml', window_bts='./nyse-window-bts.yml', output_file="./nyse-processed-data.csv")
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Let's now preview the data that will be used to **train our model**
window_out = pd.read_csv("./nyse-processed-data.csv") window_out.head()
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Modelling**Blurr** is about Data Preparation and Feature Engineering. Modeling is included here for illustration purpose, and the reader can use any modeling library or tool for such purpose.Let's start by importing the output of our Window BTS as the source dataset. We're dropping unnecessary `_identity` columns:
import numpy as np import matplotlib.pyplot as plt import pandas as pd def import_dataset(): data = pd.read_csv("./nyse-processed-data.csv") data["close"] = data["close.value"] # Moving close to the last column data.drop(['close.value'], 1, inplace=True) data.drop(['close._identity'], 1, inplace=True) data.drop(['last._identity'], 1, inplace=True) data.drop(['last_3._identity'], 1, inplace=True) data.drop(['last_7._identity'], 1, inplace=True) return data dataset = import_dataset() dataset.head()
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Each column represents a Feature, except the rightmost column which represents the Output we're trying to predic
feature_count = len(dataset.columns) - 1 print("#features=" + str(feature_count))
#features=13
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
We're splitting our dataset into Input Variables (`X`) and the Output Variable (`Y`) using pandas' [`iloc` function](http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.iloc.html):
X = dataset.iloc[:, 0:feature_count].values print(X.shape) Y = dataset.iloc[:, feature_count].values print(Y.shape)
(5978,)
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
We need to split between train and test datasets for training and evaluation of the model:
from sklearn.model_selection import train_test_split X_train_raw, X_test_raw, Y_train_raw, Y_test_raw = train_test_split(X, Y, test_size = 0.2)
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Finally, we need to scale our data before training:
from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() X_train = scaler.fit_transform(X_train_raw) X_test = scaler.transform(X_test_raw) Y_train = scaler.fit_transform(Y_train_raw.reshape(-1, 1)) Y_test = scaler.transform(Y_test_raw.reshape(-1, 1))
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
It's now time to build and train our model:
# Importing the Keras libraries and packages import keras from keras.models import Sequential from keras.layers import Dense #Initializing Neural Network model = Sequential() model.add(Dense(units = 36, kernel_initializer = 'uniform', activation = 'relu', input_dim = feature_count)) model.add(Dense(units = 36, kernel_initializer = 'uniform', activation = 'relu')) model.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'linear')) # Compiling Neural Network model.compile(loss='mse',optimizer='adam', metrics=['accuracy']) # Fitting our model model.fit(X_train, Y_train, batch_size = 512, epochs = 70, validation_split=0.1, verbose=1)
Train on 4303 samples, validate on 479 samples Epoch 1/70 4303/4303 [==============================] - 0s 46us/step - loss: 0.1025 - acc: 0.0000e+00 - val_loss: 0.0775 - val_acc: 0.0021 Epoch 2/70 4303/4303 [==============================] - 0s 4us/step - loss: 0.0942 - acc: 0.0000e+00 - val_loss: 0.0686 - val_acc: 0.0021 Epoch 3/70 4303/4303 [==============================] - 0s 4us/step - loss: 0.0813 - acc: 0.0000e+00 - val_loss: 0.0563 - val_acc: 0.0021 Epoch 4/70 4303/4303 [==============================] - 0s 4us/step - loss: 0.0645 - acc: 0.0000e+00 - val_loss: 0.0449 - val_acc: 0.0021 Epoch 5/70 4303/4303 [==============================] - 0s 4us/step - loss: 0.0494 - acc: 0.0000e+00 - val_loss: 0.0391 - val_acc: 0.0021 Epoch 6/70 4303/4303 [==============================] - 0s 4us/step - loss: 0.0385 - acc: 0.0000e+00 - val_loss: 0.0277 - val_acc: 0.0021 Epoch 7/70 4303/4303 [==============================] - 0s 4us/step - loss: 0.0242 - acc: 2.3240e-04 - val_loss: 0.0145 - val_acc: 0.0021 Epoch 8/70 4303/4303 [==============================] - 0s 4us/step - loss: 0.0113 - acc: 2.3240e-04 - val_loss: 0.0053 - val_acc: 0.0021 Epoch 9/70 4303/4303 [==============================] - 0s 5us/step - loss: 0.0034 - acc: 2.3240e-04 - val_loss: 0.0016 - val_acc: 0.0021 Epoch 10/70 4303/4303 [==============================] - 0s 4us/step - loss: 0.0010 - acc: 2.3240e-04 - val_loss: 8.0088e-04 - val_acc: 0.0021 Epoch 11/70 4303/4303 [==============================] - 0s 5us/step - loss: 7.3606e-04 - acc: 2.3240e-04 - val_loss: 7.9738e-04 - val_acc: 0.0021 Epoch 12/70 4303/4303 [==============================] - 0s 4us/step - loss: 7.4681e-04 - acc: 2.3240e-04 - val_loss: 7.1321e-04 - val_acc: 0.0021 Epoch 13/70 4303/4303 [==============================] - 0s 4us/step - loss: 6.5283e-04 - acc: 2.3240e-04 - val_loss: 5.8154e-04 - val_acc: 0.0021 Epoch 14/70 4303/4303 [==============================] - 0s 5us/step - loss: 5.3614e-04 - acc: 2.3240e-04 - val_loss: 5.1272e-04 - val_acc: 0.0021 Epoch 15/70 4303/4303 [==============================] - 0s 4us/step - loss: 4.8915e-04 - acc: 2.3240e-04 - val_loss: 4.8887e-04 - val_acc: 0.0021 Epoch 16/70 4303/4303 [==============================] - 0s 4us/step - loss: 4.5884e-04 - acc: 2.3240e-04 - val_loss: 4.4613e-04 - val_acc: 0.0021 Epoch 17/70 4303/4303 [==============================] - 0s 4us/step - loss: 4.2753e-04 - acc: 2.3240e-04 - val_loss: 4.1493e-04 - val_acc: 0.0021 Epoch 18/70 4303/4303 [==============================] - 0s 4us/step - loss: 4.0553e-04 - acc: 2.3240e-04 - val_loss: 3.9318e-04 - val_acc: 0.0021 Epoch 19/70 4303/4303 [==============================] - 0s 4us/step - loss: 3.8638e-04 - acc: 2.3240e-04 - val_loss: 3.7563e-04 - val_acc: 0.0021 Epoch 20/70 4303/4303 [==============================] - 0s 4us/step - loss: 3.6760e-04 - acc: 2.3240e-04 - val_loss: 3.5841e-04 - val_acc: 0.0021 Epoch 21/70 4303/4303 [==============================] - 0s 4us/step - loss: 3.4842e-04 - acc: 2.3240e-04 - val_loss: 3.3985e-04 - val_acc: 0.0021 Epoch 22/70 4303/4303 [==============================] - 0s 4us/step - loss: 3.2932e-04 - acc: 2.3240e-04 - val_loss: 3.2005e-04 - val_acc: 0.0021 Epoch 23/70 4303/4303 [==============================] - 0s 4us/step - loss: 3.0877e-04 - acc: 2.3240e-04 - val_loss: 3.0079e-04 - val_acc: 0.0021 Epoch 24/70 4303/4303 [==============================] - 0s 4us/step - loss: 2.8941e-04 - acc: 2.3240e-04 - val_loss: 2.8071e-04 - val_acc: 0.0021 Epoch 25/70 4303/4303 [==============================] - 0s 4us/step - loss: 2.6856e-04 - acc: 2.3240e-04 - val_loss: 2.6227e-04 - val_acc: 0.0021 Epoch 26/70 4303/4303 [==============================] - 0s 4us/step - loss: 2.4924e-04 - acc: 2.3240e-04 - val_loss: 2.4349e-04 - val_acc: 0.0021 Epoch 27/70 4303/4303 [==============================] - 0s 4us/step - loss: 2.3008e-04 - acc: 2.3240e-04 - val_loss: 2.2409e-04 - val_acc: 0.0021 Epoch 28/70 4303/4303 [==============================] - 0s 5us/step - loss: 2.1201e-04 - acc: 2.3240e-04 - val_loss: 2.0661e-04 - val_acc: 0.0021 Epoch 29/70 4303/4303 [==============================] - 0s 4us/step - loss: 1.9386e-04 - acc: 2.3240e-04 - val_loss: 1.8931e-04 - val_acc: 0.0021 Epoch 30/70 4303/4303 [==============================] - 0s 4us/step - loss: 1.7755e-04 - acc: 2.3240e-04 - val_loss: 1.7436e-04 - val_acc: 0.0021 Epoch 31/70 4303/4303 [==============================] - 0s 4us/step - loss: 1.6193e-04 - acc: 2.3240e-04 - val_loss: 1.5940e-04 - val_acc: 0.0021 Epoch 32/70 4303/4303 [==============================] - 0s 4us/step - loss: 1.4812e-04 - acc: 2.3240e-04 - val_loss: 1.4754e-04 - val_acc: 0.0021 Epoch 33/70 4303/4303 [==============================] - 0s 4us/step - loss: 1.3705e-04 - acc: 2.3240e-04 - val_loss: 1.3818e-04 - val_acc: 0.0021 Epoch 34/70 4303/4303 [==============================] - 0s 4us/step - loss: 1.2689e-04 - acc: 2.3240e-04 - val_loss: 1.2781e-04 - val_acc: 0.0021 Epoch 35/70 4303/4303 [==============================] - 0s 4us/step - loss: 1.1788e-04 - acc: 2.3240e-04 - val_loss: 1.2091e-04 - val_acc: 0.0021 Epoch 36/70 4303/4303 [==============================] - 0s 4us/step - loss: 1.0975e-04 - acc: 2.3240e-04 - val_loss: 1.1201e-04 - val_acc: 0.0021 Epoch 37/70 4303/4303 [==============================] - 0s 4us/step - loss: 1.0235e-04 - acc: 2.3240e-04 - val_loss: 1.0453e-04 - val_acc: 0.0021 Epoch 38/70 4303/4303 [==============================] - 0s 4us/step - loss: 9.5748e-05 - acc: 2.3240e-04 - val_loss: 9.8943e-05 - val_acc: 0.0021 Epoch 39/70 4303/4303 [==============================] - 0s 4us/step - loss: 9.0075e-05 - acc: 2.3240e-04 - val_loss: 9.3020e-05 - val_acc: 0.0021 Epoch 40/70 4303/4303 [==============================] - 0s 4us/step - loss: 8.4809e-05 - acc: 2.3240e-04 - val_loss: 8.7891e-05 - val_acc: 0.0021 Epoch 41/70 4303/4303 [==============================] - 0s 4us/step - loss: 8.0412e-05 - acc: 2.3240e-04 - val_loss: 8.3260e-05 - val_acc: 0.0021 Epoch 42/70 4303/4303 [==============================] - 0s 4us/step - loss: 7.6413e-05 - acc: 2.3240e-04 - val_loss: 8.0566e-05 - val_acc: 0.0021 Epoch 43/70 4303/4303 [==============================] - 0s 4us/step - loss: 7.2809e-05 - acc: 2.3240e-04 - val_loss: 7.6273e-05 - val_acc: 0.0021 Epoch 44/70 4303/4303 [==============================] - 0s 4us/step - loss: 6.9614e-05 - acc: 2.3240e-04 - val_loss: 7.2717e-05 - val_acc: 0.0021 Epoch 45/70 4303/4303 [==============================] - 0s 4us/step - loss: 6.6499e-05 - acc: 2.3240e-04 - val_loss: 6.9950e-05 - val_acc: 0.0021 Epoch 46/70 4303/4303 [==============================] - 0s 4us/step - loss: 6.3570e-05 - acc: 2.3240e-04 - val_loss: 6.6740e-05 - val_acc: 0.0021 Epoch 47/70 4303/4303 [==============================] - 0s 5us/step - loss: 6.1582e-05 - acc: 2.3240e-04 - val_loss: 6.4343e-05 - val_acc: 0.0021 Epoch 48/70 4303/4303 [==============================] - 0s 5us/step - loss: 5.9359e-05 - acc: 2.3240e-04 - val_loss: 6.2669e-05 - val_acc: 0.0021 Epoch 49/70 4303/4303 [==============================] - 0s 5us/step - loss: 5.7216e-05 - acc: 2.3240e-04 - val_loss: 5.9803e-05 - val_acc: 0.0021 Epoch 50/70 4303/4303 [==============================] - 0s 5us/step - loss: 5.5511e-05 - acc: 2.3240e-04 - val_loss: 5.8672e-05 - val_acc: 0.0021 Epoch 51/70 4303/4303 [==============================] - 0s 5us/step - loss: 5.4430e-05 - acc: 2.3240e-04 - val_loss: 5.6377e-05 - val_acc: 0.0021 Epoch 52/70 4303/4303 [==============================] - 0s 4us/step - loss: 5.2620e-05 - acc: 2.3240e-04 - val_loss: 5.4984e-05 - val_acc: 0.0021 Epoch 53/70 4303/4303 [==============================] - 0s 5us/step - loss: 5.1474e-05 - acc: 2.3240e-04 - val_loss: 5.3884e-05 - val_acc: 0.0021 Epoch 54/70 4303/4303 [==============================] - 0s 4us/step - loss: 5.1241e-05 - acc: 2.3240e-04 - val_loss: 5.1820e-05 - val_acc: 0.0021 Epoch 55/70 4303/4303 [==============================] - 0s 4us/step - loss: 4.8984e-05 - acc: 2.3240e-04 - val_loss: 5.0553e-05 - val_acc: 0.0021 Epoch 56/70 4303/4303 [==============================] - 0s 4us/step - loss: 4.7987e-05 - acc: 2.3240e-04 - val_loss: 4.9232e-05 - val_acc: 0.0021
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
We can measure the quality of our model using [MSE](https://en.wikipedia.org/wiki/Mean_squared_error) and [RMSE](https://en.wikipedia.org/wiki/Root-mean-square_deviation):
import math score = model.evaluate(X_test, Y_test, verbose=0) print('Model Score: %.5f MSE (%.2f RMSE)' % (score[0], math.sqrt(score[0])))
Model Score: 0.00004 MSE (0.01 RMSE)
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Finally, let's plot prediction vs actual data.Prior to normalisation, we undo scaling and perform a sort for graph quality:
import matplotlib.pyplot as plt2 prediction_sorted = scaler.inverse_transform(model.predict(X_test)) prediction_sorted.sort(axis=0) Y_test_sorted = scaler.inverse_transform(Y_test.copy().reshape(-1, 1)) Y_test_sorted.sort(axis=0) plt2.plot(prediction_sorted, color='red', label='Prediction') plt2.plot(Y_test_sorted, color='blue', label='Actual') plt2.xlabel('#sample') plt2.ylabel('close value') plt2.legend(loc='best') plt2.show()
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Xarray-spatial User Guide: Surface tools-----With the Surface tools, you can quantify and visualize a terrain landform represented by a digital elevation model.Starting with a raster elevation surface, represented as an Xarray DataArray, these tools can help you identify some specific patterns that may not be readily apparent in the original surface. The return of each function is also an Xarray DataArray.[Hillshade](Hillshade): Creates a shaded relief from a surface raster by considering the illumination source angle and shadows.[Slope](Slope): Identifies the slope for each cell of a raster.[Curvature](Curvature): Calculates the curvature of a raster surface.[Aspect](Aspect): Derives the aspect for each cell of a raster surface.[Viewshed](Viewshed): Determines visible locations in the input raster surface from a viewpoint with an optional observer height.----------- Let's use datashader to render our images... We'll need the basic Numpy and Pandas, as well as datashader, a data rasterization package highly compatible with Xarray-spatial. Along with the base package, we'll import several nested functions (shade, stack...) including Elevation, which we'll use below.
import numpy as np import pandas as pd import xarray as xr import datashader as ds from datashader.transfer_functions import shade from datashader.transfer_functions import stack from datashader.transfer_functions import dynspread from datashader.transfer_functions import set_background from datashader.colors import Elevation import xrspatial
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Generate Terrain DataThe rest of the geo-related functions focus on raster data, i.e. data that's been aggregated into the row-column grid of cells in a raster image. Datashader's Canvas object provides a convenient frame to set up a new raster, so we'll use that with our `generate_terrain` function to generate some fake terrain as an elevation raster. Once we have that, we'll use datashader's shade for easy visualization.
from xrspatial import generate_terrain W = 800 H = 600 terrain = xr.DataArray(np.zeros((H, W))) terrain = generate_terrain(terrain) shade(terrain, cmap=['black', 'white'], how='linear')
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
The grayscale values in the image above show elevation, scaled linearly in black-to-white color intensity (with the large black areas indicating low elevation). This shows the data, but it would look more like a landscape if we map the lowest values to colors representing water, and the highest to colors representing mountaintops. Let's try the Elevation colormap we imported above:
shade(terrain, cmap=Elevation, how='linear')
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Hillshade[Hillshade](https://en.wikipedia.org/wiki/Terrain_cartography) is a technique used to visualize terrain as shaded relief by illuminating it with a hypothetical light source. The illumination value for each cell is determined by its orientation to the light source, which can be calculated from slope and aspect.Let's apply Hillshade to our terrain and visualize the result with shade.
from xrspatial import hillshade illuminated = hillshade(terrain) hillshade_gray_white = shade(illuminated, cmap=['gray', 'white'], alpha=255, how='linear') hillshade_gray_white
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Applying hillshade reveals a lot of detail in the 3D shape of the terrain.To add even more detail, we can add the Elevation colormapped terrain from earlier and combine it with the hillshade terrain using datashader's stack function.
terrain_elevation = shade(terrain, cmap=Elevation, alpha=128, how='linear') stack(hillshade_gray_white, terrain_elevation)
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Slope[Slope](https://en.wikipedia.org/wiki/Slope) is the inclination of a surface. In geography, *slope* is the amount of change in elevation for an area in a terrain relative to its surroundings.Xarray-spatial's slope function returns the slope at each cell in degrees.Because Xarray-spatial is integrated with Xarray and Numpy, we can apply standard Numpy filters. For example, we can highlight only slopes in the [avalanche risk](https://www.gravityprotection.co.uk/blog/slope-steepness-avalanche-risk.html) range of 25 - 50 degrees. (Note the use of risky.data since these are DataArrays).Stacking the resulting raster with the hillshaded and plain terrain ones from above gives an image with areas of avalanche risk neatly highlighted.
from xrspatial import slope risky = slope(terrain) risky.data = np.where(np.logical_and(risky.data > 25, risky.data < 50), 1, np.nan) stack(shade(terrain, cmap=['black', 'white'], how='linear'), shade(illuminated, cmap=['black', 'white'], how='linear', alpha=128), shade(risky, cmap='red', how='linear', alpha=200))
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Curvature[Curvature](https://desktop.arcgis.com/en/arcmap/10.3/tools/spatial-analyst-toolbox/curvature.htm) is the second derivative of a surface's elevation, or the *slope-of-the-slope*; in other words, how fast the slope is increasing or decreasing as we move along a surface.- A positive curvature means the surface is curving up (upwardly convex) at that cell. - A negative curvature means the surface is curving down (downwardly convex) at that cell. - A curvature of 0 means the surface is striaght and constant in whatever angle it's sloped towards.The Xarray-spatial curvature function returns a raster in units one hundredth (1/100) of the z-factor, or scaling factor (which you can set explicitly in generate _terrain as "zfactor"). Reasonably expected values in the curvature raster for a hilly area (moderate relief) would be between -0.5 and 0.5, while for steep, rugged mountains (extreme relief) these can range as far as -4 and 4. For certain raster surfaces it is possible to go even larger than that.Let's generate a terrain with an appropriate z-factor and apply the curvature function to it. Then, we can apply some Numpy filtering (remember, we have access to all those functions) to highlight steeper and gentler curves in the slopes.Stacking these with the hillshaded and plain terrains gives us a fuller picture of the slopes.
from xrspatial import curvature terrain_z_one = xr.DataArray(np.zeros((H, W))) terrain_z_one = generate_terrain(terrain_z_one, zfactor=1) curv = curvature(terrain_z_one) curv_hi, curv_low = curv.copy(), curv.copy() curv_hi.data = np.where(np.logical_and(curv_hi.data > 1, curv_hi.data < 4), 1, np.nan) curv_low.data = np.where(np.logical_and(curv_low.data > 0.5, curv_low.data < 1), 1, np.nan) stack(shade(terrain, cmap=['black', 'white'], how='linear'), shade(illuminated, cmap=['black', 'white'], how='linear', alpha=128), shade(curv_hi, cmap='red', how='log', alpha=200), shade(curv_low, cmap='green', how='log', alpha=200))
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Aspect[Aspect](https://en.wikipedia.org/wiki/Aspect_(geography)) is the orientation of a slope, measured clockwise in degrees from 0 to 360, where 0 is north-facing, 90 is east-facing, 180 is south-facing, and 270 is west-facing.The Xarray-spatial aspect function returns the aspect in degrees for each cell in an elevation terrain.We can apply aspect to our terrain, then use Numpy to filter out only slopes facing close to North. Then, we can stack that with the hillshaded and plain terrains.(Note: the printout images are from a North point-of-view.)
from xrspatial import aspect north_faces = aspect(terrain) north_faces.data = np.where(np.logical_or(north_faces.data > 350 , north_faces.data < 10), 1, np.nan) stack(shade(terrain, cmap=['black', 'white'], how='linear'), shade(illuminated, cmap=['black', 'white'], how='linear', alpha=128), shade(north_faces, cmap=['aqua'], how='linear', alpha=100))
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
ViewshedThe `xrspatial.viewshed` function operates on a given aggregate to calculate the viewshed (the visible cells in the raster) for a given viewpoint, or *observer location*. The visibility model is as follows: Two cells are visible to each other if the line of sight that connects their centers is not blocked at any point by another part of the terrain. If the line of sight does not pass through the cell center, elevation is determined using bilinear interpolation. Simple Viewshed Example- The example below creates a datashader aggregate from a 2d normal distribution.- To calculate the viewshed, we need an observer location so we'll set up an aggregate for that as well.- Then, we can visualize all of that with hillshade, shade, and stack.- The observer location is indicated by the orange point in the upper-left of the plot.
from xrspatial import viewshed OBSERVER_X = -12.5 OBSERVER_Y = 10 canvas = ds.Canvas(plot_width=W, plot_height=H, x_range=(-20, 20), y_range=(-20, 20)) normal_df = pd.DataFrame({ 'x': np.random.normal(.5, 1, 10000000), 'y': np.random.normal(.5, 1, 10000000) }) normal_agg = canvas.points(normal_df, 'x', 'y') normal_agg.values = normal_agg.values.astype("float64") normal_shaded = shade(normal_agg) observer_df = pd.DataFrame({'x': [OBSERVER_X], 'y': [OBSERVER_Y]}) observer_agg = canvas.points(observer_df, 'x', 'y') observer_shaded = dynspread(shade(observer_agg, cmap=['orange']), threshold=1, max_px=4) normal_illuminated = hillshade(normal_agg) normal_illuminated_shaded = shade(normal_illuminated, cmap=['black', 'white'], alpha=128, how='linear') stack(normal_illuminated_shaded, observer_shaded)
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Calculate viewshed using the observer locationNow we can apply viewshed to the normal_agg, with the observer_agg for the viewpoint. We can then visualize it and stack it with the hillshade and observer rasters.
# Will take some time to run... %time view = viewshed(normal_agg, x=OBSERVER_X, y=OBSERVER_Y) view_shaded = shade(view, cmap=['white', 'red'], alpha=128, how='linear') stack(normal_illuminated_shaded, observer_shaded, view_shaded)
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
As you can see, the image highlights in red all points visible from the observer location marked with the orange dot. As one might expect, the areas behind the normal distribution *mountain* are blocked from the viewer. Viewshed on TerrainNow we can try using viewshed on our more complicated terrain.- We'll set up our terrain aggregate and apply hillshade and shade for easy visualization.- We'll also set up an observer location aggregate, setting the location to the center, at (x, y) = (0, 0).
from xrspatial import viewshed x_range=(-20e6, 20e6) y_range=(-20e6, 20e6) terrain = xr.DataArray(np.zeros((H, W))) terrain = generate_terrain(terrain, x_range=x_range, y_range=y_range) terrain_shaded = shade(terrain, cmap=Elevation, alpha=128, how='linear') illuminated = hillshade(terrain) OBSERVER_X = 0.0 OBSERVER_Y = 0.0 cvs = ds.Canvas(plot_width=W, plot_height=H, x_range=x_range, y_range=y_range) observer_df = pd.DataFrame({'x': [OBSERVER_X],'y': [OBSERVER_Y]}) observer_agg = cvs.points(observer_df, 'x', 'y') observer_shaded = dynspread(shade(observer_agg, cmap=['orange']), threshold=1, max_px=4) stack(shade(illuminated, cmap=['black', 'white'], alpha=128, how='linear'), terrain_shaded, observer_shaded)
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Now we can apply viewshed.- Notice the use of the `observer_elev` argument, which is the height of the observer above the terrain.
%time view = viewshed(terrain, x=OBSERVER_X, y=OBSERVER_Y, observer_elev=100) view_shaded = shade(view, cmap='fuchsia', how='linear') stack(shade(illuminated, cmap=['black', 'white'], alpha=128, how='linear'), terrain_shaded, view_shaded, observer_shaded)
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Logistic Regression with Python In this notebook, you will learn Logistic Regression, and then, you'll create a model for a telecommunication company, to predict when its customers will leave for a competitor, so that they can take some action to retain the customers. Table of contents About the dataset Data pre-processing and selection Modeling (Logistic Regression with Scikit-learn) Evaluation Practice What is the difference between Linear and Logistic Regression?While Linear Regression is suited for estimating continuous values (e.g. estimating house price), it is not the best tool for predicting the class of an observed data point. In order to estimate the class of a data point, we need some sort of guidance on what would be the most probable class for that data point. For this, we use Logistic Regression.Recall linear regression: As you know, Linear regression finds a function that relates a continuous dependent variable, y, to some predictors (independent variables $x_1$, $x_2$, etc.). For example, Simple linear regression assumes a function of the form:$$y = \theta_0 + \theta_1 x_1 + \theta_2 x_2 + \cdots$$and finds the values of parameters $\theta_0, \theta_1, \theta_2$, etc, where the term $\theta_0$ is the "intercept". It can be generally shown as:$$ℎ_\theta(𝑥) = \theta^TX$$Logistic Regression is a variation of Linear Regression, useful when the observed dependent variable, y, is categorical. It produces a formula that predicts the probability of the class label as a function of the independent variables.Logistic regression fits a special s-shaped curve by taking the linear regression and transforming the numeric estimate into a probability with the following function, which is called sigmoid function 𝜎:$$ℎ_\theta(𝑥) = \sigma({\theta^TX}) = \frac {e^{(\theta_0 + \theta_1 x_1 + \theta_2 x_2 +...)}}{1 + e^{(\theta_0 + \theta_1 x_1 + \theta_2 x_2 +\cdots)}}$$Or:$$ProbabilityOfaClass_1 = P(Y=1|X) = \sigma({\theta^TX}) = \frac{e^{\theta^TX}}{1+e^{\theta^TX}} $$In this equation, ${\theta^TX}$ is the regression result (the sum of the variables weighted by the coefficients), `exp` is the exponential function and $\sigma(\theta^TX)$ is the sigmoid or [logistic function](http://en.wikipedia.org/wiki/Logistic_function), also called logistic curve. It is a common "S" shape (sigmoid curve).So, briefly, Logistic Regression passes the input through the logistic/sigmoid but then treats the result as a probability:<imgsrc="https://ibm.box.com/shared/static/kgv9alcghmjcv97op4d6onkyxevk23b1.png" width="400" align="center">The objective of __Logistic Regression__ algorithm, is to find the best parameters θ, for $ℎ_\theta(𝑥)$ = $\sigma({\theta^TX})$, in such a way that the model best predicts the class of each case. Customer churn with Logistic RegressionA telecommunications company is concerned about the number of customers leaving their land-line business for cable competitors. They need to understand who is leaving. Imagine that you are an analyst at this company and you have to find out who is leaving and why. Lets first import required libraries:
import pandas as pd import pylab as pl import numpy as np import scipy.optimize as opt from sklearn import preprocessing %matplotlib inline import matplotlib.pyplot as plt
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
About the datasetWe will use a telecommunications dataset for predicting customer churn. This is a historical customer dataset where each row represents one customer. The data is relatively easy to understand, and you may uncover insights you can use immediately. Typically it is less expensive to keep customers than acquire new ones, so the focus of this analysis is to predict the customers who will stay with the company. This data set provides information to help you predict what behavior will help you to retain customers. You can analyze all relevant customer data and develop focused customer retention programs.The dataset includes information about:- Customers who left within the last month – the column is called Churn- Services that each customer has signed up for – phone, multiple lines, internet, online security, online backup, device protection, tech support, and streaming TV and movies- Customer account information – how long they had been a customer, contract, payment method, paperless billing, monthly charges, and total charges- Demographic info about customers – gender, age range, and if they have partners and dependents Load the Telco Churn data Telco Churn is a hypothetical data file that concerns a telecommunications company's efforts to reduce turnover in its customer base. Each case corresponds to a separate customer and it records various demographic and service usage information. Before you can work with the data, you must use the URL to get the ChurnData.csv.To download the data, we will use `!wget` to download it from IBM Object Storage.
#Click here and press Shift+Enter !wget -O ChurnData.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/ChurnData.csv
--2019-04-09 12:01:22-- https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/ChurnData.csv Resolving s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)... 67.228.254.193 Connecting to s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)|67.228.254.193|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 36144 (35K) [text/csv] Saving to: ‘ChurnData.csv’ ChurnData.csv 100%[=====================>] 35.30K --.-KB/s in 0.02s 2019-04-09 12:01:22 (1.62 MB/s) - ‘ChurnData.csv’ saved [36144/36144]
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
__Did you know?__ When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](http://cocl.us/ML0101EN-IBM-Offer-CC) Load Data From CSV File
churn_df = pd.read_csv("ChurnData.csv") churn_df.head()
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Data pre-processing and selection Lets select some features for the modeling. Also we change the target data type to be integer, as it is a requirement by the skitlearn algorithm:
churn_df = churn_df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip', 'callcard', 'wireless','churn']] churn_df['churn'] = churn_df['churn'].astype('int') churn_df.head()
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
PracticeHow many rows and columns are in this dataset in total? What are the name of columns?
# write your code here churn_df.shape
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Lets define X, and y for our dataset:
X = np.asarray(churn_df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip']]) X[0:5] y = np.asarray(churn_df['churn']) y [0:5]
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Also, we normalize the dataset:
from sklearn import preprocessing X = preprocessing.StandardScaler().fit(X).transform(X) X[0:5]
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Train/Test dataset Okay, we split our dataset into train and test set:
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4) print ('Train set:', X_train.shape, y_train.shape) print ('Test set:', X_test.shape, y_test.shape)
Train set: (160, 7) (160,) Test set: (40, 7) (40,)
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Modeling (Logistic Regression with Scikit-learn) Lets build our model using __LogisticRegression__ from Scikit-learn package. This function implements logistic regression and can use different numerical optimizers to find parameters, including ‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’ solvers. You can find extensive information about the pros and cons of these optimizers if you search it in internet.The version of Logistic Regression in Scikit-learn, support regularization. Regularization is a technique used to solve the overfitting problem in machine learning models.__C__ parameter indicates __inverse of regularization strength__ which must be a positive float. Smaller values specify stronger regularization. Now lets fit our model with train set:
from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix LR = LogisticRegression(C=0.01, solver='liblinear').fit(X_train,y_train) LR
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Now we can predict using our test set:
yhat = LR.predict(X_test) yhat
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
__predict_proba__ returns estimates for all classes, ordered by the label of classes. So, the first column is the probability of class 1, P(Y=1|X), and second column is probability of class 0, P(Y=0|X):
yhat_prob = LR.predict_proba(X_test) yhat_prob
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Evaluation jaccard indexLets try jaccard index for accuracy evaluation. we can define jaccard as the size of the intersection divided by the size of the union of two label sets. If the entire set of predicted labels for a sample strictly match with the true set of labels, then the subset accuracy is 1.0; otherwise it is 0.0.
from sklearn.metrics import jaccard_similarity_score jaccard_similarity_score(y_test, yhat)
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
confusion matrixAnother way of looking at accuracy of classifier is to look at __confusion matrix__.
from sklearn.metrics import classification_report, confusion_matrix import itertools def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') print(confusion_matrix(y_test, yhat, labels=[1,0])) # Compute confusion matrix cnf_matrix = confusion_matrix(y_test, yhat, labels=[1,0]) np.set_printoptions(precision=2) # Plot non-normalized confusion matrix plt.figure() plot_confusion_matrix(cnf_matrix, classes=['churn=1','churn=0'],normalize= False, title='Confusion matrix')
Confusion matrix, without normalization [[ 6 9] [ 1 24]]
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Look at first row. The first row is for customers whose actual churn value in test set is 1.As you can calculate, out of 40 customers, the churn value of 15 of them is 1. And out of these 15, the classifier correctly predicted 6 of them as 1, and 9 of them as 0. It means, for 6 customers, the actual churn value were 1 in test set, and classifier also correctly predicted those as 1. However, while the actual label of 9 customers were 1, the classifier predicted those as 0, which is not very good. We can consider it as error of the model for first row.What about the customers with churn value 0? Lets look at the second row.It looks like there were 25 customers whom their churn value were 0. The classifier correctly predicted 24 of them as 0, and one of them wrongly as 1. So, it has done a good job in predicting the customers with churn value 0. A good thing about confusion matrix is that shows the model’s ability to correctly predict or separate the classes. In specific case of binary classifier, such as this example, we can interpret these numbers as the count of true positives, false positives, true negatives, and false negatives.
print (classification_report(y_test, yhat))
precision recall f1-score support 0 0.73 0.96 0.83 25 1 0.86 0.40 0.55 15 micro avg 0.75 0.75 0.75 40 macro avg 0.79 0.68 0.69 40 weighted avg 0.78 0.75 0.72 40
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Based on the count of each section, we can calculate precision and recall of each label:- __Precision__ is a measure of the accuracy provided that a class label has been predicted. It is defined by: precision = TP / (TP + FP)- __Recall__ is true positive rate. It is defined as: Recall =  TP / (TP + FN) So, we can calculate precision and recall of each class.__F1 score:__Now we are in the position to calculate the F1 scores for each label based on the precision and recall of that label. The F1 score is the harmonic average of the precision and recall, where an F1 score reaches its best value at 1 (perfect precision and recall) and worst at 0. It is a good way to show that a classifer has a good value for both recall and precision.And finally, we can tell the average accuracy for this classifier is the average of the F1-score for both labels, which is 0.72 in our case. log lossNow, lets try __log loss__ for evaluation. In logistic regression, the output can be the probability of customer churn is yes (or equals to 1). This probability is a value between 0 and 1.Log loss( Logarithmic loss) measures the performance of a classifier where the predicted output is a probability value between 0 and 1.
from sklearn.metrics import log_loss log_loss(y_test, yhat_prob)
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
PracticeTry to build Logistic Regression model again for the same dataset, but this time, use different __solver__ and __regularization__ values? What is new __logLoss__ value?
# write your code here
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
T81-558: Applications of Deep Neural Networks**Module 13: Advanced/Other Topics*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module 13 Video Material* Part 13.1: Flask and Deep Learning Web Services [[Video]](https://www.youtube.com/watch?v=H73m9XvKHug&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_13_01_flask.ipynb)* **Part 13.2: Interrupting and Continuing Training** [[Video]](https://www.youtube.com/watch?v=kaQCdv46OBA&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_13_02_checkpoint.ipynb)* Part 13.3: Using a Keras Deep Neural Network with a Web Application [[Video]](https://www.youtube.com/watch?v=OBbw0e-UroI&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_13_03_web.ipynb)* Part 13.4: When to Retrain Your Neural Network [[Video]](https://www.youtube.com/watch?v=K2Tjdx_1v9g&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_13_04_retrain.ipynb)* Part 13.5: Tensor Processing Units (TPUs) [[Video]](https://www.youtube.com/watch?v=Ygyf3NUqvSc&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_13_05_tpu.ipynb) Google CoLab InstructionsThe following code ensures that Google CoLab is running the correct version of TensorFlow.
try: from google.colab import drive COLAB = True print("Note: using Google CoLab") %tensorflow_version 2.x except: print("Note: not using Google CoLab") COLAB = False # Nicely formatted time string def hms_string(sec_elapsed): h = int(sec_elapsed / (60 * 60)) m = int((sec_elapsed % (60 * 60)) / 60) s = sec_elapsed % 60 return f"{h}:{m:>02}:{s:>05.2f}"
Note: using Google CoLab
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
Part 13.2: Interrupting and Continuing TrainingWe would train our Keras models in one pass in an ideal world, utilizing as much GPU and CPU power as we need. The world in which we train our models is anything but ideal. In this part, we will see that we can stop and continue and even adjust training at later times. We accomplish this continuation with checkpoints. We begin by creating several utility functions. The first utility generates an output directory that has a unique name. This technique allows us to organize multiple runs of our experiment. We provide the Logger class to route output to a log file contained in the output directory.
import os import re import sys import time import numpy as np from typing import Any, List, Tuple, Union from tensorflow.keras.datasets import mnist from tensorflow.keras import backend as K import tensorflow as tf import tensorflow.keras import tensorflow as tf from tensorflow.keras.callbacks import EarlyStopping, \ LearningRateScheduler, ModelCheckpoint from tensorflow.keras import regularizers from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten from tensorflow.keras.layers import Conv2D, MaxPooling2D from tensorflow.keras.models import load_model import pickle def generate_output_dir(outdir, run_desc): prev_run_dirs = [] if os.path.isdir(outdir): prev_run_dirs = [x for x in os.listdir(outdir) if os.path.isdir(\ os.path.join(outdir, x))] prev_run_ids = [re.match(r'^\d+', x) for x in prev_run_dirs] prev_run_ids = [int(x.group()) for x in prev_run_ids if x is not None] cur_run_id = max(prev_run_ids, default=-1) + 1 run_dir = os.path.join(outdir, f'{cur_run_id:05d}-{run_desc}') assert not os.path.exists(run_dir) os.makedirs(run_dir) return run_dir # From StyleGAN2 class Logger(object): """Redirect stderr to stdout, optionally print stdout to a file, and optionally force flushing on both stdout and the file.""" def __init__(self, file_name: str = None, file_mode: str = "w", \ should_flush: bool = True): self.file = None if file_name is not None: self.file = open(file_name, file_mode) self.should_flush = should_flush self.stdout = sys.stdout self.stderr = sys.stderr sys.stdout = self sys.stderr = self def __enter__(self) -> "Logger": return self def __exit__(self, exc_type: Any, exc_value: Any, \ traceback: Any) -> None: self.close() def write(self, text: str) -> None: """Write text to stdout (and a file) and optionally flush.""" if len(text) == 0: return if self.file is not None: self.file.write(text) self.stdout.write(text) if self.should_flush: self.flush() def flush(self) -> None: """Flush written text to both stdout and a file, if open.""" if self.file is not None: self.file.flush() self.stdout.flush() def close(self) -> None: """Flush, close possible files, and remove stdout/stderr mirroring.""" self.flush() # if using multiple loggers, prevent closing in wrong order if sys.stdout is self: sys.stdout = self.stdout if sys.stderr is self: sys.stderr = self.stderr if self.file is not None: self.file.close() def obtain_data(): (x_train, y_train), (x_test, y_test) = mnist.load_data() print("Shape of x_train: {}".format(x_train.shape)) print("Shape of y_train: {}".format(y_train.shape)) print() print("Shape of x_test: {}".format(x_test.shape)) print("Shape of y_test: {}".format(y_test.shape)) # input image dimensions img_rows, img_cols = 28, 28 if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train shape:', x_train.shape) print("Training samples: {}".format(x_train.shape[0])) print("Test samples: {}".format(x_test.shape[0])) # convert class vectors to binary class matrices y_train = tf.keras.utils.to_categorical(y_train, num_classes) y_test = tf.keras.utils.to_categorical(y_test, num_classes) return input_shape, x_train, y_train, x_test, y_test
_____no_output_____
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
We define the basic training parameters and where we wish to write the output.
outdir = "./data/" run_desc = "test-train" batch_size = 128 num_classes = 10 run_dir = generate_output_dir(outdir, run_desc) print(f"Results saved to: {run_dir}")
Results saved to: ./data/00000-test-train
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
Keras provides a prebuilt checkpoint class named **ModelCheckpoint** that contains most of our desired functionality. This built-in class can save the model's state repeatedly as training progresses. Stopping neural network training is not always a controlled event. Sometimes this stoppage can be abrupt, such as a power failure or a network resource shutting down. If Microsoft Windows is your operating system of choice, your training can also be interrupted by a high-priority system update. Because of all of this uncertainty, it is best to save your model at regular intervals. This process is similar to saving a game at critical checkpoints, so you do not have to start over if something terrible happens to your avatar in the game.We will create our checkpoint class, named **MyModelCheckpoint**. In addition to saving the model, we also save the state of the training infrastructure. Why save the training infrastructure, in addition to the weights? This technique eases the transition back into training for the neural network and will be more efficient than a cold start. Consider if you interrupted your college studies after the first year. Sure, your brain (the neural network) will retain all the knowledge. But how much rework will you have to do? Your transcript at the university is like the training parameters. It ensures you do not have to start over when you come back.
class MyModelCheckpoint(ModelCheckpoint): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def on_epoch_end(self, epoch, logs=None): super().on_epoch_end(epoch,logs)\ # Also save the optimizer state filepath = self._get_file_path(epoch=epoch, logs=logs, batch=None) filepath = filepath.rsplit( ".", 1 )[ 0 ] filepath += ".pkl" with open(filepath, 'wb') as fp: pickle.dump( { 'opt': model.optimizer.get_config(), 'epoch': epoch+1 # Add additional keys if you need to store more values }, fp, protocol=pickle.HIGHEST_PROTOCOL) print('\nEpoch %05d: saving optimizaer to %s' % (epoch + 1, filepath))
_____no_output_____
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
The optimizer applies a step decay schedule during training to decrease the learning rate as training progresses. It is essential to preserve the current epoch that we are on to perform correctly after a training resume.
def step_decay_schedule(initial_lr=1e-3, decay_factor=0.75, step_size=10): def schedule(epoch): return initial_lr * (decay_factor ** np.floor(epoch/step_size)) return LearningRateScheduler(schedule)
_____no_output_____
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
We build the model just as we have in previous sessions. However, the training function requires a few extra considerations. We specify the maximum number of epochs; however, we also allow the user to select the starting epoch number for training continuation.
def build_model(input_shape, num_classes): model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile( loss='categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(), metrics=['accuracy']) return model def train_model(model, initial_epoch=0, max_epochs=10): start_time = time.time() checkpoint_cb = MyModelCheckpoint( os.path.join(run_dir, 'model-{epoch:02d}-{val_loss:.2f}.hdf5'), monitor='val_loss',verbose=1) lr_sched_cb = step_decay_schedule(initial_lr=1e-4, decay_factor=0.75, \ step_size=2) cb = [checkpoint_cb, lr_sched_cb] model.fit(x_train, y_train, batch_size=batch_size, epochs=max_epochs, initial_epoch = initial_epoch, verbose=2, callbacks=cb, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0, callbacks=cb) print('Test loss: {}'.format(score[0])) print('Test accuracy: {}'.format(score[1])) elapsed_time = time.time() - start_time print("Elapsed time: {}".format(hms_string(elapsed_time)))
_____no_output_____
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
We now begin training, using the **Logger** class to write the output to a log file in the output directory.
with Logger(os.path.join(run_dir, 'log.txt')): input_shape, x_train, y_train, x_test, y_test = obtain_data() model = build_model(input_shape, num_classes) train_model(model, max_epochs=3)
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11493376/11490434 [==============================] - 0s 0us/step 11501568/11490434 [==============================] - 0s 0us/step Shape of x_train: (60000, 28, 28) Shape of y_train: (60000,) Shape of x_test: (10000, 28, 28) Shape of y_test: (10000,) x_train shape: (60000, 28, 28, 1) Training samples: 60000 Test samples: 10000 Epoch 1/3 Epoch 1: saving model to ./data/00000-test-train/model-01-0.20.hdf5 Epoch 00001: saving optimizaer to ./data/00000-test-train/model-01-0.20.pkl 469/469 - 12s - loss: 0.6354 - accuracy: 0.8129 - val_loss: 0.1977 - val_accuracy: 0.9420 - lr: 1.0000e-04 - 12s/epoch - 25ms/step Epoch 2/3 Epoch 2: saving model to ./data/00000-test-train/model-02-0.11.hdf5 Epoch 00002: saving optimizaer to ./data/00000-test-train/model-02-0.11.pkl 469/469 - 2s - loss: 0.2284 - accuracy: 0.9332 - val_loss: 0.1087 - val_accuracy: 0.9677 - lr: 1.0000e-04 - 2s/epoch - 5ms/step Epoch 3/3 Epoch 3: saving model to ./data/00000-test-train/model-03-0.08.hdf5 Epoch 00003: saving optimizaer to ./data/00000-test-train/model-03-0.08.pkl 469/469 - 2s - loss: 0.1575 - accuracy: 0.9541 - val_loss: 0.0837 - val_accuracy: 0.9746 - lr: 7.5000e-05 - 2s/epoch - 5ms/step Test loss: 0.08365701138973236 Test accuracy: 0.9746000170707703 Elapsed time: 0:00:22.09
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
You should notice that the above output displays the name of the hdf5 and pickle (pkl) files produced at each checkpoint. These files serve the following functions:* Pickle files contain the state of the optimizer.* HDF5 files contain the saved model.For this training run, which went for 3 epochs, these two files were named:* ./data/00013-test-train/model-03-0.08.hdf5* ./data/00013-test-train/model-03-0.08.pklWe can inspect the output from the training run. Notice we can see a folder named "00000-test-train". This new folder was the first training run. The program will call the next training run "00001-test-train", and so on. Inside this directory, you will find the pickle and hdf5 files for each checkpoint.
!ls ./data !ls ./data/00000-test-train
log.txt model-01-0.20.pkl model-02-0.11.pkl model-03-0.08.pkl model-01-0.20.hdf5 model-02-0.11.hdf5 model-03-0.08.hdf5
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
Keras stores the model itself in an HDF5, which includes the optimizer. Because of this feature, it is not generally necessary to restore the internal state of the optimizer (such as ADAM). However, we include the code to do so. We can obtain the internal state of an optimizer by calling **get_config**, which will return a dictionary similar to the following:```{'name': 'Adam', 'learning_rate': 7.5e-05, 'decay': 0.0, 'beta_1': 0.9, 'beta_2': 0.999, 'epsilon': 1e-07, 'amsgrad': False}```In practice, I've found that different optimizers implement get_config differently. This function will always return the training hyperparameters. However, it may not always capture the complete internal state of an optimizer beyond the hyperparameters. The exact implementation of get_config can vary per optimizer implementation. Continuing TrainingWe are now ready to continue training. You will need the paths to both your HDF5 and PKL files. You can find these paths in the output above. Your values may differ from mine, so perform a copy/paste.
MODEL_PATH = './data/00000-test-train/model-03-0.08.hdf5' OPT_PATH = './data/00000-test-train/model-03-0.08.pkl'
_____no_output_____
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
The following code loads the HDF5 and PKL files and then recompiles the model based on the PKL file. Depending on the optimizer in use, you might have to recompile the model.
import tensorflow as tf from tensorflow.keras.models import load_model import pickle def load_model_data(model_path, opt_path): model = load_model(model_path) with open(opt_path, 'rb') as fp: d = pickle.load(fp) epoch = d['epoch'] opt = d['opt'] return epoch, model, opt epoch, model, opt = load_model_data(MODEL_PATH, OPT_PATH) # note: often it is not necessary to recompile the model model.compile( loss='categorical_crossentropy', optimizer=tf.keras.optimizers.Adam.from_config(opt), metrics=['accuracy'])
_____no_output_____
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
Finally, we train the model for additional epochs. You can see from the output that the new training starts at a higher accuracy than the first training run. Further, the accuracy increases with additional training. Also, you will notice that the epoch number begins at four and not one.
outdir = "./data/" run_desc = "cont-train" num_classes = 10 run_dir = generate_output_dir(outdir, run_desc) print(f"Results saved to: {run_dir}") with Logger(os.path.join(run_dir, 'log.txt')): input_shape, x_train, y_train, x_test, y_test = obtain_data() train_model(model, initial_epoch=epoch, max_epochs=6)
Results saved to: ./data/00001-cont-train Shape of x_train: (60000, 28, 28) Shape of y_train: (60000,) Shape of x_test: (10000, 28, 28) Shape of y_test: (10000,) x_train shape: (60000, 28, 28, 1) Training samples: 60000 Test samples: 10000 Epoch 4/6 Epoch 4: saving model to ./data/00001-cont-train/model-04-0.07.hdf5 Epoch 00004: saving optimizaer to ./data/00001-cont-train/model-04-0.07.pkl 469/469 - 3s - loss: 0.1272 - accuracy: 0.9634 - val_loss: 0.0692 - val_accuracy: 0.9788 - lr: 7.5000e-05 - 3s/epoch - 6ms/step Epoch 5/6 Epoch 5: saving model to ./data/00001-cont-train/model-05-0.06.hdf5 Epoch 00005: saving optimizaer to ./data/00001-cont-train/model-05-0.06.pkl 469/469 - 2s - loss: 0.1099 - accuracy: 0.9677 - val_loss: 0.0612 - val_accuracy: 0.9818 - lr: 5.6250e-05 - 2s/epoch - 5ms/step Epoch 6/6 Epoch 6: saving model to ./data/00001-cont-train/model-06-0.06.hdf5 Epoch 00006: saving optimizaer to ./data/00001-cont-train/model-06-0.06.pkl 469/469 - 2s - loss: 0.0990 - accuracy: 0.9711 - val_loss: 0.0561 - val_accuracy: 0.9827 - lr: 5.6250e-05 - 2s/epoch - 5ms/step Test loss: 0.05610647052526474 Test accuracy: 0.982699990272522 Elapsed time: 0:00:11.72
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
> Developed by [Yeison Nolberto Cardona Álvarez](https://github.com/yeisonCardona) > [Andrés Marino Álvarez Meza, PhD.](https://github.com/amalvarezme) > César Germán Castellanos Dominguez, PhD. > _Digital Signal Processing and Control Group_ | _Grupo de Control y Procesamiento Digital de Señales ([GCPDS](https://github.com/UN-GCPDS/))_ > _National University of Colombia at Manizales_ | _Universidad Nacional de Colombia sede Manizales_---- OpenBCI-Stream High level Python module for EEG/EMG/ECG acquisition and distributed streaming for OpenBCI Cyton board.![GitHub top language](https://img.shields.io/github/languages/top/un-gcpds/openbci-stream?)![PyPI - License](https://img.shields.io/pypi/l/openbci-stream?)![PyPI](https://img.shields.io/pypi/v/openbci-stream?)![PyPI - Status](https://img.shields.io/pypi/status/openbci-stream?)![PyPI - Python Version](https://img.shields.io/pypi/pyversions/openbci-stream?)![GitHub last commit](https://img.shields.io/github/last-commit/un-gcpds/openbci-stream?)![CodeFactor Grade](https://img.shields.io/codefactor/grade/github/UN-GCPDS/openbci-stream?)[![Documentation Status](https://readthedocs.org/projects/openbci-stream/badge/?version=latest)](https://openbci-stream.readthedocs.io/en/latest/?badge=latest)Comprise a set of scripts that deals with the configuration and connection with the board, also is compatible with both connection modes supported by [Cyton](https://shop.openbci.com/products/cyton-biosensing-board-8-channel?variant=38958638542): RFduino (Serial dongle) and Wi-Fi (with the OpenBCI Wi-Fi Shield). These drivers are a stand-alone library that can handle the board from three different endpoints: (i) a [Command-Line Interface](06-command_line_interface.ipynb) (CLI) with simple instructions configure, start and stop data acquisition, debug stream status, and register events markers; (ii) a [Python Module](03-data_acuisition.ipynb) with high-level instructions and asynchronous acquisition; (iii) an object-proxying using Remote Python Call (RPyC) for [distributed implementations](A4-server-based-acquisition.ipynb) that can manipulate the Python modules as if they were local, this last mode needs a daemon running in the remote host that will listen to connections and driving instructions.The main functionality of the drivers live on to serve real-time and distributed access to data flow, even on single machine implementations, this is achieved by implementing [Kafka](https://kafka.apache.org/) and their capabilities to create multiple topics for classifying the streaming, these topics are used to separate the neurophysiological data from the [event markers](05-stream_markers), so the clients can subscribe to a specific topic for injecting or read content, this means that is possible to implement an event register in a separate process that stream markers for all clients in real-time without handle dense time-series data. A crucial issue that stays on [time synchronization](A4-server-based_acquisition.ipynbStep-5---Configure-time-server), all systems components in the network should have the same real-time protocol (RTP) server reference. Main features * **Asynchronous acquisition:** Acquisition and deserialization are done in uninterrupted parallel processes. In this way, the sampling rate keeps stable as long as possible. * **Distributed streaming system:** The acquisition, processing, visualizations, and any other system that needs to be fed with EEG/EMG/ECG real-time data can run with their architecture. * **Remote board handle:** Same code syntax for developing and debug Cython boards connected to any node in the distributed system. * **Command-line interface:** A simple interface for handle the start, stop, and access to data stream directly from the command line. * **Markers/Events handler:** Besides the marker boardmode available in Cyton, a stream channel for the reading and writing of markers is available for use in any development. * **Multiple boards:** Is possible to use multiple OpenBCI boards just by adding multiple endpoints to the commands. Examples
# Acquisition with blocking call from openbci_stream.acquisition import Cyton openbci = Cyton('serial', endpoint='/dev/ttyUSB0', capture_stream=True) # blocking call openbci.stream(15) # collect data for 15 seconds # openbci.eeg_time_series # openbci.aux_time_series # openbci.timestamp_time_series # Acquisition with asynchronous call from openbci_stream.acquisition import Cyton openbci = Cyton('wifi', endpoint='192.68.1.113', capture_stream=True) openbci.stream(15) # collect data for 15 seconds # asynchronous call openbci.start_stream() time.sleep(15) # collect data for 15 seconds openbci.stop_stream() # Remote acquisition from openbci_stream.acquisition import Cyton openbci = Cyton('serial', endpoint='/dev/ttyUSB0', host='192.168.1.1', capture_stream=True) # blocking call openbci.stream(15) # collect data for 15 seconds # Consumer for active streamming from openbci_stream.acquisition import OpenBCIConsumer with OpenBCIConsumer() as stream: for i, message in enumerate(stream): if message.topic == 'eeg': print(f"received {message.value['samples']} samples") if i == 9: break # Create stream then consume data from openbci_stream.acquisition import OpenBCIConsumer with OpenBCIConsumer(mode='serial', endpoint='/dev/ttyUSB0', streaming_package_size=250) as (stream, openbci): t0 = time.time() for i, message in enumerate(stream): if message.topic == 'eeg': print(f"{i}: received {message.value['samples']} samples") t0 = time.time() if i == 9: break # Acquisition with multiple boards from openbci_stream.acquisition import Cyton openbci = Cyton('wifi', endpoint=['192.68.1.113', '192.68.1.185'], capture_stream=True) openbci.stream(15) # collect data for 15 seconds # asynchronous call openbci.start_stream() time.sleep(15) # collect data for 15 seconds openbci.stop_stream()
_____no_output_____
BSD-2-Clause
docs/source/notebooks/readme.ipynb
UN-GCPDS/openbci-stream
Notion - Update pages from database **Tags:** notion productivity Input Import library
from naas_drivers import notion
_____no_output_____
BSD-3-Clause
Notion/Notion_Update_pages_from_database.ipynb
vivard/awesome-notebooks
Setup NotionHow to get your Notion integration token ?
# Enter Token API notion_token = "*****" # Enter Database URL database_url = "https://www.notion.so/********"
_____no_output_____
BSD-3-Clause
Notion/Notion_Update_pages_from_database.ipynb
vivard/awesome-notebooks
Model Get pages from Notion DB
database_id = database_url.split("/")[-1].split("?v=")[0] pages = notion.connect(notion_token).database.query(database_id, query={}) print("📊 Pages in Notion DB:", len(pages))
_____no_output_____
BSD-3-Clause
Notion/Notion_Update_pages_from_database.ipynb
vivard/awesome-notebooks
Output Update pages
for page in pages: print(page) # page.title("Name","Page updated") # page.rich_text("Text","Ceci est toto") # page.number("Number", 42) # page.select("Select","Value3") # page.multi_select("Muti Select",["Value1","Value2","Value3"]) # page.date("Date","2021-10-03T17:01:26") #Follow ISO 8601 format # page.people("People", ["6e3bab71-beeb-484b-af99-ea30fdef4773"]) #list of ID of users # page.checkbox("Checkbox", False) # page.email("Email","jeremy@naas.ai") page.update() print(f"✅ Page updated in Notion.")
_____no_output_____
BSD-3-Clause
Notion/Notion_Update_pages_from_database.ipynb
vivard/awesome-notebooks
Copyright 2019 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
tf.function で性能アップ View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook TensorFlow 2.0 では Eager Execution が既定で有効になっています。ユーザーインターフェイスは直感的で柔軟です(演算を一度だけ行う場合にはずっと簡単に、かつ迅速に実行されます)。しかしながら、それは性能と展開の面での犠牲の上に成り立っています。最高性能を得ながら、モデルをどこへでも展開できるようにするには、`tf.function` を使ってプログラムから計算グラフを作成します。AutoGraph のおかげで、驚くほど多くの Python コードが tf.function でそのまま動作しますが、気をつけなければならない落とし穴も存在します。ポイントと推奨事項は下記の通りです。- オブジェクトの変更やリストへの追加のような Python の副作用に依存しないこと- tf.functions は NumPy の演算や Python の組み込み演算よりも、TensorFlow の演算に適していること- 迷ったときは、`for x in y` というイディオムを使うこと
from __future__ import absolute_import, division, print_function, unicode_literals try: %tensorflow_version 2.x except Exception: pass import tensorflow as tf import contextlib # 遭遇するかもしれないいくつかのエラーをデモするためのヘルパー関数 @contextlib.contextmanager def assert_raises(error_class): try: yield except error_class as e: print('Caught expected exception \n {}: {}'.format(error_class, e)) except Exception as e: print('Got unexpected exception \n {}: {}'.format(type(e), e)) else: raise Exception('Expected {} to be raised but no error was raised!'.format( error_class))
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
あなたが定義した `tf.function` は TensorFlow Core の演算に似たものです。例えばそれを即時に実行することも、計算グラフで使うこともできますし、勾配を計算することも可能です。
# function は演算のように振る舞う @tf.function def add(a, b): return a + b add(tf.ones([2, 2]), tf.ones([2, 2])) # [[2., 2.], [2., 2.]] # function は勾配を計算できる @tf.function def add(a, b): return a + b v = tf.Variable(1.0) with tf.GradientTape() as tape: result = add(v, 1.0) tape.gradient(result, v) # function 内で function を使うこともできる @tf.function def dense_layer(x, w, b): return add(tf.matmul(x, w), b) dense_layer(tf.ones([3, 2]), tf.ones([2, 2]), tf.ones([2]))
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
トレーシングとポリモーフィズムPython の動的型付けは、関数をさまざまな型の引数で呼び出すことができ、Python がそれぞれのシナリオで異なる動作をするということを意味します。他方で、TensorFlow の計算グラフでは、dtype と shape の次元が静的であることが必要です。`tf.function` は、正しい計算グラフを生成するために必要なときには関数を再トレースして、このギャップをつなぐ役割を果たします。異なる型の引数を使って関数を呼び出し、何が起きるか見てみましょう。
# Function はポリモーフィック @tf.function def double(a): print("Tracing with", a) return a + a print(double(tf.constant(1))) print() print(double(tf.constant(1.1))) print() print(double(tf.constant("a"))) print()
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
トレースの動作を制御するためには、下記のようなテクニックを使います。- 新しい `tf.function` を作成する。別々の `tf.function` オブジェクトがトレースを共有することはない。- 特定のトレースを得るには `get_concrete_function` メソッドを使用する。- 計算グラフの呼び出し時に1回だけトレースを行うには、 `input_signature` を指定して `tf.function` を呼び出す。
print("Obtaining concrete trace") double_strings = double.get_concrete_function(tf.TensorSpec(shape=None, dtype=tf.string)) print("Executing traced function") print(double_strings(tf.constant("a"))) print(double_strings(a=tf.constant("b"))) print("Using a concrete trace with incompatible types will throw an error") with assert_raises(tf.errors.InvalidArgumentError): double_strings(tf.constant(1)) @tf.function(input_signature=(tf.TensorSpec(shape=[None], dtype=tf.int32),)) def next_collatz(x): print("Tracing with", x) return tf.where(tf.equal(x % 2, 0), x // 2, 3 * x + 1) print(next_collatz(tf.constant([1, 2]))) # 1次元のテンソルを input signature として指定しているので、これは失敗する with assert_raises(ValueError): next_collatz(tf.constant([[1, 2], [3, 4]]))
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
いつ再トレースするのか?ポリモーフィックな `tf.function` はトレーシングによって生成された具象関数のキャッシュを保持しています。キャッシュのキーは、実際にはその関数の引数及びキーワード引数から生成されたキーのタプルです。`tf.Tensor` 引数から生成されるキーは、テンソルの shape と型です。Python の組み込み型引数から生成されるキーはその値です。それ以外の Python の型では、キーはオブジェクトの `id()` に基づいており、メソッドはクラスのインスタンスひとつずつ独立にトレースされます。将来、TensorFlowには、Python オブジェクトについて安全にテンソルに変換できるような、より洗練されたキャッシングが追加されるかもしれません。 引数は Python か? Tensor か?しばしば、ハイパーパラメータやグラフ構成を制御するために Python の組み込み型の引数が使われます。例えば、`num_layers=10` や `training=True` あるいは `nonlinearity='relu'` のようにです。このため、この Python の組み込み型の引数が変更されると、計算グラフを再びトレースする必要があるということになります。しかし、グラフの生成を制御するために Python の組み込み型の引数を使用する必要はありません。これらのケースでは、Python引数の値の変更が不必要な再トレースを引き起こす可能性があります。例えば、この訓練ループでは、AutoGraph は動的に展開を行います。複数回トレースを行っていますが、生成される計算グラフは全く変わりません。これは少し非効率です。
def train_one_step(): pass @tf.function def train(num_steps): print("Tracing with num_steps = {}".format(num_steps)) for _ in tf.range(num_steps): train_one_step() train(num_steps=10) train(num_steps=20)
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
ここでの簡単な回避方法は、生成されたグラフの shape が変わらないのであれば、引数をテンソルにキャストすることです。
train(num_steps=tf.constant(10)) train(num_steps=tf.constant(20))
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
`tf.function` の中の副作用一般的には、(印字やオブジェクト変更のような)Python の副作用は、トレーシングの最中にだけ発生します。それでは、どうしたら `tf.function` で安定的に副作用を起こすことができるでしょうか?一般的な原則は、トレースをデバッグする際にだけ Python の副作用を使用するというものです。あるいは、`tf.Variable.assign`、`tf.print`、そして `tf.summary` のような TensorFlow の演算を使うことで、コードがトレースされるときにも、TensorFlowランタイムによって都度呼び出される際にも、確実に実行されるようにできます。一般には、関数型のスタイルを使用することで最も良い結果を得られます。
@tf.function def f(x): print("Traced with", x) tf.print("Executed with", x) f(1) f(1) f(2)
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
`tf.function` が呼び出されるたびに Python のコードを実行したいのであれば、`tf.py_function` がぴったりです。`tf.py_function` の欠点は、ポータブルでないこと、それほど性能が高くないこと、(マルチGPU、TPUの)分散環境ではうまく動作しないことなどです。また、`tf.py_function` は計算グラフに組み込まれるため、入出力すべてをテンソルにキャストします。
external_list = [] def side_effect(x): print('Python side effect') external_list.append(x) @tf.function def f(x): tf.py_function(side_effect, inp=[x], Tout=[]) f(1) f(1) f(1) assert len(external_list) == 3 # .numpy() call required because py_function casts 1 to tf.constant(1) assert external_list[0].numpy() == 1
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
Python の状態に注意ジェネレーターやイテレーターなど Python の機能の多くは、状態を追跡するために Python のランタイムに依存しています。これらの仕組みは、一般的には Eager モードでも期待通りに動作しますが、トレーシングの振る舞いにより、`tf.function` の中では予期しないことが起きることがあります。1例として、イテレーターの状態が進むのは Python の副作用であり、トレーシングの中だけで発生します。
external_var = tf.Variable(0) @tf.function def buggy_consume_next(iterator): external_var.assign_add(next(iterator)) tf.print("Value of external_var:", external_var) iterator = iter([0, 1, 2, 3]) buggy_consume_next(iterator) # 次のコードは、イテレーターの次の値を使うのではなく、最初の値を再利用する buggy_consume_next(iterator) buggy_consume_next(iterator)
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
イテレーターが tf.function の中で生成されすべて使われる場合には、正しく動作するはずです。しかし、イテレーター全体がトレースされることとなり、巨大な計算グラフの生成をまねく可能性があります。これは、望みどおりの動作かもしれません。しかし、もし Python のリストとして表されたメモリー上の巨大なデータセットを使って訓練を行うとすると、これは非常に大きな計算グラフを生成することになり、`tf.function` がスピードアップにはつながらないと考えられます。Python データを繰り返し使用する場合、もっとも安全な方法は tf.data.Dataset でラップして、`for x in y` というイディオムを使用することです。AutoGraph には、`y` がテンソルあるいは tf.data.Dataset である場合、`for` ループを安全に変換する特別な機能があります。
def measure_graph_size(f, *args): g = f.get_concrete_function(*args).graph print("{}({}) contains {} nodes in its graph".format( f.__name__, ', '.join(map(str, args)), len(g.as_graph_def().node))) @tf.function def train(dataset): loss = tf.constant(0) for x, y in dataset: loss += tf.abs(y - x) # ダミー計算 return loss small_data = [(1, 1)] * 2 big_data = [(1, 1)] * 10 measure_graph_size(train, small_data) measure_graph_size(train, big_data) measure_graph_size(train, tf.data.Dataset.from_generator( lambda: small_data, (tf.int32, tf.int32))) measure_graph_size(train, tf.data.Dataset.from_generator( lambda: big_data, (tf.int32, tf.int32)))
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
Python/Numpy のデータを Dataset でラップする際には、`tf.data.Dataset.from_generator` と `tf.data.Dataset.from_tensors` の違いに留意しましょう。前者はデータを Python のまま保持し `tf.py_function` を通じて取得するため、性能に影響する場合があります。これに対して後者はデータのコピーを計算グラフの中の、ひとつの大きな `tf.constant()` に結びつけるため、メモリー消費に影響する可能性があります。 TFRecordDataset/CsvDataset/などを通じてデータをファイルから読み込むことが、データを使用する最も効率的な方法です。TensorFlow 自身が Python とは関係なく非同期のデータ読み込みとプリフェッチを管理することができるからです。 自動的な依存関係の制御プログラミングモデルとしての関数が一般的なデータフローグラフに対して非常に優位である点は、意図したコードの振る舞いがどのようなものであるかということについて、より多くの情報をランタイムに与えられるということにあります。例えば、同じ変数を何度も読んだり書いたりするコードを書く場合、データフローグラフではもともと意図されていた演算の順番を自然に組み込むわけではありません。`tf.function` の中では、もともとの Python コードの文の実行順序を参照することで、実行順序の曖昧さを解消します。これにより、`tf.function` の中のステートフルな演算の順序が、先行実行モードのセマンティクスを模していることになります。これは、手動で制御の依存関係を加える必要がないことを意味しています。`tf.function` は十分賢いので、あなたのコードが正しく動作するために必要十分な最小限の制御の依存関係を追加してくれます。
# 自動的な依存関係の制御 a = tf.Variable(1.0) b = tf.Variable(2.0) @tf.function def f(x, y): a.assign(y * b) b.assign_add(x * a) return a + b f(1.0, 2.0) # 10.0
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
変数`tf.function` の中では、意図したコードの実行順序を活用するという同じアイデアを使って、変数の作成と活用を簡単に行うことができます。しかし、ひとつだけ非常に重要な欠点があります。それは、変数を使った場合、先行実行モードとグラフモードでは動作が変わるコードを書いてしまう可能性があるということです。特に、呼び出しの都度新しい変数を作成する場合にこれが発生します。トレーシングの意味では、`tf.function` は呼び出しのたびに同じ変数を再利用しますが、Eager モードでは呼び出しごとに新しい変数を生成します。この間違いを防止するため、`tf.function` は危険な変数の生成動作を見つけるとエラーを発生させます。
@tf.function def f(x): v = tf.Variable(1.0) v.assign_add(x) return v with assert_raises(ValueError): f(1.0) # しかし、曖昧さの無いコードは大丈夫 v = tf.Variable(1.0) @tf.function def f(x): return v.assign_add(x) print(f(1.0)) # 2.0 print(f(2.0)) # 4.0 # 初めて関数が実行されるときだけ変数が生成されることを保証できれば # tf.function 内で変数を作成できる class C: pass obj = C(); obj.v = None @tf.function def g(x): if obj.v is None: obj.v = tf.Variable(1.0) return obj.v.assign_add(x) print(g(1.0)) # 2.0 print(g(2.0)) # 4.0 # 変数の初期化は、関数の引数や他の変数の値に依存可能 # 制御の依存関係を生成するのと同じ手法で、正しい初期化の順序を発見可能 state = [] @tf.function def fn(x): if not state: state.append(tf.Variable(2.0 * x)) state.append(tf.Variable(state[0] * 3.0)) return state[0] * x * state[1] print(fn(tf.constant(1.0))) print(fn(tf.constant(3.0)))
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
AutoGraph の使用[autograph](https://www.tensorflow.org/guide/function) ライブラリは `tf.function` に完全に統合されており、計算グラフの中で動的に実行される条件文や繰り返しを書くことができます。`tf.cond` や `tf.while_loop` は `tf.function` でも使えますが、制御フローを含むコードは、命令形式で書いたほうが書きやすいし理解しやすいです。
# 単純な繰り返し @tf.function def f(x): while tf.reduce_sum(x) > 1: tf.print(x) x = tf.tanh(x) return x f(tf.random.uniform([5])) # 興味があれば AutoGraph が生成するコードを調べることができる # ただし、アセンブリ言語を読むような感じがする def f(x): while tf.reduce_sum(x) > 1: tf.print(x) x = tf.tanh(x) return x print(tf.autograph.to_code(f))
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
AutoGraph: 条件分岐AutoGraph は `if` 文を等価である `tf.cond` の呼び出しに変換します。この置換は条件がテンソルである場合に行われます。そうでない場合には、条件分岐はトレーシングの中で実行されます。
def test_tf_cond(f, *args): g = f.get_concrete_function(*args).graph if any(node.name == 'cond' for node in g.as_graph_def().node): print("{}({}) uses tf.cond.".format( f.__name__, ', '.join(map(str, args)))) else: print("{}({}) executes normally.".format( f.__name__, ', '.join(map(str, args)))) @tf.function def hyperparam_cond(x, training=True): if training: x = tf.nn.dropout(x, rate=0.5) return x @tf.function def maybe_tensor_cond(x): if x < 0: x = -x return x test_tf_cond(hyperparam_cond, tf.ones([1], dtype=tf.float32)) test_tf_cond(maybe_tensor_cond, tf.constant(-1)) test_tf_cond(maybe_tensor_cond, -1)
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
`tf.cond` には、色々と注意すべき細かな点があります。- `tf.cond` は条件分岐の両方をトレーシングし、条件に従って実行時に適切な分岐を選択することで機能します。分岐の両方をトレースすることで、Python プログラムを予期せず実行する可能性があります。- `tf.cond` では、分岐の一方が後ほど使用されるテンソルを作成する場合、もう一方の分岐もそのテンソルを作成することが必要です。
@tf.function def f(): x = tf.constant(0) if tf.constant(True): x = x + 1 print("Tracing `then` branch") else: x = x - 1 print("Tracing `else` branch") return x f() @tf.function def f(): if tf.constant(True): x = tf.ones([3, 3]) return x # 分岐のどちらの枝でも `x` を定義する必要があるためエラーが発生 with assert_raises(ValueError): f()
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
AutoGraph と繰り返しAutoGraph には繰り返しの変換にいくつかの単純なルールがあります。- `for`: 反復可能オブジェクトがテンソルである場合に変換する- `while`: while 条件がテンソルに依存している場合に変換する繰り返しが変換される場合、`tf.while_loop` によって動的に展開されます。あるいは、 `for x in tf.data.Dataset` という特別なケースの場合には、 `tf.data.Dataset.reduce` に変換されます。繰り返しが変換されない場合、それは静的に展開されます。
def test_dynamically_unrolled(f, *args): g = f.get_concrete_function(*args).graph if any(node.name == 'while' for node in g.as_graph_def().node): print("{}({}) uses tf.while_loop.".format( f.__name__, ', '.join(map(str, args)))) elif any(node.name == 'ReduceDataset' for node in g.as_graph_def().node): print("{}({}) uses tf.data.Dataset.reduce.".format( f.__name__, ', '.join(map(str, args)))) else: print("{}({}) gets unrolled.".format( f.__name__, ', '.join(map(str, args)))) @tf.function def for_in_range(): x = 0 for i in range(5): x += i return x test_dynamically_unrolled(for_in_range) @tf.function def for_in_tfrange(): x = tf.constant(0, dtype=tf.int32) for i in tf.range(5): x += i return x test_dynamically_unrolled(for_in_tfrange) @tf.function def for_in_tfdataset(): x = tf.constant(0, dtype=tf.int64) for i in tf.data.Dataset.range(5): x += i return x test_dynamically_unrolled(for_in_tfdataset) @tf.function def while_py_cond(): x = 5 while x > 0: x -= 1 return x test_dynamically_unrolled(while_py_cond) @tf.function def while_tf_cond(): x = tf.constant(5) while x > 0: x -= 1 return x test_dynamically_unrolled(while_tf_cond)
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
繰り返しに、テンソルに依存する `break` や、途中での `return` がある場合、一番外側の条件あるいは反復可能オブジェクトはテンソルである必要があります。 比較してみましょう。
@tf.function def while_py_true_py_break(x): while True: # py true if x == 0: # py break break x -= 1 return x test_dynamically_unrolled(while_py_true_py_break, 5) @tf.function def buggy_while_py_true_tf_break(x): while True: # py true if tf.equal(x, 0): # tf break break x -= 1 return x with assert_raises(TypeError): test_dynamically_unrolled(buggy_while_py_true_tf_break, 5) @tf.function def while_tf_true_tf_break(x): while tf.constant(True): # tf true if x == 0: # py break break x -= 1 return x test_dynamically_unrolled(while_tf_true_tf_break, 5) @tf.function def buggy_py_for_tf_break(): x = 0 for i in range(5): # py for if tf.equal(i, 3): # tf break break x += i return x with assert_raises(TypeError): test_dynamically_unrolled(buggy_py_for_tf_break) @tf.function def tf_for_py_break(): x = 0 for i in tf.range(5): # tf for if i == 3: # py break break x += i return x test_dynamically_unrolled(tf_for_py_break)
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
動的に展開される繰り返しの結果を集計するため、`tf.TensorArray` を使いたくなるかもしれません。
batch_size = 2 seq_len = 3 feature_size = 4 def rnn_step(inp, state): return inp + state @tf.function def dynamic_rnn(rnn_step, input_data, initial_state): # [batch, time, features] -> [time, batch, features] input_data = tf.transpose(input_data, [1, 0, 2]) max_seq_len = input_data.shape[0] states = tf.TensorArray(tf.float32, size=max_seq_len) state = initial_state for i in tf.range(max_seq_len): state = rnn_step(input_data[i], state) states = states.write(i, state) return tf.transpose(states.stack(), [1, 0, 2]) dynamic_rnn(rnn_step, tf.random.uniform([batch_size, seq_len, feature_size]), tf.zeros([batch_size, feature_size]))
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
`tf.cond` と同様に、`tf.while_loop` にも、色々と注意すべき細かな点があります。- 繰り返しの実行回数が 0 である可能性があるため、while_loop の後で使用されるテンソルは、繰り返しの前に初期化されなければならない- すべての繰り返しの変数は、各繰り返しを通じてその形状と dtype が変わらないことが必要
@tf.function def buggy_loop_var_uninitialized(): for i in tf.range(3): x = i return x with assert_raises(ValueError): buggy_loop_var_uninitialized() @tf.function def f(): x = tf.constant(0) for i in tf.range(3): x = i return x f() @tf.function def buggy_loop_type_changes(): x = tf.constant(0, dtype=tf.float32) for i in tf.range(3): # tf.int32 型のテンソルを1つづつ取り出して… x = i return x with assert_raises(tf.errors.InvalidArgumentError): buggy_loop_type_changes() @tf.function def buggy_concat(): x = tf.ones([0, 10]) for i in tf.range(5): x = tf.concat([x, tf.ones([1, 10])], axis=0) return x with assert_raises(ValueError): buggy_concat() @tf.function def concat_with_padding(): x = tf.zeros([5, 10]) for i in tf.range(5): x = tf.concat([x[:i], tf.ones([1, 10]), tf.zeros([4-i, 10])], axis=0) x.set_shape([5, 10]) return x concat_with_padding()
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
Xenon1T We can now implement the projected limits for Xenon1T based off 83 days of exposure using the same recoil energy spectrum as for CRESST-III but with the appropriate changes made for the Xenon nuclei (it is more simple here since there are only Xenon nuclei). We assume that there is only one isotope for our calculations. Since we do not have access to the Xenon background with much detail we perform a 1D analysis using the backgrounds published in 1705.06655 as a function of the S1 signal. We therefore need to to approximate the way that the dark matter signal is distributed between S1 and S2. Now we define the signal component as,$$ \frac{dR}{dE_R} = \frac{\rho_0\xi_T}{2\pi m_{DM}} \frac{g^2 F_T^2(E_{R})}{(2m_TE_{R} + m^2_{med})^2}\eta(v_{min}(E_R))$$where $E_R$ is the recoil energy, $\rho_0$ is the dark matter density at earth (which we take to be $0.3 GeV cm^{-3}$, $m_{DM}$ is the dark matter mass, $m_{med}$ is the mediator mass, $F_T^2(E_{R})$ is the recoil form factor, and $m_T$ is the mass of the target isotope.
rho_0 = 0.3*1.e3 # MeV/cm3 # Define energy range in MeV def eta_F(): """Returns an interpolated integral over the velocity distribution, taken to be Maxwellian""" v, gave = np.loadtxt("DD_files/gave.dat", unpack=True, dtype=float) f = interp1d(v, gave, bounds_error=False, fill_value=0.0) # s km^-1 return f def dRdE(E_R, m_DM, A, xi_T): """Return differential recoil rate in 1/s/MeV/kg.""" # g is the parameter we wish to set a limit on so is left out # Form factor taken from eq4.4 of http://pa.brown.edu/articles/Lewin_Smith_DM_Review.pdf m_T = A*931.5 # MeV muT = m_DM*m_T/(m_DM + m_T) # unitless rn = A**(1./3.) * 1/197. # fm --> MeV^-1 F_T = lambda q: np.sqrt(np.exp(-((q*rn)**2.)/3.)) vmin = lambda E_R: np.sqrt(m_T*E_R/2/(muT**2.)) eta = eta_F() q = np.sqrt(2*m_T*E_R) signal = (A**2)*F_T(q)**2*eta(vmin(E_R)*c_kms)*rho_0*xi_T*g2/2./np.pi/m_DM/((q**2+m_med**2)**2) conversion = 1.96311325e24 # MeV^-4 cm^-3 s km^-1 hbar^2 c^6 --> MeV^-1 s^-1 kg^-1 signal *= conversion return signal eff1, eff2 = np.loadtxt("Swordfish_Xenon1T/Efficiency-1705.06655.txt", unpack=True) efficiency = UnivariateSpline(eff1, eff2, ext="zeros", k=1, s=0) S1_vals, E_vals = np.loadtxt("Swordfish_Xenon1T/S1vsER.txt", unpack=True) # Interpolation for the recoil energy as a function of S1 # and the derivative CalcER = UnivariateSpline(S1_vals, E_vals, k=4, s=0) dERdS1 = CalcER.derivative() # Recoil distribution as a function of S1 # taking into account the efficiency and change # of variables ER -> S1 def dRdS1(S1, m_DM): A_Xe = 131. #FIXME: Change to Xenon values xi_T_Xe = 1.0 ER_keV = CalcER(S1) ER_MeV = ER_keV*1.e-3 #Factor of 0.475 comes from the fact that #the reference region should contain about #47.5% of nuclear recoils (between median and 2sigma lines) # Factor of 1/1e3 to convert 1/MeV --> 1/keV return 0.475*efficiency(ER_keV)*dRdE(ER_MeV,m_DM,A_Xe,xi_T_Xe)/1e3*dERdS1(S1) # We are now working in distributions as a function of s1 s1 = np.linspace(3,70,num=100) s1width = s1[1]-s1[0] s1means = s1[0:-1]+s1width/2. bkgs = ['acc','Anom','ElectronRecoil','n','Neutrino','Wall'] def load_bkgs(): b = dict() for i in range(len(bkgs)): S1, temp = np.loadtxt("DD_files/" + bkgs[i] + ".txt", unpack=True) interp = interp1d(S1, temp, bounds_error=False, fill_value=0.0) b[bkgs[i]] = interp(s1means) return b def XenonIT_sig(m_DM): m_DM *= 1.e3 # conversion to MeV sig = dRdS1(s1means,m_DM)*s1width return sig b_dict = load_bkgs() obsT = np.ones_like(s1means)*24.*3600.*35636. mlist = np.logspace(1, 3, 50) # GeV b = np.array(b_dict[bkgs[0]]/obsT) K = np.diag((b.flatten()*0.01)**2) B = [b_dict[bkgs[0]]/obsT, b_dict[bkgs[1]]/obsT, b_dict[bkgs[2]]/obsT, b_dict[bkgs[3]]/obsT, b_dict[bkgs[4]]/obsT, b_dict[bkgs[5]]/obsT] def g(m, sigma): # Takes in sigma and returns g^2 mu_temp = m*mp/(m+mp) return np.ones_like(s1means)*np.pi*((m_med/1.e3)**4.)*sigma/(GeV_inv_cm**2.)/(mu_temp**2.) SF = sf.Swordfish(B, T=[0.1,0.1,0.1,0.1,0.1,0.1], E=obsT, K=K) ULlist_Xenon = [] DRlist_Xenon = [] for i, m in enumerate(mlist): sig = XenonIT_sig(m) UL = SF.upperlimit(sig, 0.05) DR = SF.discoveryreach(sig, 2.87e-7) DRlist_Xenon.append(DR*g2) ULlist_Xenon.append(UL*g2) mu_xp = mlist*mp/(mlist+mp) sigma_Xe = (GeV_inv_cm**2.)*np.array(ULlist_Xenon)*mu_xp**2./np.pi/(m_med/1.e3)**4. sigma_Xe_DR = (GeV_inv_cm**2.)*np.array(DRlist_Xenon)*mu_xp**2./np.pi/(m_med/1.e3)**4. m10list = np.linspace(1, 3, 50) # GeV s10list = np.linspace(-46, -44, 50) S = lambda m, sigma: g(10**m, 10**sigma)*(g2**(-1))*XenonIT_sig(10**m) print S(1.7, -46).sum()*3600.*24*35636 TF = SF.getfield(S, m10list, s10list) vf1, vf2 = TF.VectorFields() plt.figure(figsize=(5,4)) mask = lambda x, y: (y > np.interp(x, np.log10(mlist), np.log10(sigma_Xe))) & (y<-44) vf1.streamlines(color='0.5', mask = mask, Nmax = 40); vf2.streamlines(color='0.5', mask = mask, Nmax = 40); plt.plot(np.log10(mlist), np.log10(sigma_Xe), label=r"95\% CL Exclusion Limit") plt.plot(np.log10(mlist), np.log10(sigma_Xe_DR), "-.", label=r"$5\sigma$ Discovery Reach") TF.contour([1.4, -45.], 1., color='r', ls='-'); TF.contour([1.4, -45.], 2., color='r', ls='--'); TF.contour([1.5, -44.25], 1., color='b', ls='-'); TF.contour([1.5, -44.25], 2., color='b', ls='--'); plt.legend(loc=4) y = [-46,-45,-44] x = [1,2,3] plt.xlim(1.,3.) plt.ylim(-46,-44) plt.xlabel(r"$\log_{10}(m_{\mathrm{DM}}/\rm GeV)$") plt.ylabel(r"$\log_{10}(\sigma /\rm cm^{-2})$") plt.yticks(np.arange(min(y), max(y)+1, 1.0)) plt.xticks(np.arange(min(x), max(x)+1, 1.0)) plt.tight_layout(pad=0.3) plt.savefig("Xe_stream_limits.eps")
_____no_output_____
MIT
Examples/swordfish_DD.ipynb
bradkav/swordfish
Setup
array_geometry = uniform_linear_array(n_mics=10, spacing=0.5) microphone_array = MicrophoneArray(array_geometry) us = 0 vs = compute_steering_vector_ULA(us, microphone_array) SNRs = np.arange(0, 31, 10) n_SNRs = len(SNRs) sigma_n = 1
_____no_output_____
MIT
playground_baseline_dictionary_various_training_snapshots_various_noise_interferences_random.ipynb
dung-n-tran/speech-enhancement-beamforming