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 new numerical featureCreate synthetic column, strongly correlated with target.Each value is calculated according to the formula: v = y * a + random(-b, b) So its scaled target value with some noise.Then a fraction of values is permuted, to reduce the correlation.In this case, a=10, b=5, fraction=0.05
if 'new_feature' in df.columns: df.pop('new_feature') new_feature, corr = create_numerical_feature_classification(y, fraction=0.05, seed=SEED, verbose=True) df = pd.concat([pd.Series(new_feature, name='new_feature'), df], axis=1) plt.scatter(new_feature, y, alpha=0.3) plt.xlabel('Feature value') plt.ylabel('Targe...
Initial new feature - target point biserial correlation, without shuffling: 0.878, p: 0.0 New feature - target point biserial correlation, after shuffling: 0.849, p: 0.0
BSD-3-Clause
examples/bias/Bias.ipynb
dabrze/similarity_forest
Random Forest feature importanceRandom Forest offers a simple way to measure feature importance. A certain feature is considered to be important if it reduced node impurity often, during fitting the trees.We can see that adding a feature strongly correlated with target improved the model's performance, compared to res...
X_train, X_test, y_train, y_test = train_test_split( df, y, test_size=0.3, random_state=SEED) scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) rf = RandomForestClassifier(random_state=SEED) rf.fit(X_train, y_train) rf_pred = rf.predict(X_test) print(f'Random Fore...
Random Forest f1 score: 0.985
BSD-3-Clause
examples/bias/Bias.ipynb
dabrze/similarity_forest
Permutation feature importanceThe impurity-based feature importance of Random Forests suffers from being computed on statistics derived from the training dataset: the importances can be high even for features that are not predictive of the target variable, as long as the model has the capacity to use them to overfit.F...
sf = SimilarityForestClassifier(n_estimators=100, random_state=SEED).fit(X_train, y_train) perm_importance_results = get_permutation_importances(rf, sf, X_train, y_train, X_test, y_test, corr, df.columns.value...
19it [31:09, 98.37s/it]
BSD-3-Clause
examples/bias/Bias.ipynb
dabrze/similarity_forest
New categorical feature
if 'new_feature' in df.columns: df.pop('new_feature') new_feature, corr = create_categorical_feature_classification(y, fraction=0.05, seed=SEED, verbose=True) df = pd.concat([pd.Series(new_feature, name='new_feature'), df], axis=1) df_category = pd.concat([pd.Series(new_feature, name='new_feature'), pd.Series(y, ...
19it [26:26, 83.49s/it]
BSD-3-Clause
examples/bias/Bias.ipynb
dabrze/similarity_forest
Regression, numerical feature
X, y = load_svmlight_file('data/mpg') X = X.toarray().astype(np.float32) features = [f'f{i+1}' for i in range(X.shape[1])] df = pd.DataFrame(X, columns=features) df.head() if 'new_feature' in df.columns: df.pop('new_feature') new_feature, corr = create_numerical_feature_regression(y, fraction=0.2, seed=SEED, verb...
19it [42:41, 134.82s/it]
BSD-3-Clause
examples/bias/Bias.ipynb
dabrze/similarity_forest
Regression, categorical feature
if 'new_feature' in df.columns: df.pop('new_feature') new_feature, corr = create_categorical_feature_regression(y, fraction=0.15, seed=SEED, verbose=True) df = pd.concat([pd.Series(new_feature, name='new_feature'), df], axis=1) plt.scatter(new_feature, y, alpha=0.3) plt.xlabel('Feature value') plt.ylabel('Target'...
19it [46:58, 148.33s/it]
BSD-3-Clause
examples/bias/Bias.ipynb
dabrze/similarity_forest
Heap MapsA heat map is a two-dimensional representation of data in which values are represented by colors. A simple heat map provides an immediate visual summary of information.
from beakerx import * data = [[533.08714795974, 484.92105712087596, 451.63070008303896, 894.4451947886148, 335.44965728686225, 640.9424094527392, 776.2709495045433, 621.8819257981404, 793.2905673902735, 328.97078791524234, 139.26962328268513, 800.9314566259062, 629.0795214099808, 418.90954534196544, 513.8036215...
_____no_output_____
Apache-2.0
doc/python/Heatmap.ipynb
ssadedin/beakerx
Copyright 2019 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
MIT
Course2Part4Lesson4.ipynb
MBadriNarayanan/TensorFlow
Building a Small Model from ScratchBut before we continue, let's start defining the model:Step 1 will be to import tensorflow.
import tensorflow as tf
_____no_output_____
MIT
Course2Part4Lesson4.ipynb
MBadriNarayanan/TensorFlow
We then add convolutional layers as in the previous example, and flatten the final result to feed into the densely connected layers. Finally we add the densely connected layers. Note that because we are facing a two-class classification problem, i.e. a *binary classification problem*, we will end our network with a [*s...
model = tf.keras.models.Sequential([ # Note the input shape is the desired size of the image 300x300 with 3 bytes color # This is the first convolution tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(300, 300, 3)), tf.keras.layers.MaxPooling2D(2, 2), # The second convolution tf...
_____no_output_____
MIT
Course2Part4Lesson4.ipynb
MBadriNarayanan/TensorFlow
Adversarial Examples Let's start out by importing all the required libraries
import os import sys sys.path.append(os.path.join(os.getcwd(), "venv")) import numpy as np import torch import torchvision.transforms as transforms from matplotlib import pyplot as plt from torch import nn from torch.autograd import Variable from torch.utils.data import DataLoader from torchvision.datasets import MN...
_____no_output_____
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
MNIST Pytorch expects `Dataset` objects as input. Luckily, for MNIST (and few other datasets such as CIFAR and SVHN), torchvision has a ready made function to convert the dataset to a pytorch `Dataset` object. Keep in mind that these functions return `PIL` images so you will have to apply a transformation on them.
path = os.path.join(os.getcwd(), "MNIST") transform = transforms.Compose([transforms.ToTensor()]) train_mnist = MNIST(path, train=True, transform=transform) test_mnist = MNIST(path, train=False, transform=transform)
_____no_output_____
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
Visualize Dataset Set `batch_size` to 1 to visualize the dataset.
batch_size = 1 train_set = DataLoader(train_mnist, batch_size=batch_size, shuffle=True) test_set = DataLoader(test_mnist, batch_size=batch_size, shuffle=True) num_images = 2 for i, (image, label) in enumerate(train_set): if i == num_images: break #Pytorch returns batch_size x num_channels x 28 x 28 ...
_____no_output_____
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
Train a Model Set `batch_size` to start training a model on the dataset.
batch_size = 64 train_set = DataLoader(train_mnist, batch_size=batch_size, shuffle=True)
_____no_output_____
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
Define a `SimpleCNN` model to train on MNIST
def identity(): return lambda x: x class CustomConv2D(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, activation, stride): super().__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size-2) self.activation = a...
_____no_output_____
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
Create 4 model variations: identity_model: SimpleCNN model with identity activation functions relu_model: SimpleCNN model with relu activation functions sig_model: SimpleCNN model with sigmoid activation functions tanh_model: SimpleCNN model with tanh activation functions
identity_model = SimpleCNN() relu_model = SimpleCNN(activation=nn.ReLU()) sig_model = SimpleCNN(activation=nn.Sigmoid()) tanh_model = SimpleCNN(activation=nn.Tanh())
_____no_output_____
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
Create a function to train the model
def train_model(model, train_set, num_epochs): optimizer = torch.optim.Adam(lr=0.001, params=model.parameters()) for epoch in range(num_epochs): epoch_accuracy, epoch_loss = 0, 0 train_set_size = 0 for images, labels in train_set: batch_size = images.size(0) image...
epoch 1: loss= 1.86, accuracy= 35.7 epoch 2: loss= 1.49, accuracy= 49.69 epoch 3: loss= 1.44, accuracy= 51.29 epoch 4: loss= 1.4, accuracy= 52.41 epoch 5: loss= 1.37, accuracy= 53.35 epoch 6: loss= 1.34, accuracy= 54.23 epoch 7: loss= 1.32, accuracy= 54.97 epoch 8: loss= 1.3, accuracy= 55.83 epoch 9: loss= 1.29, accura...
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
Generating Adversarial Examples Now that we have a trained model, we can generate adversarial examples. Gradient Ascent Use Gradient Ascent to generate a targeted adversarial example.
def np_val(torch_var): return torch_var.data.numpy()[0] class AttackNet(nn.Module): def __init__(self, model, image_size): super().__init__() self.model = model self.params = nn.Parameter(torch.zeros(image_size), requires_grad=True) def forward(self, image): # clamp parame...
_____no_output_____
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
Define a `GradientAscent` object
gradient_ascent = GradientAscent(trained_model)
_____no_output_____
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
Define a function to help plot the results
%matplotlib inline def plot_results(image, perturbation, orig_pred, orig_con, adv_pred, adv_con): plot_image = image.numpy()[0][0] plot_perturbation = perturbation.data.numpy()[0][0] fig_size = plt.rcParams["figure.figsize"] fig_size[0] = 10 fig_size[1] = 5 plt.rcParams["figure.figsize"] =...
_____no_output_____
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
Let's generate some adversarial examples!
num_images = 2 for i, (test_image, test_label) in enumerate(test_set): if i == num_images: break target_classes = list(range(10)) target_classes.remove(test_label.numpy()[0]) target = np.random.choice(target_classes) perturbation, (orig_con, orig_pred), ( adv_con, adv_pred) = gradie...
Adversarial attack succeeded after 3 steps!
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
Fast Gradient Now let's use the Fast Gradient Sign Method to generate untargeted adversarial examples.
class FastGradient(object): def __init__(self, model, confidence=0, alpha=0.1): super().__init__() self.model = model self.confidence = confidence self.alpha = alpha def attack(self, image, label): image_var = Variable(image, requires_grad=True) target = Variable...
_____no_output_____
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
Define a `FastGradient` object
fast_gradient = FastGradient(trained_model)
_____no_output_____
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
Let's generate some adversarial examples!
num_images = 20 for i, (test_image, test_label) in enumerate(test_set): if i == num_images: break perturbation, (orig_con, orig_pred), ( adv_con, adv_pred) = fast_gradient.attack(test_image, test_label) if perturbation is not None: plot_results(test_image, perturbation, orig_pred, o...
Adversarial attack failed
MIT
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
Introduccion a la Inteligencia Artificial Veremos dos ejercicios con para entender el concepto de inteligencia artificial Objeto Rebotador En el siguiente ejercicio, realizaremos un objeto que al chocar con una de las paredes, este cambie de direccion y siga con su camino
!pip3 install ColabTurtle
_____no_output_____
MIT
day_1/Actividad_02.ipynb
Fhrozen/2021_clubes_ciencia_speech
Llamamos las librerias
import ColabTurtle.Turtle as robot import random
_____no_output_____
MIT
day_1/Actividad_02.ipynb
Fhrozen/2021_clubes_ciencia_speech
Ahora el codigo principal. De momento el robot rebota y vuelve en la misma dirección.Lo que tienes que hacer es poner un inicio aleatorio y modificar el `if` dentro del lazo `while` de manera que este cambie en un solo eje.
robot.initializeTurtle(initial_speed=1) pad = 15 max_w = robot.window_width() - pad max_h = robot.window_height() - pad robot.shape("circle") robot.color("green") robot.penup() robot.goto(0 + pad, 200) robot.dx = 10 # Velociad en x robot.dy = 10 # Velociad en y reflections = 0 # El numero de reflexiones puede se...
_____no_output_____
MIT
day_1/Actividad_02.ipynb
Fhrozen/2021_clubes_ciencia_speech
ChatBot Para el siguiente ejercicio, utilizaremos un ChatBot con definido por reglas. (Ejemplo tomado de: https://www.analyticsvidhya.com/blog/2021/07/build-a-simple-chatbot-using-python-and-nltk/)
!pip install nltk import nltk from nltk.chat.util import Chat, reflections
_____no_output_____
MIT
day_1/Actividad_02.ipynb
Fhrozen/2021_clubes_ciencia_speech
**Chat**: es la clase que contiene toda lo logica para processar el texto que el chatbot recibe y encontrar informacion util.**reflections**: es un diccionario que contiene entradas basica y sus correspondientes salidas.
print(reflections)
_____no_output_____
MIT
day_1/Actividad_02.ipynb
Fhrozen/2021_clubes_ciencia_speech
Comenzemos contruyendo las reglas. Las siguientes lineas generan un conjunto de reglas simples.
pairs = [ [ r"my name is (.*)", ["Hello %1, How are you today ?",] ], [ r"hi|hey|hello", ["Hello", "Hey there",] ], [ r"what is your name ?", ["I am a bot created by Analytics Vidhya. you can call me crazy!",] ], [ r"how are you ?", ...
_____no_output_____
MIT
day_1/Actividad_02.ipynb
Fhrozen/2021_clubes_ciencia_speech
Después de definir las reglas, definimos la función para ejecutar el proceso de chat.
def chat(this_creator='Nelson Yalta'): print(f"Hola!!! Yo soy un chatbot creado por {this_creator}, y estoy listo para sus servicios. Recuede que hablo inglés.") chat = Chat(pairs, reflections) chat.converse() chat()
_____no_output_____
MIT
day_1/Actividad_02.ipynb
Fhrozen/2021_clubes_ciencia_speech
Pi Estimation Using Monte Carlo In this exercise, we will use MapReduce and a Monte-Carlo-Simulation to estimate $\Pi$.If we are looking at this image from this [blog](https://towardsdatascience.com/how-to-make-pi-part-1-d0b41a03111f), we see a unit circle in a unit square:![Circle_Box](https://miro.medium.com/max/700...
%%writefile pi.py #!/usr/bin/python3 from mrjob.job import MRJob from random import uniform class MyJob(MRJob): def mapper(self, _, line): for x in range(100): x = uniform(-1,1) y = uniform(-1,1) in_circle = x*x + y*y <=1 yield None, in_c...
_____no_output_____
MIT
V3/v3_exercises_material/solutions/4_Pi-Estimation/Pi_Solution.ipynb
fred1234/BDLC_FS22
Another ApproachComputing the mean in the mapper
%%writefile pi.py #!/usr/bin/python3 from mrjob.job import MRJob from random import uniform class MyJob(MRJob): def mapper(self, _, line): num_samples = 100 in_circles_list = [] for x in range(num_samples): x = uniform(-1,1) y = uniform(-1,1) ...
_____no_output_____
MIT
V3/v3_exercises_material/solutions/4_Pi-Estimation/Pi_Solution.ipynb
fred1234/BDLC_FS22
Running the JobUnfortunately, the library does not work without an input file. I guess this comes from the fact that the hadoop streaming library also does not support this feature, see [stack overflow](https://stackoverflow.com/questions/22821005/hadoop-streaming-job-with-no-input-file).We fake the number of mappers ...
!python pi.py /data/dataset/text/small.txt !python pi.py /data/dataset/text/holmes.txt
_____no_output_____
MIT
V3/v3_exercises_material/solutions/4_Pi-Estimation/Pi_Solution.ipynb
fred1234/BDLC_FS22
Download and prepare the MS-COCO datasetYou will use the [MS-COCO dataset](http://cocodataset.org/home) to train our model. The dataset contains over 82,000 images, each of which has at least 5 different caption annotations. The code below downloads and extracts the dataset automatically.**Caution: large download ahea...
# Download caption annotation files annotation_folder = '/annotations/' if not os.path.exists(os.path.abspath('.') + annotation_folder): annotation_zip = tf.keras.utils.get_file('captions.zip', cache_subdir=os.path.abspath('.'), origi...
_____no_output_____
Apache-2.0
train_captioning_model.ipynb
sidphbot/visual-to-audio-aid-for-visually-impaired
Preprocess the images using InceptionV3Next, you will use InceptionV3 (which is pretrained on Imagenet) to classify each image. You will extract features from the last convolutional layer.First, you will convert the images into InceptionV3's expected format by:* Resizing the image to 299px by 299px* [Preprocess the im...
def load_image(image_path): img = tf.io.read_file(image_path) img = tf.image.decode_jpeg(img, channels=3) img = tf.image.resize(img, (299, 299)) img = tf.keras.applications.inception_v3.preprocess_input(img) return img, image_path
_____no_output_____
Apache-2.0
train_captioning_model.ipynb
sidphbot/visual-to-audio-aid-for-visually-impaired
Initialize InceptionV3 and load the pretrained Imagenet weightsNow you'll create a tf.keras model where the output layer is the last convolutional layer in the InceptionV3 architecture. The shape of the output of this layer is ```8x8x2048```. You use the last convolutional layer because you are using attention in this...
image_model = tf.keras.applications.InceptionV3(include_top=False, weights='imagenet') new_input = image_model.input hidden_layer = image_model.layers[-1].output image_features_extract_model = tf.keras.Model(new_input, hidden_layer)
_____no_output_____
Apache-2.0
train_captioning_model.ipynb
sidphbot/visual-to-audio-aid-for-visually-impaired
Caching the features extracted from InceptionV3You will pre-process each image with InceptionV3 and cache the output to disk. Caching the output in RAM would be faster but also memory intensive, requiring 8 \* 8 \* 2048 floats per image. At the time of writing, this exceeds the memory limitations of Colab (currently 1...
# Get unique images encode_train = sorted(set(img_name_vector)) # Feel free to change batch_size according to your system configuration image_dataset = tf.data.Dataset.from_tensor_slices(encode_train) image_dataset = image_dataset.map( load_image, num_parallel_calls=tf.data.experimental.AUTOTUNE).batch(16) for img,...
_____no_output_____
Apache-2.0
train_captioning_model.ipynb
sidphbot/visual-to-audio-aid-for-visually-impaired
Preprocess and tokenize the captions* First, you'll tokenize the captions (for example, by splitting on spaces). This gives us a vocabulary of all of the unique words in the data (for example, "surfing", "football", and so on).* Next, you'll limit the vocabulary size to the top 5,000 words (to save memory). You'll re...
# Find the maximum length of any caption in our dataset def calc_max_length(tensor): return max(len(t) for t in tensor) # Choose the top 5000 words from the vocabulary top_k = 5000 tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=top_k, oov_token="<unk>",...
_____no_output_____
Apache-2.0
train_captioning_model.ipynb
sidphbot/visual-to-audio-aid-for-visually-impaired
Split the data into training and testing
# Create training and validation sets using an 80-20 split img_name_train, img_name_val, cap_train, cap_val = train_test_split(img_name_vector, cap_vector, test_size=0.2, ...
_____no_output_____
Apache-2.0
train_captioning_model.ipynb
sidphbot/visual-to-audio-aid-for-visually-impaired
Create a tf.data dataset for training
# Feel free to change these parameters according to your system's configuration BATCH_SIZE = 64 BUFFER_SIZE = 1000 embedding_dim = 256 units = 512 vocab_size = top_k + 1 num_steps = len(img_name_train) // BATCH_SIZE # Shape of the vector extracted from InceptionV3 is (64, 2048) # These two variables represent that vec...
_____no_output_____
Apache-2.0
train_captioning_model.ipynb
sidphbot/visual-to-audio-aid-for-visually-impaired
ModelFun fact: the decoder below is identical to the one in the example for [Neural Machine Translation with Attention](../sequences/nmt_with_attention.ipynb).The model architecture is inspired by the [Show, Attend and Tell](https://arxiv.org/pdf/1502.03044.pdf) paper.* In this example, you extract the features from t...
class BahdanauAttention(tf.keras.Model): def __init__(self, units): super(BahdanauAttention, self).__init__() self.W1 = tf.keras.layers.Dense(units) self.W2 = tf.keras.layers.Dense(units) self.V = tf.keras.layers.Dense(1) def call(self, features, hidden): # features(CNN_encoder output) shape ==...
_____no_output_____
Apache-2.0
train_captioning_model.ipynb
sidphbot/visual-to-audio-aid-for-visually-impaired
Checkpoint
checkpoint_path = "/gdrive/My Drive/checkpoints/train" if not os.path.exists(checkpoint_path): os.mkdir(checkpoint_path) ckpt = tf.train.Checkpoint(encoder=encoder, decoder=decoder, optimizer = optimizer) ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_...
_____no_output_____
Apache-2.0
train_captioning_model.ipynb
sidphbot/visual-to-audio-aid-for-visually-impaired
Training* You extract the features stored in the respective `.npy` files and then pass those features through the encoder.* The encoder output, hidden state(initialized to 0) and the decoder input (which is the start token) is passed to the decoder.* The decoder returns the predictions and the decoder hidden state.* T...
# adding this in a separate cell because if you run the training cell # many times, the loss_plot array will be reset loss_plot = [] @tf.function def train_step(img_tensor, target): loss = 0 # initializing the hidden state for each batch # because the captions are not related from image to image hidden = decod...
_____no_output_____
Apache-2.0
train_captioning_model.ipynb
sidphbot/visual-to-audio-aid-for-visually-impaired
Predict stateHere is the current implementation of the `predict_state` function. It takes in a state (a Python list), and then separates those into position and velocity to calculate a new, predicted state. It uses a constant velocity motion model.**In this exercise, we'll be improving this function, and using matrix ...
# The current predict state function # Predicts the next state based on a motion model def predict_state(state, dt): # Assumes a valid state had been passed in x = state[0] velocity = state[1] # Assumes a constant velocity model new_x = x + velocity*dt # Create and return the new, pred...
_____no_output_____
MIT
Object Tracking and Localization/Representing State and Motion/Matrix Multiplication/Matrix_Multiplication.ipynb
brand909/Computer-Vision
Matrix operationsYou've been given a matrix class that can create new matrices and performs one operation: multiplication. In our directory this is called `matrix.py`.Similar to the Car class, we can use this to initialize matrix objects.
# import the matrix file import matrix # Initialize a state vector initial_position = 0 # meters velocity = 50 # m/s # Notice the syntax for creating a state column vector ([ [x], [v] ]) # Commas separate these items into rows and brackets into columns initial_state = matrix.Matrix([ [initial_position], ...
_____no_output_____
MIT
Object Tracking and Localization/Representing State and Motion/Matrix Multiplication/Matrix_Multiplication.ipynb
brand909/Computer-Vision
Transformation matrixNext, define the state transformation matrix and print it out!
# Define the state transformation matrix dt = 1 tx_matrix = matrix.Matrix([ [1, dt], [0, 1] ]) print(tx_matrix)
[[1 1 ] [0 1 ] ]
MIT
Object Tracking and Localization/Representing State and Motion/Matrix Multiplication/Matrix_Multiplication.ipynb
brand909/Computer-Vision
TODO: Modify the predict state function to use matrix multiplicationNow that you know how to create matrices, modify the `predict_state` function to work with them!Note: you can multiply a matrix A by a matrix B by writing `A*B` and it will return a new matrix.
# The current predict state function def predict_state_mtx(state, dt): ## TODO: Assume that the state passed in is a Matrix object ## Using a constant velocity model and a transformation matrix ## Create and return the new, predicted state! tx_matrix = matrix.Matrix([ [1, dt], ...
_____no_output_____
MIT
Object Tracking and Localization/Representing State and Motion/Matrix Multiplication/Matrix_Multiplication.ipynb
brand909/Computer-Vision
Test cellHere is an initial state vector and dt to test your function with!
# initial state variables initial_position = 10 # meters velocity = 30 # m/s # Initial state vector initial_state = matrix.Matrix([ [initial_position], [velocity] ]) print('The initial state is: ' + str(initial_state)) # after 2 seconds make a prediction using the new function stat...
State after 3 more seconds is: [[160.0 ] [30.0 ] ] Final state after 3 more seconds is: [[250.0 ] [30.0 ] ]
MIT
Object Tracking and Localization/Representing State and Motion/Matrix Multiplication/Matrix_Multiplication.ipynb
brand909/Computer-Vision
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
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
Simple TFX Pipeline Tutorial using Penguin dataset***A Short tutorial to run a simple TFX pipeline.*** Note: We recommend running this tutorial in a Colab notebook, with no setup required! Just click "Run in Google Colab".View on TensorFlow.orgRun in Google ColabView source on GitHubDownload notebook In this notebook...
try: import colab !pip install --upgrade pip except: pass
_____no_output_____
Apache-2.0
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
Install TFX
!pip install -U tfx
_____no_output_____
Apache-2.0
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
Did you restart the runtime?If you are using Google Colab, the first time that you runthe cell above, you must restart the runtime by clickingabove "RESTART RUNTIME" button or using "Runtime > Restartruntime ..." menu. This is because of the way that Colabloads packages. Check the TensorFlow and TFX versions.
import tensorflow as tf print('TensorFlow version: {}'.format(tf.__version__)) from tfx import v1 as tfx print('TFX version: {}'.format(tfx.__version__))
_____no_output_____
Apache-2.0
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
Set up variablesThere are some variables used to define a pipeline. You can customize thesevariables as you want. By default all output from the pipeline will begenerated under the current directory.
import os PIPELINE_NAME = "penguin-simple" # Output directory to store artifacts generated from the pipeline. PIPELINE_ROOT = os.path.join('pipelines', PIPELINE_NAME) # Path to a SQLite DB file to use as an MLMD storage. METADATA_PATH = os.path.join('metadata', PIPELINE_NAME, 'metadata.db') # Output directory where c...
_____no_output_____
Apache-2.0
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
Prepare example dataWe will download the example dataset for use in our TFX pipeline. The dataset weare using is[Palmer Penguins dataset](https://allisonhorst.github.io/palmerpenguins/articles/intro.html)which is also used in other[TFX examples](https://github.com/tensorflow/tfx/tree/master/tfx/examples/penguin).There...
import urllib.request import tempfile DATA_ROOT = tempfile.mkdtemp(prefix='tfx-data') # Create a temporary directory. _data_url = 'https://raw.githubusercontent.com/tensorflow/tfx/master/tfx/examples/penguin/data/penguins_processed.csv' _data_filepath = os.path.join(DATA_ROOT, "data.csv") urllib.request.urlretrieve(_...
_____no_output_____
Apache-2.0
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
Take a quick look at the CSV file.
!head {_data_filepath}
_____no_output_____
Apache-2.0
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
You should be able to see five values. `species` is one of 0, 1 or 2, and allother features should have values between 0 and 1. Create a pipelineTFX pipelines are defined using Python APIs. We will define a pipeline whichconsists of following three components.- CsvExampleGen: Reads in data files and convert them to TF...
_trainer_module_file = 'penguin_trainer.py' %%writefile {_trainer_module_file} from typing import List from absl import logging import tensorflow as tf from tensorflow import keras from tensorflow_transform.tf_metadata import schema_utils from tfx import v1 as tfx from tfx_bsl.public import tfxio from tensorflow_meta...
_____no_output_____
Apache-2.0
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
Now you have completed all preparation steps to build a TFX pipeline. Write a pipeline definitionWe define a function to create a TFX pipeline. A `Pipeline` objectrepresents a TFX pipeline which can be run using one of pipelineorchestration systems that TFX supports.
def _create_pipeline(pipeline_name: str, pipeline_root: str, data_root: str, module_file: str, serving_model_dir: str, metadata_path: str) -> tfx.dsl.Pipeline: """Creates a three component penguin pipeline with TFX.""" # Brings data into the pipeline. example_gen = tfx.co...
_____no_output_____
Apache-2.0
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
Run the pipelineTFX supports multiple orchestrators to run pipelines.In this tutorial we will use `LocalDagRunner` which is included in the TFXPython package and runs pipelines on local environment.We often call TFX pipelines "DAGs" which stands for directed acyclic graph.`LocalDagRunner` provides fast iterations for ...
tfx.orchestration.LocalDagRunner().run( _create_pipeline( pipeline_name=PIPELINE_NAME, pipeline_root=PIPELINE_ROOT, data_root=DATA_ROOT, module_file=_trainer_module_file, serving_model_dir=SERVING_MODEL_DIR, metadata_path=METADATA_PATH))
_____no_output_____
Apache-2.0
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
You should see "INFO:absl:Component Pusher is finished." at the end of thelogs if the pipeline finished successfully. Because `Pusher` component is thelast component of the pipeline.The pusher component pushes the trained model to the `SERVING_MODEL_DIR` whichis the `serving_model/penguin-simple` directory if you did n...
# List files in created model directory. !find {SERVING_MODEL_DIR}
_____no_output_____
Apache-2.0
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
Using a Different Corpuszh_segment makes it easy to use a different corpus for word segmentation.If you simply want to "teach" the algorithm a single phrase it doesn't know then read [this StackOverflow answer](http://stackoverflow.com/questions/20695825/english-word-segmentation-in-nlp).Now, let's get a new corpus. F...
import requests response = requests.get('https://www.gutenberg.org/ebooks/1342.txt.utf-8') text = response.text print len(text)
717573
Apache-2.0
docs/using-a-different-corpus.ipynb
wuhaifengdhu/zh_segment
Great. We've got a new corpus for `zh_segment`. Now let's look at what parts of the API we need to change. There's one function and two dictionaries: `zh_segment.clean`, `zh_segment.bigram_counts` and `zh_segment.unigram_counts`. We'll work on these in reverse.
import zh_segment print type(zh_segment.unigram_counts), type(zh_segment.bigram_counts) print zh_segment.unigram_counts.items()[:3] print zh_segment.bigram_counts.items()[:3]
[('biennials', 37548.0), ('verplank', 48349.0), ('tsukino', 19771.0)] [('personal effects', 151369.0), ('basic training', 294085.0), ('it absolutely', 130505.0)]
Apache-2.0
docs/using-a-different-corpus.ipynb
wuhaifengdhu/zh_segment
Ok, so `zh_segment.unigram_counts` is just a dictionary mapping unigrams to their counts. Let's write a method to tokenize our text.
import re def tokenize(text): pattern = re.compile('[a-zA-Z]+') return (match.group(0) for match in pattern.finditer(text)) print list(tokenize("Wait, what did you say?"))
['Wait', 'what', 'did', 'you', 'say']
Apache-2.0
docs/using-a-different-corpus.ipynb
wuhaifengdhu/zh_segment
Now we'll build our dictionaries.
from collections import Counter zh_segment.unigram_counts = Counter(tokenize(text)) def pairs(iterable): iterator = iter(iterable) values = [next(iterator)] for value in iterator: values.append(value) yield ' '.join(values) del values[0] zh_segment.bigram_counts = Counter(pairs(to...
_____no_output_____
Apache-2.0
docs/using-a-different-corpus.ipynb
wuhaifengdhu/zh_segment
That's it.Now, by default, `zh_segment.segment` lowercases all input and removes punctuation. In our corpus we have capitals so we'll also have to change the `clean` function. Our heaviest hammer is to simply replace it with the identity function. This will do no sanitation of the input to `segment`.
def identity(value): return value zh_segment.clean = identity zh_segment.segment('wantofawife')
_____no_output_____
Apache-2.0
docs/using-a-different-corpus.ipynb
wuhaifengdhu/zh_segment
If you find this behaves poorly then you may need to change the `zh_segment.TOTAL` variable to reflect the total of all unigrams. In our case that's simply:
zh_segment.TOTAL = float(sum(zh_segment.unigram_counts.values()))
_____no_output_____
Apache-2.0
docs/using-a-different-corpus.ipynb
wuhaifengdhu/zh_segment
zh_segment doesn't require any fancy machine learning training algorithms. Simply update the unigram and bigram count dictionaries and you're ready to go.
_____no_output_____
Apache-2.0
docs/using-a-different-corpus.ipynb
wuhaifengdhu/zh_segment
Checking Container Dwell TimesThis works with the CSV export of ConFlowGen. Import libraries
import os import pathlib import ipywidgets as widgets import pandas as pd from IPython.display import Markdown import matplotlib.pyplot as plt from matplotlib import gridspec
_____no_output_____
MIT
example-usage/Jupyter Notebook/output data inspection/checking container dwell times.ipynb
1grasse/conflowgen
Select input data
folder_of_this_jupyter_notebook = pathlib.Path.cwd() export_folder = os.path.join( folder_of_this_jupyter_notebook, os.pardir, os.pardir, os.pardir, "conflowgen", "data", "exports" ) folders = [ folder for folder in os.listdir(export_folder) if os.path.isdir( os.path.join...
_____no_output_____
MIT
example-usage/Jupyter Notebook/output data inspection/checking container dwell times.ipynb
1grasse/conflowgen
Load containers
path_to_containers = os.path.join( path_to_selected_exported_content, "containers.csv" ) print(f"Opening {path_to_containers}") df_containers = pd.read_csv(path_to_containers, index_col="id", dtype={ "delivered_by_truck": "Int64", "picked_up_by_truck": "Int64", "delivered_by_large_scheduled_vehicle"...
_____no_output_____
MIT
example-usage/Jupyter Notebook/output data inspection/checking container dwell times.ipynb
1grasse/conflowgen
Check number of large scheduled vehicles (deep sea vessels, feeders, barges, and trains).
df_containers.groupby(by="delivered_by_large_scheduled_vehicle").count()
_____no_output_____
MIT
example-usage/Jupyter Notebook/output data inspection/checking container dwell times.ipynb
1grasse/conflowgen
Load scheduled vehiclesLoad the vehicles to enrich the information regarding the arrival and departure of the containers.
path_to_deep_sea_vessels = os.path.join( path_to_selected_exported_content, "deep_sea_vessels.csv" ) path_to_feeders = os.path.join( path_to_selected_exported_content, "feeders.csv" ) path_to_barges = os.path.join( path_to_selected_exported_content, "barges.csv" ) path_to_trains = os.path.joi...
_____no_output_____
MIT
example-usage/Jupyter Notebook/output data inspection/checking container dwell times.ipynb
1grasse/conflowgen
Plot arrival pattern.
plt.figure(figsize=(15, 3)) x, y, z = [], [], [] y_axis = [] y_scaling_factor = 2 for i, (name, df) in enumerate(scheduled_vehicle_dfs.items()): y_axis.append((i/y_scaling_factor, name)) if len(df) == 0: continue arrivals_and_capacity = df[["scheduled_arrival", "moved_capacity"]] for _, row i...
_____no_output_____
MIT
example-usage/Jupyter Notebook/output data inspection/checking container dwell times.ipynb
1grasse/conflowgen
Transform data to check how many containers are delivered and picked up by which vehicle.
vehicle_to_teu_to_deliver = {} vehicle_to_teu_to_pickup = {} for i, container in df_containers.iterrows(): teu = container["length"] / 20 assert 1 <= teu <= 2.5 if container["delivered_by"] != "truck": vehicle = container["delivered_by_large_scheduled_vehicle"] if vehicle not in vehicle_to...
_____no_output_____
MIT
example-usage/Jupyter Notebook/output data inspection/checking container dwell times.ipynb
1grasse/conflowgen
Add transformed data to vehicles.
s_delivery = pd.Series(vehicle_to_teu_to_deliver) s_pickup = pd.Series(vehicle_to_teu_to_pickup) df_large_scheduled_vehicle["capacity_delivery"] = s_delivery df_large_scheduled_vehicle["capacity_pickup"] = s_pickup df_large_scheduled_vehicle for large_scheduled_vehicle_id in df_large_scheduled_vehicle.index: delive...
_____no_output_____
MIT
example-usage/Jupyter Notebook/output data inspection/checking container dwell times.ipynb
1grasse/conflowgen
Load trucks
path_to_trucks = os.path.join( path_to_selected_exported_content, "trucks.csv" ) assert os.path.isfile(path_to_trucks) df_truck = pd.read_csv( path_to_trucks, index_col=0, parse_dates=[ # Pickup "planned_container_pickup_time_prior_berthing", "realized_container_pickup_time", ...
_____no_output_____
MIT
example-usage/Jupyter Notebook/output data inspection/checking container dwell times.ipynb
1grasse/conflowgen
This is the probability of the truck to show up at any given hour of the week (by index).
delivered_and_picked_up_by_large_vessels_df = df_containers.loc[ ~pd.isna(df_containers["picked_up_by_large_scheduled_vehicle"]) ].join( df_large_scheduled_vehicle, on="picked_up_by_large_scheduled_vehicle", rsuffix="_picked_up" ).loc[ ~pd.isna(df_containers["delivered_by_large_scheduled_vehicle"]) ].join( ...
_____no_output_____
MIT
example-usage/Jupyter Notebook/output data inspection/checking container dwell times.ipynb
1grasse/conflowgen
2019 Formula One World Championship A Formula One season consists of a series of races, known as Grands Prix (French for ''grand prizes' or 'great prizes''), which take place worldwide on purpose-built circuits and on public roads. The results of each race are evaluated using a points system to determine two annu...
#A Probability Distribution; an {outcome: probability} mapping. # Make probabilities sum to 1.0; assert no negative probabilities class ProbDist(dict): """A Probability Distribution; an {outcome: probability} mapping.""" def __init__(self, mapping=(), **kwargs): self.update(mapping, **kwargs) ...
_____no_output_____
MIT
Formula One World Championship Analysis.ipynb
mbadamve/Machine-Learning-projects
Question Set 1what is the Probability Distribution for each F1 driver to win the Singaporean Grand Prix? What is the Probability Distribution for each F1 driver to win both the Singaporean and Russian Grand Prix?What is the probability for Mercedes to win both races?What is the probability for Mercedes to win at least...
SGP = ProbDist(LH=284,VB=221,CL=182,MV=185,SV=169,PG=65,CS=58,AA=34,DR=34,DK=33,NH=31,LN=25,KR=31,SP=27,LS=19,KM=18,RG=8,AG=3,RK=1, GR=0) print ("The probability of each driver winnning Singaporean Grand Prix ") SGP #Driver standing divided by / total of all driver standings, SGP returns total probability as 1
The probability of each driver winnning Singaporean Grand Prix
MIT
Formula One World Championship Analysis.ipynb
mbadamve/Machine-Learning-projects
2. What is the Probability Distribution for each F1 driver to win both the Singaporean and Russian Grand Prix?
SGP = ProbDist( LH=284,VB=221,CL=182,MV=185,SV=169,PG=65,CS=58,AA=34,DR=34,DK=33,NH=31,LN=25,KR=31,SP=27,LS=19,KM=18, RG=8,AG=3,RK=1,GR=0) # data taken on saturday before race starts for Singapore RGP = ProbDist( LH=296,VB=231,CL=200,MV=200,SV=194,PG=69,CS=58,AA=42,DR=34,DK=33,NH=33,LN=31,KR=31,SP=27,LS=1...
The probability of each driver winnning Singaporean Grand Prix and Russian Grand Prix
MIT
Formula One World Championship Analysis.ipynb
mbadamve/Machine-Learning-projects
3. What is the probability for Mercedes to win both races?
def mercedes_T(outcome): return outcome == "VB" or outcome == "LH" mercedesWinningSGPRace = p(mercedes_T, SGP) #calculate probability of mercedes winning Singapore Frand Pix def mercedes_T(outcome): return outcome == "VB" or outcome == "LH" mercedesWinningRGPRace = p(mercedes_T, RGP) #calculate probability of mercedes ...
The probability of mercedes winnning both the races
MIT
Formula One World Championship Analysis.ipynb
mbadamve/Machine-Learning-projects
4. What is the probability for Mercedes to win at least one race?
def p(event, space): """The probability of an event, given a sample space of outcomes. event: a collection of outcomes, or a predicate that is true of outcomes in the event. space: a set of outcomes or a probability distribution of {outcome: frequency} pairs.""" # if event is a predicate it, "un...
The probability of mercedes winnning at least one of the races
MIT
Formula One World Championship Analysis.ipynb
mbadamve/Machine-Learning-projects
Question Set 2 If Mercedes wins the first race, what is the probability that Mercedes wins the next one? If Mercedes wins at least one of these two races, what is the probability Mercedes wins both races? How about Ferrari, Red Bull, and Renault? Solution If Mercedes wins the first race, what is the probability that...
SGP = ProbDist( LH=284,VB=221,CL=182,MV=185,SV=169,PG=65,CS=58,AA=34,DR=34,DK=33,NH=31,LN=25,KR=31,SP=27,LS=19,KM=18, RG=8,AG=3,RK=1,GR=0) RGP = ProbDist( LH=296,VB=231,CL=200,MV=200,SV=194,PG=69,CS=58,AA=42,DR=34,DK=33,NH=33,LN=31,KR=31,SP=27,LS=19,KM=18, RG=8,AG=4,RK=1,GR=0) Weather = ProbDist(RA=1, ...
_____no_output_____
MIT
Formula One World Championship Analysis.ipynb
mbadamve/Machine-Learning-projects
If Ferrari wins the first race, what is the probability that Ferrari wins the next one?
def Ferrari_WinBoth(outcome): return 'CL CL' in outcome or 'CL SV' in outcome or 'SV SV' in outcome or 'SV CL' in outcome def Ferrari_Win(outcome): return 'CL' in outcome or 'SV' in outcome p(Ferrari_WinBoth, such_that(Ferrari_Win,bothSGPRGP))
_____no_output_____
MIT
Formula One World Championship Analysis.ipynb
mbadamve/Machine-Learning-projects
If RedBull wins the first race, what is the probability that RedBull wins the next one
def RedBull_WinBoth(outcome): return 'MV MV' in outcome or 'MV AA' in outcome or 'AA AA' in outcome or 'AA MV' in outcome def RedBull_Win(outcome): return 'MV' in outcome or 'AA' in outcome p(RedBull_WinBoth, such_that(RedBull_Win,bothSGPRGP))
_____no_output_____
MIT
Formula One World Championship Analysis.ipynb
mbadamve/Machine-Learning-projects
If Renault wins the first race, what is the probability that Renault wins the next one?
def Renault_WinBoth(outcome): return 'DR DR' in outcome or 'DR NH' in outcome or 'NH NH' in outcome or 'NH DR' in outcome def Renault_Win(outcome): return 'DR' in outcome or 'NH' in outcome p(Renault_WinBoth, such_that(Renault_Win,bothSGPRGP))
_____no_output_____
MIT
Formula One World Championship Analysis.ipynb
mbadamve/Machine-Learning-projects
Question Set 3Mercedes wins one of these two races on a rainy day. What is the probability Mercedes wins both races, assuming races can be held on either rainy, sunny, cloudy, snowy or foggy days? Assume that rain, sun, clouds, snow, and fog are the only possible weather conditions on race tracks. Solution Mercedes ...
#create Probability Distribution for given Weather Condtions wher p(weather) will be 0.20 GivenFiveWeatherConditons = ProbDist( RainyDay=1, SunnyDay=1, CloudyDay=1, SnowyDay=1, FoggyDay=1 ) GivenFiveWeatherConditons #perfoms joint probabilities on SGP & weather and RGP & weather probability distributions Respectively d...
_____no_output_____
MIT
Formula One World Championship Analysis.ipynb
mbadamve/Machine-Learning-projects
import pandas as pd from typing import List from datetime import datetime from random import randint from dateutil.relativedelta import * factionName: List[str] = [] systemName: List[str] = [] population: List[int] = [] influence: List[float] = [] updated: List[datetime] = [] factionName: List[str]...
_____no_output_____
BSD-3-Clause
notebooks/ANN.ipynb
HausReport/ClubRaiders
WELCOME BACK TO SACNAS' PYTHON WORKSHOP hosted by Luis and Emily Introduction:Sign in and grab food! Import the necessary libraries/packages:There are tools you can download into your code to implement. Think of these like your toolbox, to create plots, analyze data, and endless possibilities
import pandas as pd import numpy as np # visualization libraries import matplotlib.pyplot as plt
_____no_output_____
MIT
Copy_of_Workshop2Final.ipynb
feliz10/papus
Import data and assign it to a variable called tips
url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/07_Visualization/Tips/tips.csv'
_____no_output_____
MIT
Copy_of_Workshop2Final.ipynb
feliz10/papus
.describe()Generate descriptive statistics that summarize the central tendency, dispersion and shape of a dataset’s distribution, excluding NaN values.
_____no_output_____
MIT
Copy_of_Workshop2Final.ipynb
feliz10/papus
For loops a for-loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly.
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_____no_output_____
MIT
Copy_of_Workshop2Final.ipynb
feliz10/papus
Working with our datasetRecap on worksheet. What day are people more likely to tip?
_____no_output_____
MIT
Copy_of_Workshop2Final.ipynb
feliz10/papus
How can we automate a print statement using a For loop?
_____no_output_____
MIT
Copy_of_Workshop2Final.ipynb
feliz10/papus
How do we store these values?
_____no_output_____
MIT
Copy_of_Workshop2Final.ipynb
feliz10/papus
Lists, Arrays , Dictionaries
_____no_output_____
MIT
Copy_of_Workshop2Final.ipynb
feliz10/papus
Plotting a bar graphparameters are what you need inside the paranthesis for the function you are calling to work. plt.bar(x coordinate, height)
_____no_output_____
MIT
Copy_of_Workshop2Final.ipynb
feliz10/papus
Who tips more? Smokers or non smokers?
_____no_output_____
MIT
Copy_of_Workshop2Final.ipynb
feliz10/papus
Who tips more? Women or Men
_____no_output_____
MIT
Copy_of_Workshop2Final.ipynb
feliz10/papus
Plot the total_bill column using a histogram
_____no_output_____
MIT
Copy_of_Workshop2Final.ipynb
feliz10/papus