CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
DanielBarnes18

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: DanielBarnes18/IBM-Data-Science-Professional-Certificate
Path: blob/main/10. Applied Data Science Capstone/05. Predictive Analysis (Classification)/05. Predictive Analysis (Classification).ipynb
Views: 4598
Kernel: Python 3.8
cognitiveclass.ai logo

Space X Falcon 9 First Stage Landing Prediction

Assignment: Machine Learning Prediction

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.

Objectives

Perform exploratory Data Analysis and determine Training Labels

  • create a column for the class

  • Standardize the data

  • Split into training data and test data

-Find best Hyperparameter for SVM, Classification Trees and Logistic Regression

  • Find the method performs best using test data


Import Libraries and Define Auxiliary Functions

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 standardize 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 dataframe

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") # 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') # 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)

TASK 1

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
array([0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int64)

TASK 2

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(X).transform(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.

TASK 3

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

X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=2)

we can see we only have 18 test samples.

Y_test.shape
(18,)

TASK 4

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']} #limited-memory BFGS algorithm
parameters ={"C":[0.01,0.1,1],'penalty':['l2'], 'solver':['lbfgs']}# l1 lasso l2 ridge lr=LogisticRegression() gridsearch_cv_lr = GridSearchCV(lr, parameters, scoring='accuracy', cv=10) logreg_cv = gridsearch_cv_lr.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 hyperparameters :(best parameters) ", logreg_cv.best_params_) lr_best_score = logreg_cv.best_score_ print("accuracy :", lr_best_score)
tuned hyperparameters :(best parameters) {'C': 0.01, 'penalty': 'l2', 'solver': 'lbfgs'} accuracy : 0.8464285714285713

TASK 5

Calculate the accuracy on the test data using the method score:

lr_score = logreg_cv.score(X_test, Y_test)
print(f"Logistic Regression - Accuracy using method score: {lr_score}")
Logistic Regression - Accuracy using method score: 0.8333333333333334

Lets look at the confusion matrix:

yhat=logreg_cv.predict(X_test) plot_confusion_matrix(Y_test,yhat)
Image in a Jupyter notebook

Examining the confusion matrix, we see that logistic regression can distinguish between the different classes. We see that the major problem is false positives.

TASK 6

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()
gridsearch_cv_svm = GridSearchCV(svm, parameters, scoring='accuracy', cv=10) svm_cv = gridsearch_cv_svm.fit(X_train, Y_train)
print("tuned hyperparameters :(best parameters) ",svm_cv.best_params_) svm_best_score = svm_cv.best_score_ print("accuracy :",svm_best_score)
tuned hyperparameters :(best parameters) {'C': 1.0, 'gamma': 0.03162277660168379, 'kernel': 'sigmoid'} accuracy : 0.8482142857142856

TASK 7

Calculate the accuracy on the test data using the method score:

svm_score = svm_cv.score(X_test, Y_test)
print(f"SVM - Accuracy using method score: {svm_score}")
SVM - Accuracy using method score: 0.8333333333333334

We can plot the confusion matrix

yhat=svm_cv.predict(X_test) plot_confusion_matrix(Y_test,yhat)
Image in a Jupyter notebook

TASK 8

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()
gridsearch_cv_tree = GridSearchCV(tree, parameters, scoring='accuracy', cv=10) tree_cv = gridsearch_cv_tree.fit(X_train, Y_train)
print("tuned hyperparameters :(best parameters) ",tree_cv.best_params_) tree_best_score = tree_cv.best_score_ print("accuracy :",tree_best_score)
tuned hyperparameters :(best parameters) {'criterion': 'entropy', 'max_depth': 6, 'max_features': 'sqrt', 'min_samples_leaf': 1, 'min_samples_split': 10, 'splitter': 'random'} accuracy : 0.9035714285714287

TASK 9

Calculate the accuracy of tree_cv on the test data using the method score:

tree_score = tree_cv.score(X_test, Y_test)
print(f"Decision Tree - Accuracy using method score: {tree_score}")
Decision Tree - Accuracy using method score: 0.9444444444444444

We can plot the confusion matrix

yhat = tree_cv.predict(X_test) plot_confusion_matrix(Y_test,yhat)
Image in a Jupyter notebook

TASK 10

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()
gridsearch_cv_knn = GridSearchCV(KNN, parameters, scoring='accuracy', cv=10) knn_cv = gridsearch_cv_tree.fit(X_train, Y_train)
print("tuned hyperparameters :(best parameters) ",knn_cv.best_params_) knn_best_score = knn_cv.best_score_ print("accuracy :",knn_best_score)
tuned hyperparameters :(best parameters) {'criterion': 'gini', 'max_depth': 14, 'max_features': 'auto', 'min_samples_leaf': 4, 'min_samples_split': 10, 'splitter': 'best'} accuracy : 0.8767857142857143

TASK 11

Calculate the accuracy of tree_cv on the test data using the method score:

knn_score = knn_cv.score(X_test, Y_test)
print(f"KNN - Accuracy using method score: {knn_score}")
KNN - Accuracy using method score: 0.8888888888888888

We can plot the confusion matrix

yhat = knn_cv.predict(X_test) plot_confusion_matrix(Y_test,yhat)
Image in a Jupyter notebook

TASK 12

Find the method performs best:

algorithms = ['Logistic Regression', 'Support Vector Machine', 'Decision Tree', 'K Nearest Neighbours'] scores = [lr_score, svm_score, tree_score, knn_score] best_scores = [lr_best_score, svm_best_score, tree_best_score, knn_best_score] column_names = ['Algorithm', 'Accuracy Score', 'Best Score']
df = pd.DataFrame(list(zip(algorithms, scores, best_scores)),columns = column_names)
df
sns.set(style="whitegrid") plt.figure(figsize=(15,8)) sns.barplot(x=algorithms, y=best_scores, palette="Blues") plt.title("Determining the Best Performing Classification Algorithm") plt.ylabel("Best Score") plt.show()
Image in a Jupyter notebook
plt.figure(figsize=(15,8)) sns.barplot(x=algorithms, y=scores, palette="Blues") plt.title("Determining the Best Performing Classification Algorithm") plt.ylabel("Accuracy Score") plt.show()
Image in a Jupyter notebook

Authors

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.

Change Log

Date (YYYY-MM-DD)VersionChanged ByChange Description
2021-08-311.1Lakshmi HollaModified markdown
2020-09-201.0JosephModified Multiple Areas

Copyright © 2020 IBM Corporation. All rights reserved.