# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: 'Python 3.8.5 64-bit (''microsoft'': conda)'
#     name: python38564bitmicrosoftcondaa3295319a17f4ae4a671465397595e70
# ---

#Required libraries
import pandas as pd
import numpy as np
from sklearn import linear_model, model_selection, metrics
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
from sklearn import preprocessing
import pydotplus
from IPython.display import Image 

#Loading data
launch_data = pd.read_excel('RocketLaunchDataCompleted.xlsx')
launch_data.head()

launch_data.columns

# + tags=[]
""" We only have 60 launches in this dataset and we have data for other days as before and after launch, this means
we will choose 60 records where the field Launched? is Y' """
launch_data.info()
# -

"""To handle missing values, we will fill the missing values with appropriate values, for instance:
    Launched? is Na -> (we'll assume that wasn't launch)
    Crewed or Uncrewed is Na -> (Assume that the launch was uncrewed)
    Wind condition is Na -> (Assume as unkown)
    Condition is Na -> (Assume as Fair)
    """
launch_data['Launched?'].fillna('N',inplace=True)
launch_data['Crewed or Uncrewed'].fillna('Uncrewed',inplace=True)
launch_data['Wind Direction'].fillna('unknown',inplace=True)
launch_data['Condition'].fillna('Fair',inplace=True)
launch_data.fillna(0,inplace=True)
launch_data.head()

# +
## As part of the data cleaning process, we have to convert text data to numerical because computers understand only numbers
label_encoder = preprocessing.LabelEncoder()

# Three columns have categorical text info, and we convert them to numbers
# For instance, 0 for Crewed - 1 for Uncrewed
launch_data['Crewed or Uncrewed'] = label_encoder.fit_transform(launch_data['Crewed or Uncrewed'])
launch_data['Wind Direction'] = label_encoder.fit_transform(launch_data['Wind Direction'])
launch_data['Condition'] = label_encoder.fit_transform(launch_data['Condition'])
# -

launch_data.head()

# +
#Building the model

# +
# First, we save the output we are interested in. In this case, "launch" yes and no's go into the output variable.
y = launch_data['Launched?']

# Removing the columns we are not interested in
launch_data.drop(['Name','Date','Time (East Coast)','Location','Launched?','Hist Ave Sea Level Pressure','Sea Level Pressure','Day Length','Notes','Hist Ave Visibility', 'Hist Ave Max Wind Speed'],axis=1, inplace=True)

# Saving the rest of the data as input data
X = launch_data

# List of variables that our machine learning algorithm is going to look at:
X.columns
# -

"""The X input data represents the weather for a particular day. In this case, we aren't worried about the date or time. We want the profile of the weather for that day to be the indicator for whether a launch should happen, not the date or time."""
X.head()

# +
""" Predict a rocket launch given weather conditions is a yes or no question. This is a two-class classification problem. We'll use a decision tree given that is an accurate and fast training algorithm.

For this job we'll use sickit-learn. """

tree_model = DecisionTreeClassifier(random_state=0,max_depth=5)
# -

#Splitting data
"""
Test size: 0.2 - 80% training size, 20% test size 
Random state: 99 -  random seed"""
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=99)

# Fitting the model to the training data
tree_model.fit(X_train,y_train)

# + tags=[]
#Testing the model
y_pred = tree_model.predict(X_test)
print(y_pred)
# -

#Scoring the model
# Calculate accuracy
tree_model.score(X_test,y_test)

# +
#Creating the visual tree
# Let's  visualizing our decision tree.
from sklearn.tree import export_graphviz

def tree_graph_to_png(tree, feature_names,class_names, png_file_to_save):
    tree_str = export_graphviz(tree, feature_names=feature_names, class_names=class_names,
                                     filled=True, out_file=None)
    graph = pydotplus.graph_from_dot_data(tree_str)  
    return Image(graph.create_png())


# -

# This function  visualizes the model.
tree_graph_to_png(tree=tree_model, feature_names=X.columns.values,class_names=['No Launch','Launch'], png_file_to_save='decision-tree.png')

"""
192 are no launches
48 are launches

Given the visualization we could think the following:
"If the wind speed was less than 1.0, then 191 of the 240 samples guessed that no launch was possible on that day."
"""

# +
#A test for a recent lauch.
"""On July 30, 2020, NASA launched the Perseverance rover to Mars from Cape Canaveral at 7:50 AM Eastern Time. The next is hypotethical data: """
# ['Crewed or Uncrewed', 'High Temp', 'Low Temp', 'Ave Temp',
#        'Temp at Launch Time', 'Hist High Temp', 'Hist Low Temp',
#        'Hist Ave Temp', 'Precipitation at Launch Time',
#        'Hist Ave Precipitation', 'Wind Direction', 'Max Wind Speed',
#        'Visibility', 'Wind Speed at Launch Time', 'Hist Ave Max Wind Speed',
#        'Hist Ave Visibility', 'Condition']

data_input = [ 1.  , 75.  , 68.  , 71.  ,  0.  , 75.  , 55.  , 65.  ,  0.  , 0.08,  0.  , 16.  , 15.  ,  0.  ,  0. ]

test = tree_model.predict([data_input])

# + tags=[]
print(test)

StarcoderdataJupyterScriptsDedupFiltered