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 |
|---|---|---|---|---|---|
Question 3*How accurate would a prediction be that all female passengers and all male passengers younger than 10 survived?* **Hint:** Run the code cell below to see the accuracy of this prediction. | print accuracy_score(outcomes, predictions) | Predictions have an accuracy of 79.35%.
| MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
**Answer**: 79.35% ***Adding the feature **Age** as a condition in conjunction with **Sex** improves the accuracy by a small margin more than with simply using the feature **Sex** alone. Now it's your turn: Find a series of features and conditions to split the data on to obtain an outcome prediction accuracy of at leas... | survival_stats(data, outcomes, 'Embarked', ["Pclass == 3", "Age < 30", "Sex == female", "SibSp == 2"]) | _____no_output_____ | MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
After exploring the survival statistics visualization, fill in the missing code below so that the function will make your prediction. Make sure to keep track of the various features and conditions you tried before arriving at your final prediction model. **Hint:** You can start your implementation of this function us... | def predictions_3(data):
""" Model with multiple features. Makes a prediction with an accuracy of at least 80%. """
predictions = []
for _, passenger in data.iterrows():
# Remove the 'pass' statement below
# and write your prediction conditions here
if (passenger.Sex =... | _____no_output_____ | MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
Question 4*Describe the steps you took to implement the final prediction model so that it got an accuracy of at least 80%. What features did you look at? Were certain features more informative than others? Which conditions did you use to split the survival outcomes in the data? How accurate are your predictions?* **H... | print accuracy_score(outcomes, predictions) | Predictions have an accuracy of 82.15%.
| MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
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_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Text classification with TensorFlow Lite Model Maker View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook The TensorFlow Lite Model Maker library simplifies the process of adapting and converting a TensorFlow model to particular input data when deploying this ... | !pip install -q tflite-model-maker | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Import the required packages. | import numpy as np
import os
from tflite_model_maker import configs
from tflite_model_maker import ExportFormat
from tflite_model_maker import model_spec
from tflite_model_maker import text_classifier
from tflite_model_maker import TextClassifierDataLoader
import tensorflow as tf
assert tf.__version__.startswith('2')... | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Download the sample training data.In this tutorial, we will use the [SST-2](https://nlp.stanford.edu/sentiment/index.html) (Stanford Sentiment Treebank) which is one of the tasks in the [GLUE](https://gluebenchmark.com/) benchmark. It contains 67,349 movie reviews for training and 872 movie reviews for testing. The da... | data_dir = tf.keras.utils.get_file(
fname='SST-2.zip',
origin='https://dl.fbaipublicfiles.com/glue/data/SST-2.zip',
extract=True)
data_dir = os.path.join(os.path.dirname(data_dir), 'SST-2') | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
The SST-2 dataset is stored in TSV format. The only difference between TSV and CSV is that TSV uses a tab `\t` character as its delimiter instead of a comma `,` in the CSV format.Here are the first 5 lines of the training dataset. label=0 means negative, label=1 means positive.| sentence ... | import pandas as pd
def replace_label(original_file, new_file):
# Load the original file to pandas. We need to specify the separator as
# '\t' as the training data is stored in TSV format
df = pd.read_csv(original_file, sep='\t')
# Define how we want to change the label name
label_map = {0: 'negative', 1: '... | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
QuickstartThere are five steps to train a text classification model:**Step 1. Choose a text classification model archiecture.**Here we use the average word embedding model architecture, which will produce a small and fast model with decent accuracy. | spec = model_spec.get('average_word_vec') | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Model Maker also supports other model architectures such as [BERT](https://arxiv.org/abs/1810.04805). If you are interested to learn about other architecture, see the [Choose a model architecture for Text Classifier](scrollTo=kJ_B8fMDOhMR) section below. **Step 2. Load the training and test data, then preprocess them... | train_data = TextClassifierDataLoader.from_csv(
filename='train.csv',
text_column='sentence',
label_column='label',
model_spec=spec,
is_training=True)
test_data = TextClassifierDataLoader.from_csv(
filename='dev.csv',
text_column='sentence',
label_column='label',
mo... | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
**Step 3. Train the TensorFlow model with the training data.**The average word embedding model use `batch_size = 32` by default. Therefore you will see that it takes 2104 steps to go through the 67,349 sentences in the training dataset. We will train the model for 10 epochs, which means going through the training datas... | model = text_classifier.create(train_data, model_spec=spec, epochs=10) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
**Step 4. Evaluate the model with the test data.**After training the text classification model using the sentences in the training dataset, we will use the remaining 872 sentences in the test dataset to evaluate how the model perform against new data it has never seen before.As the default batch size is 32, it will tak... | loss, acc = model.evaluate(test_data) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
**Step 5. Export as a TensorFlow Lite model.**Let's export the text classification that we have trained in the TensorFlow Lite format. We will specify which folder to export the model.You may see an warning about `vocab.txt` file does not exist in the metadata but they can be safely ignore. | model.export(export_dir='average_word_vec') | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
You can download the TensorFlow Lite model file using the left sidebar of Colab. Go into the `average_word_vec` folder as we specified in `export_dir` parameter above, right-click on the `model.tflite` file and choose `Download` to download it to your local computer.This model can be integrated into an Android or an iO... | mb_spec = model_spec.get('mobilebert_classifier') | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Load training dataYou can upload your own dataset to work through this tutorial. Upload your dataset by using the left sidebar in Colab.If you prefer not to upload your dataset to the cloud, you can also locally run the library by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_exam... | train_data = TextClassifierDataLoader.from_csv(
filename='train.csv',
text_column='sentence',
label_column='label',
model_spec=mb_spec,
is_training=True)
test_data = TextClassifierDataLoader.from_csv(
filename='dev.csv',
text_column='sentence',
label_column='label',
... | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
The Model Maker library also supports the `from_folder()` method to load data. It assumes that the text data of the same class are in the same subdirectory and that the subfolder name is the class name. Each text file contains one movie review sample. The `class_labels` parameter is used to specify which the subfolders... | model = text_classifier.create(train_data, model_spec=mb_spec, epochs=3) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Examine the detailed model structure. | model.summary() | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Evaluate the modelEvaluate the model that we have just trained using the test data and measure the loss and accuracy value. | loss, acc = model.evaluate(test_data) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Quantize the modelIn many on-device ML application, the model size is an important factor. Therefore, it is recommended that you apply quantize the model to make it smaller and potentially run faster. Model Maker automatically applies the recommended quantization scheme for each model architecture but you can customiz... | config = configs.QuantizationConfig.create_dynamic_range_quantization(optimizations=[tf.lite.Optimize.OPTIMIZE_FOR_LATENCY])
config.experimental_new_quantizer = True | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Export as a TensorFlow Lite modelConvert the trained model to TensorFlow Lite model format with [metadata](https://www.tensorflow.org/lite/convert/metadata) so that you can later use in an on-device ML application. The label file and the vocab file are embedded in metadata. The default TFLite filename is `model.tflite... | model.export(export_dir='mobilebert/', quantization_config=config) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
The TensorFlow Lite model file can be integrated in a mobile app using the [BertNLClassifier API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/bert_nl_classifier) in [TensorFlow Lite Task Library](https://www.tensorflow.org/lite/inference_with_metadata/task_library/overview). Please note that th... | model.export(export_dir='mobilebert/', export_format=[ExportFormat.LABEL, ExportFormat.VOCAB]) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
You can evaluate the TFLite model with `evaluate_tflite` method to measure its accuracy. Converting the trained TensorFlow model to TFLite format and apply quantization can affect its accuracy so it is recommended to evaluate the TFLite model accuracy before deployment. | accuracy = model.evaluate_tflite('mobilebert/model.tflite', test_data)
print('TFLite model accuracy: ', accuracy) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Advanced UsageThe `create` function is the driver function that the Model Maker library uses to create models. The `model_spec` parameter defines the model specification. The `AverageWordVecModelSpec` and `BertClassifierModelSpec` classes are currently supported. The `create` function comprises of the following steps:... | new_model_spec = model_spec.get('mobilebert_classifier')
new_model_spec.seq_len = 256 | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Customize the average word embedding model hyperparametersYou can adjust the model infrastructure like the `wordvec_dim` and the `seq_len` variables in the `AverageWordVecModelSpec` class. For example, you can train the model with a larger value of `wordvec_dim`. Note that you must construct a new `model_spec` if you ... | new_model_spec = model_spec.AverageWordVecModelSpec(wordvec_dim=32) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Get the preprocessed data. | new_train_data = TextClassifierDataLoader.from_csv(
filename='train.csv',
text_column='sentence',
label_column='label',
model_spec=new_model_spec,
is_training=True) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Train the new model. | model = text_classifier.create(new_train_data, model_spec=new_model_spec) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Tune the training hyperparametersYou can also tune the training hyperparameters like `epochs` and `batch_size` that affect the model accuracy. For instance,* `epochs`: more epochs could achieve better accuracy, but may lead to overfitting.* `batch_size`: the number of samples to use in one training step.For exampl... | model = text_classifier.create(new_train_data, model_spec=new_model_spec, epochs=20) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Evaluate the newly retrained model with 20 training epochs. | new_test_data = TextClassifierDataLoader.from_csv(
filename='dev.csv',
text_column='sentence',
label_column='label',
model_spec=new_model_spec,
is_training=False)
loss, accuracy = model.evaluate(new_test_data) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Change the Model ArchitectureYou can change the model by changing the `model_spec`. The following shows how to change to BERT-Base model.Change the `model_spec` to BERT-Base model for the text classifier. | spec = model_spec.get('bert_classifier') | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | simonmaurer/tensorflow |
Using Transfer Learning to Classify Flower Images with PyTorch In this blog post, I will detail my repository that performs object classification with transfer learning. The project is broken down into multiple steps:* Load and preprocess the image dataset* Train the image classifier on your dataset* Use the trained c... | data_dir = './flowers'
train_dir = data_dir + '/train'
valid_dir = data_dir + '/valid'
test_dir = data_dir + '/test'
# Defining data transforms for training, validation and test data and also normalizing whole data
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
... | _____no_output_____ | MIT | 102_Flowers_classification(1).ipynb | styluna7/notebooks |
Label mappingI had load in a mapping from category label to category name. I got this in the file cat_to_name.json. It's a JSON object which i have read in with the json module. This gave a dictionary mapping the integer encoded categories to the actual names of the flowers. | import json
with open('cat_to_name.json', 'r') as f:
cat_to_name = json.load(f)
# changing categories to their actual names
for i in range(0,len(class_names)):
class_names[i] = cat_to_name.get(class_names[i]) | _____no_output_____ | MIT | 102_Flowers_classification(1).ipynb | styluna7/notebooks |
Visualize a few imagesLet's visualize a few training images so as to understand the data augmentations. | def imshow(inp, title=None):
"""Imshow for Tensor."""
inp = inp.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = std * inp + mean
inp = np.clip(inp, 0, 1)
plt.imshow(inp)
if title is not None:
plt.title(title)
plt... | _____no_output_____ | MIT | 102_Flowers_classification(1).ipynb | styluna7/notebooks |
Building and training the classifierNow that the data is ready, it's time to build and train the classifier. As usual, you should use one of the pretrained models from `torchvision.models` to get the image features. Build and train a new feed-forward classifier using those features.* Load a [pre-trained network](http:... | model_ft = train_model(model_ft, criterion, optimizer_ft,num_epochs=20) | Epoch 0/19
----------
train Loss: 0.8074 Acc: 0.3168
valid Loss: 0.5147 Acc: 0.4707
Epoch 1/19
----------
train Loss: 0.6572 Acc: 0.4287
valid Loss: 0.3435 Acc: 0.6247
Epoch 2/19
----------
train Loss: 0.5526 Acc: 0.5258
valid Loss: 0.2481 Acc: 0.7396
Epoch 3/19
----------
train Loss: 0.4813 Acc: 0.5861
valid Loss: ... | MIT | 102_Flowers_classification(1).ipynb | styluna7/notebooks |
Inference for classificationNow let's pass an image into the network and predict the class of the flower in the image. Using a function called `predict` that takes an image and a model, then returns the top $K$ most likely classes along with the probabilities. It looks like ```pythonprobs, classes = predict(image_path... | def predict(image_path, model, top_num=5):
# Process image
img = process_image(image_path)
# Numpy -> Tensor
image_tensor = torch.from_numpy(img).type(torch.FloatTensor)
# Add batch of size 1 to image
model_input = image_tensor.unsqueeze(0)
# Probs
probs = torch.exp(model.forwa... | _____no_output_____ | MIT | 102_Flowers_classification(1).ipynb | styluna7/notebooks |
Sanity CheckingNow I have used a trained model for predictions. Even if the testing accuracy is high, it's always good to check that there aren't obvious bugs. I have used matplotlib to plot the probabilities for the top 5 classes as a bar graph, along with the input image. | def plot_solution(image_path, model):
# Set up plot
plt.figure(figsize = (6,10))
ax = plt.subplot(2,1,1)
# Set up title
flower_num = image_path.split('/')[2]
title_ = cat_to_name[flower_num]
# Plot flower
img = process_image(image_path)
imshow(img, ax, title = title_);
# Make pre... | /usr/local/lib/python3.6/dist-packages/seaborn/categorical.py:1428: FutureWarning: remove_na is deprecated and is a private function. Do not use.
stat_data = remove_na(group_data)
| MIT | 102_Flowers_classification(1).ipynb | styluna7/notebooks |
A brief look at the data | data.shape
data.head()
data["Embarked"].value_counts()
data["Sex"].value_counts()
data["Ticket"].value_counts()
data.describe()
data.describe(include=['O'])
data.hist(bins=50, figsize=(20,15))
save_fig("attribute_histogram_plots")
plt.show() | Saving figure attribute_histogram_plots
| Apache-2.0 | clean/process_data.ipynb | franpog859/titanic-competition |
Split the data into train and validation sets | # Split the data into train and validation sets before diving into analysis
train_data, validation_data = model_selection.train_test_split(data, test_size=0.2, random_state=42)
print("Train data shape:")
print(train_data.shape)
print("Train data columns:")
print(train_data.columns)
# Save the data sets
train_data.to_cs... | _____no_output_____ | Apache-2.0 | clean/process_data.ipynb | franpog859/titanic-competition |
Reshaping data | correlation_matrix = train_data.corr()
correlation_matrix["Survived"].sort_values(ascending=False)
train_set = [train_data]
#train_set.type()
for dataset in train_set:
dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\.', expand=False)
pd.crosstab(train_data['Title'], train_data['Sex'])
for dataset in trai... | _____no_output_____ | Apache-2.0 | clean/process_data.ipynb | franpog859/titanic-competition |
Principal Component Analysis | from sklearn.decomposition import PCA
data = hourly[np.arange(24)].values
data_pca = PCA(2).fit_transform(data)
hourly['projection1'], hourly['projection2'] = data_pca.T
hourly['total rides'] = hourly.sum(axis=1)
hourly.plot('projection1', 'projection2', kind='scatter', c='total rides', cmap='Blues_r');
plt.savefig('f... | /Users/jakevdp/anaconda/envs/python3.4/lib/python3.4/site-packages/matplotlib/collections.py:590: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
if self._edgecolors == str('face'):
| MIT | WorkHabits.ipynb | jakevdp/ProntoData |
Automated Clustering | from sklearn.mixture import GMM
gmm = GMM(3, covariance_type='full', random_state=2)
data = hourly[['projection1', 'projection2']]
gmm.fit(data)
# require high-probability cluster membership
hourly['cluster'] = (gmm.predict_proba(data)[:, 0] > 0.6).astype(int)
from datetime import time
fig, ax = plt.subplots(1, 2, fig... | /Users/jakevdp/anaconda/envs/python3.4/lib/python3.4/site-packages/matplotlib/collections.py:590: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
if self._edgecolors == str('face'):
| MIT | WorkHabits.ipynb | jakevdp/ProntoData |
Identifying Mismatches | mismatch = hourly.query('cluster == 0 & commute')
mismatch = mismatch.reset_index('usertype')[['usertype', 'projection1', 'projection2']]
mismatch
from pandas.tseries.holiday import USFederalHolidayCalendar
cal = USFederalHolidayCalendar()
holidays = cal.holidays('2014-08', '2015-10', return_name=True)
holidays_all = p... | /Users/jakevdp/anaconda/envs/python3.4/lib/python3.4/site-packages/matplotlib/collections.py:590: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
if self._edgecolors == str('face'):
| MIT | WorkHabits.ipynb | jakevdp/ProntoData |
Misc functions and utilities | orientations = EAST, NORTH, WEST, SOUTH = [(1, 0), (0, 1), (-1, 0), (0, -1)]
turns = LEFT, RIGHT = (+1, -1)
def vector_add(a, b):
"""Component-wise addition of two vectors."""
return tuple(map(operator.add, a, b))
def turn_heading(heading, inc, headings=orientations):
return headings[(headings.index(heading... | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Class definitions Base `MDP` class | class MDP:
"""A Markov Decision Process, defined by an initial state, transition model,
and reward function. We also keep track of a gamma value, for use by
algorithms. The transition model is represented somewhat differently from
the text. Instead of P(s' | s, a) being a probability number for each
... | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
A custom MDP class to extend functionalityWe will write a CustomMDP class to extend the MDP class for the problem at hand. This class will implement the `T` method to implement the transition model. | class CustomMDP(MDP):
def __init__(self, transition_matrix, rewards, terminals, init, gamma=.9):
# All possible actions.
actlist = []
for state in transition_matrix.keys():
actlist.extend(transition_matrix[state])
actlist = list(set(actlist))
#print(actlist)
... | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Problem 1: Simple MDP--- State dependent reward functionMarkov Decision Processes are formally described as processes that follow the Markov property which states that "The future is independent of the past given the present". MDPs formally describe environments for reinforcement learning and we assume that the enviro... | t = {
'leisure': {
'facebook': {'leisure':0.9, 'class1':0.1},
'quit': {'leisure':0.1, 'class1':0.9},
'study': {},
'sleep': {},
'pub': {}
},
'class1': {
'study': {'class2':0.6, '... | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Defining rewardsWe now need to define the reward for each state. | rewards = {
'class1': 4,
'class2': 6,
'class3': 10,
'leisure': -1,
'end': 0
} | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Terminal stateThis MDP has only one terminal state | terminals = ['end'] | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Setting initial state to `Class 1` | init = 'class1' | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Read in an instance of the custom class | school_mdp = CustomMDP(t, rewards, terminals, init, gamma=.95) | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Let's see the actions and rewards of the MDP | school_mdp.states
school_mdp.actions('class1')
school_mdp.actions('leisure')
school_mdp.T('class1','sleep')
school_mdp.actions('end')
school_mdp.reward | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Value iteration | def value_iteration(mdp, epsilon=0.001):
"""Solving an MDP by value iteration.
mdp: The MDP object
epsilon: Stopping criteria
"""
U1 = {s: 0 for s in mdp.states}
R, T, gamma = mdp.R, mdp.T, mdp.gamma
while True:
U = U1.copy()
delta = 0
for s in mdp.states:
... | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Value iteration on the school MDP | value_iteration(school_mdp)
value_iteration_over_time(school_mdp,iterations=10) | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Plotting value updates over time/iterations | def plot_value_update(mdp,iterations=10,plot_kw=None):
"""
Plot value updates over iterations for a given MDP.
"""
x = value_iteration_over_time(mdp,iterations=iterations)
value_states = {k:[] for k in mdp.states}
for i in x:
for k,v in i.items():
value_states[k].append(v)
... | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Value iterations for various discount factors ($\gamma$) | for i in range(4):
mdp = CustomMDP(t, rewards, terminals, init, gamma=1-0.2*i)
plot_value_update(mdp,10) | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Value iteration for two different reward structures | rewards1 = {
'class1': 4,
'class2': 6,
'class3': 10,
'leisure': -1,
'end': 0
}
mdp1 = CustomMDP(t, rewards1, terminals, init, gamma=.95)
plot_value_update(mdp1,20)
rewards2 = {
'class1': 1,
'class2': 1.5,
'class3': 2.5,
'leisure': -4,
'end': 0
}
mdp2 = CustomMDP(t, rewards2, t... | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Policy iteration | def expected_utility(a, s, U, mdp):
"""The expected utility of doing a in state s, according to the MDP and U."""
return sum([p * U[s1] for (p, s1) in mdp.T(s, a)])
def policy_evaluation(pi, U, mdp, k=20):
"""Returns an updated utility mapping U from each state in the MDP to its
utility, using an approx... | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Policy iteration over the school MDP | policy_iteration(school_mdp)
policy_iteration(school_mdp,verbose=1) | Initial random choice: {'leisure': 'study', 'class2': 'sleep', 'class3': 'facebook', 'class1': 'pub', 'end': None}
Policy after iteration 1: {'leisure': 'quit', 'class2': 'study', 'class3': 'pub', 'class1': 'study', 'end': None}
Policy after iteration 2: {'leisure': 'quit', 'class2': 'study', 'class3': 'pub', 'class1':... | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Does the result match using value iteration? We use the `best_policy` function to find out | best_policy(school_mdp,value_iteration(school_mdp,0.01)) | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Comparing computation efficiency (time) of value and policy iterationsClearly values iteration method takes more iterations to reach the same steady-state compared to policy iteration technique. But how does their computation time compare? Let's find out. Running value and policy iteration on the school MDP many time... | def compute_time(mdp,iteration_technique='value',n_run=1000,epsilon=0.01):
"""
Computes the average time for value or policy iteration for a given MDP
n_run: Number of runs to average over, default 1000
epsilon: Error margin for the value iteration
"""
if iteration_technique=='value':
t1... | Average policy iteration took 0.7556800842285156 milliseconds
| Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Q-learning Q-learning class | class QLearningAgent:
""" An exploratory Q-learning agent. It avoids having to learn the transition
model because the Q-value of a state can be related directly to those of
its neighbors.
"""
def __init__(self, mdp, Ne, Rplus, alpha=None):
self.gamma = mdp.gamma
self.termina... | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Trial run | def run_single_trial(agent_program, mdp):
"""Execute trial for given agent_program
and mdp."""
def take_single_action(mdp, s, a):
"""
Select outcome of taking action a
in state s. Weighted Sampling.
"""
x = random.uniform(0, 1)
cumulative_probability = 0.0
... | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Testing Q-learning | # Define an agent
q_agent = QLearningAgent(school_mdp, Ne=1000, Rplus=2,alpha=lambda n: 60./(59+n))
q_agent.actions_in_state('leisure')
run_single_trial(q_agent,school_mdp)
q_agent.Q
for i in range(200):
run_single_trial(q_agent,school_mdp)
q_agent.Q
def get_U_from_Q(q_agent):
U = defaultdict(lambda: -100.) # L... | {'leisure': 18.079639654154484, 'class2': 15.792664558035112, 'class3': 20.61614864677164, 'class1': 20.306571436730533, 'end': 0.0}
| Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Function for utility estimate by Q-learning by many iterations | def qlearning_iter(agent_program,mdp,iterations=1000,print_final_utility=True):
"""
Function for utility estimate by Q-learning by many iterations
Returns a history object i.e. a list of dictionaries, where utility estimate for each iteration is stored
q_agent = QLearningAgent(grid_1, Ne=25, Rplus=... | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
How do the long-term utility estimates with Q-learning compare with value iteration? | def plot_qlearning_vi(hist, vi,plot_n_states=None):
"""
Compares and plots a Q-learning and value iteration results for the utility estimate of an MDP's states
hist: A history object from a Q-learning run
vi: A value iteration estimate for the same MDP
plot_n_states: Restrict the plotting for n stat... | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Testing the long-term utility learning for the small (default) grid world | # Define the Q-learning agent
q_agent = QLearningAgent(school_mdp, Ne=100, Rplus=2,alpha=lambda n: 100/(99+n))
# Obtain the history by running the Q-learning for many iterations
hist=qlearning_iter(q_agent,school_mdp,iterations=20000,print_final_utility=False)
# Get a value iteration estimate using the same MDP
vi = va... | _____no_output_____ | Apache-2.0 | Assignmet_4/CS7641_Assignment4_MDP_1.ipynb | stjordanis/CS7641 |
Copyright 2018 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | site/ja/tutorials/keras/overfit_and_underfit.ipynb | gabrielrufino/docs-l10n |
過学習と学習不足について知る View on TensorFlow.org Run in Google Colab View source on GitHub Note: これらのドキュメントは私たちTensorFlowコミュニティが翻訳したものです。コミュニティによる 翻訳は**ベストエフォート**であるため、この翻訳が正確であることや[英語の公式ドキュメント](https://www.tensorflow.org/?hl=en)の 最新の状態を反映したものであることを保証することはできません。 この翻訳の品質を向上させるためのご意見をお持ちの方は、GitHubリポジトリ[tensor... | from __future__ import absolute_import, division, print_function, unicode_literals
try:
# Colab only
%tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__) | _____no_output_____ | Apache-2.0 | site/ja/tutorials/keras/overfit_and_underfit.ipynb | gabrielrufino/docs-l10n |
IMDBデータセットのダウンロード以前のノートブックで使用したエンベディングの代わりに、ここでは文をマルチホットエンコードします。このモデルは、訓練用データセットをすぐに過学習します。このモデルを使って、過学習がいつ起きるかということと、どうやって過学習と戦うかをデモします。リストをマルチホットエンコードすると言うのは、0と1のベクトルにするということです。具体的にいうと、例えば`[3, 5]`というシーケンスを、インデックス3と5の値が1で、それ以外がすべて0の、10,000次元のベクトルに変換するということを意味します。 | NUM_WORDS = 10000
(train_data, train_labels), (test_data, test_labels) = keras.datasets.imdb.load_data(num_words=NUM_WORDS)
def multi_hot_sequences(sequences, dimension):
# 形状が (len(sequences), dimension)ですべて0の行列を作る
results = np.zeros((len(sequences), dimension))
for i, word_indices in enumerate(sequences... | _____no_output_____ | Apache-2.0 | site/ja/tutorials/keras/overfit_and_underfit.ipynb | gabrielrufino/docs-l10n |
結果として得られるマルチホットベクトルの1つを見てみましょう。単語のインデックスは頻度順にソートされています。このため、インデックスが0に近いほど1が多く出現するはずです。分布を見てみましょう。 | plt.plot(train_data[0]) | _____no_output_____ | Apache-2.0 | site/ja/tutorials/keras/overfit_and_underfit.ipynb | gabrielrufino/docs-l10n |
過学習のデモ過学習を防止するための最も単純な方法は、モデルのサイズ、すなわち、モデル内の学習可能なパラメータの数を小さくすることです(学習パラメータの数は、層の数と層ごとのユニット数で決まります)。ディープラーニングでは、モデルの学習可能なパラメータ数を、しばしばモデルの「キャパシティ」と呼びます。直感的に考えれば、パラメータ数の多いモデルほど「記憶容量」が大きくなり、訓練用のサンプルとその目的変数の間の辞書のようなマッピングをたやすく学習することができます。このマッピングには汎化能力がまったくなく、これまで見たことが無いデータを使って予測をする際には役に立ちません。ディープラーニングのモデルは訓練用データに適応しやすいけれど、本... | baseline_model = keras.Sequential([
# `.summary` を見るために`input_shape`が必要
keras.layers.Dense(16, activation='relu', input_shape=(NUM_WORDS,)),
keras.layers.Dense(16, activation='relu'),
keras.layers.Dense(1, activation='sigmoid')
])
baseline_model.compile(optimizer='adam',
loss='b... | _____no_output_____ | Apache-2.0 | site/ja/tutorials/keras/overfit_and_underfit.ipynb | gabrielrufino/docs-l10n |
より小さいモデルの構築 今作成したばかりの比較基準となるモデルに比べて隠れユニット数が少ないモデルを作りましょう。 | smaller_model = keras.Sequential([
keras.layers.Dense(4, activation='relu', input_shape=(NUM_WORDS,)),
keras.layers.Dense(4, activation='relu'),
keras.layers.Dense(1, activation='sigmoid')
])
smaller_model.compile(optimizer='adam',
loss='binary_crossentropy',
met... | _____no_output_____ | Apache-2.0 | site/ja/tutorials/keras/overfit_and_underfit.ipynb | gabrielrufino/docs-l10n |
同じデータを使って訓練します。 | smaller_history = smaller_model.fit(train_data,
train_labels,
epochs=20,
batch_size=512,
validation_data=(test_data, test_labels),
verbose=2... | _____no_output_____ | Apache-2.0 | site/ja/tutorials/keras/overfit_and_underfit.ipynb | gabrielrufino/docs-l10n |
より大きなモデルの構築練習として、より大きなモデルを作成し、どれほど急速に過学習が起きるかを見ることもできます。次はこのベンチマークに、この問題が必要とするよりはるかに容量の大きなネットワークを追加しましょう。 | bigger_model = keras.models.Sequential([
keras.layers.Dense(512, activation='relu', input_shape=(NUM_WORDS,)),
keras.layers.Dense(512, activation='relu'),
keras.layers.Dense(1, activation='sigmoid')
])
bigger_model.compile(optimizer='adam',
loss='binary_crossentropy',
... | _____no_output_____ | Apache-2.0 | site/ja/tutorials/keras/overfit_and_underfit.ipynb | gabrielrufino/docs-l10n |
このモデルもまた同じデータを使って訓練します。 | bigger_history = bigger_model.fit(train_data, train_labels,
epochs=20,
batch_size=512,
validation_data=(test_data, test_labels),
verbose=2) | _____no_output_____ | Apache-2.0 | site/ja/tutorials/keras/overfit_and_underfit.ipynb | gabrielrufino/docs-l10n |
訓練時と検証時の損失をグラフにする 実線は訓練用データセットの損失、破線は検証用データセットでの損失です(検証用データでの損失が小さい方が良いモデルです)。これをみると、小さいネットワークのほうが比較基準のモデルよりも過学習が始まるのが遅いことがわかります(4エポックではなく6エポック後)。また、過学習が始まっても性能の低下がよりゆっくりしています。 | def plot_history(histories, key='binary_crossentropy'):
plt.figure(figsize=(16,10))
for name, history in histories:
val = plt.plot(history.epoch, history.history['val_'+key],
'--', label=name.title()+' Val')
plt.plot(history.epoch, history.history[key], color=val[0].get_color(),
... | _____no_output_____ | Apache-2.0 | site/ja/tutorials/keras/overfit_and_underfit.ipynb | gabrielrufino/docs-l10n |
より大きなネットワークでは、すぐに、1エポックで過学習が始まり、その度合も強いことに注目してください。ネットワークの容量が大きいほど訓練用データをモデル化するスピードが早くなり(結果として訓練時の損失値が小さくなり)ますが、より過学習しやすく(結果として訓練時の損失値と検証時の損失値が大きく乖離しやすく)なります。 過学習防止の戦略 重みの正則化を加える 「オッカムの剃刀」の原則をご存知でしょうか。何かの説明が2つあるとすると、最も正しいと考えられる説明は、仮定の数が最も少ない「一番単純な」説明だというものです。この原則は、ニューラルネットワークを使って学習されたモデルにも当てはまります。ある訓練用データとネットワーク構造があっ... | l2_model = keras.models.Sequential([
keras.layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001),
activation='relu', input_shape=(NUM_WORDS,)),
keras.layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001),
activation='relu'),
keras.layers.De... | _____no_output_____ | Apache-2.0 | site/ja/tutorials/keras/overfit_and_underfit.ipynb | gabrielrufino/docs-l10n |
```l2(0.001)```というのは、層の重み行列の係数全てに対して```0.001 * 重み係数の値 **2```をネットワークの損失値合計に加えることを意味します。このペナルティは訓練時のみに加えられるため、このネットワークの損失値は、訓練時にはテスト時に比べて大きくなることに注意してください。L2正則化の影響を見てみましょう。 | plot_history([('baseline', baseline_history),
('l2', l2_model_history)]) | _____no_output_____ | Apache-2.0 | site/ja/tutorials/keras/overfit_and_underfit.ipynb | gabrielrufino/docs-l10n |
ご覧のように、L2正則化ありのモデルは比較基準のモデルに比べて過学習しにくくなっています。両方のモデルのパラメータ数は同じであるにもかかわらずです。 ドロップアウトを追加するドロップアウトは、ニューラルネットワークの正則化テクニックとして最もよく使われる手法の一つです。この手法は、トロント大学のヒントンと彼の学生が開発したものです。ドロップアウトは層に適用するもので、訓練時に層から出力された特徴量に対してランダムに「ドロップアウト(つまりゼロ化)」を行うものです。例えば、ある層が訓練時にある入力サンプルに対して、普通は`[0.2, 0.5, 1.3, 0.8, 1.1]` というベクトルを出力するとします。ドロップアウトを適用する... | dpt_model = keras.models.Sequential([
keras.layers.Dense(16, activation='relu', input_shape=(NUM_WORDS,)),
keras.layers.Dropout(0.5),
keras.layers.Dense(16, activation='relu'),
keras.layers.Dropout(0.5),
keras.layers.Dense(1, activation='sigmoid')
])
dpt_model.compile(optimizer='adam',
... | _____no_output_____ | Apache-2.0 | site/ja/tutorials/keras/overfit_and_underfit.ipynb | gabrielrufino/docs-l10n |
An Auto correct system is an application that changes mispelled words into the correct ones. | # In this notebook I'll show how to implement an Auto Correct System that its very usefull.
# This auto correct system only search for spelling erros, not contextual errors. | _____no_output_____ | MIT | Auto Correct System/.ipynb_checkpoints/Auto Correct System-checkpoint.ipynb | rodrigoamorimml/NaturalLanguageProcessing |
*The implementation can be divided into 4 steps:*[1]. **Identity a mispelled word.**[2]. **Find strings n Edit Distance away**[3]. **Filter Candidates** (*as Real Words that are spelled correct*)[4]. **Calculate Word Probabilities.** (*Choose the most likely cadidate to be the replacement*) 1. Identity a mispelled Wor... | vocab = ['dean','deer','dear','fries','and','coke', 'congratulations', 'my']
word_test = 'Congratulations my deah'
word_test = word_test.lower()
word_test = word_test.split()
for word in word_test:
if word in vocab:
print(f'The word: {word} is in the vocab')
else:
print(f"The word: {word} isn'... | The word: congratulations is in the vocab
The word: my is in the vocab
The word: deah isn't in the vocabulary
| MIT | Auto Correct System/.ipynb_checkpoints/Auto Correct System-checkpoint.ipynb | rodrigoamorimml/NaturalLanguageProcessing |
2. Find strings n Edit Distance Away*Edit is a operation performed on a string to change into another string. Edit distance count the number of these operations**So **n Edit Distance** tells you how many operations away one string is from another.**For this application we'll use the Levenshtein Distance value's cost, ... | # To implement this operations we need to split the word into 2 parts in all possible ways
word = 'dear'
split_word = [[word[:i], word[i:]] for i in range(len(word) + 1)]
for i in split_word:
print(i)
# The delete operation need to delete each possible letter from the original word.
delete_operation = [[L + R[1:... | the first replace operations:
aear
bear
cear
dear
the last replace operations:
deaw
deax
deay
deaz
| MIT | Auto Correct System/.ipynb_checkpoints/Auto Correct System-checkpoint.ipynb | rodrigoamorimml/NaturalLanguageProcessing |
3. Filter Candidates*We only want to consider real and correctly spelled words form the candidate lists, so we need to compare to a know dictionary.**If the string does not appears in the dict, remove from the candidates, this way resulting in a list of actual words only* | vocab = ['dean','deer','dear','fries','and','coke', 'congratulations', 'my']
# for example we can use the replace operations words to filter in our vocab
filtered_words = [word for word in replace_operation if word in vocab]
print(filtered_words) | ['deer', 'dean']
| MIT | Auto Correct System/.ipynb_checkpoints/Auto Correct System-checkpoint.ipynb | rodrigoamorimml/NaturalLanguageProcessing |
4. Calculate the words probabilities*We need to find the most likely word from the cadidate list, to calculate the probability of a word in the sentence we need to first calculate the word frequencies, also we want to count the total number of word in the body of textsor corpus.**So we compute the probability that eac... | # import libraries
import re
from collections import Counter
import numpy as np
import pandas as pd | _____no_output_____ | MIT | Auto Correct System/.ipynb_checkpoints/Auto Correct System-checkpoint.ipynb | rodrigoamorimml/NaturalLanguageProcessing |
*The first thing to do is the data pre processing, for this example we'll use the file called **'shakespeare.txt'** this file can be found in the directory.* | def process_data(filename):
"""
Input:
A file_name which is found in the current directory. We just have to read it in.
Output:
words: a list containing all the words in the corpus (text file you read) in lower case.
"""
words = []
with open(filename, 'r') as f:
... | The vocabulary has 6116 unique words.
| MIT | Auto Correct System/.ipynb_checkpoints/Auto Correct System-checkpoint.ipynb | rodrigoamorimml/NaturalLanguageProcessing |
*The second step, we need to count the frequency of every word in the dictionary to later calculate the probabilities* | def get_count(word):
'''
Input:
word_l: a set of words representing the corpus.
Output:
word_count_dict: The wordcount dictionary where key is the word and value is its frequency.
'''
word_count_dict = {}
word_count_dict = Counter(word)
return word_count_dict
wor... | There are 6116 key par values
The count for the word 'thee' is 240
| MIT | Auto Correct System/.ipynb_checkpoints/Auto Correct System-checkpoint.ipynb | rodrigoamorimml/NaturalLanguageProcessing |
*Now we must calculate the probability that each word appears using the (eq 01):* |
def get_probs(word_count_dict):
'''
Input:
word_count_dict: The wordcount dictionary where key is the word and value is its frequency.
Output:
probs: A dictionary where keys are the words and the values are the probability that a word will occur.
'''
probs = {}
total_words... | Length of probs is 6116
P('thee') is 0.0045
| MIT | Auto Correct System/.ipynb_checkpoints/Auto Correct System-checkpoint.ipynb | rodrigoamorimml/NaturalLanguageProcessing |
*Now, that we have computed $P(w_i)$ for all the words in the corpus, we'll write the functions such as delete, insert, switch and replace to manipulate strings so that we can edit the erroneous strings and return the right spellings of the words.* | def delete_letter(word, verbose = False):
'''
Input:
word: the string/word for which you will generate all possible words
in the vocabulary which have 1 missing character
Output:
delete_l: a list of all possible strings obtained by deleting 1 character from word
'''
... | Input word at
split = [('', 'at'), ('a', 't'), ('at', '')]
insert = ['aat', 'bat', 'cat', 'dat', 'eat', 'fat', 'gat', 'hat', 'iat', 'jat', 'kat', 'lat', 'mat', 'nat', 'oat', 'pat', 'qat', 'rat', 'sat', 'tat', 'uat', 'vat', 'wat', 'xat', 'yat', 'zat', 'aat', 'abt', 'act', 'adt', 'aet', 'aft', 'agt', 'aht', 'ait', 'ajt... | MIT | Auto Correct System/.ipynb_checkpoints/Auto Correct System-checkpoint.ipynb | rodrigoamorimml/NaturalLanguageProcessing |
*Now that we have implemented the string manipulations, we'll create two functions that, given a string, will return all the possible single and double edits on that string. These will be `edit_one_letter()` and `edit_two_letters()`.* | def edit_one_letter(word, allow_switches = True): # The 'switch' function is a less common edit function,
# so will be selected by an "allow_switches" input argument.
"""
Input:
word: the string/word for which we will generate all possible wordsthat are ... | Number of strings with edit distance of two: 2654
First 10 strings ['', 'a', 'aa', 'aaa', 'aab', 'aac', 'aad', 'aae', 'aaf', 'aag']
Last 10 strings ['zv', 'zva', 'zw', 'zwa', 'zx', 'zxa', 'zy', 'zya', 'zz', 'zza']
The data type of the returned object should be a set <class 'set'>
Number of strings that are 2 edit dista... | MIT | Auto Correct System/.ipynb_checkpoints/Auto Correct System-checkpoint.ipynb | rodrigoamorimml/NaturalLanguageProcessing |
*Now we will use the `edit_two_letters` function to get a set of all the possible 2 edits on our word. We will then use those strings to get the most probable word we meant to substitute our word typing suggestion.* | def get_corrections(word, probs, vocab, n=2, verbose = False):
'''
Input:
word: a user entered string to check for suggestions
probs: a dictionary that maps each word to its probability in the corpus
vocab: a set containing all the vocabulary
n: number of possible word correctio... | entered word = dys
suggestions = {'days', 'dye'}
word 0: days, probability 0.000410
word 1: dye, probability 0.000019
The highest score for all the candidates is the word days
| MIT | Auto Correct System/.ipynb_checkpoints/Auto Correct System-checkpoint.ipynb | rodrigoamorimml/NaturalLanguageProcessing |
*Now that we have implemented the auto-correct system, how do you evaluate the similarity between two strings? For example: 'waht' and 'what'.**Also how do you efficiently find the shortest path to go from the word, 'waht' to the word 'what'?**We will implement a dynamic programming system that will tell you the minimu... | def min_edit_distance(source, target, ins_cost = 1, del_cost = 1, rep_cost = 2):
'''
Input:
source: a string corresponding to the string you are starting with
target: a string corresponding to the string you want to end with
ins_cost: an integer setting the insert cost
del_cost:... | minimum edits: 3
# n e a r
# 0 1 2 3 4
e 1 2 1 2 3
e 2 3 2 3 4
r 3 4 3 4 3
| MIT | Auto Correct System/.ipynb_checkpoints/Auto Correct System-checkpoint.ipynb | rodrigoamorimml/NaturalLanguageProcessing |
Birthday Paradox In a group of 5 people, how likely is it that everyone has a unique birthday (assuming that nobody was born on February 29th of a leap year)? You may feel it is highly likely because there are $365$ days in a year and loosely speaking, $365$ is "much greater" than $5$. Indeed, as you shall see, this p... | import itertools
import random
import matplotlib.pyplot as plt
import numpy as np
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
# Range of number of people
PEOPLE = np.arange(1, 26)
# Days in year
DAYS = 365
def prob_unique_birthdays(num_people):
'''
Re... | _____no_output_____ | MIT | Week 6 _ Condiitonal Probability/Topic6_Lecture.ipynb | ebishwaraj/ProbabilityStatisticsPython_DSE210x_UCSD_DataScienceMicroMasters |
Conditional Probability Oftentimes it is advantageous to infer the probability of certain events conditioned on other events. Say you want to estimate the probability that it will rain on a particular day. There are copious number of factors that affect rain on a particular day, but [certain clouds are good indicator... | import pandas as pd
import matplotlib.pyplot as plt | _____no_output_____ | MIT | Week 6 _ Condiitonal Probability/Topic6_Lecture.ipynb | ebishwaraj/ProbabilityStatisticsPython_DSE210x_UCSD_DataScienceMicroMasters |
The dataset consists of two parts, `student-por.csv` and `student-mat.csv`, represents the students' performance in Portuguese and Math courses, respectively. We will consider the scores in the Portuguese courses, and leave the math courses optionally to you. | data_por = pd.read_csv("student-por.csv") | _____no_output_____ | MIT | Week 6 _ Condiitonal Probability/Topic6_Lecture.ipynb | ebishwaraj/ProbabilityStatisticsPython_DSE210x_UCSD_DataScienceMicroMasters |
Of the dataset's [various attributes](https://www.kaggle.com/uciml/student-alcohol-consumption/home), we will use the following two- `G3` - final grade related with the course subject, Math or Portuguese (numeric: from 0 to 20, output target) - `studytime` - weekly study time (numeric: 1 : 10 hours) | attributes = ["G3","studytime"]
data_por = data_por[attributes] | _____no_output_____ | MIT | Week 6 _ Condiitonal Probability/Topic6_Lecture.ipynb | ebishwaraj/ProbabilityStatisticsPython_DSE210x_UCSD_DataScienceMicroMasters |
We are interested in the relationship between study-time and grade performance, but to start, let us view each attribute individually. The probability that a student's study-time falls in an interval can be approximated by$${P(\text{study interval}) = \frac{\text{Number of students with this study interval}}{Total\ num... | data_temp = data_por["studytime"].value_counts()
P_studytime = pd.DataFrame((data_temp/data_temp.sum()).sort_index())
P_studytime.index = ["< 2 hours","2 to 5 hours","5 to 10 hours","> 10 hours"]
P_studytime.columns = ["Probability"]
P_studytime.columns.name = "Study Interval"
P_studytime.plot.bar(figsize=(12,9),fonts... | _____no_output_____ | MIT | Week 6 _ Condiitonal Probability/Topic6_Lecture.ipynb | ebishwaraj/ProbabilityStatisticsPython_DSE210x_UCSD_DataScienceMicroMasters |
Note that the largest number of students studied between two and five hours, and the smallest studied over 10 hours. Let us call scores of at least 15 "high". The probability of a student getting a high score can be approximated by$$P(\text{high score}) = \frac{\text{Number of students with high scores}}{\text{Total nu... | data_temp = (data_por["G3"]>=15).value_counts()
P_score15_p = pd.DataFrame(data_temp/data_temp.sum())
P_score15_p.index = ["Low","High"]
P_score15_p.columns = ["Probability"]
P_score15_p.columns.name = "Score"
print(P_score15_p)
P_score15_p.plot.bar(figsize=(10,6),fontsize=16)
plt.xlabel("Score",fontsize=18)
plt.ylabel... | Score Probability
Low 0.798151
High 0.201849
| MIT | Week 6 _ Condiitonal Probability/Topic6_Lecture.ipynb | ebishwaraj/ProbabilityStatisticsPython_DSE210x_UCSD_DataScienceMicroMasters |
Proceeding to more interesting observations, suppose we want to find the probability of the various study-intervals when the student scored high. By conditional probability, this can be calculated by:$$P(\text{study interval}\ |\ \text{highscore})=\frac{\text{Number of students with study interval AND highscore}}{\text... | score = 15
data_temp = data_por.loc[data_por["G3"]>=score,"studytime"]
P_T_given_score15= pd.DataFrame((data_temp.value_counts()/data_temp.shape[0]).sort_index())
P_T_given_score15.index = ["< 2 hours","2 to 5 hours","5 to 10 hours","> 10 hours"]
P_T_given_score15.columns = ["Probability"]
print("Probability of study i... | Probability of study interval given that the student gets a highscore:
| MIT | Week 6 _ Condiitonal Probability/Topic6_Lecture.ipynb | ebishwaraj/ProbabilityStatisticsPython_DSE210x_UCSD_DataScienceMicroMasters |
The above metric is something we can only calculate after the students have obtained their results. But how about the other way? What if we want to **predict** the probability that a student gets a score greater than 15 given that they studied for a particular period of time . Using the estimated values we can use the ... | P_score15_given_T_p = P_T_given_score15 * P_score15_p.loc["High"] / P_studytime
print("Probability of high score given study interval :")
pd.DataFrame(P_score15_given_T_p).plot.bar(figsize=(12,9),fontsize=18).legend(loc="best")
plt.xlabel("Study interval",fontsize=18)
plt.ylabel("Probability",fontsize=18) | Probability of high score given study interval :
| MIT | Week 6 _ Condiitonal Probability/Topic6_Lecture.ipynb | ebishwaraj/ProbabilityStatisticsPython_DSE210x_UCSD_DataScienceMicroMasters |
Do you find the results surprising? Roughly speaking, the longer students study, the more likely they are to score high. However, once they study over 10 hours, their chances of scoring high decline. You may want to check whether the same phenomenon occurs for the math scores too. Try it yourself If interested, you ... | data_math = pd.read_csv("student-mat.csv")
data_temp = data_math["studytime"].value_counts()
P_studytime_m = pd.DataFrame(data_temp/data_temp.sum())
P_studytime_m.index = ["< 2 hours","2 to 5 hours","5 to 10 hours","> 10 hours"]
P_studytime_m.columns = ["Probability"]
P_studytime_m.columns.name = "Study Interval"
P_stu... | _____no_output_____ | MIT | Week 6 _ Condiitonal Probability/Topic6_Lecture.ipynb | ebishwaraj/ProbabilityStatisticsPython_DSE210x_UCSD_DataScienceMicroMasters |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.