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
**Memory Stats**
import GPUtil def memory_stats(): for gpu in GPUtil.getGPUs(): print("GPU RAM Free: {0:.0f}MB | Used: {1:.0f}MB | Util {2:3.0f}% | Total {3:.0f}MB".format(gpu.memoryFree, gpu.memoryUsed, gpu.memoryUtil*100, gpu.memoryTotal)) memory_stats()
GPU RAM Free: 10721MB | Used: 267MB | Util 2% | Total 10988MB GPU RAM Free: 10988MB | Used: 1MB | Util 0% | Total 10989MB GPU RAM Free: 10988MB | Used: 1MB | Util 0% | Total 10989MB GPU RAM Free: 10988MB | Used: 1MB | Util 0% | Total 10989MB
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
**Deterministic Measurements** This statements help making the experiments reproducible by fixing the random seeds. Despite fixing the random seeds, experiments are usually not reproducible using different PyTorch releases, commits, platforms or between CPU and GPU executions. Please find more details in the PyTorch do...
SEED = 0 t.manual_seed(SEED) t.cuda.manual_seed(SEED) t.backends.cudnn.deterministic = True t.backends.cudnn.benchmark = False np.random.seed(SEED) random.seed(SEED)
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
**Loading Data** The dataset is structured in multiple small folders of 7 images each. This generator iterates through the folders and returns the category and 7 paths: one for each image in the folder. The paths are ordered; the order is important since each folder contains 3 types of images, first 5 are with acetic a...
def sortByLastDigits(elem): chars = [c for c in elem if c.isdigit()] return 0 if len(chars) == 0 else int(''.join(chars)) def getImagesPaths(root_path): for class_folder in [root_path + f for f in listdir(root_path)]: category = int(class_folder[-1]) for case_folder in listdir(class_folder): ...
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
We define 3 datasets, which load 3 kinds of images: natural images, images taken through a green lens and images where the doctor applied iodine solution (which gives a dark red color). Each dataset has dynamic and static transformations which could be applied to the data. The static transformations are applied on the ...
class SimpleImagesDataset(t.utils.data.Dataset): def __init__(self, root_path, transforms_x_static = None, transforms_x_dynamic = None, transforms_y_static = None, transforms_y_dynamic = None): self.dataset = [] self.transforms_x = transforms_x_dynamic self.transforms_y = transforms_y_dynamic for cate...
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
**Preprocess Data** Convert pytorch tensor to numpy array.
def to_numpy(x): return x.cpu().detach().numpy()
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
Data transformations for the test and training sets.
norm_mean = [0.485, 0.456, 0.406] norm_std = [0.229, 0.224, 0.225] transforms_train = tv.transforms.Compose([ tv.transforms.RandomAffine(degrees = 45, translate = None, scale = (1., 2.), shear = 30), # tv.transforms.CenterCrop(CROP_SIZE), tv.transforms.Resize(IMAGE_SIZE), tv.transforms.RandomHorizonta...
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
Initialize pytorch datasets and loaders for training and test.
def create_loaders(dataset_class): dataset_train = dataset_class(TRAIN_PATH, transforms_x_dynamic = transforms_train, transforms_y_dynamic = y_transform) dataset_test = dataset_class(TEST_PATH, transforms_x_static = transforms_test, transforms_x_dynamic = tv.transfor...
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
**Visualize Data** Load a few images so that we can see the effects of the data augmentation on the training set.
def plot_one_prediction(x, label, pred): x, label, pred = to_numpy(x), to_numpy(label), to_numpy(pred) x = np.transpose(x, [1, 2, 0]) if x.shape[-1] == 1: x = x.squeeze() x = x * np.array(norm_std) + np.array(norm_mean) plt.title(label, color = 'green' if label == pred else 'red') plt.imshow(x) def p...
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
**Model** Define a few models to experiment with.
def get_mobilenet_v2(): model = t.hub.load('pytorch/vision', 'mobilenet_v2', pretrained=True) model.classifier[1] = Linear(in_features=1280, out_features=4, bias=True) model = model.cuda() return model def get_vgg_19(): model = tv.models.vgg19(pretrained = True) model = model.cuda() model.classifier[6].o...
Using cache found in /root/.cache/torch/hub/pytorch_vision_master
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
**Train & Evaluate** Timer utility function. This is used to measure the execution speed.
time_start = 0 def timer_start(): global time_start time_start = time.time() def timer_end(): return time.time() - time_start
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
This function trains the network and evaluates it at the same time. It outputs the metrics recorded during the training for both train and test. We are measuring accuracy and the loss. The function also saves a checkpoint of the model every time the accuracy is improved. In the end we will have a checkpoint of the mode...
def train_eval(optimizer, model, loader_train, loader_test, chekpoint_name, epochs): metrics = { 'losses_train': [], 'losses_test': [], 'acc_train': [], 'acc_test': [], 'prec_train': [], 'prec_test': [], 'rec_train': [], 'rec_test': [], 'f_score_train': [], ...
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
Plot a metric for both train and test.
def plot_train_test(train, test, title, y_title): plt.plot(range(len(train)), train, label = 'train') plt.plot(range(len(test)), test, label = 'test') plt.xlabel('Epochs') plt.ylabel(y_title) plt.title(title) plt.legend() plt.show()
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
Plot precision - recall curve
def plot_precision_recall(metrics): plt.scatter(metrics['prec_train'], metrics['rec_train'], label = 'train') plt.scatter(metrics['prec_test'], metrics['rec_test'], label = 'test') plt.legend() plt.title('Precision-Recall') plt.xlabel('Precision') plt.ylabel('Recall')
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
Train a model for several epochs. The steps_learning parameter is a list of tuples. Each tuple specifies the steps and the learning rate.
def do_train(model, loader_train, loader_test, checkpoint_name, steps_learning): for steps, learn_rate in steps_learning: metrics = train_eval(t.optim.Adam(model.parameters(), lr = learn_rate, weight_decay = 0), model, loader_train, loader_test, checkpoint_name, steps) print('Best test accuracy :', max(metric...
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
Perform actual training.
def do_train(model, loader_train, loader_test, checkpoint_name, steps_learning): t.cuda.empty_cache() for steps, learn_rate in steps_learning: metrics = train_eval(t.optim.Adam(model.parameters(), lr = learn_rate, weight_decay = 0), model, loader_train, loader_test, checkpoint_name, steps) index_max = ...
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
graphblas.matrix_multiplyThis example will go over how to use the `--graphblas-lower` pass from `graphblas-opt` to lower the `graphblas.matrix_multiply` op.Let’s first import some necessary modules and generate an instance of our JIT engine.
import mlir_graphblas import mlir_graphblas.sparse_utils import numpy as np engine = mlir_graphblas.MlirJitEngine()
_____no_output_____
Apache-2.0
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
Here are the passes we'll use.
passes = [ "--graphblas-lower", "--sparsification", "--sparse-tensor-conversion", "--linalg-bufferize", "--func-bufferize", "--tensor-bufferize", "--tensor-constant-bufferize", "--finalizing-bufferize", "--convert-linalg-to-loops", "--convert-scf-to-std", "--convert-std-to-ll...
_____no_output_____
Apache-2.0
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
Similar to our examples using the GraphBLAS dialect, we'll need some helper functions to convert sparse tensors to dense tensors. We'll also need some helpers to convert our sparse matrices to CSC format.
mlir_text = """ #trait_densify_csr = { indexing_maps = [ affine_map<(i,j) -> (i,j)>, affine_map<(i,j) -> (i,j)> ], iterator_types = ["parallel", "parallel"] } #CSR64 = #sparse_tensor.encoding<{ dimLevelType = [ "dense", "compressed" ], dimOrdering = affine_map<(i,j) -> (i,j)>, pointerBitWidth = 64,...
_____no_output_____
Apache-2.0
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
Let's compile our MLIR code.
engine.add(mlir_text, passes)
_____no_output_____
Apache-2.0
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
Overview of graphblas.matrix_multiplyHere, we'll show how to use the `graphblas.matrix_multiply` op. `graphblas.matrix_multiply` takes a sparse matrix operand in CSR format, a sparse matrix operand in CSC format, and a `semiring` attribute. The single `semiring` attribute indicates an element-wise operator and an aggr...
indices = np.array( [ [0, 3], [1, 3], [2, 0], [3, 0], [3, 1], ], dtype=np.uint64, ) values = np.array([1, 2, 3, 4, 5], dtype=np.float64) sizes = np.array([4, 4], dtype=np.uint64) sparsity = np.array([False, True], dtype=np.bool8) A = mlir_graphblas.sparse_utils.MLIRS...
_____no_output_____
Apache-2.0
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
graphblas.matrix_multiply (Plus-Times Semiring)Here, we'll simply perform a conventional matrix-multiply by using `graphblas.matrix_multiply` with the plus-times semiring.
mlir_text = """ #CSR64 = #sparse_tensor.encoding<{ dimLevelType = [ "dense", "compressed" ], dimOrdering = affine_map<(i,j) -> (i,j)>, pointerBitWidth = 64, indexBitWidth = 64 }> #CSC64 = #sparse_tensor.encoding<{ dimLevelType = [ "dense", "compressed" ], dimOrdering = affine_map<(i,j) -> (j,i)>, pointer...
_____no_output_____
Apache-2.0
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
The result looks sane. Let's verify that it has the same behavior as NumPy.
np.all(A_dense @ B_dense == engine.csr_densify4x4(sparse_matmul_result))
_____no_output_____
Apache-2.0
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
graphblas.matrix_multiply (Plus-Plus Semiring with Mask)Here, we'll perform a matrix-multiply with the plus-plus semiring. We'll show the result with and without a mask to demonstrate how the masking works.
mlir_text = """ #CSR64 = #sparse_tensor.encoding<{ dimLevelType = [ "dense", "compressed" ], dimOrdering = affine_map<(i,j) -> (i,j)>, pointerBitWidth = 64, indexBitWidth = 64 }> #CSC64 = #sparse_tensor.encoding<{ dimLevelType = [ "dense", "compressed" ], dimOrdering = affine_map<(i,j) -> (j,i)>, pointer...
_____no_output_____
Apache-2.0
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
Note how the results in the masked output only have elements present in the positions where the mask had elements present. Since we can't verify the results via NumPy given that it doesn't support semirings in its matrix multiply implementation, we'll leave the task of verifying the results as an exercise for the reade...
mlir_text = """ #CSR64 = #sparse_tensor.encoding<{ dimLevelType = [ "dense", "compressed" ], dimOrdering = affine_map<(i,j) -> (i,j)>, pointerBitWidth = 64, indexBitWidth = 64 }> #CSC64 = #sparse_tensor.encoding<{ dimLevelType = [ "dense", "compressed" ], dimOrdering = affine_map<(i,j) -> (j,i)>, pointer...
_____no_output_____
Apache-2.0
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
The code in the region of `matrix_multiply_plus_pair_and_square` simply squares each individual element's value. The use of `graphblas.yield` is used here to indicate the result of each element-wise squaring.Let's first get our results without the region. `matrix_multiply_plus_pair_no_region` simply does a matrix mult...
no_region_result = engine.matrix_multiply_plus_pair_no_region(A, B) engine.csr_densify4x4(no_region_result)
_____no_output_____
Apache-2.0
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
Let's now get the results from `matrix_multiply_plus_pair_and_square`.
with_region_result = engine.matrix_multiply_plus_pair_and_square(A, B) engine.csr_densify4x4(with_region_result)
_____no_output_____
Apache-2.0
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
Let's verify that our results are sane.
np.all(engine.csr_densify4x4(with_region_result) == engine.csr_densify4x4(no_region_result)**2)
_____no_output_____
Apache-2.0
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
Classify 10 different object with Convolutional Neural NetworkDatasetThe dataset we will use is built into tensorflow and called the [**CIFAR Image Dataset.**](https://www.cs.toronto.edu/~kriz/cifar.html) It contains 60,000 32x32 color images with 6000 images of each class. The labels in this dataset are the following...
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Load the image data and split into "train" and "test" dataNormalize the pixel values to be between 0 and 1Define class names
Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz 170500096/170498071 [==============================] - 6s 0us/step 170508288/170498071 [==============================] - 6s 0us/step
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Show an example image
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
CNN ArchitectureA common architecture for a CNN is a stack of Conv2D and MaxPooling2D layers followed by a few denesly connected layers. The stack of convolutional and maxPooling layers extract the features from the image. Then these features are flattened and fed to densly connected layers that determine the class of ...
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Show model summary:Total trainable parameters: 56,320The depth of the feature map increases but the spacial dimensions reduce.
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 30, 30, 32) 896 ____________________________________...
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Feature MapsThe term *feature map* stands for a 3D tensor with two spacial axes (width and height) and one depth axis. Our convolutional layers take feature maps as their input and return a new feature map that reprsents the prescence of spcific filters from the previous feature map. These are what we call *response ma...
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Show model summaryTotal trainable parameters: 122,570
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Train the ModelTrain and compile the model using the recommended hyper paramaters from tensorflow.
Epoch 1/20 1563/1563 [==============================] - 73s 46ms/step - loss: 1.5072 - accuracy: 0.4521 - val_loss: 1.2174 - val_accuracy: 0.5625 Epoch 2/20 1563/1563 [==============================] - 73s 47ms/step - loss: 1.1273 - accuracy: 0.6023 - val_loss: 1.0827 - val_accuracy: 0.6188 Epoch 3/20 1563/1563 [======...
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Evaluate the ModelWe evaluate how well the model performs by looking at it's performance on the test data set.You should get an accuracy of about 70%. This isn't bad for a simple model like this, but we'll dive into some better approaches for computer vision.
313/313 - 3s - loss: 1.2848 - accuracy: 0.6964 0.696399986743927
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Working with Small DatasetsIn the situation where you don't have millions of images it is difficult to train a CNN from scratch that performs very well. This is why we will learn about a few techniques we can use to train CNN's on small datasets of just a few thousand images. Data AugmentationTo avoid overfitting and ...
from keras.preprocessing import image from keras.preprocessing.image import ImageDataGenerator # creates a data generator object that transforms images datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='neare...
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Use a Pretrained ModelIn this section we will combine the tecniques we learned above and use a pretrained model and fine tuning to classify images of dogs and cats using a small dataset.Pretrained ModelsIn this section we will use a pretrained CNN as part of our own custom network to improve the accuracy of our model. ...
#Imports import os import numpy as np import matplotlib.pyplot as plt import tensorflow as tf keras = tf.keras
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Load the DatasetWe will load the *cats_vs_dogs* dataset from the modoule tensorflow_datatsets.This dataset contains (image, label) pairs where images have different dimensions and 3 color channels.
import tensorflow_datasets as tfds tfds.disable_progress_bar() # split the data manually into 80% training, 10% testing, 10% validation (raw_train, raw_validation, raw_test), metadata = tfds.load( 'cats_vs_dogs', split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'], with_info=True, as_supervised=True...
Downloading and preparing dataset cats_vs_dogs/4.0.0 (download: 786.68 MiB, generated: Unknown size, total: 786.68 MiB) to /root/tensorflow_datasets/cats_vs_dogs/4.0.0...
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Display images from the dataset
get_label_name = metadata.features['label'].int2str # creates a function object that we can use to get labels for image, label in raw_train.take(5): plt.figure() plt.imshow(image) plt.title(get_label_name(label))
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Data PreprocessingSince the sizes of our images are all different, we need to convert them all to the same size. We can create a function that will do that for us below.
IMG_SIZE = 160 # All images will be resized to 160x160 def format_example(image, label): """ returns an image that is reshaped to IMG_SIZE """ image = tf.cast(image, tf.float32) image = (image/127.5) - 1 image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE)) return image, label
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Now we can apply this function to all our images using ```.map()```.
train = raw_train.map(format_example) validation = raw_validation.map(format_example) test = raw_test.map(format_example)
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Let's have a look at our images now.
for image, label in train.take(2): plt.figure() plt.imshow(image) plt.title(get_label_name(label))
WARNING:matplotlib.image:Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers). WARNING:matplotlib.image:Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Finally we will shuffle and batch the images.
BATCH_SIZE = 32 SHUFFLE_BUFFER_SIZE = 1000 train_batches = train.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE) validation_batches = validation.batch(BATCH_SIZE) test_batches = test.batch(BATCH_SIZE)
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Now if we look at the shape of an original image vs the new image we will see it has been changed.
for img, label in raw_train.take(2): print("Original shape:", img.shape) for img, label in train.take(2): print("New shape:", img.shape)
Original shape: (262, 350, 3) Original shape: (409, 336, 3) New shape: (160, 160, 3) New shape: (160, 160, 3)
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Pick a Pretrained ModelThe model we are going to use as the convolutional base for our model is the **MobileNet V2** developed at Google. This model is trained on 1.4 million images and has 1000 different classes.We want to use this model but only its convolutional base. So, when we load in the model, we'll specify tha...
IMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3) # Create the base model from the pre-trained model MobileNet V2 base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, include_top=False, weights='imagenet') base_model.summa...
Model: "mobilenetv2_1.00_160" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ============================================================================================...
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
At this point this *base_model* will simply output a shape (32, 5, 5, 1280) tensor that is a feature extraction from our original (1, 160, 160, 3) image. The 32 means that we have 32 layers of differnt filters/features.
for image, _ in train_batches.take(1): pass feature_batch = base_model(image) print(feature_batch.shape)
(32, 5, 5, 1280)
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Freeze the BaseThe term **freezing** refers to disabling the training property of a layer. It simply means we won’t make any changes to the weights of any layers that are frozen during training. This is important as we don't want to change the convolutional base that already has learned weights.
base_model.trainable = False base_model.summary()
Model: "mobilenetv2_1.00_160" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ============================================================================================...
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Adding our ClassifierNow that we have our base layer setup, we can add the classifier. Instead of flattening the feature map of the base layer we will use a global average pooling layer that will average the entire 5x5 area of each 2D feature map and return to us a single 1280 element vector per filter.
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Finally, we will add the predicition layer that will be a single dense neuron. We can do this because we only have two classes to predict for.
prediction_layer = keras.layers.Dense(1)
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Now we will combine these layers together in a model.
model = tf.keras.Sequential([ base_model, global_average_layer, prediction_layer ]) model.summary()
Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= mobilenetv2_1.00_160 (Functi (None, 5, 5, 1280) 2257984 __________________________________...
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Train the ModelWe will train and compile the model. We will use a very small learning rate to ensure that the model does not have any major changes made to it.
base_learning_rate = 0.0001 model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=base_learning_rate), loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), metrics=['accuracy']) # We can evaluate the model right now to see how it does before training it on our new images initial_epoch...
_____no_output_____
MIT
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
Library Imports
from time import time notebook_start_time = time() import os import re import gc import pickle import random as r import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch from torch import nn, optim from torch.utils.data import Dataset from torch.utils.data import DataLoader as DL from torch...
_____no_output_____
MIT
PF-2/Notebooks/Train/D169 Last Block (Rand Init) (SGD0.9) (10CV).ipynb
pchandrasekaran1595/PetFinder.my---Pawpularity-Contest
Constants and Utilities
SEED = 49 DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") NUM_FEATURES = 1664 TRANSFORM = transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), ...
_____no_output_____
MIT
PF-2/Notebooks/Train/D169 Last Block (Rand Init) (SGD0.9) (10CV).ipynb
pchandrasekaran1595/PetFinder.my---Pawpularity-Contest
Dataset Template and Build Dataloader
class DS(Dataset): def __init__(self, images=None, targets=None, transform=None): self.images = images self.targets = targets self.transform = transform def __len__(self): return self.images.shape[0] def __getitem__(self, idx): return self.transform(self.ima...
_____no_output_____
MIT
PF-2/Notebooks/Train/D169 Last Block (Rand Init) (SGD0.9) (10CV).ipynb
pchandrasekaran1595/PetFinder.my---Pawpularity-Contest
Build Model
def build_model(IL: int, seed: int): class Model(nn.Module): def __init__(self, IL=None): super(Model, self).__init__() self.features = models.densenet169(pretrained=True, progress=False) self.features = nn.Sequential(*[*self.features.children()][:-1]) self.f...
_____no_output_____
MIT
PF-2/Notebooks/Train/D169 Last Block (Rand Init) (SGD0.9) (10CV).ipynb
pchandrasekaran1595/PetFinder.my---Pawpularity-Contest
Fit and Predict
def fit(model=None, optimizer=None, scheduler=None, epochs=None, early_stopping_patience=None, dataloaders=None, fold=None, verbose=False) -> tuple: name = "./Fold_{}_state.pt".format(fold) if verbose: breaker() print("Training Fold {}...".format(fold)) breaker...
_____no_output_____
MIT
PF-2/Notebooks/Train/D169 Last Block (Rand Init) (SGD0.9) (10CV).ipynb
pchandrasekaran1595/PetFinder.my---Pawpularity-Contest
Train
def train(images: np.ndarray, targets: np.ndarray, n_splits: int, batch_size: int, lr: float, wd: float, epochs: int, early_stopping: int, patience=None, eps=None) -> list: metrics = [] KFold_start_time = time() breaker() print("Performing...
************************************************** Clean Memory, 63 Objects Collected ... ************************************************** Loading Data ... ************************************************** Performing 10 Fold CV ... ************************************************** Building Train and Validat...
MIT
PF-2/Notebooks/Train/D169 Last Block (Rand Init) (SGD0.9) (10CV).ipynb
pchandrasekaran1595/PetFinder.my---Pawpularity-Contest
End
breaker() print("Notebook Rumtime : {:.2f} minutes".format((time() - notebook_start_time)/60)) breaker()
************************************************** Notebook Rumtime : 149.44 minutes **************************************************
MIT
PF-2/Notebooks/Train/D169 Last Block (Rand Init) (SGD0.9) (10CV).ipynb
pchandrasekaran1595/PetFinder.my---Pawpularity-Contest
linear regression 解析式直接求解
df['x4'] = 1 X = df.iloc[:,(0,1,2,4)].values y = df.y.values
_____no_output_____
MIT
Linear_regression/Linear_regression.ipynb
xpgeng/exercises_of_machine_learning
$y = Xw$ $ w = (X^T*X)^[-1]*X^T*y$
inv_XX_T = inv(X.T.dot(X)) w = inv_XX_T.dot(X.T).dot(df.y.values) w
_____no_output_____
MIT
Linear_regression/Linear_regression.ipynb
xpgeng/exercises_of_machine_learning
Resultsw1 = 2.97396653 w2 = -0.54139002 w3 = 0.97132913 b = 2.03076198
qr(inv_XX_T) X.shape #solve(X,y)##只能解方阵
_____no_output_____
MIT
Linear_regression/Linear_regression.ipynb
xpgeng/exercises_of_machine_learning
梯度下降法求解- 目标函数选取要合适一些, 前边乘以适当的系数.- 注意检验梯度的计算是否正确...
def f(w,X,y): return ((X.dot(w)-y)**2/(2*1000)).sum() def grad_f(w,X,y): return (X.dot(w) - y).dot(X)/1000 w0 = np.array([100.0,100.0,100.0,100.0]) epsilon = 1e-10 alpha = 0.1 check_condition = 1 while check_condition > epsilon: w0 += -alpha*grad_f(w0,X,y) check_condition = abs(grad_f(w0,X,y)).sum...
[ 2.97396671 -0.5414066 0.97132728 2.03076759]
MIT
Linear_regression/Linear_regression.ipynb
xpgeng/exercises_of_machine_learning
随机梯度下降法求解- Stochastic gradient descent- 使用了固定步长 - 一开始用的0.1, 始终达不到给定的精度- 于是添加了判定条件用来更新步长.
def cost_function(w,X,y): return (X.dot(w)-y)**2/2 def grad_cost_f(w,X,y): return (np.dot(X, w) - y)*X w0 = np.array([1.0, 1.0, 1.0, 1.0]) epsilon = 1e-3 alpha = 0.01 # 生成随机index,用来随机索引数据. random_index = np.arange(1000) np.random.shuffle(random_index) cost_value = np.inf #初始化目标函数值 while abs(grad_f(w0,X,y))...
[ 2.97376767 -0.54075842 0.97217986 2.03067711]
MIT
Linear_regression/Linear_regression.ipynb
xpgeng/exercises_of_machine_learning
--- Merge Datasets
combo = pd.merge(train_values, train_labels, on = 'building_id') combo.head(5) plt.figure (figsize=(5,10)); sns.heatmap(df.corr()[['damage_grade']].sort_values(by='damage_grade', ascending = False),annot=True ) sns.scatterplot(data=combo, x='age', y='damage_grade', hue='age');
_____no_output_____
CC0-1.0
Workspace/.ipynb_checkpoints/EricCheng-checkpoint.ipynb
vleong1/modeling_earthquake_damage
---
#Baseline train_labels['damage_grade'].value_counts(normalize=True) le = LabelEncoder() train_enc = train_values.apply(le.fit_transform) train_enc #From Chris #X = train_enc #y = trainlabel['damage_grade'] #X_train, X_test, y_train, y_test = train_test_split(X,y,stratify=y, random_state=123) #pipe_forest = make_pipeli...
_____no_output_____
CC0-1.0
Workspace/.ipynb_checkpoints/EricCheng-checkpoint.ipynb
vleong1/modeling_earthquake_damage
Model
#from Hackathon2 #Cvect and logreg #pipe = make_pipeline(CountVectorizer(stop_words = 'english'), LogisticRegression(n_jobs=-1)) # #params = {'countvectorizer__max_features':[500, 1000, 15000, 2000, 2500]} # #grid=GridSearchCV(pipe, param_grid=params, n_jobs= -1) #grid.fit(X_train, y_train) #
_____no_output_____
CC0-1.0
Workspace/.ipynb_checkpoints/EricCheng-checkpoint.ipynb
vleong1/modeling_earthquake_damage
logreg
#Cvect and logreg pipe = make_pipeline(StandardScaler(),LogisticRegression(n_jobs=-1)) # #params = {'countvectorizer__max_features':[500, 1000, 15000, 2000, 2500]} # #grid=GridSearchCV(pipe, n_jobs= -1) pipe.fit(X_train, y_train) pipe.score(X_train, y_train) pipe.fit(X_test, y_test) pipe.score(X_test, y_test) pipe.get_...
_____no_output_____
CC0-1.0
Workspace/.ipynb_checkpoints/EricCheng-checkpoint.ipynb
vleong1/modeling_earthquake_damage
Modeling KNN
# define models and parameters # model = KNeighborsClassifier() # n_neighbors = range(1, 21, 2) # weights = ['uniform', 'distance'] # #metric = ['euclidean', 'manhattan', 'minkowski'] # metric = ['euclidean'] # # define grid search # grid = dict(n_neighbors=n_neighbors,weights=weights,metric=metric) # #cv = Rep...
_____no_output_____
CC0-1.0
Workspace/.ipynb_checkpoints/EricCheng-checkpoint.ipynb
vleong1/modeling_earthquake_damage
Trying Veronica's code - KNN testing
pipe_knn = make_pipeline(StandardScaler(), KNeighborsClassifier(n_jobs = -1)) # n_neighbors must be odd to avoid an even split #Note: tried leaf size and p, but it didn't give us any value params = {'kneighborsclassifier__n_neighbors' : [5, 7, 9, 11]} grid_knn = GridSearchCV(pipe_knn, param_grid = params) grid_knn....
_____no_output_____
CC0-1.0
Workspace/.ipynb_checkpoints/EricCheng-checkpoint.ipynb
vleong1/modeling_earthquake_damage
5/13 per Jacob, use OHE instead of LabelEncoding LOG with OHE
X = train_values y = train_labels['damage_grade'] X_train, X_test, y_train, y_test = train_test_split(X,y,stratify=y, random_state=123)
_____no_output_____
CC0-1.0
Workspace/.ipynb_checkpoints/EricCheng-checkpoint.ipynb
vleong1/modeling_earthquake_damage
---
#Cvect and logreg #define X and y X = train_values y = train_labels['damage_grade'] X_train, X_test, y_train, y_test = train_test_split(X,y,stratify=y, random_state=123) #Create pipeline pipe = make_pipeline(OneHotEncoder(),StandardScaler(with_mean=False), LogisticRegression(n_jobs=-1)) params = {'logisticregression...
Train Score: 0.5925300588385777 Test Score: 0.585111281657713
CC0-1.0
Workspace/.ipynb_checkpoints/EricCheng-checkpoint.ipynb
vleong1/modeling_earthquake_damage
KNN with OHE
#train_values = train_values.head(int(len(train_values) * 0.1)) #train_labels = train_labels.head(int(len(train_labels) * 0.1)) X = train_values y = train_labels['damage_grade'] X_train, X_test, y_train, y_test = train_test_split(X,y,stratify=y, random_state=123) pipe_knn = make_pipeline(OneHotEncoder(),StandardScaler...
Train Score: 0.6720900486057815 Test Score: 0.575287797390637
CC0-1.0
Workspace/.ipynb_checkpoints/EricCheng-checkpoint.ipynb
vleong1/modeling_earthquake_damage
---
#https://medium.datadriveninvestor.com/k-nearest-neighbors-in-python-hyperparameters-tuning-716734bc557f #List Hyperparameters that we want to tune. leaf_size = list(range(1,50)) n_neighbors = list(range(1,30)) p=[1,2] #Convert to dictionary hyperparameters = dict(leaf_size=leaf_size, n_neighbors=n_neighbors, p=p) #Cr...
_____no_output_____
CC0-1.0
Workspace/.ipynb_checkpoints/EricCheng-checkpoint.ipynb
vleong1/modeling_earthquake_damage
LDA TrainingThe LDA training algorithm from Parameter estimation for text analysis
import random import numpy as np from collections import defaultdict, OrderedDict from types import SimpleNamespace from tqdm.notebook import tqdm from visualize import visualize_topic_word # === corpus loading === class NeurIPSCorpus: def __init__(self, data_path, num_topics, mode, start_doc_idx=0, max_num_docs=10...
Initializing... Gibbs sampling...
MIT
Understanding_the_LDA_Algorithm_20xx.ipynb
mistylight/Understanding_the_LDA_Algorithm
Inference on unseen documents
# === inference on unseen documents === test_corpus = NeurIPSCorpus( data_path="data/papers.txt", mode="test", num_topics=10, start_doc_idx=1000, max_num_docs=5, max_num_words=10000, max_doc_length=200, train_corpus=corpus, ) # === inference via Gibbs sampling === for i, doc in enumerat...
num_docs: 5 num_topics: 10 num_words: 0 Test Doc [0] === inference graphical models semidefinite programming a microsoft research cs toronto edu mit microsoft research mit edu andrea montanari stanford university montanari stanford edu abstract maximum posteriori probability map inference graphical model amount solve ...
MIT
Understanding_the_LDA_Algorithm_20xx.ipynb
mistylight/Understanding_the_LDA_Algorithm
Set plot font size
FS = 18
_____no_output_____
BSD-3-Clause
190211_evolve_p3_p7_compute_best_conv_ts_from_err_and_p-val_info.ipynb
amwilson149/baby-andross
Get dictionary with information about errors and p-values during convergent time steps
fname = './data/p3_p7_evolve_results/190211_errs_per_conv_ts_pr_0.005_g_1.1_niter_100.json' with open(fname,'r') as f: c_err_results = json.loads(f.read()) # Inspect keys print(c_err_results.keys()) # Go through simulation iterations and compute the min, max, and best # (where errors are minimized and p-values are ...
_____no_output_____
BSD-3-Clause
190211_evolve_p3_p7_compute_best_conv_ts_from_err_and_p-val_info.ipynb
amwilson149/baby-andross
[View in Colaboratory](https://colab.research.google.com/github/schwaaweb/aimlds1_11-NLP/blob/master/M11_A_DJ_NLP_Assignment.ipynb) Assignment: Natural Language Processing In this assignment, you will work with a data set that contains restaurant reviews. You will use a Naive Bayes model to classify the reviews (posit...
#%%time #!wget -c https://www.dropbox.com/s/yl5r7kx9nq15gmi/Restaurant_Reviews.tsv?raw=1 && mv Restaurant_Reviews.tsv?raw=1 Restaurant_Reviews.tsv !ls -lh *tsv %%time import numpy as np import pandas as pd import matplotlib.pyplot as plt import re import string import nltk nltk.download('all') df = pd.read_csv('Rest...
_____no_output_____
Unlicense
M11_A_DJ_NLP_Assignment.ipynb
schwaaweb/aimlds1_11-NLP
**2)** Convert the reviews into a list of tokens
review = df['Review'] # dropping the like here print(review) len(review)
0 Wow... Loved this place. 1 Crust is not good. 2 Not tasty and the texture was just nasty. 3 Stopped by during the late May bank holiday of... 4 The selection on the menu was great and so wer... 5 Now I am getting angry an...
Unlicense
M11_A_DJ_NLP_Assignment.ipynb
schwaaweb/aimlds1_11-NLP
**3) **You will most likely have to eliminate stop words **4)** You may have to utilize stemming or lemmatization to determine the base form of the words
stopwords = nltk.corpus.stopwords.words('english') ps = nltk.PorterStemmer() #Elmiminate punctations #Tokenize based on whitespace #Stem the text #Remove stopwords def process_text(txt): eliminate_punct = "".join([word.lower() for word in txt if word not in string.punctuation]) tokens = re.split('\W+', txt) ...
_____no_output_____
Unlicense
M11_A_DJ_NLP_Assignment.ipynb
schwaaweb/aimlds1_11-NLP
**5) **You will have to vectorize the data (i.e. construct a document term/word matix) wherein select words from the reviews will constitute the columns of the matrix and the individual reviews will be part of the rows of the matrix
from pprint import pprint %%time from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer def cv(data): count_vectorizer = CountVectorizer() emb = count_vectorizer.fit_transform(data) return emb, count_vectorizer list_corpus = df...
(1000, 1000)
Unlicense
M11_A_DJ_NLP_Assignment.ipynb
schwaaweb/aimlds1_11-NLP
Machine Learning Engineer Nanodegree Unsupervised Learning Project 3: Creating Customer Segments Welcome to the third project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality necessary ...
# Import libraries necessary for this project import numpy as np import pandas as pd import renders as rs from IPython.display import display # Allows the use of display() for DataFrames # Show matplotlib plots inline (nicely formatted in the notebook) %matplotlib inline # Load the wholesale customers dataset try: ...
Wholesale customers dataset has 440 samples with 6 features each.
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
Data ExplorationIn this section, you will begin exploring the data through visualizations and code to understand how each feature is related to the others. You will observe a statistical description of the dataset, consider the relevance of each feature, and select a few sample data points from the dataset which you w...
# Display a description of the dataset display(data.describe())
_____no_output_____
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
Implementation: Selecting SamplesTo get a better understanding of the customers and how their data will transform through the analysis, it would be best to select a few sample data points and explore them in more detail. In the code block below, add **three** indices of your choice to the `indices` list which will rep...
# TODO: Select three indices of your choice you wish to sample from the dataset indices = [0, 15, 45] # Create a DataFrame of the chosen samples samples = pd.DataFrame(data.loc[indices], columns = data.keys()).reset_index(drop = True) print "Chosen samples of wholesale customers dataset:" display(samples)
Chosen samples of wholesale customers dataset:
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
Question 1Consider the total purchase cost of each product category and the statistical description of the dataset above for your sample customers. *What kind of establishment (customer) could each of the three samples you've chosen represent?* **Hint:** Examples of establishments include places like markets, cafes,...
# TODO: Make a copy of the DataFrame, using the 'drop' function to drop the given feature new_data = data.drop('Detergents_Paper',axis=1) # TODO: Split the data into training and testing sets using the given feature as the target from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = ...
0.671835598453
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
Question 2*Which feature did you attempt to predict? What was the reported prediction score? Is this feature is necessary for identifying customers' spending habits?* **Hint:** The coefficient of determination, `R^2`, is scored between 0 and 1, with 1 being a perfect fit. A negative `R^2` implies the model fails to f...
# Produce a scatter matrix for each pair of features in the data pd.scatter_matrix(data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
_____no_output_____
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
Question 3*Are there any pairs of features which exhibit some degree of correlation? Does this confirm or deny your suspicions about the relevance of the feature you attempted to predict? How is the data for those features distributed?* **Hint:** Is the data normally distributed? Where do most of the data points lie?...
# TODO: Scale the data using the natural logarithm log_data = np.log(data) # TODO: Scale the sample data using the natural logarithm log_samples = np.log(samples) # Produce a scatter matrix for each pair of newly-transformed features pd.scatter_matrix(log_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
_____no_output_____
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
ObservationAfter applying a natural logarithm scaling to the data, the distribution of each feature should appear much more normal. For any pairs of features you may have identified earlier as being correlated, observe here whether that correlation is still present (and whether it is now stronger or weaker than before...
# Display the log-transformed sample data display(log_samples)
_____no_output_____
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
Implementation: Outlier DetectionDetecting outliers in the data is extremely important in the data preprocessing step of any analysis. The presence of outliers can often skew results which take into consideration these data points. There are many "rules of thumb" for what constitutes an outlier in a dataset. Here, we ...
from sets import Set outliers_indices = {} # For each feature find the data points with extreme high or low values for feature in log_data.keys(): # TODO: Calculate Q1 (25th percentile of the data) for the given feature Q1 = np.percentile(log_data[feature], 25) # TODO: Calculate Q3 (75th percenti...
Data points considered outliers for the feature 'Fresh':
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
Question 4*Are there any data points considered outliers for more than one feature based on the definition above? Should these data points be removed from the dataset? If any data points were added to the `outliers` list to be removed, explain why.* **Answer:** Datapoints which were outliers in the more than one feat...
# TODO: Apply PCA by fitting the good data with the same number of dimensions as features from sklearn.decomposition import PCA pca = PCA(n_components=6) pca.fit(good_data) # TODO: Transform the sample log-data using the PCA fit above pca_samples = pca.transform(log_samples) # Generate PCA results plot pca_results = ...
[ 0.44302505 0.70681723 0.82988103 0.93109011 0.97959207 1. ]
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
Question 5*How much variance in the data is explained* ***in total*** *by the first and second principal component? What about the first four principal components? Using the visualization provided above, discuss what the first four dimensions best represent in terms of customer spending.* **Hint:** A positive increas...
# Display sample log-data after having a PCA transformation applied display(pd.DataFrame(np.round(pca_samples, 4), columns = pca_results.index.values))
_____no_output_____
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
Implementation: Dimensionality ReductionWhen using principal component analysis, one of the main goals is to reduce the dimensionality of the data — in effect, reducing the complexity of the problem. Dimensionality reduction comes at a cost: Fewer dimensions used implies less of the total variance in the data is being...
# TODO: Apply PCA by fitting the good data with only two dimensions pca = PCA(n_components=2).fit(good_data) # TODO: Transform the good data using the PCA fit above reduced_data = pca.transform(good_data) # TODO: Transform the sample log-data using the PCA fit above pca_samples = pca.transform(log_samples) # Create ...
_____no_output_____
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
ObservationRun the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it using only two dimensions. Observe how the values for the first two dimensions remains unchanged when compared to a PCA transformation in six dimensions.
# Display sample log-data after applying PCA transformation in two dimensions display(pd.DataFrame(np.round(pca_samples, 4), columns = ['Dimension 1', 'Dimension 2']))
_____no_output_____
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
ClusteringIn this section, you will choose to use either a K-Means clustering algorithm or a Gaussian Mixture Model clustering algorithm to identify the various customer segments hidden in the data. You will then recover specific data points from the clusters to understand their significance by transforming them back ...
scores = [] # TODO: Apply your clustering algorithm of choice to the reduced data for num_clusters in range(2,15): from sklearn.cluster import KMeans clusterer = KMeans(n_clusters=num_clusters).fit(reduced_data) # TODO: Predict the cluster for each data point preds = clusterer.predict(reduced_data) ...
_____no_output_____
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
Question 7*Report the silhouette score for several cluster numbers you tried. Of these, which number of clusters has the best silhouette score?* **Answer:** I tried the cluster numbers from 2 to 14 as shown above. The best silhoutte score is reported from K=2. Cluster VisualizationOnce you've chosen the optimal numb...
# Display the results of the clustering from implementation rs.cluster_results(reduced_data, preds, centers, pca_samples)
_____no_output_____
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
Implementation: Data RecoveryEach cluster present in the visualization above has a central point. These centers (or means) are not specifically data points from the data, but rather the *averages* of all the data points predicted in the respective clusters. For the problem of creating customer segments, a cluster's ce...
# TODO: Inverse transform the centers log_centers = pca.inverse_transform(centers) # TODO: Exponentiate the centers true_centers = np.exp(log_centers) # Display the true centers segments = ['Segment {}'.format(i) for i in range(0,len(centers))] true_centers = pd.DataFrame(np.round(true_centers), columns = data.keys()...
_____no_output_____
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
Question 8Consider the total purchase cost of each product category for the representative data points above, and reference the statistical description of the dataset at the beginning of this project. *What set of establishments could each of the customer segments represent?* **Hint:** A customer who is assigned to `...
# Display the predictions for i, pred in enumerate(sample_preds): print "Sample point", i, "predicted to be in Cluster", pred
Sample point 0 predicted to be in Cluster 1 Sample point 1 predicted to be in Cluster 0 Sample point 2 predicted to be in Cluster 1
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
**Answer:** The predictions for Sample point 0 and 2 are assigned to cluster 1. This indeed matches the prediction at the start of this assignment where these customers were predicted to be restaurant or caffe.The prediction for sample point 1 is cluster 0 which I predicted to be small ice-cream parlor. However, at the...
# Display the clustering results based on 'Channel' data rs.channel_results(reduced_data, outliers, pca_samples)
_____no_output_____
MIT
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
Simple Oscillator ExampleThis example shows the most simple way of using a solver.We solve free vibration of a simple oscillator:$$m \ddot{u} + k u = 0,\quad u(0) = u_0,\quad \dot{u}(0) = \dot{u}_0$$using the CVODE solver. An analytical solution exists, given by$$u(t) = u_0 \cos\left(\sqrt{\frac{k}{m}} t\right)+\frac{...
from __future__ import print_function import matplotlib.pyplot as plt import numpy as np from scikits.odes import ode #data of the oscillator k = 4.0 m = 1.0 #initial position and speed data on t=0, x[0] = u, x[1] = \dot{u}, xp = \dot{x} initx = [1, 0.1]
_____no_output_____
BSD-3-Clause
ipython_examples/Simple Oscillator.ipynb
tinosulzer/odes