markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Unique values
Sometimes it is helpful to know what unique values are in a column. Especially when there are many rows (millions), it is impractical to manually scan through the columns to look for unique values. However, we can use a pandas function unique() to do just that. We will see this is particularly helpful in ... | sampledata['CatCol'].unique() | Class03/Class03.ipynb | madsenmj/ml-introduction-course | apache-2.0 |
Text regex features
Another type of text feature extraction using a regex or regular expression pattern recognition code. The date/time conversion uses one form of this, but we can be more general in identifying patterns. There are some very useful tools for testing your pattern. I like the tester at https://regex101.c... | # This simple text pattern gathers all the letters up to (but not including) the last 'e' in the text entry. There are lots of other pattern recognition tools to extract features from text.
# Note that it returns "NaN" if there are no 'e's in the text string. We could use that to find all the strings without an 'e' in ... | Class03/Class03.ipynb | madsenmj/ml-introduction-course | apache-2.0 |
Converting to categorical
We already saw how to convert text columns to categorical columns. We can also covert other data types to categorical columns. For example, we could bin a float column into regularly sized bins, then create a categorical column from those bins.
Word/Text cleaning
Finally, it is often useful to... | textDF = pd.read_csv('Class03_text.tsv',sep='\t')
testcase = textDF['review'][3]
testcase | Class03/Class03.ipynb | madsenmj/ml-introduction-course | apache-2.0 |
The first thing we notice is that there are hypertext bits in the text (the <br /> items). We want to clean all of those out. The BeautifulSoup function does this for us. | from bs4 import BeautifulSoup
cleantext = BeautifulSoup(testcase,"html5lib").text
cleantext | Class03/Class03.ipynb | madsenmj/ml-introduction-course | apache-2.0 |
We now want to get rid of everything that isn't an alphabetical letter. That will clean up all punctuation and get rid of all numbers. We'll use a regex substitution function to do this. It looks for everything that is not an alphabetical character and replaces it with a blank space. | import re
onlyletters = re.sub("[^a-zA-Z]"," ",cleantext)
onlyletters | Class03/Class03.ipynb | madsenmj/ml-introduction-course | apache-2.0 |
We'll get rid of upper-case letters to only look at the words themselves. | lowercase = onlyletters.lower()
lowercase | Class03/Class03.ipynb | madsenmj/ml-introduction-course | apache-2.0 |
The next two steps we'll do at once because we need to split up the text into individual words to do them. The split() function breaks up the string into an array of words. We will then eliminate any words that are stopwords in English. These are words like "and", "or", "the" that don't communciate any information but ... | import nltk
from nltk.corpus import stopwords # Import the stop word list
words = lowercase.split()
meaningfulwords = [w for w in words if not w in stopwords.words("english")]
from nltk.stem import SnowballStemmer
snowball_stemmer = SnowballStemmer("english")
stemmedwords = [snowball_stemmer.stem(w) for w in meanin... | Class03/Class03.ipynb | madsenmj/ml-introduction-course | apache-2.0 |
Data Cleaning Example In-class Activity
The tutorial on cleaning messy data is located here: http://nbviewer.jupyter.org/github/jvns/pandas-cookbook/blob/v0.1/cookbook/Chapter%207%20-%20Cleaning%20up%20messy%20data.ipynb
Follow the tutorial, looking at the data and how to do a preliminary clean to eliminate entries tha... | requests = pd.read_csv("Class03_311_data.csv") | Class03/Class03.ipynb | madsenmj/ml-introduction-course | apache-2.0 |
This was developed using Python 3.6 (Anaconda) and TensorFlow version: | tf.__version__ | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Load Data
The MNIST data-set is about 12 MB and will be downloaded automatically if it is not located in the given path. | from mnist import MNIST
data = MNIST(data_dir="data/MNIST/") | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The MNIST data-set has now been loaded and consists of 70.000 images and class-numbers for the images. The data-set is split into 3 mutually exclusive sub-sets. We will only use the training and test-sets in this tutorial. | print("Size of:")
print("- Training-set:\t\t{}".format(data.num_train))
print("- Validation-set:\t{}".format(data.num_val))
print("- Test-set:\t\t{}".format(data.num_test)) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Copy some of the data-dimensions for convenience. | # The number of pixels in each dimension of an image.
img_size = data.img_size
# The images are stored in one-dimensional arrays of this length.
img_size_flat = data.img_size_flat
# Tuple with height and width of images used to reshape arrays.
img_shape = data.img_shape
# Number of classes, one class for each of 10 ... | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-functions for plotting images
Function used to plot 9 images in a 3x3 grid, and writing the true and predicted classes below each image. | def plot_images(images, cls_true, cls_pred=None):
assert len(images) == len(cls_true) == 9
# Create figure with 3x3 sub-plots.
fig, axes = plt.subplots(3, 3)
fig.subplots_adjust(hspace=0.3, wspace=0.3)
for i, ax in enumerate(axes.flat):
# Plot image.
ax.imshow(images[i].reshape... | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Function used to plot 10 images in a 2x5 grid. | def plot_images10(images, smooth=True):
# Interpolation type.
if smooth:
interpolation = 'spline16'
else:
interpolation = 'nearest'
# Create figure with sub-plots.
fig, axes = plt.subplots(2, 5)
# Adjust vertical spacing.
fig.subplots_adjust(hspace=0.1, wspace=0.1)
# F... | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Function used to plot a single image. | def plot_image(image):
plt.imshow(image, interpolation='nearest', cmap='binary')
plt.xticks([])
plt.yticks([]) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Plot a few images to see if data is correct | # Get the first images from the test-set.
images = data.x_test[0:9]
# Get the true classes for those images.
cls_true = data.y_test_cls[0:9]
# Plot the images and labels using our helper-function above.
plot_images(images=images, cls_true=cls_true) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
TensorFlow Graph
The neural network is constructed as a computational graph in TensorFlow using the tf.layers API, which is described in detail in Tutorial #03-B.
Placeholder variables
Placeholder variables serve as the input to the TensorFlow computational graph that we may change each time we execute the graph.
First... | x = tf.placeholder(tf.float32, shape=[None, img_size_flat], name='x') | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The convolutional layers expect x to be encoded as a 4-rank tensor so we have to reshape it so its shape is instead [num_images, img_height, img_width, num_channels]. Note that img_height == img_width == img_size and num_images can be inferred automatically by using -1 for the size of the first dimension. So the reshap... | x_image = tf.reshape(x, [-1, img_size, img_size, num_channels]) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Next we have the placeholder variable for the true labels associated with the images that were input in the placeholder variable x. The shape of this placeholder variable is [None, num_classes] which means it may hold an arbitrary number of labels and each label is a vector of length num_classes which is 10 in this cas... | y_true = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_true') | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
We could also have a placeholder variable for the class-number, but we will instead calculate it using argmax. Note that this is a TensorFlow operator so nothing is calculated at this point. | y_true_cls = tf.argmax(y_true, axis=1) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Neural Network
We now implement the Convolutional Neural Network using the Layers API. We use the net-variable to refer to the last layer while building the neural network. This makes it easy to add or remove layers in the code if you want to experiment. First we set the net-variable to the reshaped input image. | net = x_image | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The input image is then input to the first convolutional layer, which has 16 filters each of size 5x5 pixels. The activation-function is the Rectified Linear Unit (ReLU) described in more detail in Tutorial #02. | net = tf.layers.conv2d(inputs=net, name='layer_conv1', padding='same',
filters=16, kernel_size=5, activation=tf.nn.relu) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
After the convolution we do a max-pooling which is also described in Tutorial #02. | net = tf.layers.max_pooling2d(inputs=net, pool_size=2, strides=2) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Then we make a second convolutional layer, also with max-pooling. | net = tf.layers.conv2d(inputs=net, name='layer_conv2', padding='same',
filters=36, kernel_size=5, activation=tf.nn.relu)
net = tf.layers.max_pooling2d(inputs=net, pool_size=2, strides=2) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The output then needs to be flattened so it can be used in fully-connected (aka. dense) layers. | net = tf.layers.flatten(net)
# This should eventually be replaced by:
# net = tf.layers.flatten(net) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
We can now add fully-connected (or dense) layers to the neural network. | net = tf.layers.dense(inputs=net, name='layer_fc1',
units=128, activation=tf.nn.relu) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
We need the neural network to classify the input images into 10 different classes. So the final fully-connected layer has num_classes=10 output neurons. | net = tf.layers.dense(inputs=net, name='layer_fc_out',
units=num_classes, activation=None) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The outputs of the final fully-connected layer are sometimes called logits, so we have a convenience variable with that name which we will also use further below. | logits = net | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
We use the softmax function to 'squash' the outputs so they are between zero and one, and so they sum to one. | y_pred = tf.nn.softmax(logits=logits) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
This tells us how likely the neural network thinks the input image is of each possible class. The one that has the highest value is considered the most likely so its index is taken to be the class-number. | y_pred_cls = tf.argmax(y_pred, axis=1) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Loss-Function to be Optimized
To make the model better at classifying the input images, we must somehow change the variables of the neural network.
The cross-entropy is a performance measure used in classification. The cross-entropy is a continuous function that is always positive and if the predicted output of the mod... | cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_true, logits=logits) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
We have now calculated the cross-entropy for each of the image classifications so we have a measure of how well the model performs on each image individually. But in order to use the cross-entropy to guide the optimization of the model's variables we need a single scalar value, so we simply take the average of the cros... | loss = tf.reduce_mean(cross_entropy) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Optimization Method
Now that we have a cost measure that must be minimized, we can then create an optimizer. In this case it is the Adam optimizer with a learning-rate of 1e-4.
Note that optimization is not performed at this point. In fact, nothing is calculated at all, we just add the optimizer-object to the TensorFlo... | optimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(loss) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Classification Accuracy
We need to calculate the classification accuracy so we can report progress to the user.
First we create a vector of booleans telling us whether the predicted class equals the true class of each image. | correct_prediction = tf.equal(y_pred_cls, y_true_cls) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The classification accuracy is calculated by first type-casting the vector of booleans to floats, so that False becomes 0 and True becomes 1, and then taking the average of these numbers. | accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Optimize the Neural Network
Create TensorFlow session
Once the TensorFlow graph has been created, we have to create a TensorFlow session which is used to execute the graph. | session = tf.Session() | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Initialize variables
The variables for the TensorFlow graph must be initialized before we start optimizing them. | session.run(tf.global_variables_initializer()) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-function to perform optimization iterations
There are 55,000 images in the training-set. It takes a long time to calculate the gradient of the model using all these images. We therefore only use a small batch of images in each iteration of the optimizer.
If your computer crashes or becomes very slow because you ... | train_batch_size = 64 | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
This function performs a number of optimization iterations so as to gradually improve the variables of the neural network layers. In each iteration, a new batch of data is selected from the training-set and then TensorFlow executes the optimizer using those training samples. The progress is printed every 100 iteration... | # Counter for total number of iterations performed so far.
total_iterations = 0
def optimize(num_iterations):
# Ensure we update the global variable rather than a local copy.
global total_iterations
for i in range(total_iterations,
total_iterations + num_iterations):
# Get a ba... | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-function to plot example errors
Function for plotting examples of images from the test-set that have been mis-classified. | def plot_example_errors(cls_pred, correct):
# This function is called from print_test_accuracy() below.
# cls_pred is an array of the predicted class-number for
# all images in the test-set.
# correct is a boolean array whether the predicted class
# is equal to the true class for each image in the... | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-function to plot confusion matrix | def plot_confusion_matrix(cls_pred):
# This is called from print_test_accuracy() below.
# cls_pred is an array of the predicted class-number for
# all images in the test-set.
# Get the true classifications for the test-set.
cls_true = data.y_test_cls
# Get the confusion matrix using sklea... | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-function for showing the performance
Below is a function for printing the classification accuracy on the test-set.
It takes a while to compute the classification for all the images in the test-set, that's why the results are re-used by calling the above functions directly from this function, so the classificatio... | # Split the test-set into smaller batches of this size.
test_batch_size = 256
def print_test_accuracy(show_example_errors=False,
show_confusion_matrix=False):
# Number of images in the test-set.
num_test = data.num_test
# Allocate an array for the predicted classes which
# wil... | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Performance before any optimization
The accuracy on the test-set is very low because the variables for the neural network have only been initialized and not optimized at all, so it just classifies the images randomly. | print_test_accuracy() | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Performance after 10,000 optimization iterations
After 10,000 optimization iterations, the model has a classification accuracy on the test-set of about 99%. | %%time
optimize(num_iterations=10000)
print_test_accuracy(show_example_errors=True,
show_confusion_matrix=True) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Optimizing the Input Images
Now that the neural network has been optimized so it can recognize hand-written digits with about 99% accuracy, we will then find the input images that maximize certain features inside the neural network. This will show us what images the neural network likes to see the most.
We will do this... | def get_conv_layer_names():
graph = tf.get_default_graph()
# Create a list of names for the operations in the graph
# for the Inception model where the operator-type is 'Conv2D'.
names = [op.name for op in graph.get_operations() if op.type=='Conv2D']
return names
conv_names = get_conv_layer_n... | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-function for finding the input image
This function finds the input image that maximizes a given feature in the network. It essentially just performs optimization with gradient ascent. The image is initialized with small random values and is then iteratively updated using the gradient for the given feature with r... | def optimize_image(conv_id=None, feature=0,
num_iterations=30, show_progress=True):
"""
Find an image that maximizes the feature
given by the conv_id and feature number.
Parameters:
conv_id: Integer identifying the convolutional layer to
maximize. It is an index into... | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
This next function finds the images that maximize the first 10 features of a layer, by calling the above function 10 times. | def optimize_images(conv_id=None, num_iterations=30):
"""
Find 10 images that maximize the 10 first features in the layer
given by the conv_id.
Parameters:
conv_id: Integer identifying the convolutional layer to
maximize. It is an index into conv_names.
If None then us... | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
First Convolutional Layer
These are the input images that maximize the features in the first convolutional layer, so these are the images that it likes to see. | optimize_images(conv_id=0) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Note how these are very simple shapes such as lines and angles. Some of these images may be completely white, which suggests that those features of the neural network are perhaps unused, so the number of features could be reduced in this layer.
Second Convolutional Layer
This shows the images that maximize the features... | optimize_images(conv_id=1) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Final output layer
Now find the image for the 2nd feature of the final output of the neural network. That is, we want to find an image that makes the neural network classify that image as the digit 2. This is the image that the neural network likes to see the most for the digit 2. | image = optimize_image(conv_id=None, feature=2,
num_iterations=10, show_progress=True) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Note how the predicted class indeed becomes 2 already within the first few iterations so the optimization is working as intended. Also note how the loss-measure is increasing rapidly until it apparently converges. This is because the loss-measure is actually just the value of the feature or neuron that we are trying to... | plot_image(image) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Although some of the curves do hint somewhat at the digit 2, it is hard for a human to see why the neural network believes this is the optimal image for the digit 2. This can only be understood when the optimal images for the remaining digits are also shown. | optimize_images(conv_id=None) | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
These images may vary each time you run the optimization. Some of the images can be seen to somewhat resemble the hand-written digits. But the other images are often impossible to recognize and it is hard to understand why the neural network thinks these are the optimal input images for those digits.
The reason is perh... | # This has been commented out in case you want to modify and experiment
# with the Notebook without having to restart it.
# session.close() | 13B_Visual_Analysis_MNIST.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Lesson: Develop a Predictive Theory | print("labels.txt \t : \t reviews.txt\n")
pretty_print_review_and_label(2137)
pretty_print_review_and_label(12816)
pretty_print_review_and_label(6267)
pretty_print_review_and_label(21934)
pretty_print_review_and_label(5297)
pretty_print_review_and_label(4998) | sentiment_network/Sentiment Classification - How to Best Frame a Problem for a Neural Network (Lesson 5).ipynb | y2ee201/Deep-Learning-Nanodegree | mit |
Project 1: Quick Theory Validation | from collections import Counter
import numpy as np
positive_counts = Counter()
negative_counts = Counter()
total_counts = Counter()
for i in range(len(reviews)):
if(labels[i] == 'POSITIVE'):
for word in reviews[i].split(" "):
positive_counts[word] += 1
total_counts[word] += 1
e... | sentiment_network/Sentiment Classification - How to Best Frame a Problem for a Neural Network (Lesson 5).ipynb | y2ee201/Deep-Learning-Nanodegree | mit |
Transforming Text into Numbers | from IPython.display import Image
review = "This was a horrible, terrible movie."
Image(filename='sentiment_network.png')
review = "The movie was excellent"
Image(filename='sentiment_network_pos.png') | sentiment_network/Sentiment Classification - How to Best Frame a Problem for a Neural Network (Lesson 5).ipynb | y2ee201/Deep-Learning-Nanodegree | mit |
Project 2: Creating the Input/Output Data | vocab = set(total_counts.keys())
vocab_size = len(vocab)
print(vocab_size)
list(vocab)
import numpy as np
layer_0 = np.zeros((1,vocab_size))
layer_0
from IPython.display import Image
Image(filename='sentiment_network.png')
word2index = {}
for i,word in enumerate(vocab):
word2index[word] = i
word2index
def up... | sentiment_network/Sentiment Classification - How to Best Frame a Problem for a Neural Network (Lesson 5).ipynb | y2ee201/Deep-Learning-Nanodegree | mit |
Project 3: Building a Neural Network
Start with your neural network from the last chapter
3 layer neural network
no non-linearity in hidden layer
use our functions to create the training data
create a "pre_process_data" function to create vocabulary for our training data generating functions
modify "train" to train ov... | import time
import sys
import numpy as np
# Let's tweak our network from before to model these phenomena
class SentimentNetwork:
def __init__(self, reviews,labels,hidden_nodes = 10, learning_rate = 0.1):
# set our random number generator
np.random.seed(1)
self.pre_process_data... | sentiment_network/Sentiment Classification - How to Best Frame a Problem for a Neural Network (Lesson 5).ipynb | y2ee201/Deep-Learning-Nanodegree | mit |
Understanding Neural Noise | from IPython.display import Image
Image(filename='sentiment_network.png')
def update_input_layer(review):
global layer_0
# clear out previous state, reset the layer to be all 0s
layer_0 *= 0
for word in review.split(" "):
layer_0[0][word2index[word]] += 1
update_input_layer(reviews[0... | sentiment_network/Sentiment Classification - How to Best Frame a Problem for a Neural Network (Lesson 5).ipynb | y2ee201/Deep-Learning-Nanodegree | mit |
Project 4: Reducing Noise in our Input Data | import time
import sys
import numpy as np
# Let's tweak our network from before to model these phenomena
class SentimentNetwork:
def __init__(self, reviews,labels,hidden_nodes = 10, learning_rate = 0.1):
# set our random number generator
np.random.seed(1)
self.pre_process_data... | sentiment_network/Sentiment Classification - How to Best Frame a Problem for a Neural Network (Lesson 5).ipynb | y2ee201/Deep-Learning-Nanodegree | mit |
Analyzing Inefficiencies in our Network | Image(filename='sentiment_network_sparse.png')
layer_0 = np.zeros(10)
layer_0
layer_0[4] = 1
layer_0[9] = 1
layer_0
weights_0_1 = np.random.randn(10,5)
layer_0.dot(weights_0_1)
indices = [4,9]
layer_1 = np.zeros(5)
for index in indices:
layer_1 += (weights_0_1[index])
layer_1
Image(filename='sentiment_ne... | sentiment_network/Sentiment Classification - How to Best Frame a Problem for a Neural Network (Lesson 5).ipynb | y2ee201/Deep-Learning-Nanodegree | mit |
Acquire data
The Python Pandas packages helps us work with our datasets. We start by acquiring the training and testing datasets into Pandas DataFrames. | # read titanic training & test csv files as a pandas DataFrame
train_df = pd.read_csv('data/titanic-kaggle/train.csv')
test_df = pd.read_csv('data/titanic-kaggle/test.csv') | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Analyze by describing data
Pandas also helps describe the datasets answering following questions early in our project.
Which features are available in the dataset?
Noting the feature names for directly manipulating or analyzing these. These feature names are described on the Kaggle data page here. | print train_df.columns.values | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Which features are categorical?
These values classify the samples into sets of similar samples. Within categorical features are the values nominal, ordinal, ratio, or interval based? Among other things this helps us select the appropriate plots for visualization.
Categorical: Survived, Sex, and Embarked. Ordinal: Pcla... | # preview the data
train_df.head() | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Which features are mixed data types?
Numerical, alphanumeric data within same feature. These are candidates for correcting goal.
Ticket is a mix of numeric and alphanumeric data types. Cabin is alphanumeric.
Which features may contain errors or typos?
This is harder to review for a large dataset, however reviewing a ... | train_df.tail() | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Which features contain blank, null or empty values?
These will require correcting.
Cabin > Age > Embarked features contain a number of null values in that order for the training dataset.
Cabin > Age are incomplete in case of test dataset.
What are the data types for various features?
Helping us during converting goal... | train_df.info()
print('_'*40)
test_df.info() | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
What is the distribution of numerical feature values across the samples?
This helps us determine, among other early insights, how representative is the training dataset of the actual problem domain.
Total samples are 891 or 40% of the actual number of passengers on board the Titanic (2,224).
Survived is a categorical ... | train_df.describe(percentiles=[.25, .5, .75])
# Review survived rate using `percentiles=[.61, .62]` knowing our problem description mentions 38% survival rate.
# Review Parch distribution using `percentiles=[.75, .8]`
# Sibling distribution `[.65, .7]`
# Age and Fare `[.1, .2, .3, .4, .5, .6, .7, .8, .9, .99]` | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
What is the distribution of categorical features?
Names are unique across the dataset (count=unique=891)
Sex variable as two possible values with 65% male (top=male, freq=577/count=891).
Cabin values have several dupicates across samples. Alternatively several passengers shared a cabin.
Embarked takes three possible v... | train_df.describe(include=['O']) | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Assumtions based on data analysis
We arrive at following assumptions based on data analysis done so far. We may validate these assumptions further before taking appropriate actions.
Completing.
We may want to complete Age feature as it is definitely correlated to survival.
We may want to complete the Embarked feature ... | g = sns.FacetGrid(train_df, col='Survived')
g.map(plt.hist, 'Age', bins=20) | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
We can combine multiple features for identifying correlations using a single plot. This can be done with numerical and categorical features which have numeric values.
Observations.
Pclass=3 had most passengers, however most did not survive. Confirms our classifying assumption #2.
Infant passengers in Pclass=2 mostly s... | grid = sns.FacetGrid(train_df, col='Pclass', hue='Survived')
grid.map(plt.hist, 'Age', alpha=.5, bins=20)
grid.add_legend(); | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Correlating categorical features
Now we can correlate categorical features with our solution goal.
Observations.
Female passengers had much better survival rate than males. Confirms classifying (#1).
Exception in Embarked=C where males had higher survival rate.
Males had better survival rate in Pclass=3 when compared ... | grid = sns.FacetGrid(train_df, col='Embarked')
grid.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', palette='deep')
grid.add_legend() | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Correlating categorical and numerical features
We may also want to correlate categorical features (with non-numeric values) and numeric features. We can consider correlating Embarked (Categorical non-numeric), Sex (Categorical non-numeric), Fare (Numeric continuous), with Survived (Categorical numeric).
Observations.
... | grid = sns.FacetGrid(train_df, col='Embarked', hue='Survived', palette={0: 'k', 1: 'w'})
grid.map(sns.barplot, 'Sex', 'Fare', alpha=.5, ci=None)
grid.add_legend() | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Wrangle data
We have collected several assumptions and decisions regarding our datasets and solution requirements. So far we did not have to change a single feature or value to arrive at these. Let us now execute our decisions and assumptions for correcting, creating, and completing goals.
Correcting by dropping featur... | train_df = train_df.drop(['Ticket', 'Cabin'], axis=1)
test_df = test_df.drop(['Ticket', 'Cabin'], axis=1) | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Creating new feature extracting from existing
We want to analyze if Name feature can be engineered to extract titles and test correlation between titles and survival, before dropping Name and PassengerId features.
In the following code we extract Title feature using regular expressions. The RegEx pattern (\w+\.) matche... | train_df['Title'] = train_df.Name.str.extract('(\w+\.)', expand=False)
sns.barplot(hue="Survived", x="Age", y="Title", data=train_df, ci=False) | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Let us extract the Title feature for the training dataset as well.
Then we can safely drop the Name feature from training and testing datasets and the PassengerId feature from the training dataset. | test_df['Title'] = test_df.Name.str.extract('(\w+\.)', expand=False)
train_df = train_df.drop(['Name', 'PassengerId'], axis=1)
test_df = test_df.drop(['Name'], axis=1)
test_df.describe(include=['O']) | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Converting a categorical feature
Now we can convert features which contain strings to numerical values. This is required by most model algorithms. Doing so will also help us in achieving the feature completing goal.
Let us start by converting Sex feature to a new feature called Gender where female=1 and male=0. | train_df['Gender'] = train_df['Sex'].map( {'female': 1, 'male': 0} ).astype(int)
train_df.loc[:, ['Gender', 'Sex']].head() | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
We do this both for training and test datasets. | test_df['Gender'] = test_df['Sex'].map( {'female': 1, 'male': 0} ).astype(int)
test_df.loc[:, ['Gender', 'Sex']].head() | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
We can now drop the Sex feature from our datasets. | train_df = train_df.drop(['Sex'], axis=1)
test_df = test_df.drop(['Sex'], axis=1)
train_df.head() | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Completing a numerical continuous feature
Now we should start estimating and completing features with missing or null values. We will first do this for the Age feature.
We can consider three methods to complete a numerical continuous feature.
A simple way is to generate random numbers between mean and standard deviat... | grid = sns.FacetGrid(train_df, col='Pclass', hue='Gender')
grid.map(plt.hist, 'Age', alpha=.5, bins=20)
grid.add_legend(); | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Let us start by preparing an empty array to contain guessed Age values based on Pclass x Gender combinations. | guess_ages = np.zeros((2,3))
guess_ages | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Now we iterate over Gender (0 or 1) and Pclass (1, 2, 3) to calculate guessed values of Age for the six combinations.
Note that we also tried creating the AgeFill feature using method 3 and realized during model stage that the correlation coeffficient of AgeFill is better when compared with the method 2. | for i in range(0, 2):
for j in range(0, 3):
guess_df = train_df[(train_df['Gender'] == i) & \
(train_df['Pclass'] == j+1)]['Age'].dropna()
# Correlation of AgeFill is -0.014850
# age_mean = guess_df.mean()
# age_std = guess_df.std()
# ag... | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
We repeat the feature completing goal for the test dataset. | guess_ages = np.zeros((2,3))
for i in range(0, 2):
for j in range(0, 3):
guess_df = test_df[(test_df['Gender'] == i) & \
(test_df['Pclass'] == j+1)]['Age'].dropna()
# Correlation of AgeFill is -0.014850
# age_mean = guess_df.mean()
# age_std = guess_df... | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
We can now drop the Age feature from our datasets. | train_df = train_df.drop(['Age'], axis=1)
test_df = test_df.drop(['Age'], axis=1)
train_df.head() | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Create new feature combining existing features
We can create a new feature for FamilySize which combines Parch and SibSp. This will enable us to drop Parch and SibSp from our datasets.
Note that we commented out this code as we realized during model stage that the combined feature is reducing the confidence score of ou... | # Logistic Regression Score is 0.81032547699214363
# Parch correlation is -0.065878 and SibSp correlation is -0.370618
# Decision: Retain Parch and SibSp as separate features
# Logistic Regression Score is 0.80808080808080807
# FamilySize correlation is -0.233974
# train_df['FamilySize'] = train_df['SibSp'] + train_... | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
We can also create an artificial feature combining Pclass and AgeFill. | test_df['Age*Class'] = test_df.AgeFill * test_df.Pclass
train_df['Age*Class'] = train_df.AgeFill * train_df.Pclass
train_df.loc[:, ['Age*Class', 'AgeFill', 'Pclass']].head(10) | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Completing a categorical feature
Embarked feature takes S, Q, C values based on port of embarkation. Our training dataset has two missing values. We simply fill these with the most common occurance. | freq_port = train_df.Embarked.dropna().mode()[0]
freq_port
train_df['EmbarkedFill'] = train_df['Embarked']
train_df.loc[train_df['Embarked'].isnull(), 'EmbarkedFill'] = freq_port
train_df[train_df['Embarked'].isnull()][['Embarked','EmbarkedFill']].head(10) | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
We can now drop the Embarked feature from our datasets. | test_df['EmbarkedFill'] = test_df['Embarked']
train_df = train_df.drop(['Embarked'], axis=1)
test_df = test_df.drop(['Embarked'], axis=1)
train_df.head() | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Converting categorical feature to numeric
We can now convert the EmbarkedFill feature by creating a new numeric Port feature. | Ports = list(enumerate(np.unique(train_df['EmbarkedFill'])))
Ports_dict = { name : i for i, name in Ports }
train_df['Port'] = train_df.EmbarkedFill.map( lambda x: Ports_dict[x]).astype(int)
Ports = list(enumerate(np.unique(test_df['EmbarkedFill'])))
Ports_dict = { name : i for i, name in Ports }
test_df... | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Similarly we can convert the Title feature to numeric enumeration TitleBand banding age groups with titles. | Titles = list(enumerate(np.unique(train_df['Title'])))
Titles_dict = { name : i for i, name in Titles }
train_df['TitleBand'] = train_df.Title.map( lambda x: Titles_dict[x]).astype(int)
Titles = list(enumerate(np.unique(test_df['Title'])))
Titles_dict = { name : i for i, name in Titles }
test_df[... | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Now we can safely drop the EmbarkedFill and Title features. We this we now have a dataset that only contains numerical values, a requirement for the model stage in our workflow. | train_df = train_df.drop(['EmbarkedFill', 'Title'], axis=1)
test_df = test_df.drop(['EmbarkedFill', 'Title'], axis=1)
train_df.head() | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Quick completing and converting a numeric feature
We can now complete the Fare feature for single missing value in test dataset using mode to get the value that occurs most frequently for this feature. We do this in a single line of code.
Note that we are not creating an intermediate new feature or doing any further an... | test_df['Fare'].fillna(test_df['Fare'].dropna().median(), inplace=True)
train_df['Fare'] = train_df['Fare'].round(2)
test_df['Fare'] = test_df['Fare'].round(2)
test_df.head(10) | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Model, predict and solve
Now we are ready to train a model and predict the required solution. There are 60+ predictive modelling algorithms to choose from. We must understand the type of problem and solution requirement to narrow down to a select few models which we can evaluate. Our problem is a classification and reg... | X_train = train_df.drop("Survived", axis=1)
Y_train = train_df["Survived"]
X_test = test_df.drop("PassengerId", axis=1).copy()
X_train.shape, Y_train.shape, X_test.shape | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Logistic Regression is a useful model to run early in the workflow. Logistic regression measures the relationship between the categorical dependent variable (feature) and one or more independent variables (features) by estimating probabilities using a logistic function, which is the cumulative logistic distribution. Re... | # Logistic Regression
logreg = LogisticRegression()
logreg.fit(X_train, Y_train)
Y_pred = logreg.predict(X_test)
acc_log = round(logreg.score(X_train, Y_train) * 100, 2)
acc_log | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
We can use Logistic Regression to validate our assumptions and decisions for feature creating and completing goals. This can be done by calculating the correlation coefficient for all features as these relate to survival.
Gender as expected has the highest corrlation with Survived.
Surprisingly Fare ranks higher than ... | coeff_df = pd.DataFrame(train_df.columns.delete(0))
coeff_df.columns = ['Feature']
coeff_df["Correlation"] = pd.Series(logreg.coef_[0])
coeff_df.sort_values(by='Correlation', ascending=False) | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Next we model using Support Vector Machines which are supervised learning models with associated learning algorithms that analyze data used for classification and regression analysis. Given a set of training samples, each marked as belonging to one or the other of two categories, an SVM training algorithm builds a mode... | # Support Vector Machines
svc = SVC()
svc.fit(X_train, Y_train)
Y_pred = svc.predict(X_test)
acc_svc = round(svc.score(X_train, Y_train) * 100, 2)
acc_svc | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
In pattern recognition, the k-Nearest Neighbors algorithm (or k-NN for short) is a non-parametric method used for classification and regression. A sample is classified by a majority vote of its neighbors, with the sample being assigned to the class most common among its k nearest neighbors (k is a positive integer, typ... | knn = KNeighborsClassifier(n_neighbors = 3)
knn.fit(X_train, Y_train)
Y_pred = knn.predict(X_test)
acc_knn = round(knn.score(X_train, Y_train) * 100, 2)
acc_knn | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
In machine learning, naive Bayes classifiers are a family of simple probabilistic classifiers based on applying Bayes' theorem with strong (naive) independence assumptions between the features. Naive Bayes classifiers are highly scalable, requiring a number of parameters linear in the number of variables (features) in ... | # Gaussian Naive Bayes
gaussian = GaussianNB()
gaussian.fit(X_train, Y_train)
Y_pred = gaussian.predict(X_test)
acc_gaussian = round(gaussian.score(X_train, Y_train) * 100, 2)
acc_gaussian | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
The perceptron is an algorithm for supervised learning of binary classifiers (functions that can decide whether an input, represented by a vector of numbers, belongs to some specific class or not). It is a type of linear classifier, i.e. a classification algorithm that makes its predictions based on a linear predictor ... | # Perceptron
perceptron = Perceptron()
perceptron.fit(X_train, Y_train)
Y_pred = perceptron.predict(X_test)
acc_perceptron = round(perceptron.score(X_train, Y_train) * 100, 2)
acc_perceptron
# Linear SVC
linear_svc = LinearSVC()
linear_svc.fit(X_train, Y_train)
Y_pred = linear_svc.predict(X_test)
acc_linear_svc = ro... | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
This model uses a decision tree as a predictive model which maps features (tree branches) to conclusions about the target value (tree leaves). Tree models where the target variable can take a finite set of values are called classification trees; in these tree structures, leaves represent class labels and branches repre... | # Decision Tree
decision_tree = DecisionTreeClassifier()
decision_tree.fit(X_train, Y_train)
Y_pred = decision_tree.predict(X_test)
acc_decision_tree = round(decision_tree.score(X_train, Y_train) * 100, 2)
acc_decision_tree | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
The next model Random Forests is one of the most popular. Random forests or random decision forests are an ensemble learning method for classification, regression and other tasks, that operate by constructing a multitude of decision trees (n_estimators=100) at training time and outputting the class that is the mode of ... | # Random Forest
random_forest = RandomForestClassifier(n_estimators=100)
random_forest.fit(X_train, Y_train)
Y_pred = random_forest.predict(X_test)
random_forest.score(X_train, Y_train)
acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)
acc_random_forest | titanic-data-science-solutions.ipynb | Startupsci/data-science-notebooks | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.