# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# + [markdown] id="EWShR05ThHZL"
# ## Preprocessing

# + id="3wm65VAhhHZN"
# Import our dependencies
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import pandas as pd
import tensorflow as tf



# + colab={"base_uri": "https://localhost:8080/", "height": 302} id="isXrTC56h2n9" outputId="4724c5dd-b6f8-4bed-a4a7-fc64d66f4687"
#  Import and read the charity_data.csv.
url = "https://raw.githubusercontent.com/dmtiblin/UR--Deep-Learning-Assignment/main/Resources/charity_data.csv"
application_df = pd.read_csv(url)
application_df.head()

# + colab={"base_uri": "https://localhost:8080/", "height": 206} id="3jC-bBjLhHZQ" outputId="4807c2e8-cb38-4859-d60d-e53cd5e0b8ec"
# Drop the non-beneficial ID columns, 'EIN' and 'NAME'.
df = application_df.drop(['EIN','NAME'], axis = 1)
df.head()

# + colab={"base_uri": "https://localhost:8080/"} id="fbqQTL8qhHZR" outputId="2caf7a58-fb9b-46bc-b50f-aa5aac807eb8"
# Determine the number of unique values in each column.
df.nunique()

# + colab={"base_uri": "https://localhost:8080/"} id="gtqaXp9ChHZS" outputId="4806aa7e-f401-4b7f-ade0-74612b5dd9bb"
# Look at APPLICATION_TYPE value counts for binning
df['APPLICATION_TYPE'].value_counts()

# + colab={"base_uri": "https://localhost:8080/"} id="3n9eU3iehHZS" outputId="7c97f372-0b72-4931-8438-6ead6ca71472"
# Choose a cutoff value and create a list of application types to be replaced
# use the variable name `application_types_to_replace`

application_types_to_replace = ['T17','T29','T15','T25','T14','T2','T12','T13']
                                      
application_types_to_replace
# Replace in dataframe
for app in application_types_to_replace:
    df['APPLICATION_TYPE'] = df['APPLICATION_TYPE'].replace(app,"Other")

# Check to make sure binning was successful
df['APPLICATION_TYPE'].value_counts()

# + colab={"base_uri": "https://localhost:8080/", "height": 424} id="KCNVBjfuhHZT" outputId="de06a091-2a1c-4557-a3fe-020a5922cc67"
# Look at CLASSIFICATION value counts for binning
class_list = df['CLASSIFICATION'].value_counts()
class_list_df = pd.DataFrame(class_list)
class_list_df

# + colab={"base_uri": "https://localhost:8080/"} id="7VNW7g1DhHZU" outputId="4421b945-c884-4d94-e0b3-022fe9181632"
# You may find it helpful to look at CLASSIFICATION value counts >1
df['CLASSIFICATION'].value_counts().loc[lambda x : x>1]


# + colab={"base_uri": "https://localhost:8080/"} id="byKIjx-XhHZV" outputId="f1f16cf6-5c53-40d7-a374-4986b6f84d7f"
# Choose a cutoff value and create a list of classifications to be replaced
# use the variable name `classifications_to_replace`

classifications_to_keep = ['C1000','C2000', 'C1200', 'C3000', 'C2100', 'C7000']
classifications_to_replace = []
for index, row in class_list_df.iterrows():
  if index not in classifications_to_keep:
      classifications_to_replace.append(index)

# Replace in dataframe
for cls in classifications_to_replace:
    df['CLASSIFICATION'] = df['CLASSIFICATION'].replace(cls,"Other")
   
# Check to make sure binning was successful
df['CLASSIFICATION'].value_counts()

# + colab={"base_uri": "https://localhost:8080/"} id="yyNFBNEAM7p0" outputId="a465bd0b-537b-4b92-9416-af7b1787f492"
df.dtypes

# + id="5HONvbyHhHZW" colab={"base_uri": "https://localhost:8080/", "height": 288} outputId="d747468d-6d34-4d29-8f4f-22b3a8e89c14"
# Convert categorical data to numeric with `pd.get_dummies`
encoded_df = pd.get_dummies(df)
encoded_df.head()


# + colab={"base_uri": "https://localhost:8080/"} id="78fwZWiSPOEq" outputId="33baad04-3c90-4ee2-bde0-d6b67cb8c5ab"
len(encoded_df.columns)

# + id="Ijfb1XGqhHZX"
# Split our preprocessed data into our features and target arrays
X = encoded_df.drop('IS_SUCCESSFUL', axis =1)
y = encoded_df['IS_SUCCESSFUL']

# Split the preprocessed data into a training and testing dataset
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=78)

# + id="n7ag8QRzhHZX"
# Create a StandardScaler instances
scaler = StandardScaler()

# Fit the StandardScaler
X_scaler = scaler.fit(X_train)

# Scale the data
X_train_scaled = X_scaler.transform(X_train)
X_test_scaled = X_scaler.transform(X_test)

# + [markdown] id="UkVqv8zdhHZY"
# ## Compile, Train and Evaluate the Model

# + id="ogslzwY5PE_-"


# + id="NWirXZQWhHZY" outputId="b0bf0214-d545-4ca0-c2db-b0be5a643fed" colab={"base_uri": "https://localhost:8080/"}
# Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer.
#  YOUR CODE GOES HERE

nn_model = tf.keras.models.Sequential()

# First hidden layer
nn_model.add(tf.keras.layers.Dense(units=45, activation="relu", input_dim=45))

# Second hidden layer
nn_model.add(tf.keras.layers.Dense(units=45, activation="relu"))

# Output layer
nn_model.add(tf.keras.layers.Dense(units=1, activation="sigmoid"))

# Check the structure of the model
nn_model.summary()

# + id="HW6-IQMChHZZ"
# Compile the model
nn_model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])



# + id="XRPb-axPFj3B"
#Create a callback that saves the model's weights every 5 epochs

batch_size = 32 
epochs = 20
steps_per_epoch = y_train.size / batch_size
save_period = 5


from keras.callbacks import ModelCheckpoint
checkpoint = ModelCheckpoint("training_weights.hdf5", verbose = 1, save_weights_only = True,save_freq = int(save_period * steps_per_epoch))


# + id="DO5ygkA9hHZZ" outputId="0ade5f7a-5f9b-4137-b69d-1ac542f94506" colab={"base_uri": "https://localhost:8080/"}
# Train the model


fit_model = nn_model.fit(X_train_scaled, y_train, batch_size= 32,steps_per_epoch = steps_per_epoch, epochs=epochs,   callbacks = [checkpoint])

# + id="ItafpVaPhHZa" outputId="d365be64-70a5-4d42-a1f2-9ced4a09df94" colab={"base_uri": "https://localhost:8080/"}
# Evaluate the model using the test data
model_loss, model_accuracy = nn_model.evaluate(X_test_scaled,y_test,verbose=2)
print(f"Loss: {model_loss}, Accuracy: {model_accuracy}")

# + id="k3i6IpvqhHZa"
# Export our model to HDF5 file


import numpy as np
import h5py

# creating a file
#f = h5py.File("AlphabetSoupCharity.h5", "w")

nn_model.save("AlphabetSoupCharity.h5")

StarcoderdataJupyterScriptsDedupFiltered