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
Doing some computeWe'll use a "big" table to get some sense of timings
spy = taq_tb.get_node(max_sym) # PyTables is record oriented... %timeit np.mean(list(x['Bid_Price'] for x in spy.iterrows())) # But this is faster... %timeit np.mean(spy[:]['Bid_Price']) np.mean(spy[:]['Bid_Price'])
_____no_output_____
BSD-2-Clause
tests/Basic HDF5 Operations.ipynb
dlab-projects/marketflow
Using numexpr?numexpr is currently not set up to do reductions via HDF5. I've opened an issue here:https://github.com/PyTables/PyTables/issues/548
spy_bp = spy.cols.Bid_Price # this works... np.mean(spy_bp) # But it can't use numexpr expr = tb.Expr('sum(spy_bp)') # You can use numexpr to get the values of the column... but that's silly # (sum doesn't work right, and the axis argument is non-functional) %timeit result = expr.eval().mean() tb.Expr('spy_bp').eval()....
_____no_output_____
BSD-2-Clause
tests/Basic HDF5 Operations.ipynb
dlab-projects/marketflow
h5py
taq_tb.close() %%time spy_h5py = h5py.File(fname)[max_sym] np.mean(spy_h5py['Bid_Price'])
_____no_output_____
BSD-2-Clause
tests/Basic HDF5 Operations.ipynb
dlab-projects/marketflow
h5py may be a *touch* faster than pytables for this kind of usage. But why does pandas use pytables?
%%timeit np.mean(spy_h5py['Bid_Price'])
The slowest run took 5.02 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 253 µs per loop
BSD-2-Clause
tests/Basic HDF5 Operations.ipynb
dlab-projects/marketflow
Dask It seems that there should be no need to, e.g., use h5py - but dask's read_hdf doens't seem to be working nicely...
taq_tb.close()
_____no_output_____
BSD-2-Clause
tests/Basic HDF5 Operations.ipynb
dlab-projects/marketflow
spy_h5py = h5py.File(fname)[max_sym]
store = pd.HDFStore(fname) store = pd.HDFStore('../test-data/') # this is a fine way to iterate over our datasets (in addition to what's available in PyTables and h5py) it = store.items() key, tab = next(it) tab # The columns argument doesn't seem to work... store.select(max_sym, columns=['Bid_Price']).head() # columns...
1 loop, best of 3: 9.55 s per loop
BSD-2-Clause
tests/Basic HDF5 Operations.ipynb
dlab-projects/marketflow
Dask for an actual distributed task (but only on one file for now)
class DDFs: # A (key, table) list datasets = [] dbag = None def __init__(self, h5fname): h5in = h5py.File(h5fname) h5in.visititems(self.collect_dataset) def collect_dataset(self, key, table): if isinstance(table, h5py.Dataset): self.datasets.append(dd.from_a...
_____no_output_____
BSD-2-Clause
tests/Basic HDF5 Operations.ipynb
dlab-projects/marketflow
This ends up being a *little* faster than just using blaze (see below), but about half the time is spent setting thigs up in Dask.
from dask import delayed @delayed def mean_column(key, data, column='Bid_Price'): return key, blaze.data(data)[column].mean() class DDFs: # A (key, table) list datasets = [] def __init__(self, h5fname): h5in = h5py.File(h5fname) h5in.visititems(self.collect_dataset) def colle...
_____no_output_____
BSD-2-Clause
tests/Basic HDF5 Operations.ipynb
dlab-projects/marketflow
Blaze?Holy crap!
spy_blaze = blaze.data(spy_h5py) %time spy_blaze['Ask_Price'].mean() taq_tb = tb.open_file(fname) spy_tb = taq_tb.get_node(max_sym) spy_blaze = blaze.data(spy_tb) %time spy_blaze['Bid_Price'].mean() taq_tb.close()
_____no_output_____
BSD-2-Clause
tests/Basic HDF5 Operations.ipynb
dlab-projects/marketflow
Read directly with BlazeSomehow this is not as impressive
%%time blaze_h5_file = blaze.data(fname) # This is rather nice blaze_h5_file.SPY.no_suffix.Bid_Price.mean() blaze_h5_file.ZFKOJB.no_suffix.Bid_Price.mean()
_____no_output_____
BSD-2-Clause
tests/Basic HDF5 Operations.ipynb
dlab-projects/marketflow
Do some actual compute with Blaze
taq_h5py = h5py.File(fname) class SymStats: means = {} def compute_stats(self, key, table): if isinstance(table, h5py.Dataset): self.means[key] = blaze.data(table)['Bid_Price'].mean() ss = SymStats() %time taq_h5py.visititems(ss.compute_stats) means = iter(ss.means.items()) next(means) ...
_____no_output_____
BSD-2-Clause
tests/Basic HDF5 Operations.ipynb
dlab-projects/marketflow
Pandas? To load with Pandas, you need to close the pytables session
taq_tb = tb.open_file(fname) taq_tb.close() pd.read_hdf? pd.read_hdf(fname, max_sym, start=0, stop=1, chunksize=1) max_sym fname %%timeit node = taq_tb.get_node(max_sym) pd.DataFrame.from_records(node[0:1]) %%timeit # I've also tried this with `.get_node()`, same speed pd.DataFrame.from_records(taq_tb.root.IXQAJE.no_su...
The slowest run took 6.25 times longer than the fastest. This could mean that an intermediate result is being cached 10000 loops, best of 3: 57.8 µs per loop
BSD-2-Clause
tests/Basic HDF5 Operations.ipynb
dlab-projects/marketflow
Answers for Comparison Operations Exercises Question 1Which one is the odd number?A) 13B) 72C) 255
13 % 2 == 1 72 % 2 == 1 255 % 2 == 1
_____no_output_____
Unlicense
Module-02/ComparisonOperations.ipynb
rbsorilla/ReneTraining
Question 3Check if 63 is between 50 and 100.
a = 63 50 < a < 100
_____no_output_____
Unlicense
Module-02/ComparisonOperations.ipynb
rbsorilla/ReneTraining
**Copyright 2021 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...
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
View on TensorFlow.org Run in Google Colab View on GitHub Download notebook Sparsity and cluster preserving quantization aware training (PCQAT) Keras example OverviewThis is an end to end example showing the usage of the **sparsity and cluster preserving quantization aware training (PCQAT...
! pip install -q tensorflow-model-optimization import tensorflow as tf import numpy as np import tempfile import zipfile import os
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
Train a tf.keras model for MNIST to be pruned and clustered
# Load MNIST dataset mnist = tf.keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() # Normalize the input image so that each pixel value is between 0 to 1. train_images = train_images / 255.0 test_images = test_images / 255.0 model = tf.keras.Sequential([ tf.keras.laye...
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
Evaluate the baseline model and save it for later usage
_, baseline_model_accuracy = model.evaluate( test_images, test_labels, verbose=0) print('Baseline test accuracy:', baseline_model_accuracy) _, keras_file = tempfile.mkstemp('.h5') print('Saving model to: ', keras_file) tf.keras.models.save_model(model, keras_file, include_optimizer=False)
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
Prune and fine-tune the model to 50% sparsity Apply the `prune_low_magnitude()` API to achieve the pruned model that is to be clustered in the next step. Refer to the [pruning comprehensive guide](https://www.tensorflow.org/model_optimization/guide/pruning/comprehensive_guide) for more information on the pruning API. ...
import tensorflow_model_optimization as tfmot prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude pruning_params = { 'pruning_schedule': tfmot.sparsity.keras.ConstantSparsity(0.5, begin_step=0, frequency=100) } callbacks = [ tfmot.sparsity.keras.UpdatePruningStep() ] pruned_model = prune_low_ma...
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
Fine-tune the model, check sparsity, and evaluate the accuracy against baselineFine-tune the model with pruning for 3 epochs.
# Fine-tune model pruned_model.fit( train_images, train_labels, epochs=3, validation_split=0.1, callbacks=callbacks)
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
Define helper functions to calculate and print the sparsity and clusters of the model.
def print_model_weights_sparsity(model): for layer in model.layers: if isinstance(layer, tf.keras.layers.Wrapper): weights = layer.trainable_weights else: weights = layer.weights for weight in weights: if "kernel" not in weight.name or "centroid" in weight...
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
Let's strip the pruning wrapper first, then check that the model kernels were correctly pruned.
stripped_pruned_model = tfmot.sparsity.keras.strip_pruning(pruned_model) print_model_weights_sparsity(stripped_pruned_model)
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
Apply sparsity preserving clustering and check its effect on model sparsity in both cases Next, apply sparsity preserving clustering on the pruned model and observe the number of clusters and check that the sparsity is preserved.
import tensorflow_model_optimization as tfmot from tensorflow_model_optimization.python.core.clustering.keras.experimental import ( cluster, ) cluster_weights = tfmot.clustering.keras.cluster_weights CentroidInitialization = tfmot.clustering.keras.CentroidInitialization cluster_weights = cluster.cluster_weights ...
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
Strip the clustering wrapper first, then check that the model is correctly pruned and clustered.
stripped_clustered_model = tfmot.clustering.keras.strip_clustering(sparsity_clustered_model) print("Model sparsity:\n") print_model_weights_sparsity(stripped_clustered_model) print("\nModel clusters:\n") print_model_weight_clusters(stripped_clustered_model)
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
Apply QAT and PCQAT and check effect on model clusters and sparsity Next, apply both QAT and PCQAT on the sparse clustered model and observe that PCQAT preserves weight sparsity and clusters in your model. Note that the stripped model is passed to the QAT and PCQAT API.
# QAT qat_model = tfmot.quantization.keras.quantize_model(stripped_clustered_model) qat_model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) print('Train qat model:') qat_model.fit(train_images, train_labels, batch_size=...
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
See compression benefits of PCQAT modelDefine helper function to get zipped model file.
def get_gzipped_model_size(file): # It returns the size of the gzipped model in kilobytes. _, zipped_file = tempfile.mkstemp('.zip') with zipfile.ZipFile(zipped_file, 'w', compression=zipfile.ZIP_DEFLATED) as f: f.write(file) return os.path.getsize(zipped_file)/1000
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
Observe that applying sparsity, clustering and PCQAT to a model yields significant compression benefits.
# QAT model converter = tf.lite.TFLiteConverter.from_keras_model(qat_model) converter.optimizations = [tf.lite.Optimize.DEFAULT] qat_tflite_model = converter.convert() qat_model_file = 'qat_model.tflite' # Save the model. with open(qat_model_file, 'wb') as f: f.write(qat_tflite_model) # PCQAT model converter = tf....
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
See the persistence of accuracy from TF to TFLiteDefine a helper function to evaluate the TFLite model on the test dataset.
def eval_model(interpreter): input_index = interpreter.get_input_details()[0]["index"] output_index = interpreter.get_output_details()[0]["index"] # Run predictions on every image in the "test" dataset. prediction_digits = [] for i, test_image in enumerate(test_images): if i % 1000 == 0: print(f"Ev...
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
Evaluate the model, which has been pruned, clustered and quantized, and then see that the accuracy from TensorFlow persists in the TFLite backend.
interpreter = tf.lite.Interpreter(pcqat_model_file) interpreter.allocate_tensors() pcqat_test_accuracy = eval_model(interpreter) print('Pruned, clustered and quantized TFLite test_accuracy:', pcqat_test_accuracy) print('Baseline TF test accuracy:', baseline_model_accuracy)
_____no_output_____
Apache-2.0
site/en-snapshot/model_optimization/guide/combine/pcqat_example.ipynb
phoenix-fork-tensorflow/docs-l10n
Copyright (C)2016 - 2019 Pinard Liu(liujianping-ok@163.com)https://www.cnblogs.com/pinardPermission given to modify the code as long as you keep this declaration at the top机器学习算法的随机数据生成 https://www.cnblogs.com/pinard/p/6047802.html
import numpy as np import matplotlib.pyplot as plt %matplotlib inline np.random.rand(3,2,2) np.random.randn(3,2) 2*np.random.randn(3,2) + 1 np.random.randint(3, size=[2,3,4]) np.random.randint(3, 6, size=[2,3]) (5-2)*np.random.random_sample(3)+2 from sklearn.datasets.samples_generator import make_regression # X为样本特征,y为...
_____no_output_____
MIT
mathematics/random_data_generation.ipynb
yefang008514/machinelearning
Testing cnn for classifying universesNov 10, 2020
import argparse import os import random import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data from torchsummary import summary from torch.utils.data import DataLoader, TensorDataset import numpy as np import pandas as pd i...
_____no_output_____
BSD-3-Clause-LBNL
code/2_class_cnn/1_cnn_classify.ipynb
vmos1/cosmogan_pytorch
Modules
def f_load_config(config_file): with open(config_file) as f: config = yaml.load(f, Loader=yaml.SafeLoader) return config ### Transformation functions for image pixel values def f_transform(x): return 2.*x/(x + 4.) - 1. def f_invtransform(s): return 4.*(1. + s)/(1. - s) # custom weights initi...
_____no_output_____
BSD-3-Clause-LBNL
code/2_class_cnn/1_cnn_classify.ipynb
vmos1/cosmogan_pytorch
Main code
torch.backends.cudnn.benchmark=True t0=time.time() ################################# ###### Initialize variables ####### config_file='config_128.yaml' config_dict=f_load_config(config_file) print(config_dict) workers=config_dict['training']['workers'] nc,nz,ngf,ndf=config_dict['training']['nc'],config_dict['training']...
_____no_output_____
BSD-3-Clause-LBNL
code/2_class_cnn/1_cnn_classify.ipynb
vmos1/cosmogan_pytorch
User Demo
url = "http://127.0.0.1:5000" filepath = 'C:\\Users\\reonh\Documents\\NUS\AY2022_S1\Capstone\capstone_21\python_backend\database\lpdlprnet\plate_2.jpg' folderpath = 'C:\\Users\\reonh\Documents\\NUS\AY2022_S1\Capstone\capstone_21\python_backend\database\lpdlprnet\\' filename = 'plate.jpg'
_____no_output_____
MIT
demo.ipynb
neilshah13/capstone21
Check Server Status
import requests response = requests.get( url + "/api/lpdlprnet/" + 'internal') print(response.json(), flush=True)
{'HTTPStatus': 200, 'status': 'Active'}
MIT
demo.ipynb
neilshah13/capstone21
Scenario: Developer needs to recognise license plates for the following images Get Predictions
import matplotlib.pyplot as plt import matplotlib.image as mpimg files = [folderpath + 'plate.jpg'] def process(filename: str=None): """ View multiple images stored in files, stacking vertically Arguments: filename: str - path to filename containing image """ image = mpimg.imr...
3SAM123 FE002CA
MIT
demo.ipynb
neilshah13/capstone21
Can we explain this output?
import requests baseURL = url filename = filename filepath = filepath files=[ ('image',(filename,open(filepath,'rb'),'image/jpeg')) ] headers = {} response = requests.post( baseURL + "/api/lpdlprnet/explain/internal", headers=headers, data=payload, files=files) from IPython.display import Markdown, disp...
_____no_output_____
MIT
demo.ipynb
neilshah13/capstone21
How to write this code?
import requests baseURL = url files=[ ('image',(filename,open(filepath,'rb'),'image/jpeg')) ] headers = {} response = requests.post( baseURL + "/api/lpdlprnet/internal", headers=headers, data=payload, files=files) response.json()
_____no_output_____
MIT
demo.ipynb
neilshah13/capstone21
Abstract Classes: contains abstract methods Abstract methods are those which are only declared but they've no implementation**All methods need to be implemented (mandatory)Module -- abc | | |---> ABC (Class) | |---> Abstract method (as a functiona...
from abc import ABC, abstractmethod class Automobile(ABC): def __init__(self): print("Automobile Created") def start(self): pass def start(self): pass def start(self): pass c = Automobile() from abc import ABC, abstractmethod class Automobil...
Car created Bus Created
Unlicense
05 OOPS-3/5.1 Abstract Classes.ipynb
suhassuhas/Coding-Ninjas---Data-Structures-and-Algorithms-in-Python
1) Object of abstract class cannot be created 2) Implement all the abstract methods in the child class
# Predict the output: from abc import ABC,abstractmethod class A(ABC): @abstractmethod def fun1(self): pass @abstractmethod def fun2(self): pass o = A() o.fun1() # Predict the output: from abc import ABC,abstractmethod class A(ABC): @abstractmethod def fun1(self): ...
function 1 called
Unlicense
05 OOPS-3/5.1 Abstract Classes.ipynb
suhassuhas/Coding-Ninjas---Data-Structures-and-Algorithms-in-Python
1. Classification of Facial Expressions 1.1 Importing the data
#load the data data = np.load("2023683_face.npz") data.files data["X_train"] #put the data into corresponding arrays X_train = data["X_train"] y_train = data["y_train"] X_test = data["X_test"] y_test = data["y_test"] X_valid = data["X_valid"] y_valid = data["y_valid"]
_____no_output_____
MIT
2023683_code_classification.ipynb
andreypeshev/classification-and-regression
1.2 EDA
print(X_train.shape) print(y_train.shape) #unique categories np.unique(y_train) X_train X_train[0].shape
_____no_output_____
MIT
2023683_code_classification.ipynb
andreypeshev/classification-and-regression
1.2.1 Plotting an image from each category in the data
#finding the indexes of the first occurances of the unique categories unique_categories = np.unique(y_train, return_index=True)[1] #idea adopted from practical 10 fig, axs = plt.subplots(1, 3, figsize=(10, 10), subplot_kw={'xticks': (), 'yticks': ()}) for index, ax in zip(unique_categories, [0,1,2]): image = X_t...
_____no_output_____
MIT
2023683_code_classification.ipynb
andreypeshev/classification-and-regression
1.2.2 Displaying the number of observations for each class
#combining all the target labels combined_labels = np.concatenate((y_train, y_test, y_valid)) combined_labels.shape labels, counts = np.unique(combined_labels, return_counts=True) plt.bar(labels, counts) plt.xticks(labels) plt.title("Number of observations for each class") plt.xlabel("Class") plt.ylabel("Count") #bala...
_____no_output_____
MIT
2023683_code_classification.ipynb
andreypeshev/classification-and-regression
The data seems to be unbalanced because category 0 is observed 1200 times, 1 - a little less than 800 and 2 - around 400. Fitting a PCA:
#starting with a PCA with 250 components pca = PCA(n_components=250, random_state=202) pca.fit(X_train_res) X_train_pca = pca.transform(X_train_res) X_test_pca = pca.transform(X_test_res) X_train_pca.shape #plotting the explained variance ratio: looks like the best number of components is around 75 plt.plot(np.cumsum(p...
_____no_output_____
MIT
2023683_code_classification.ipynb
andreypeshev/classification-and-regression
1.3 Classfication task 1.3.1 Training KNN Classifier Initializing the baseline model.
start = time.time() knn = KNeighborsClassifier(n_neighbors=1) knn.fit(X_train_pca, y_train_res) pred = knn.predict(X_test_pca) print(f"Test set score: {knn.score(X_test_pca, y_test_res)}") end = time.time() print(f"Time elapsed: {end-start}") print(f"Confusion matrix:\n {metrics.confusion_matrix(y_test_res, pred)}") ...
Test set score: 0.6502732240437158 Time elapsed: 0.07080960273742676 Confusion matrix: [[108 3 11] [ 25 95 2] [ 72 15 35]] Classification report: precision recall f1-score support class 0 0.53 0.89 0.66 122 class 1 0.84 0.78 0.81 122...
MIT
2023683_code_classification.ipynb
andreypeshev/classification-and-regression
Plotting missclassified images.
#displaying two missclassified images for each class (code adapted from workbook 11) index = 0 misclassifiedIndexes = [] lab_0 = 0 lab_1 = 0 lab_2 = 0 for label, predict in zip(y_test_res, pred): if label != predict: #we need this part in order to have only 2 images from each class if label == 0 a...
_____no_output_____
MIT
2023683_code_classification.ipynb
andreypeshev/classification-and-regression
1.3.2 Finding the optimal number of neighbors for KNN
#finding the best number of neighbors using a loop n_neighbors = [1, 2, 3, 4, 5, 6] max_accuracy = 0 best_neighbors = 0 start = time.time() for n in n_neighbors: knn = KNeighborsClassifier(n_neighbors=n) knn.fit(X_train_pca, y_train_res) if knn.score(X_valid_pca, y_valid_res) > max_accuracy: ...
Best accuracy: 0.66 Optimal number of neighbors: 5 Time elapsed: 0.2662501335144043 Test set score with best parameters: 0.6912568306010929 Classification report: precision recall f1-score support class 0 0.59 0.82 0.69 122 class 1 0.88 0.70 0.78 ...
MIT
2023683_code_classification.ipynb
andreypeshev/classification-and-regression
1.3.3 Fitting different classifiers For the hyperparameter tunings I used this resource. It had some useful tips for the different models. https://machinelearningmastery.com/hyperparameters-for-classification-machine-learning-algorithms/
#SVM Classifier without hyperparameter tuning start = time.time() svc = SVC() svc.fit(X_train_pca, y_train_res) pred = svc.predict(X_test_pca) end = time.time() print(f"Time elapsed: {end-start}") print(f"Test set score: {svc.score(X_test_pca, y_test_res)}") print(f"Confusion matrix:\n{metrics.confusion_matrix(pred, y...
Test set score: 0.825136612021858 Confusion matrix: [[104 8 33] [ 3 109 0] [ 15 5 89]]
MIT
2023683_code_classification.ipynb
andreypeshev/classification-and-regression
Title> Small summary- toc: true- branch: master- badges: true- comments: true- categories: [cathegory 1, other cathegory]- image: images/post_image_generic.jpg- hide: false- search_exclude: false- author: Joao Rodrigues Subtitle Subsubtitle And some text here
#collapse-hide var1 = 5 #hide_input print("This code cell was not shown, only the output") import matplotlib.pyplot as plt import numpy as np x = np.linspace(1, 100, 100) y = np.random.randn(100) plt.plot(x,y) plt.show()
_____no_output_____
Apache-2.0
__writing/2021-02-03-template.ipynb
joaodmrodrigues/elements-financial-machine-learning
Ex2 - Getting and Knowing your Data This time we are going to pull data directly from the internet.Special thanks to: https://github.com/justmarkham for sharing the dataset and materials. Step 1. Import the necessary libraries Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/justmarkha...
# Solution 1 # Solution 2
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/Chipotle/.ipynb_checkpoints/Exercises-checkpoint.ipynb
Gioparra91/Pandas-exercise
Step 6. What is the number of columns in the dataset? Step 7. Print the name of all the columns. Step 8. How is the dataset indexed? Step 9. Which was the most-ordered item? Step 10. For the most-ordered item, how many items were ordered? Step 11. What was the most ordered item in the choice_description column? ...
# Solution 1 # Solution 2
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/Chipotle/.ipynb_checkpoints/Exercises-checkpoint.ipynb
Gioparra91/Pandas-exercise
Introduction to PyTorchYou've written a lot of code in this assignment to provide a whole host of neural network functionality. Dropout, Batch Norm, and 2D convolutions are some of the workhorses of deep learning in computer vision. You've also worked hard to make your code efficient and vectorized.For the last part o...
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from torch.utils.data import sampler import torchvision.datasets as dset import torchvision.transforms as T import numpy as np USE_GPU = True dtype = torch.float32 # We will be using float throughout this tutorial....
using device: cuda
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Part I. PreparationNow, let's load the CIFAR-10 dataset. This might take a couple minutes the first time you do it, but the files should stay cached after that.In previous parts of the assignment we had to write our own code to download the CIFAR-10 dataset, preprocess it, and iterate through it in minibatches; PyTorc...
NUM_TRAIN = 49000 # The torchvision.transforms package provides tools for preprocessing data # and for performing data augmentation; here we set up a transform to # preprocess the data by subtracting the mean RGB value and dividing by the # standard deviation of each RGB value; we've hardcoded the mean and std. transf...
Files already downloaded and verified Files already downloaded and verified Files already downloaded and verified
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Part II. Barebones PyTorchPyTorch ships with high-level APIs to help us define model architectures conveniently, which we will cover in Part II of this tutorial. In this section, we will start with the barebone PyTorch elements to understand the autograd engine better. After this exercise, you will come to appreciate ...
def flatten(x): N = x.shape[0] # read in N, C, H, W return x.view(N, -1) # "flatten" the C * H * W values into a single vector per image def test_flatten(): x = torch.arange(12).view(2, 1, 3, 2) print('Before flattening: ', x) print('After flattening: ', flatten(x)) test_flatten()
Before flattening: tensor([[[[ 0, 1], [ 2, 3], [ 4, 5]]], [[[ 6, 7], [ 8, 9], [10, 11]]]]) After flattening: tensor([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11]])
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Barebones PyTorch: Two-Layer NetworkHere we define a function `two_layer_fc` which performs the forward pass of a two-layer fully-connected ReLU network on a batch of image data. After defining the forward pass we check that it doesn't crash and that it produces outputs of the right shape by running zeros through the ...
import torch.nn.functional as F # useful stateless functions def two_layer_fc(x, params): """ A fully-connected neural networks; the architecture is: NN is fully connected -> ReLU -> fully connected layer. Note that this function only defines the forward pass; PyTorch will take care of the backwa...
torch.Size([64, 10])
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Barebones PyTorch: Three-Layer ConvNetHere you will complete the implementation of the function `three_layer_convnet`, which will perform the forward pass of a three-layer convolutional network. Like above, we can immediately test our implementation by passing zeros through the network. The network should have the fol...
def three_layer_convnet(x, params): """ Performs the forward pass of a three-layer convolutional network with the architecture defined above. Inputs: - x: A PyTorch Tensor of shape (N, 3, H, W) giving a minibatch of images - params: A list of PyTorch Tensors giving the weights and biases for th...
_____no_output_____
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
After defining the forward pass of the ConvNet above, run the following cell to test your implementation.When you run this function, scores should have shape (64, 10).
def three_layer_convnet_test(): x = torch.zeros((64, 3, 32, 32), dtype=dtype) # minibatch size 64, image size [3, 32, 32] conv_w1 = torch.zeros((6, 3, 5, 5), dtype=dtype) # [out_channel, in_channel, kernel_H, kernel_W] conv_b1 = torch.zeros((6,)) # out_channel conv_w2 = torch.zeros((9, 6, 3, 3), dty...
torch.Size([64, 10])
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Barebones PyTorch: InitializationLet's write a couple utility methods to initialize the weight matrices for our models.- `random_weight(shape)` initializes a weight tensor with the Kaiming normalization method.- `zero_weight(shape)` initializes a weight tensor with all zeros. Useful for instantiating bias parameters.T...
def random_weight(shape): """ Create random Tensors for weights; setting requires_grad=True means that we want to compute gradients for these Tensors during the backward pass. We use Kaiming normalization: sqrt(2 / fan_in) """ if len(shape) == 2: # FC weight fan_in = shape[0] else: ...
_____no_output_____
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Barebones PyTorch: Check AccuracyWhen training the model we will use the following function to check the accuracy of our model on the training or validation sets.When checking accuracy we don't need to compute any gradients; as a result we don't need PyTorch to build a computational graph for us when we compute scores...
def check_accuracy_part2(loader, model_fn, params): """ Check the accuracy of a classification model. Inputs: - loader: A DataLoader for the data split we want to check - model_fn: A function that performs the forward pass of the model, with the signature scores = model_fn(x, params) ...
_____no_output_____
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
BareBones PyTorch: Training LoopWe can now set up a basic training loop to train our network. We will train the model using stochastic gradient descent without momentum. We will use `torch.functional.cross_entropy` to compute the loss; you can [read about it here](http://pytorch.org/docs/stable/nn.htmlcross-entropy).T...
def train_part2(model_fn, params, learning_rate): """ Train a model on CIFAR-10. Inputs: - model_fn: A Python function that performs the forward pass of the model. It should have the signature scores = model_fn(x, params) where x is a PyTorch Tensor of image data, params is a list of Py...
_____no_output_____
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
BareBones PyTorch: Train a Two-Layer NetworkNow we are ready to run the training loop. We need to explicitly allocate tensors for the fully connected weights, `w1` and `w2`. Each minibatch of CIFAR has 64 examples, so the tensor shape is `[64, 3, 32, 32]`. After flattening, `x` shape should be `[64, 3 * 32 * 32]`. Thi...
hidden_layer_size = 4000 learning_rate = 1e-2 w1 = random_weight((3 * 32 * 32, hidden_layer_size)) w2 = random_weight((hidden_layer_size, 10)) train_part2(two_layer_fc, [w1, w2], learning_rate)
Iteration 0, loss = 4.4703 Checking accuracy on the val set Got 158 / 1000 correct (15.80%) Iteration 100, loss = 2.5019 Checking accuracy on the val set Got 358 / 1000 correct (35.80%) Iteration 200, loss = 1.8195 Checking accuracy on the val set Got 403 / 1000 correct (40.30%) Iteration 300, loss = 1.8267 Checking...
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
BareBones PyTorch: Training a ConvNetIn the below you should use the functions defined above to train a three-layer convolutional network on CIFAR. The network should have the following architecture:1. Convolutional layer (with bias) with 32 5x5 filters, with zero-padding of 22. ReLU3. Convolutional layer (with bias) ...
learning_rate = 3e-3 channel_1 = 32 channel_2 = 16 conv_w1 = None conv_b1 = None conv_w2 = None conv_b2 = None fc_w = None fc_b = None ################################################################################ # TODO: Initialize the parameters of a three-layer ConvNet. # ####################...
Iteration 0, loss = 3.2898 Checking accuracy on the val set Got 123 / 1000 correct (12.30%) Iteration 100, loss = 1.8016 Checking accuracy on the val set Got 369 / 1000 correct (36.90%) Iteration 200, loss = 1.5645 Checking accuracy on the val set Got 400 / 1000 correct (40.00%) Iteration 300, loss = 1.7513 Checking...
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Part III. PyTorch Module APIBarebone PyTorch requires that we track all the parameter tensors by hand. This is fine for small networks with a few tensors, but it would be extremely inconvenient and error-prone to track tens or hundreds of tensors in larger networks.PyTorch provides the `nn.Module` API for you to defin...
class TwoLayerFC(nn.Module): def __init__(self, input_size, hidden_size, num_classes): super().__init__() # assign layer objects to class attributes self.fc1 = nn.Linear(input_size, hidden_size) # nn.init package contains convenient initialization methods # http://pytorch.org...
torch.Size([64, 10])
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Module API: Three-Layer ConvNetIt's your turn to implement a 3-layer ConvNet followed by a fully connected layer. The network architecture should be the same as in Part II:1. Convolutional layer with `channel_1` 5x5 filters with zero-padding of 22. ReLU3. Convolutional layer with `channel_2` 3x3 filters with zero-padd...
class ThreeLayerConvNet(nn.Module): def __init__(self, in_channel, channel_1, channel_2, num_classes): super().__init__() ######################################################################## # TODO: Set up the layers you need for a three-layer ConvNet with the # # architecture d...
torch.Size([64, 10])
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Module API: Check AccuracyGiven the validation or test set, we can check the classification accuracy of a neural network. This version is slightly different from the one in part II. You don't manually pass in the parameters anymore.
def check_accuracy_part34(loader, model): if loader.dataset.train: print('Checking accuracy on validation set') else: print('Checking accuracy on test set') num_correct = 0 num_samples = 0 model.eval() # set model to evaluation mode with torch.no_grad(): for x, y in l...
_____no_output_____
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Module API: Training LoopWe also use a slightly different training loop. Rather than updating the values of the weights ourselves, we use an Optimizer object from the `torch.optim` package, which abstract the notion of an optimization algorithm and provides implementations of most of the algorithms commonly used to op...
def train_part34(model, optimizer, epochs=1): """ Train a model on CIFAR-10 using the PyTorch Module API. Inputs: - model: A PyTorch Module giving the model to train. - optimizer: An Optimizer object we will use to train the model - epochs: (Optional) A Python integer giving the number of e...
_____no_output_____
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Module API: Train a Two-Layer NetworkNow we are ready to run the training loop. In contrast to part II, we don't explicitly allocate parameter tensors anymore.Simply pass the input size, hidden layer size, and number of classes (i.e. output size) to the constructor of `TwoLayerFC`. You also need to define an optimizer...
hidden_layer_size = 4000 learning_rate = 1e-2 model = TwoLayerFC(3 * 32 * 32, hidden_layer_size, 10) optimizer = optim.SGD(model.parameters(), lr=learning_rate) train_part34(model, optimizer)
Iteration 0, loss = 4.2223 Checking accuracy on validation set Got 156 / 1000 correct (15.60) Iteration 100, loss = 2.1946 Checking accuracy on validation set Got 333 / 1000 correct (33.30) Iteration 200, loss = 1.7546 Checking accuracy on validation set Got 368 / 1000 correct (36.80) Iteration 300, loss = 1.9863 Ch...
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Module API: Train a Three-Layer ConvNetYou should now use the Module API to train a three-layer ConvNet on CIFAR. This should look very similar to training the two-layer network! You don't need to tune any hyperparameters, but you should achieve above above 45% after training for one epoch.You should train the model u...
learning_rate = 3e-3 channel_1 = 32 channel_2 = 16 model = None optimizer = None ################################################################################ # TODO: Instantiate your ThreeLayerConvNet model and a corresponding optimizer # ############################################################################...
Iteration 0, loss = 2.5947 Checking accuracy on validation set Got 158 / 1000 correct (15.80) Iteration 100, loss = 1.9449 Checking accuracy on validation set Got 324 / 1000 correct (32.40) Iteration 200, loss = 1.7619 Checking accuracy on validation set Got 366 / 1000 correct (36.60) Iteration 300, loss = 1.7287 Ch...
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Part IV. PyTorch Sequential APIPart III introduced the PyTorch Module API, which allows you to define arbitrary learnable layers and their connectivity. For simple models like a stack of feed forward layers, you still need to go through 3 steps: subclass `nn.Module`, assign layers to class attributes in `__init__`, an...
# We need to wrap `flatten` function in a module in order to stack it # in nn.Sequential class Flatten(nn.Module): def forward(self, x): return flatten(x) hidden_layer_size = 4000 learning_rate = 1e-2 model = nn.Sequential( Flatten(), nn.Linear(3 * 32 * 32, hidden_layer_size), nn.ReLU(), n...
Iteration 0, loss = 2.3411 Checking accuracy on validation set Got 182 / 1000 correct (18.20) Iteration 100, loss = 1.8701 Checking accuracy on validation set Got 389 / 1000 correct (38.90) Iteration 200, loss = 1.6901 Checking accuracy on validation set Got 417 / 1000 correct (41.70) Iteration 300, loss = 1.6675 Ch...
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Sequential API: Three-Layer ConvNetHere you should use `nn.Sequential` to define and train a three-layer ConvNet with the same architecture we used in Part III:1. Convolutional layer (with bias) with 32 5x5 filters, with zero-padding of 22. ReLU3. Convolutional layer (with bias) with 16 3x3 filters, with zero-padding ...
channel_1 = 32 channel_2 = 16 learning_rate = 1e-2 model = None optimizer = None ################################################################################ # TODO: Rewrite the 2-layer ConvNet with bias from Part III with the # # Sequential API. ...
Iteration 0, loss = 2.3069 Checking accuracy on validation set Got 87 / 1000 correct (8.70) Iteration 100, loss = 1.8110 Checking accuracy on validation set Got 431 / 1000 correct (43.10) Iteration 200, loss = 1.5242 Checking accuracy on validation set Got 480 / 1000 correct (48.00) Iteration 300, loss = 1.3371 Chec...
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Part V. CIFAR-10 open-ended challengeIn this section, you can experiment with whatever ConvNet architecture you'd like on CIFAR-10. Now it's your job to experiment with architectures, hyperparameters, loss functions, and optimizers to train a model that achieves **at least 70%** accuracy on the CIFAR-10 **validation**...
################################################################################ # TODO: # # Experiment with any architectures, optimizers, and hyperparameters. # # Achieve AT LEAST 70% accuracy on the *validation set* within 10 ep...
Iteration 0, loss = 2.3076 Checking accuracy on validation set Got 113 / 1000 correct (11.30) Iteration 100, loss = 1.5164 Checking accuracy on validation set Got 372 / 1000 correct (37.20) Iteration 200, loss = 1.2780 Checking accuracy on validation set Got 480 / 1000 correct (48.00) Iteration 300, loss = 1.0746 Ch...
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
Describe what you did In the cell below you should write an explanation of what you did, any additional features that you implemented, and/or any graphs that you made in the process of training and evaluating your network. **Answer:** Test set -- run this only onceNow that we've gotten a result we're happy with, we t...
best_model = model check_accuracy_part34(loader_test, best_model)
Checking accuracy on test set Got 8208 / 10000 correct (82.08)
MIT
assignments/assignment2/PyTorch.ipynb
mirzaim/cs231n
[Dictionaries](https://docs.python.org/3/library/stdtypes.htmldict) Collections of `key`-`value` pairs.
my_empty_dict = {} # alternative: my_empty_dict = dict() print('dict: {}, type: {}'.format(my_empty_dict, type(my_empty_dict)))
dict: {}, type: <class 'dict'>
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
Initialization
dict1 = {'value1': 1.6, 'value2': 10, 'name': 'John Doe'} dict2 = dict(value1=1.6, value2=10, name='John Doe') print(dict1) print(dict2) print('equal: {}'.format(dict1 == dict2)) print('length: {}'.format(len(dict1)))
{'value1': 1.6, 'value2': 10, 'name': 'John Doe'} {'value1': 1.6, 'value2': 10, 'name': 'John Doe'} equal: True length: 3
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
`dict.keys(), dict.values(), dict.items()`
print('keys: {}'.format(dict1.keys())) print('values: {}'.format(dict1.values())) print('items: {}'.format(dict1.items()))
keys: dict_keys(['value1', 'value2', 'name']) values: dict_values([1.6, 10, 'John Doe']) items: dict_items([('value1', 1.6), ('value2', 10), ('name', 'John Doe')])
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
Accessing and setting values
my_dict = {} my_dict['key1'] = 'value1' my_dict['key2'] = 99 my_dict['key1'] = 'new value' # overriding existing value print(my_dict) print('value of key1: {}'.format(my_dict['key1']))
{'key1': 'new value', 'key2': 99} value of key1: new value
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
Accessing a nonexistent key will raise `KeyError` (see [`dict.get()`](dict_get) for workaround):
# print(my_dict['nope'])
_____no_output_____
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
Deleting
my_dict = {'key1': 'value1', 'key2': 99, 'keyX': 'valueX'} del my_dict['keyX'] print(my_dict) # Usually better to make sure that the key exists (see also pop() and popitem()) key_to_delete = 'my_key' if key_to_delete in my_dict: del my_dict[key_to_delete] else: print('{key} is not in {dictionary}'.format(key=k...
{'key1': 'value1', 'key2': 99} my_key is not in {'key1': 'value1', 'key2': 99}
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
Dictionaries are mutable
my_dict = {'ham': 'good', 'carrot': 'semi good'} my_other_dict = my_dict my_other_dict['carrot'] = 'super tasty' my_other_dict['sausage'] = 'best ever' print('my_dict: {}\nother: {}'.format(my_dict, my_other_dict)) print('equal: {}'.format(my_dict == my_other_dict))
my_dict: {'ham': 'good', 'carrot': 'super tasty', 'sausage': 'best ever'} other: {'ham': 'good', 'carrot': 'super tasty', 'sausage': 'best ever'} equal: True
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
Create a new `dict` if you want to have a copy:
my_dict = {'ham': 'good', 'carrot': 'semi good'} my_other_dict = dict(my_dict) my_other_dict['beer'] = 'decent' print('my_dict: {}\nother: {}'.format(my_dict, my_other_dict)) print('equal: {}'.format(my_dict == my_other_dict))
_____no_output_____
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
`dict.get()`Returns `None` if `key` is not in `dict`. However, you can also specify `default` return value which will be returned if `key` is not present in the `dict`.
my_dict = {'a': 1, 'b': 2, 'c': 3} d = my_dict.get('d') print('d: {}'.format(d)) d = my_dict.get('d', 'my default value') print('d: {}'.format(d))
d: None d: my default value
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
`dict.pop()`
my_dict = dict(food='ham', drink='beer', sport='football') print('dict before pops: {}'.format(my_dict)) food = my_dict.pop('food') print('food: {}'.format(food)) print('dict after popping food: {}'.format(my_dict)) food_again = my_dict.pop('food', 'default value for food') print('food again: {}'.format(food_again)) ...
dict before pops: {'food': 'ham', 'drink': 'beer', 'sport': 'football'} food: ham dict after popping food: {'drink': 'beer', 'sport': 'football'} food again: default value for food dict after popping food again: {'drink': 'beer', 'sport': 'football'}
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
`dict.setdefault()`Returns the `value` of `key` defined as first parameter. If the `key` is not present in the dict, adds `key` with default value (second parameter).
my_dict = {'a': 1, 'b': 2, 'c': 3} a = my_dict.setdefault('a', 'my default value') d = my_dict.setdefault('d', 'my default value') print('a: {}\nd: {}\nmy_dict: {}'.format(a, d, my_dict))
a: 1 d: my default value my_dict: {'a': 1, 'b': 2, 'c': 3, 'd': 'my default value'}
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
`dict.update()`Merge two `dict`s
dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3} dict1.update(dict2) print(dict1) # If they have same keys: dict1.update({'c': 4}) print(dict1)
{'a': 1, 'b': 2, 'c': 3} {'a': 1, 'b': 2, 'c': 4}
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
The keys of a `dict` have to be immutable Thus you can not use e.g. a `list` or a `dict` as key because they are mutable types:
# bad_dict = {['my_list'], 'value'} # Raises TypeError
_____no_output_____
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
Values can be mutable
good_dict = {'my key': ['Python', 'is', 'still', 'cool']} print(good_dict)
{'my key': ['Python', 'is', 'still', 'cool']}
MIT
notebooks/beginner/notebooks/dictionaries.ipynb
4TINI/learn-python3
Copyright 2018 The TensorFlow Authors. [Licensed under the Apache License, Version 2.0](scrollTo=bPJq2qP2KE3u).
// #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } // 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/LICE...
_____no_output_____
Apache-2.0
site/en-snapshot/swift/tutorials/raw_tensorflow_operators.ipynb
NarimaneHennouni/docs-l10n
View on TensorFlow.org Run in Google Colab View source on GitHub Raw TensorFlow operatorsBuilding on TensorFlow, Swift for TensorFlow takes a fresh approach to API design. APIs are carefully curated from established libraries and combined with new language idioms. This means that not all TensorFl...
import TensorFlow
_____no_output_____
Apache-2.0
site/en-snapshot/swift/tutorials/raw_tensorflow_operators.ipynb
NarimaneHennouni/docs-l10n
Calling raw operatorsSimply find the function you need under the `_Raw` namespace via code completion.
print(_Raw.mul(Tensor([2.0, 3.0]), Tensor([5.0, 6.0])))
_____no_output_____
Apache-2.0
site/en-snapshot/swift/tutorials/raw_tensorflow_operators.ipynb
NarimaneHennouni/docs-l10n
Defining a new multiply operatorMultiply is already available as operator `*` on `Tensor`, but let us pretend that we wanted to make it available under a new name as `.*`. Swift allows you to retroactively add methods or computed properties to existing types using `extension` declarations.Now, let us add `.*` to `Tens...
infix operator .* : MultiplicationPrecedence extension Tensor where Scalar: Numeric { static func .* (_ lhs: Tensor, _ rhs: Tensor) -> Tensor { return _Raw.mul(lhs, rhs) } } let x: Tensor<Double> = [[1.0, 2.0], [3.0, 4.0]] let y: Tensor<Double> = [[8.0, 7.0], [6.0, 5.0]] print(x .* y)
_____no_output_____
Apache-2.0
site/en-snapshot/swift/tutorials/raw_tensorflow_operators.ipynb
NarimaneHennouni/docs-l10n
Defining a derivative of a wrapped functionNot only can you easily define a Swift API for a raw TensorFlow operator, you can also make it differentiable to work with Swift's first-class automatic differentiation.To make `.*` differentiable, use the `@derivative` attribute on the derivative function and specify the ori...
infix operator .* : MultiplicationPrecedence extension Tensor where Scalar: Numeric { @differentiable(where Scalar: TensorFlowFloatingPoint) static func .* (_ lhs: Tensor, _ rhs: Tensor) -> Tensor { return _Raw.mul(lhs, rhs) } } extension Tensor where Scalar : TensorFlowFloatingPoint { @deri...
_____no_output_____
Apache-2.0
site/en-snapshot/swift/tutorials/raw_tensorflow_operators.ipynb
NarimaneHennouni/docs-l10n
More examples
let matrix = Tensor<Float>([[1, 2], [3, 4]]) print(_Raw.matMul(matrix, matrix, transposeA: true, transposeB: true)) print(_Raw.matMul(matrix, matrix, transposeA: true, transposeB: false)) print(_Raw.matMul(matrix, matrix, transposeA: false, transposeB: true)) print(_Raw.matMul(matrix, matrix, transposeA: false, transp...
_____no_output_____
Apache-2.0
site/en-snapshot/swift/tutorials/raw_tensorflow_operators.ipynb
NarimaneHennouni/docs-l10n
.. _nb_mutation:
## Mutation
_____no_output_____
Apache-2.0
doc/source/operators/mutation.ipynb
AIasd/pymoo
.. _nb_mutation_pm:
### Polynomial Mutation ('real_pm', 'int_pm') Details about the mutation can be found in <cite data-cite="sbx"></cite>. This mutation follows the same probability distribution as the simulated binary crossover.
_____no_output_____
Apache-2.0
doc/source/operators/mutation.ipynb
AIasd/pymoo
from pymoo.interface import mutationfrom pymoo.factory import get_mutationimport numpy as npimport matplotlib.pyplot as pltdef show(eta_mut): a = np.full((5000, 1), 0.5) off = mutation(get_mutation("real_pm", eta=eta_mut, prob=1.0), a) plt.hist(off, range=(0,1), bins=200, density=True, color="red") plt.show...
Basically, the same can be applied to discrete variables as well:
_____no_output_____
Apache-2.0
doc/source/operators/mutation.ipynb
AIasd/pymoo
def show(eta_mut): a = np.full((10000, 1), 0) off = mutation(get_mutation("int_pm", eta=eta_mut, prob=1.0), a, xl=-20, xu=20) plt.hist(off, range=(-20, 20), bins=40, density=True, color="red") plt.show()show(30)
.. _nb_mutation_bitflip:
_____no_output_____
Apache-2.0
doc/source/operators/mutation.ipynb
AIasd/pymoo
Bitflip Mutation ('bin_bitflip')The bitlip mutation randomly flips a bit.
def show(M): plt.figure(figsize=(4,4)) plt.imshow(M, cmap='Greys', interpolation='nearest') plt.show() a = np.full((100,100), False) mut = mutation(get_mutation("bin_bitflip", prob=0.1), a) show(a != mut)
_____no_output_____
Apache-2.0
doc/source/operators/mutation.ipynb
AIasd/pymoo
API
.. autofunction:: pymoo.factory.get_mutation :noindex: .. autofunction:: pymoo.model.mutation.Mutation :noindex:
_____no_output_____
Apache-2.0
doc/source/operators/mutation.ipynb
AIasd/pymoo
Table of Contents1&nbsp;&nbsp;Libraries and functions1.1&nbsp;&nbsp;Import libraries1.2&nbsp;&nbsp;Definition of functions used locally2&nbsp;&nbsp;Options3&nbsp;&nbsp;Load data4&nbsp;&nbsp;Create base indices4.1&nbsp;&nbsp;Market cap weighted4.2&nbsp;&nbsp;Equal weights4.3&nbsp;&nbsp;compute index returns5&nbsp;&nbsp...
# libraries # general import sys import os import itertools import dateutil.relativedelta as relativedelta import datetime import numpy as np import pandas as pd # plotting %matplotlib inline import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns # # statistics and machine learning from ...
_____no_output_____
MIT
notebooks/index_generation_odsc.ipynb
jbauer44/factor_investing