Estimated time needed: 60 minutes
Space X advertises Falcon 9 rocket launches on its website with a cost of 62 million dollars; other providers cost upward of 165 million dollars each, much of the savings is because Space X can reuse the first stage. Therefore if we can determine if the first stage will land, we can determine the cost of a launch. This information can be used if an alternate company wants to bid against space X for a rocket launch. In this lab, you will create a machine learning pipeline to predict if the first stage will land given the data from the preceding labs.
Several examples of an unsuccessful landing are shown here:
Most unsuccessful landings are planed. Space X; performs a controlled landing in the oceans.
Perform exploratory Data Analysis and determine Training Labels
-Find best Hyperparameter for SVM, Classification Trees and Logistic Regression
We will import the following libraries for the lab
# Pandas is a software library written for the Python programming language for data manipulation and analysis.
import pandas as pd
# NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays
import numpy as np
# Matplotlib is a plotting library for python and pyplot gives us a MatLab like plotting framework. We will use this in our plotter function to plot data.
import matplotlib.pyplot as plt
#Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics
import seaborn as sns
# Preprocessing allows us to standarsize our data
from sklearn import preprocessing
# Allows us to split our data into training and testing data
from sklearn.model_selection import train_test_split
# Allows us to test parameters of classification algorithms and find the best one
from sklearn.model_selection import GridSearchCV
# Logistic Regression classification algorithm
from sklearn.linear_model import LogisticRegression
# Support Vector Machine classification algorithm
from sklearn.svm import SVC
# Decision Tree classification algorithm
from sklearn.tree import DecisionTreeClassifier
# K Nearest Neighbors classification algorithm
from sklearn.neighbors import KNeighborsClassifier
This function is to plot the confusion matrix.
def plot_confusion_matrix(y,y_predict):
"this function plots the confusion matrix"
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y, y_predict)
ax= plt.subplot()
sns.heatmap(cm, annot=True, ax = ax); #annot=True to annotate cells
ax.set_xlabel('Predicted labels')
ax.set_ylabel('True labels')
ax.set_title('Confusion Matrix');
ax.xaxis.set_ticklabels(['did not land', 'land']); ax.yaxis.set_ticklabels(['did not land', 'landed'])
Load the data
# data = pd.read_csv("https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/dataset_part_2.csv")
data = pd.read_csv("data/IBM-DS0321EN-SkillsNetwork/datasets/dataset_part_2.csv")
# If you were unable to complete the previous lab correctly you can uncomment and load this csv
# data = pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DS0701EN-SkillsNetwork/api/dataset_part_2.csv')
data.head()
# X = pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/dataset_part_3.csv')
X = pd.read_csv('data/IBM-DS0321EN-SkillsNetwork/datasets/dataset_part_3.csv')
# If you were unable to complete the previous lab correctly you can uncomment and load this csv
# X = pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DS0701EN-SkillsNetwork/api/dataset_part_3.csv')
X.head(100)
Create a NumPy array from the column
Class
in
data
, by applying the method
to_numpy()
then
assign it to the variable
Y
,make sure the output is a Pandas series (only one bracket df['name of column']).
Y = data['Class'].to_numpy()
Y
Standardize the data in
X
then reassign it to the variable
X
using the transform provided below.
# students get this
transform = preprocessing.StandardScaler()
X = transform.fit_transform(X)
X
We split the data into training and testing data using the function
train_test_split
. The training data is divided into validation data, a second set used for training data; then the models are trained and hyperparameters are selected using the function
GridSearchCV
.
Use the function train_test_split to split the data X and Y into training and test data. Set the parameter test_size to 0.2 and random_state to 2. The training data and test data should be assigned to the following labels.
X_train, X_test, Y_train, Y_test
RANDOM_STATE = 2
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=RANDOM_STATE)
we can see we only have 18 test samples.
Y_test.shape
Create a logistic regression object then create a GridSearchCV object
logreg_cv
with cv = 10. Fit the object to find the best parameters from the dictionary
parameters
.
parameters ={'C':[0.01,0.1,1],
'penalty':['l2'],
'solver':['lbfgs']}
parameters ={"C":[0.01,0.1,1],'penalty':['l2'], 'solver':['lbfgs']}# l1 lasso l2 ridge
lr=LogisticRegression(random_state=RANDOM_STATE)
logreg_cv = GridSearchCV(lr, param_grid=parameters, cv=10)
logreg_cv.fit(X_train,Y_train)
We output the
GridSearchCV
object for logistic regression. We display the best parameters using the data attribute
best_params\_
and the accuracy on the validation data using the data attribute
best_score\_
.
print("tuned hpyerparameters :(best parameters) ",logreg_cv.best_params_)
print("accuracy :",logreg_cv.best_score_)
Calculate the accuracy on the test data using the method
score
:
logreg_cv.score(X_test,Y_test)
Lets look at the confusion matrix:
yhat=logreg_cv.predict(X_test)
plot_confusion_matrix(Y_test,yhat)
Examining the confusion matrix, we see that logistic regression can distinguish between the different classes. We see that the major problem is false positives.
Create a support vector machine object then create a
GridSearchCV
object
svm_cv
with cv - 10. Fit the object to find the best parameters from the dictionary
parameters
.
parameters = {'kernel':('linear', 'rbf','poly','rbf', 'sigmoid'),
'C': np.logspace(-3, 3, 5),
'gamma':np.logspace(-3, 3, 5)}
svm = SVC(random_state=RANDOM_STATE)
svm_cv = GridSearchCV(svm, param_grid=parameters, cv=10)
svm_cv.fit(X_train, Y_train)
print("tuned hpyerparameters :(best parameters) ",svm_cv.best_params_)
print("accuracy :",svm_cv.best_score_)
Calculate the accuracy on the test data using the method
score
:
svm_cv.score(X_test,Y_test)
We can plot the confusion matrix
yhat=svm_cv.predict(X_test)
plot_confusion_matrix(Y_test,yhat)
Create a decision tree classifier object then create a
GridSearchCV
object
tree_cv
with cv = 10. Fit the object to find the best parameters from the dictionary
parameters
.
parameters = {'criterion': ['gini', 'entropy'],
'splitter': ['best', 'random'],
'max_depth': [2*n for n in range(1,10)],
'max_features': ['auto', 'sqrt'],
'min_samples_leaf': [1, 2, 4],
'min_samples_split': [2, 5, 10]}
tree = DecisionTreeClassifier(random_state=RANDOM_STATE)
tree_cv = GridSearchCV(tree,parameters,cv=10)
tree_cv.fit(X_train,Y_train)
print("tuned hpyerparameters :(best parameters) ",tree_cv.best_params_)
print("accuracy :",tree_cv.best_score_)
Calculate the accuracy of tree_cv on the test data using the method
score
:
tree_cv.score(X_test,Y_test)
We can plot the confusion matrix
yhat = svm_cv.predict(X_test)
plot_confusion_matrix(Y_test,yhat)
Create a k nearest neighbors object then create a
GridSearchCV
object
knn_cv
with cv = 10. Fit the object to find the best parameters from the dictionary
parameters
.
parameters = {'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'algorithm': ['auto', 'ball_tree', 'kd_tree', 'brute'],
'p': [1,2]}
KNN = KNeighborsClassifier()
knn_cv = GridSearchCV(KNN,parameters,cv=10)
knn_cv.fit(X_train,Y_train)
print("tuned hpyerparameters :(best parameters) ",knn_cv.best_params_)
print("accuracy :",knn_cv.best_score_)
Calculate the accuracy of
knn_cv
on the test data using the method
score
:
knn_cv.score(X_test,Y_test)
We can plot the confusion matrix
yhat = knn_cv.predict(X_test)
plot_confusion_matrix(Y_test,yhat)
Find the method performs best:
all_models = [logreg_cv, svm_cv, tree_cv, knn_cv]
all_scores = [model.score(X_test,Y_test) for model in all_models]
all_scores
sns.barplot(x='Model', y='Score', data=pd.DataFrame({
'Model': ["Log. Reg.", "SVM", "Tree", "KNN"],
'Score': all_scores
}))
plt.yticks(np.linspace(0,1,11))
plt.title("Model accuracy for all built classification models")
plt.show()
from sklearn.metrics import jaccard_score
[jaccard_score(Y_test, model.predict(X_test)) for model in all_models]
best_model = all_models[all_scores.index(max(all_scores))]
best_model
best_model.score(X_test,Y_test)
yhat = best_model.predict(X_test)
plot_confusion_matrix(Y_test,yhat)
Joseph Santarcangelo has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.
Date (YYYY-MM-DD) | Version | Changed By | Change Description |
---|---|---|---|
2021-08-31 | 1.1 | Lakshmi Holla | Modified markdown |
2020-09-20 | 1.0 | Joseph | Modified Multiple Areas |
Copyright © 2020 IBM Corporation. All rights reserved.