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
Add a column indicating week/weekend
# %load snippets/01-pandas_introduction103.py
_____no_output_____
MIT
pandas/01-pandas_introduction.ipynb
jai-singhal/data_science
Now we can groupby the hour of the day and the weekend (or use `pivot_table`):
# %load snippets/01-pandas_introduction104.py # %load snippets/01-pandas_introduction105.py # %load snippets/01-pandas_introduction106.py # %load snippets/01-pandas_introduction107.py
_____no_output_____
MIT
pandas/01-pandas_introduction.ipynb
jai-singhal/data_science
EXERCISE: What are the number of exceedances of hourly values above the European limit 200 µg/m3 ?Count the number of exceedances of hourly values above the European limit 200 µg/m3 for each year and station after 2005. Make a barplot of the counts. Add an horizontal line indicating the maximum number of exceedances (w...
# re-reading the data to have a clean version no2 = pd.read_csv('data/20000101_20161231-NO2.csv', sep=';', skiprows=[1], na_values=['n/d'], index_col=0, parse_dates=True) # %load snippets/01-pandas_introduction109.py # %load snippets/01-pandas_introduction110.py # %load snippets/01-pandas_introduction111.py
_____no_output_____
MIT
pandas/01-pandas_introduction.ipynb
jai-singhal/data_science
Testa se um modulo foi importado
'my_keras_utilities' in sys.modules
_____no_output_____
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
try: train_network(model_week05, model_name, train_generator, validation_generator, **fit_params);except AttributeError: print('nope')
import keras.backend as K K.set_image_data_format('channels_first') K.set_floatx('float32') print('Backend: {}'.format(K.backend())) print('Data format: {}'.format(K.image_data_format())) !nvidia-smib !ls ../Task\ 5
ls: cannot access '../Task 5': No such file or directory
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
Função auxiliar
class MyCb(TrainingPlotter): def on_epoch_end(self, epoch, logs={}): super().on_epoch_end(epoch, logs) def train_network(model, model_name, train_generator, validation_generator, train_steps=10, valid_steps=10, opt='rmsprop', nepochs=50, patience=50, reset=False,...
_____no_output_____
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
Subindo o dataset
#auternar o comentário, se estiver no client ou no remote data = np.load('/etc/jupyterhub/ia368z_2s2017/datasets/cifar10-redux.npz') #data = np.load('../Task 5/cifar10-redux.npz') X_train = data['X_train'] y_train = data['y_train'] X_test = data['X_test'] y_test = data['y_test'] X_train.dtype, y_train.dtype, X_test.dty...
_____no_output_____
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
Separando o conjunto de treinamento em validação e treinamento, numa proporção 80/20 %
p=np.random.permutation(len(X_train)) percent_factor=0.85 new_train_x = X_train[p] new_train_y = y_train[p] new_X_train = new_train_x[0:(np.floor(len(new_train_x)*percent_factor))] new_y_train = new_train_y[0:(np.floor(len(new_train_y)*percent_factor))] new_X_val = new_train_x[(np.ceil(len(new_train_x)*percent_factor...
Número de diferentes classes 3
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
Normalizando os dados
a=0 print(np.mean(X_train))
113.781868652
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
Guaranteeing that it only runs onceif (a==0): X_test = X_test.astype('float32') new_X_train = new_X_train.astype('float32') new_X_val = new_X_val.astype('float32') new_X_val /= 255. new_X_train /= 255. X_test /= 255. a=1print(np.mean(new_X_train))print(np.mean(new_X_val))print(np.mean(X_tes...
from keras.utils import np_utils ## Transforma o vetor de labels para o formato de one-hot encoding. n_classes = 3 y_train_oh = np_utils.to_categorical(new_y_train-3, n_classes) y_val_oh = np_utils.to_categorical(new_y_val-3, n_classes) y_test_oh = np_utils.to_categorical(y_test-3, n_classes) print(y_train_oh.shape) p...
(1700, 3) (300, 3) (500, 3)
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
Fazendo o data augmentation
print(X_train.shape) print(X_test.shape) print('new x train shape', new_X_train.shape) print('y train oh shape', y_train_oh.shape) print('new x val shape', new_X_val.shape) print('y val oh shape', y_val_oh.shape) from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array nb_train_samples = new_...
_____no_output_____
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
Conjunto de treinaemntosamples_train = train_datagen.flow(new_X_train)n_samples_train = nb_train_samples/batch_sizeConjunto de testesamples_test = train_datagen.flow(X_test)n_samples_test = nb_test_samples/batch_sizeConjunto de validacaosamples_val = train_datagen.flow(new_X_val)n_samples_val = nb_val_samples/batch_siz...
n_classes = len(np.unique(y_test)) print(n_classes)
3
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
Treinamento Transfer_Learning Subindo a VGG-16
print(y_train_oh.shape) from keras.applications.vgg16 import VGG16 modelvgg = VGG16(include_top=False, weights='imagenet',classes=y_train_oh.shape[1]) train_feature = modelvgg.predict_generator(generator=train_generator, steps=int(np.round(train_generator.n / batch_size))) print(train_feature.shape, train_feature.dtyp...
_____no_output_____
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
topmodel.summary() modelvgg.summary()
train_feature.shape[1:] train_feat = train_feature.reshape(1700,512) print(train_feat.shape) modelvgg.output def model_build(): img_rows, img_cols = 32, 32 # Dimensões das imagens #imagens com 3 canais e 32x32 input_shape = (3, img_rows, img_cols) # Definindo a rede model = Sequential() #primei...
cifar_redux_augmented_vgg.history utils week05 cifar_redux_augmented_vgg.model week02 week06 models week03 my_cifar_dataplus_model_weights.h5 week04
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
w1, b1, w2, b2 = load_model('../my_cifar_dataplus_model_weights.h5').get_weights() w1, b1, w2, b2 = load_model('../my_cifar_dataplus_model_weights').get_weights()m m mmm
model2.load_weights('../my_cifar_dataplus_model_weights.h5')
_____no_output_____
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
Aqui os features deixam de ser imagens model.add(Flatten()) model.add(Dense(128)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(n_classes)) model.add(Activation('softmax')) topmodel = Sequential() topmodel.add(layer=keras.layers.Flatten(input_shape=feat_train.shape[1:])) t...
modelvgg.layers.pop(18) modelvgg.layers.pop(17) modelvgg.layers.pop(16) modelvgg.layers.pop(15) #modelvgg.summary() train_features = modelvgg.predict(new_X_train) print('train_features shape and type',train_features.shape,train_features.dtype) validation_features = modelvgg.predict(new_X_val) print('validation_features...
_____no_output_____
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
Treinando class MyCb(TrainingPlotter):
class MyCb(TrainingPlotter): def on_epoch_end(self, epoch, logs={}): super().on_epoch_end(epoch, logs) def train_network(model, model_name, Xtra, ytra, Xval, yval, opt='rmsprop', batch_size=100, nepochs=50, patience=50, reset=False, ploss=1.0): do_plot = (ploss > 0.0) ...
_____no_output_____
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
Construção da rede neural
print(train_features.shape) print(new_X_train.shape) img_height, img_width = new_X_train.shape[2],new_X_train.shape[3] print(img_height,img_width) !ls .. from keras.models import Model from keras.models import load_model model_name = '../cifar10_vgg_finetune' # modelo da rede atual top_model_name = '../cifar_redux_a...
(1700, 3, 32, 32) (1700, 3) (300, 3, 32, 32) (300, 3)
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
(1600, 32, 32, 3) (1600, 3) (400, 32, 32, 3) (400, 3)
h = model.fit(new_X_train.reshape(1700,3,32,32), y_train_oh, validation_data=(new_X_val.reshape(300,3,32,32), y_val_oh), batch_size=batch_size, epochs=100, ) h = model.fit(X_train[train_i], y_train_oh[train_i], validation_data=(X_train[val_i], y_trai...
[INFO] compiling model... [INFO] training for 100 epochs ...
MIT
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
Data Distribution vs. Sampling Distribution: What You Need to Know This notebook is accompanying the article [Data Distribution vs. Sampling Distribution: What You Need to Know](https://www.ealizadeh.com/blog/statistics-data-vs-sampling-distribution/).Subscribe to **[my mailing list](https://www.ealizadeh.com/subscrib...
from IPython.display import Image Image("https://www.ealizadeh.com/wp-content/uploads/2021/01/data_dist_sampling_dist_featured_image.png", width=1200)
_____no_output_____
MIT
notebooks/data_vs_sampling_distributions.ipynb
e-alizadeh/medium
--- It is important to distinguish between the data distribution (aka population distribution) and the sampling distribution. The distinction is critical when working with the central limit theorem or other concepts like the standard deviation and standard error.In this post we will go over the above concepts and as we...
# Plotting packages and initial setup import seaborn as sns sns.set_theme(palette="pastel") sns.set_style("white") import matplotlib.pyplot as plt import matplotlib as mpl mpl.rcParams["figure.dpi"] = 150 savefig_options = dict(format="png", dpi=150, bbox_inches="tight") from scipy.stats import skewnorm from sklearn.p...
_____no_output_____
MIT
notebooks/data_vs_sampling_distributions.ipynb
e-alizadeh/medium
Plotting the data distribution
fig, ax = plt.subplots(figsize=(10, 6)) ax.set_title("Data Distribution", fontsize=24, fontweight="bold") sns.histplot(skewed_data_scaled, bins=30, stat="density", kde=True, legend=False, ax=ax) # fig.savefig("original_skewed_data_distribution.png", **savefig_options)
_____no_output_____
MIT
notebooks/data_vs_sampling_distributions.ipynb
e-alizadeh/medium
Sampling DistributionIn the sampling distribution, you draw samples from the dataset and compute a statistic like the mean. It's very important to differentiate between the data distribution and the sampling distribution as most confusion comes from the operation done on either the original dataset or its (re)samples....
import numpy as np import random sample_size = 50 sample_means = [] random.seed(1) # Setting the seed for reproducibility of the result for _ in range(2000): sample = random.sample(skewed_data_scaled.tolist(), sample_size) sample_means.append(np.mean(sample)) print( f"Mean: {np.mean(...
_____no_output_____
MIT
notebooks/data_vs_sampling_distributions.ipynb
e-alizadeh/medium
Above sampling distribution is basically the histogram of the mean of each drawn sample (in above, we draw samples of 50 elements over 2000 iterations). The mean of the above sampling distribution is around 0.23, as can be noted from computing the mean of all samples means.⚠️ *Do not confuse the sampling distribution w...
from mlxtend.evaluate import bootstrap avg, std_err, ci_bounds = bootstrap( skewed_data_scaled, num_rounds=1000, func=np.mean, # A function to compute a sample statistic can be passed here ci=0.95, seed=123 # Setting the seed for reproducibility of the result ) print( f"Mean: {avg.round(5)...
Mean: 0.23293 Standard Error: +/- 0.00144 CI95: [0.23023, 0.23601]
MIT
notebooks/data_vs_sampling_distributions.ipynb
e-alizadeh/medium
Test "best of two" classifier This notebook test a classifier that operates in two layers:- First we use a SVM classifier to label utterances with high degree of certainty.- Afterwards we use heuristics to complete the labeling
import os import sys import pandas as pd import numpy as np import random import pickle import matplotlib.pyplot as plt root_path = os.path.dirname(os.path.abspath(os.getcwd())) sys.path.append(root_path) from sklearn.svm import SVC from sklearn.svm import LinearSVC from sklearn.metrics import classification_report f...
Accuracy of SVM classifier on training set: 0.30
MIT
notebooks/3-. Check combination 2 layers classifier with test set [utterance level][180t].ipynb
cinai/classification_ibl
Test 2
test_i = '[test2]' file_name = test_i+'IBL_topic_distribution_by_utterance_before_after_{}_{}.xlsx'.format(WITH_STEMMING,NUM_TOPICS) df_data = pd.read_excel(os.path.join(tables_path,'test','before_after',file_name)) the_keys = list(set(df_data['phase'])) total_samples = 0 class_samples = {} for key in the_keys: n =...
Accuracy 0.466
MIT
notebooks/3-. Check combination 2 layers classifier with test set [utterance level][180t].ipynb
cinai/classification_ibl
Classifying Digits with K-Nearest-Neighbors (KNN) This is a very simple implementation of classifying images using the k-nearest-neighbors algorithm. The accuracy is pretty good for how simple the algorithm is. The parameters can be tinkered with but at the time of writing I am using k = 5, training data size = 10000,...
k = 5 batch_size_train = 10000 batch_size_test = 1000 train_mnist = torchvision.datasets.MNIST('C:/projects/summer2020/vision/digits/', train=True, download=True, transform=torchvision.transforms.ToTensor()) train_loader = torch.utils.data.DataLoader(train_mnist, batch_size=batch_size_train, shu...
_____no_output_____
MIT
digits_knn.ipynb
sasiegel/mnist-classification
The k-nearest-neighbors algorithm is not very efficient and my implementation is even less efficient. I was aiming for simplicity over efficiency. We loop through each test image and find the distance to every training image. Distance is measured as Euclidean (p=2). We take the k nearest images and record the ground tr...
n_test = test_imgs.shape[0] n_train = train_imgs.shape[0] pred_test_targets = torch.zeros_like(test_targets) for i in range(n_test): test_img = test_imgs[i] distances = [torch.dist(test_img, train_imgs[j], p=2) for j in range(n_train)] nearest_indices = np.array(distances).argsort()[:5] pred_test_target...
Prediction accuracy: 0.959
MIT
digits_knn.ipynb
sasiegel/mnist-classification
Distributed data parallel BERT training with TensorFlow2 and SMDataParallelHSMDataParallel is a new capability in Amazon SageMaker to train deep learning models faster and cheaper. SMDataParallel is a distributed data parallel training framework for TensorFlow, PyTorch, and MXNet.This notebook example shows how to use...
%%time ! python3 -m pip install --upgrade sagemaker import sagemaker from sagemaker import get_execution_role from sagemaker.estimator import Estimator import boto3 sagemaker_session = sagemaker.Session() bucket = sagemaker_session.default_bucket() role = get_execution_role() # provide a pre-existing role ARN as an a...
SageMaker Execution Role:arn:aws:iam::835319576252:role/service-role/AmazonSageMaker-ExecutionRole-20191006T135881 AWS account:835319576252 AWS region:us-east-1
Apache-2.0
08_optimize/distributed-training/tensorflow/data_parallel/bert/tensorflow2_smdataparallel_bert_demo.ipynb
MarcusFra/workshop
Prepare SageMaker Training Images1. SageMaker by default use the latest [Amazon Deep Learning Container Images (DLC)](https://github.com/aws/deep-learning-containers/blob/master/available_images.md) TensorFlow training image. In this step, we use it as a base image and install additional dependencies required for trai...
image = "tf2-smdataparallel-bert-sagemaker" # Example: tf2-smdataparallel-bert-sagemaker tag = "latest" # Example: latest !pygmentize ./Dockerfile !pygmentize ./build_and_push.sh %%time ! chmod +x build_and_push.sh; bash build_and_push.sh {region} {image} {tag}
WARNING! Using --password via the CLI is insecure. Use --password-stdin. WARNING! Your password will be stored unencrypted in /home/ec2-user/.docker/config.json. Configure a credential helper to remove this warning. See https://docs.docker.com/engine/reference/commandline/login/#credentials-store Login Succeeded Sendi...
Apache-2.0
08_optimize/distributed-training/tensorflow/data_parallel/bert/tensorflow2_smdataparallel_bert_demo.ipynb
MarcusFra/workshop
Preparing FSx Input for SageMaker1. Download and prepare your training dataset on S3.2. Follow the steps listed here to create a FSx linked with your S3 bucket with training data - https://docs.aws.amazon.com/fsx/latest/LustreGuide/create-fs-linked-data-repo.html. Make sure to add an endpoint to your VPC allowing S3 a...
# Clone herring forks repository for reference implementation BERT with TensorFlow2-SMDataParallel !rm -rf deep-learning-models !git clone --recursive https://github.com/HerringForks/deep-learning-models.git import boto3 import sagemaker sm = boto3.client('sagemaker') notebook_instance_name = sm.list_notebook_instances...
_____no_output_____
Apache-2.0
08_optimize/distributed-training/tensorflow/data_parallel/bert/tensorflow2_smdataparallel_bert_demo.ipynb
MarcusFra/workshop
Configure FSx Input for the SageMaker Training Job
from sagemaker.inputs import FileSystemInput #YOUR_MOUNT_PATH_FOR_TRAINING_DATA # NOTE: '/fsx/' will be the root mount path. Example: '/fsx/albert'''' file_system_directory_path='/fsx/' file_system_access_mode='rw' file_system_type='FSxLustre' train_fs = FileSystemInput(file_system_id=file_system_id, ...
_____no_output_____
Apache-2.0
08_optimize/distributed-training/tensorflow/data_parallel/bert/tensorflow2_smdataparallel_bert_demo.ipynb
MarcusFra/workshop
Continuous Control---In this notebook I will implement the distributed disttributional deep determenstic policy gradients (D4PG) algorithm. different algorithm can also be used to solve this problem such as : ''' 1 - Deep determenstic policy gradients (DDPG) 2 - Proximal policy optimization (PPO) 3 - Async...
import random import time import torch import torch.nn as nn import numpy as np from collections import deque import matplotlib.pyplot as plt %matplotlib inline device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") from unityagents import UnityEnvironment from d4pg_agent import Agent # select thi...
INFO:unityagents: 'Academy' started successfully! Unity Academy name: Academy Number of Brains: 1 Number of External Brains : 1 Lesson number : 0 Reset Parameters : goal_speed -> 1.0 goal_size -> 5.0 Unity brain name: ReacherBrain Number of Visual Observations (per agent): 0 ...
MIT
Project-2_Continuous-Control/Continuous-Control/Continuous_Control.ipynb
Mohammedabdalqader/DRL
Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python.
# get the default brain brain_name = env.brain_names[0] brain = env.brains[brain_name]
_____no_output_____
MIT
Project-2_Continuous-Control/Continuous-Control/Continuous_Control.ipynb
Mohammedabdalqader/DRL
2. Examine the State and Action SpacesRun the code cell below to print some information about the environment.
# reset the environment env_info = env.reset(train_mode=True)[brain_name] # number of agents num_agents = len(env_info.agents) print('Number of agents:', num_agents) # size of each action action_size = brain.vector_action_space_size print('Size of each action:', action_size) # examine the state space states = env_i...
Number of agents: 20 Size of each action: 4 There are 20 agents. Each observes a state with length: 33 The state for the first agent looks like: [ 0.00000000e+00 -4.00000000e+00 0.00000000e+00 1.00000000e+00 -0.00000000e+00 -0.00000000e+00 -4.37113883e-08 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e...
MIT
Project-2_Continuous-Control/Continuous-Control/Continuous_Control.ipynb
Mohammedabdalqader/DRL
3. Take Random Actions in the EnvironmentIn the next code cell, you will learn how to use the Python API to control the agent and receive feedback from the environment.Note that **in this coding environment, you will not be able to watch the agents while they are training**, and you should set `train_mode=True` to res...
for i in range(10): env_info = env.reset(train_mode=True)[brain_name] # reset the environment states = env_info.vector_observations # get the current state (for each agent) scores = np.zeros(num_agents) # initialize the score (for each agent) while True...
_____no_output_____
MIT
Project-2_Continuous-Control/Continuous-Control/Continuous_Control.ipynb
Mohammedabdalqader/DRL
4. ImplementationNow i will implement the D4PG Algorithm
agent = Agent(state_size=state_size, action_size=action_size,num_agents=num_agents, seed=7) # Training the agent over a number of episodes until we reach the desired average reward, which is > 30 def d4pg(n_episodes=2000): scores = [] scores_deque = deque(maxlen=100) rolling_average_score = [] ...
_____no_output_____
MIT
Project-2_Continuous-Control/Continuous-Control/Continuous_Control.ipynb
Mohammedabdalqader/DRL
NewEgg.Com WebScraping Program For Laptops - Beta v1.0 - April 2020---
# Import dependencies. import os import re import time import glob import random import datetime import requests import pandas as pd from re import search from splinter import Browser from playsound import playsound from bs4 import BeautifulSoup as soup
_____no_output_____
MIT
archive/newer_notebooks_wip_drafts/drafts/new_egg_webscraper_app_NOTFINAL_review_too_much.ipynb
jhustles/new_egg_webscraper
Functions & Classes Setup---
# Build a function to return date throughout the program. def return_dt(): global current_date current_date = str(datetime.datetime.now()).replace(':','.').replace(' ','_')[:-7] return current_date """ NewEgg WebScraper function that scrapes data, saves it into a csv file, and creates Laptop...
_____no_output_____
MIT
archive/newer_notebooks_wip_drafts/drafts/new_egg_webscraper_app_NOTFINAL_review_too_much.ipynb
jhustles/new_egg_webscraper
Main Program Logic---
""" Welcome to the program message! """ print("=== NewEgg.Com Laptop WebScraper Beta v1.0 ===") print("=="*30) print('Scope: This project is a beta and is only built to scrape the laptop section of NewEgg.com due to limited time. \n') print("Instructions: \n") return_dt() print(f'Current Date And Time: {current_da...
_____no_output_____
MIT
archive/newer_notebooks_wip_drafts/drafts/new_egg_webscraper_app_NOTFINAL_review_too_much.ipynb
jhustles/new_egg_webscraper
Saliency visualization
from chainer_chemistry.saliency.calculator.gradient_calculator import GradientCalculator from chainer_chemistry.saliency.calculator.integrated_gradients_calculator import IntegratedGradientsCalculator from chainer_chemistry.link_hooks.variable_monitor_link_hook import VariableMonitorLinkHook # 1. instantiation gradie...
_____no_output_____
MIT
examples/table/visualize-saliency-table.ipynb
corochann/chainer-saliency
visualize saliency of all data --> this can be considered as "feature importance"
saliency_mean = np.mean(saliency_vanilla, axis=0) visualizer.visualize(saliency_mean, feature_names=iris.feature_names, num_visualize=-1, scaler=normalize_scaler) visualizer.visualize(saliency_mean, feature_names=iris.feature_names, num_visualize=-1, scaler=normalize_scaler, save...
_____no_output_____
MIT
examples/table/visualize-saliency-table.ipynb
corochann/chainer-saliency
sklearn random forest feature importanceRef: - https://qiita.com/TomokIshii/items/290adc16e2ca5032ca07 - https://stackoverflow.com/questions/44101458/random-forest-feature-importance-chart-using-python
import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.ensemble import RandomForestClassifier iris = load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split( X,...
_____no_output_____
MIT
examples/table/visualize-saliency-table.ipynb
corochann/chainer-saliency
Twin-Delayed DDPGComplete credit goes to this [awesome Deep Reinforcement Learning 2.0 Course on Udemy](https://www.udemy.com/course/deep-reinforcement-learning/) for the code. Installing the packages
!pip install pybullet
Requirement already satisfied: pybullet in /usr/local/lib/python3.6/dist-packages (2.7.1)
Apache-2.0
P2S10.ipynb
aks1981/ML
Importing the libraries
import os import time import random import numpy as np import matplotlib.pyplot as plt import pybullet_envs import gym import torch import torch.nn as nn import torch.nn.functional as F from gym import wrappers from torch.autograd import Variable from collections import deque
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
Step 1: We initialize the Experience Replay memory
class ReplayBuffer(object): def __init__(self, max_size=1e6): self.storage = [] self.max_size = max_size self.ptr = 0 def add(self, transition): if len(self.storage) == self.max_size: self.storage[int(self.ptr)] = transition self.ptr = (self.ptr + 1) % self.max_size else: sel...
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
Step 2: We build one neural network for the Actor model and one neural network for the Actor target
class Actor(nn.Module): def __init__(self, state_dim, action_dim, max_action): super(Actor, self).__init__() self.layer_1 = nn.Linear(state_dim, 400) self.layer_2 = nn.Linear(400, 300) self.layer_3 = nn.Linear(300, action_dim) self.max_action = max_action def forward(self, x): x = F.relu...
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
Step 3: We build two neural networks for the two Critic models and two neural networks for the two Critic targets
class Critic(nn.Module): def __init__(self, state_dim, action_dim): super(Critic, self).__init__() # Defining the first Critic neural network self.layer_1 = nn.Linear(state_dim + action_dim, 400) self.layer_2 = nn.Linear(400, 300) self.layer_3 = nn.Linear(300, 1) # Defining the second Criti...
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
Steps 4 to 15: Training Process
# Selecting the device (CPU or GPU) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Building the whole Training Process into a class class TD3(object): def __init__(self, state_dim, action_dim, max_action): self.actor = Actor(state_dim, action_dim, max_action).to(device) self.acto...
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
We make a function that evaluates the policy by calculating its average reward over 10 episodes
def evaluate_policy(policy, eval_episodes=10): avg_reward = 0. for _ in range(eval_episodes): obs = env.reset() done = False while not done: action = policy.select_action(np.array(obs)) obs, reward, done, _ = env.step(action) avg_reward += reward avg_reward /= eval_episodes print (...
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
We set the parameters
env_name = "AntBulletEnv-v0" # Name of a environment (set it to any Continous environment you want) seed = 0 # Random seed number start_timesteps = 1e4 # Number of iterations/timesteps before which the model randomly chooses an action, and after which it starts to use the policy network eval_freq = 5e3 # How often the ...
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
We create a file name for the two saved models: the Actor and Critic models
file_name = "%s_%s_%s" % ("TD3", env_name, str(seed)) print ("---------------------------------------") print ("Settings: %s" % (file_name)) print ("---------------------------------------")
--------------------------------------- Settings: TD3_AntBulletEnv-v0_0 ---------------------------------------
Apache-2.0
P2S10.ipynb
aks1981/ML
We create a folder inside which will be saved the trained models
if not os.path.exists("./results"): os.makedirs("./results") if save_models and not os.path.exists("./pytorch_models"): os.makedirs("./pytorch_models")
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
We create the PyBullet environment
env = gym.make(env_name)
/usr/local/lib/python3.6/dist-packages/gym/logger.py:30: UserWarning: WARN: Box bound precision lowered by casting to float32 warnings.warn(colorize('%s: %s'%('WARN', msg % args), 'yellow'))
Apache-2.0
P2S10.ipynb
aks1981/ML
We set seeds and we get the necessary information on the states and actions in the chosen environment
env.seed(seed) torch.manual_seed(seed) np.random.seed(seed) state_dim = env.observation_space.shape[0] action_dim = env.action_space.shape[0] max_action = float(env.action_space.high[0])
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
We create the policy network (the Actor model)
policy = TD3(state_dim, action_dim, max_action)
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
[link text](https://) We create the Experience Replay memory
replay_buffer = ReplayBuffer()
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
We define a list where all the evaluation results over 10 episodes are stored
evaluations = [evaluate_policy(policy)]
--------------------------------------- Average Reward over the Evaluation Step: 9.804960 ---------------------------------------
Apache-2.0
P2S10.ipynb
aks1981/ML
We create a new folder directory in which the final results (videos of the agent) will be populated
def mkdir(base, name): path = os.path.join(base, name) if not os.path.exists(path): os.makedirs(path) return path work_dir = mkdir('exp', 'brs') monitor_dir = mkdir(work_dir, 'monitor') max_episode_steps = env._max_episode_steps save_env_vid = False if save_env_vid: env = wrappers.Monitor(env, mon...
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
We initialize the variables
total_timesteps = 0 timesteps_since_eval = 0 episode_num = 0 done = True t0 = time.time()
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
Training
max_timesteps = 500000 # We start the main loop over 500,000 timesteps while total_timesteps < max_timesteps: # If the episode is done if done: # If we are not at the very beginning, we start the training process of the model if total_timesteps != 0: print("Total Timesteps: {} Episode Num: {} Rewa...
Total Timesteps: 1000 Episode Num: 1 Reward: 512.6232988347093 Total Timesteps: 2000 Episode Num: 2 Reward: 493.70176430884203 Total Timesteps: 3000 Episode Num: 3 Reward: 492.40008391554187 Total Timesteps: 4000 Episode Num: 4 Reward: 476.3080060617612 Total Timesteps: 5000 Episode Num: 5 Reward: 494.0312655821267 ---...
Apache-2.0
P2S10.ipynb
aks1981/ML
Inference
class Actor(nn.Module): def __init__(self, state_dim, action_dim, max_action): super(Actor, self).__init__() self.layer_1 = nn.Linear(state_dim, 400) self.layer_2 = nn.Linear(400, 300) self.layer_3 = nn.Linear(300, action_dim) self.max_action = max_action def forward(self, x): x = F.relu...
_____no_output_____
Apache-2.0
P2S10.ipynb
aks1981/ML
Web predictionsThe purpose of this notebook is to experiment with making predictions from "raw" accumulated user values, thatcould for instance be user input from a web form.
import findspark findspark.init() findspark.find() import pyspark from pyspark import SparkContext, SparkConf from pyspark.sql import SparkSession conf = pyspark.SparkConf().setAppName('sparkify-capstone-web').setMaster('local') sc = pyspark.SparkContext(conf=conf) spark = SparkSession(sc) from pyspark.ml.classificat...
_____no_output_____
MIT
udacity/data-scientist-nanodegree/sparkify/.ipynb_checkpoints/web_pred-checkpoint.ipynb
thomasrobertz/mooc
Lecture 9 - Motor Control Introduction to modeling and simulation of human movementhttps://github.com/BMClab/bmc/blob/master/courses/ModSim2018.md * In class:
import numpy as np #import pandas as pd #import pylab as pl import matplotlib.pyplot as plt import math %matplotlib notebook
_____no_output_____
MIT
courses/modsim2018/matheuspiquini/Lecture11.ipynb
MatheusKP/bmc
Muscle properties
Lslack = .223 Umax = .04 Lce_o = .093 #optmal l width = .63 Fmax = 3000 a = .25 b = .25*10
_____no_output_____
MIT
courses/modsim2018/matheuspiquini/Lecture11.ipynb
MatheusKP/bmc
Initial conditions
LceNorm = .087/Lce_o t0 = 0 tf = 2.99 h = 1e-3 u = 1 a = 0 t = np.arange(t0,tf,h) F = np.empty(t.shape) Fkpe = np.empty(t.shape) FiberLength = np.empty(t.shape) TendonLength = np.empty(t.shape) U = np.arange(t0,1,h) ## Funcoes def computeTendonForce(LseeNorm, Lce_o, Lslack): ''' Compute Tendon Length I...
_____no_output_____
MIT
courses/modsim2018/matheuspiquini/Lecture11.ipynb
MatheusKP/bmc
Simulation - Parallel
for i in range (len(t)): #ramp if t[i]<=1: Lm = 0.31 elif t[i]>1 and t[i]<2: Lm = .31 - .04*(t[i]-1) #print(Lm) ##################################################################### LseeNorm = (Lm/Lce_o) - LceNorm FTendonNorm = computeTendonForce(LseeNorm, Lce_o...
_____no_output_____
MIT
courses/modsim2018/matheuspiquini/Lecture11.ipynb
MatheusKP/bmc
Plot
fig, ax = plt.subplots(1, 1, figsize=(6,6), sharex=True) ax.plot(t,F,c='red') plt.grid() plt.xlabel('time (s)') plt.ylabel('Force [N]') #ax.legend() fig, ax = plt.subplots(1, 1, figsize=(6,6), sharex=True) ax.plot(t,FiberLength, label = 'fibra') ax.plot(t, TendonLength, label = 'tendao') ax.plot(t,FiberLength + Ten...
_____no_output_____
MIT
courses/modsim2018/matheuspiquini/Lecture11.ipynb
MatheusKP/bmc
Load a scope from a yaml file.
with open('gbnrtc_scope.yaml') as yf: for _ in range(100): print(yf.readline(), end="") scope = emat.Scope('gbnrtc_scope.yaml') scope
_____no_output_____
BSD-3-Clause
docs/source/emat.examples/GBNRTC/gbnrtc_fresh_boxes.ipynb
tlumip/tmip-emat
Create a brand new set of `Boxes`.
boxes = emat.Boxes(scope=scope)
_____no_output_____
BSD-3-Clause
docs/source/emat.examples/GBNRTC/gbnrtc_fresh_boxes.ipynb
tlumip/tmip-emat
Define a new top-level box (i.e. a box with no parents to inherit from).
box_1 = emat.Box(name='High Population Growth', scope=scope)
_____no_output_____
BSD-3-Clause
docs/source/emat.examples/GBNRTC/gbnrtc_fresh_boxes.ipynb
tlumip/tmip-emat
Add a lower bound for population growth, to ensure the include values are all "high".
box_1.set_lower_bound('Land Use - CBD Focus', 1.0)
_____no_output_____
BSD-3-Clause
docs/source/emat.examples/GBNRTC/gbnrtc_fresh_boxes.ipynb
tlumip/tmip-emat
Add some things as "relevant features" that we are interested in analyzing,even though we do not set bounds on them (yet).
box_1.relevant_features.add('Total LRT Boardings') box_1.relevant_features.add('Downtown to Airport Travel Time') box_1.relevant_features.add('Peak Transit Share') box_1.relevant_features.add('AM Trip Time (minutes)') box_1.relevant_features.add('AM Trip Length (miles)') box_1.relevant_features.add('Region-wide VMT') b...
_____no_output_____
BSD-3-Clause
docs/source/emat.examples/GBNRTC/gbnrtc_fresh_boxes.ipynb
tlumip/tmip-emat
Define a new lower level box, which will inherit from the top level box we just created.
box_2 = emat.Box(name='Automated Vehicles', scope=scope, parent='High Population Growth')
_____no_output_____
BSD-3-Clause
docs/source/emat.examples/GBNRTC/gbnrtc_fresh_boxes.ipynb
tlumip/tmip-emat
Set some thresholds on this lower level box.
box_2.set_lower_bound('Freeway Capacity', 1.25) box_2.set_upper_bound('Auto IVTT Sensitivity', 0.9) box_2 box_2.parent_box_name
_____no_output_____
BSD-3-Clause
docs/source/emat.examples/GBNRTC/gbnrtc_fresh_boxes.ipynb
tlumip/tmip-emat
So far, the individual boxes we created are just loose boxes. To connect them, we need to add them to the master `Boxes` object.
boxes.add(box_1) boxes.add(box_2)
_____no_output_____
BSD-3-Clause
docs/source/emat.examples/GBNRTC/gbnrtc_fresh_boxes.ipynb
tlumip/tmip-emat
We can check on what named boxes are in a `Boxes` object with the `plain_names` method,which just gives the names, or the `fancy_names` method, which adds some iconsto help indicate the hierarchy.
boxes.plain_names() boxes.fancy_names()
_____no_output_____
BSD-3-Clause
docs/source/emat.examples/GBNRTC/gbnrtc_fresh_boxes.ipynb
tlumip/tmip-emat
Now that the boxes are linked together in a `Boxes` object, we can use the `get_chain` method to aggregatethe attributes of any box along with all parents in the chain.
boxes.get_chain('Automated Vehicles')
_____no_output_____
BSD-3-Clause
docs/source/emat.examples/GBNRTC/gbnrtc_fresh_boxes.ipynb
tlumip/tmip-emat
Time Series analysis of O'hare taxi rides data
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import GradientBoostingRegressor from sklearn.model_selection import TimeSeriesSplit, cross_validate, GridSearchCV pd.set_option('display.max_rows', 6) plt.style.use('ggplot') ...
_____no_output_____
MIT
src/time_series_modelling.ipynb
jsleslie/Ohare_taxi_demand
Tom's functions
# Custom functions def lag_df(df, lag, cols): return df.assign(**{f"{col}-{n}": df[col].shift(n) for n in range(1, lag + 1) for col in cols}) def ts_predict(input_data, model, n=20, responses=1): predictions = [] n_features = input_data.size for _ in range(n): predictions = np.append(predicti...
_____no_output_____
MIT
src/time_series_modelling.ipynb
jsleslie/Ohare_taxi_demand
Lesson 04: Numpy - Used for working with tensors- Provides vectors, matrices, and tensors- Provides mathematical functions that operate on vectors, matrices, and tensors- Implemented in Fortran and C in the backend
import numpy as np
_____no_output_____
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Making Arrays
arr = np.array([1, 2, 3]) print(arr, type(arr), arr.shape, arr.dtype, arr.ndim) matrix = np.array( [[1, 2, 3], [4, 5, 6.2]] ) print(matrix, type(matrix), matrix.shape, matrix.dtype, matrix.ndim) a = np.zeros((10, 2)) print(a) a = np.ones((4, 5)) print(a) a = np.full((2, 3, 5), 6) print(a) a = np.eye(4) print(a)...
[[0.94118745 0.22994581 0.75183424 0.3433619 0.53614551] [0.4701853 0.68700713 0.3685086 0.19023418 0.17094098] [0.96813951 0.00628098 0.02295652 0.9007116 0.03263926] [0.56018717 0.13823581 0.71362452 0.57653406 0.9263221 ] [0.22776242 0.92652569 0.04206205 0.13036483 0.10911229]]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Indexing
arr = np.array([ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15] ]) print(arr)
[[ 1 2 3 4 5] [ 6 7 8 9 10] [11 12 13 14 15]]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
The indexing format is: [rows , columns]You can then slice the individual dimension as follows: [start : end , start : end]
print(arr[1:, 2:4]) a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]]) print(a[ [0, 1, 2, 3], [1, 0, 2, 0] ]) print(a[0, 1], a[1, 0], a[2, 2], a[3, 0]) print(np.array([a[0, 1], a[1, 0], a[2, 2], a[3, 0]])) b = np.array([1, 0, 2, 0]) print(a[np.arange(4), b]) a[np.arange(4), b] += 7 print(a) a = np.array([[1,2,3...
[ 8 9 10 11 12]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Data Types
b = np.array([1, 2, 3], dtype=np.float64) print(b.dtype)
float64
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
https://numpy.org/doc/stable/reference/arrays.dtypes.html Operations
x = np.array([ [1, 2], [3, 4] ]) y = np.array([ [5, 6], [7, 8] ]) print(x, x.shape) print(y, y.shape) print(x + y) print(np.add(x, y)) print(x - y) print(np.subtract(x, y)) print(x * y) print(np.multiply(x, y)) print(x / y) print(np.divide(x, y))
[[0.2 0.33333333] [0.42857143 0.5 ]] [[0.2 0.33333333] [0.42857143 0.5 ]]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Matrix Multiplication
w = np.array([2, 4]) v = np.array([4, 6]) print(x) print(y) print(w) print(v)
[[1 2] [3 4]] [[5 6] [7 8]] [2 4] [4 6]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Vector-vector multiplication
print(v.dot(w)) print(np.dot(v, w))
32 32
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Matrix-vector multiplication
print(x.dot(w))
[10 22]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Matrix multiplication
print(x.dot(y)) print(np.dot(x, y))
[[19 22] [43 50]] [[19 22] [43 50]]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Transpose
print(x) print(x.T)
[[1 2] [3 4]] [[1 3] [2 4]]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
http://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html Other Operations
print(x) print(np.sum(x)) print(np.sum(x, axis=0)) print(np.sum(x, axis=1))
[[1 2] [3 4]] 10 [4 6] [3 7]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
More array operations are listed here:http://docs.scipy.org/doc/numpy/reference/routines.math.html Broadcasting Broadcasting allows Numpy to work with arrays of different shapes. Operations which would have required loops can now be done without them hence speeding up your program.
x = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], ]) print(x, x.shape) y = np.array([1, 2, 3]) print(y, y.shape)
[1 2 3] (3,)
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Loop Approach
z = np.empty_like(x) print(z, z.shape) for i in range(x.shape[0]): z[i, :] = x[i, :] + y print(z)
[[ 2 4 6] [ 5 7 9] [ 8 10 12] [11 13 15] [14 16 18] [17 19 21]]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Tile Approach
yy = np.tile(y, (6, 1)) print(yy, yy.shape) print(x + y)
[[ 2 4 6] [ 5 7 9] [ 8 10 12] [11 13 15] [14 16 18] [17 19 21]]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Broadcasting Approach
print(x, x.shape) print(y, y.shape) print(x + y)
[[ 2 4 6] [ 5 7 9] [ 8 10 12] [11 13 15] [14 16 18] [17 19 21]]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
- https://numpy.org/doc/stable/user/basics.broadcasting.html- http://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc- http://docs.scipy.org/doc/numpy/reference/ufuncs.htmlavailable-ufuncs Reshape
x = np.array([ [1, 2, 3], [4, 5, 6] ]) y = np.array([2, 2]) print(x, x.shape) print(y, y.shape)
[[1 2 3] [4 5 6]] (2, 3) [2 2] (2,)
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Transpose Approach
xT = x.T print(xT) xTw = xT + y print(xTw) x = xTw.T print(x)
[[3 4 5] [6 7 8]]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Transpose approach in one line
print( (x.T + y).T )
[[3 4 5] [6 7 8]]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
Reshape Approach
print(y, y.shape, y.ndim) y = np.reshape(y, (2, 1)) print(y, y.shape, y.ndim) print(x + y)
[[3 4 5] [6 7 8]]
MIT
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV