<jupyter_start><jupyter_text>Preprocessing<jupyter_code>%matplotlib
# Import our dependencies
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import pandas as pd
import tensorflow as tf

#  Import and read the charity_data.csv.
import pandas as pd 
application_df = pd.read_csv("./drive/MyDrive/Module_21/Resources/charity_data.csv")
application_df.head()
# Drop the non-beneficial ID columns, 'EIN' and 'NAME'.
df_drop = application_df.drop(["EIN", "NAME"], axis='columns')
df_drop
from google.colab import drive
drive.mount('/content/drive')
# Determine the number of unique values in each column.
df_drop.nunique()
# Look at APPLICATION_TYPE value counts for binning
app_type_count = df_drop["APPLICATION_TYPE"].value_counts()
app_type_count
# 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 = list(app_type_count[app_type_count < 500].index)

# Replace in dataframe
for app in application_types_to_replace:
    df_drop['APPLICATION_TYPE'] = df_drop['APPLICATION_TYPE'].replace(app,"Other")

# Check to make sure binning was successful
df_drop['APPLICATION_TYPE'].value_counts()
# Look at CLASSIFICATION value counts for binning
class_count = df_drop["CLASSIFICATION"].value_counts()
class_count
# You may find it helpful to look at CLASSIFICATION value counts >1
class_count[class_count > 1]
# Choose a cutoff value and create a list of classifications to be replaced
# use the variable name `classifications_to_replace`
classifications_to_replace = list(class_count[class_count < 1000].index)

# Replace in dataframe
for cls in classifications_to_replace:
    df_drop['CLASSIFICATION'] = df_drop['CLASSIFICATION'].replace(cls,"Other")
    
# Check to make sure binning was successful
df_drop['CLASSIFICATION'].value_counts()
# Convert categorical data to numeric with `pd.get_dummies`
app_df_new = pd.get_dummies(df_drop)
app_df_new
# Split our preprocessed data into our features and target arrays
X = app_df_new.drop(["IS_SUCCESSFUL"], axis="columns").values
y= app_df_new["IS_SUCCESSFUL"].values


# Split the preprocessed data into a training and testing dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)

# 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)
# Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer.
#  YOUR CODE GOES HERE
num_input_feat = len(X_train[0])
hidden_node_layer1 = 100
hidden_node_layer2 = 30
hidden_node_layer3 = 10

nn = tf.keras.models.Sequential()

# First hidden layer
nn.add(
    tf.keras.layers.Dense(units=hidden_node_layer1, input_dim=num_input_feat, activation="relu")
)

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

# Third hidden layer
nn.add(
    tf.keras.layers.Dense(units=hidden_node_layer3, activation="relu")
)

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

# Check the structure of the model
nn.summary()<jupyter_output>Model: "sequential_1"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 dense_4 (Dense)             (None, 100)               4400      
                                                                 
 dense_5 (Dense)             (None, 30)                3030      
                                                                 
 dense_6 (Dense)             (None, 10)                310       
                                                                 
 dense_7 (Dense)             (None, 1)                 11        
                                                                 
=================================================================
Total params: 7,751
Trainable params: 7,751
Non-trainable params: 0
_________________________________________________________________<jupyter_text>Compile, Train and Evaluate the Model<jupyter_code># Compile the model
nn.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])
# Train the model
fit_model = nn.fit(X_train_scaled, y_train, epochs=100)
# Evaluate the model using the test data
model_loss, model_accuracy = nn.evaluate(X_test_scaled,y_test,verbose=2)
print(f"Loss: {model_loss}, Accuracy: {model_accuracy}")
# Attempt 2 at increasing accuracy by increasing epochs
fit_model = nn.fit(X_train_scaled, y_train, epochs=200)
# Check the second attempt accuracy
model_loss, model_accuracy = nn.evaluate(X_test_scaled,y_test,verbose=2)
print(f"Loss: {model_loss}, Accuracy: {model_accuracy}")
# Third attempt at improving accuracy by dropping more columns
df_drop_new = df_drop.drop(["SPECIAL_CONSIDERATIONS", "STATUS"], axis='columns')
df_drop_new

app_type_count2 = df_drop_new["APPLICATION_TYPE"].value_counts()
app_type_count2
# 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_replace2 = list(app_type_count2[app_type_count2 < 500].index)

# Replace in dataframe
for app in application_types_to_replace2:
    df_drop_new['APPLICATION_TYPE'] = df_drop_new['APPLICATION_TYPE'].replace(app,"Other")

# Check to make sure binning was successful
df_drop_new['APPLICATION_TYPE'].value_counts()
# Look at CLASSIFICATION value counts for binning
class_count2 = df_drop_new["CLASSIFICATION"].value_counts()
class_count2

class_count2[class_count2 > 1]
classifications_to_replace2 = list(class_count2[class_count2 < 1000].index)

# Replace in dataframe
for cls in classifications_to_replace2:
    df_drop_new['CLASSIFICATION'] = df_drop_new['CLASSIFICATION'].replace(cls,"Other")
    
# Check to make sure binning was successful
df_drop_new['CLASSIFICATION'].value_counts()
# Convert categorical data to numeric with `pd.get_dummies`
app_get_df = pd.get_dummies(df_drop_new)
app_get_df
# Split our preprocessed data into our features and target arrays
X = app_get_df.drop(["IS_SUCCESSFUL"], axis="columns").values
y= app_get_df["IS_SUCCESSFUL"].values


# Split the preprocessed data into a training and testing dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
# 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)
# Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer.
num_input_feat = len(X_train[0])
hidden_node_layer1 = 100
hidden_node_layer2 = 30
hidden_node_layer3 = 10


nn = tf.keras.models.Sequential()

# First hidden layer
nn.add(
    tf.keras.layers.Dense(units=hidden_node_layer1, input_dim=num_input_feat, activation="relu")
)

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

# Third hidden layer
nn.add(
    tf.keras.layers.Dense(units=hidden_node_layer3, activation="relu")
)

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

# Check the structure of the model
nn.summary()
# Compile the model
nn.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])
# Train the model
fit_model = nn.fit(X_train_scaled, y_train, epochs=100)
# Evaluate the model using the test data
model_loss, model_accuracy = nn.evaluate(X_test_scaled,y_test,verbose=2)
print(f"Loss: {model_loss}, Accuracy: {model_accuracy}")
# Export our model to HDF5 file
nn.save("AlphabetSoupCharity_Optimization.h5")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10620027781285515, 'fraction_numerical': 0.014774592751610052, 'mean_word_length': 4.70194384449244, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '613723', 'license': 'MIT', 'n_tokens_mistral': 2577, 'n_tokens_neox': 2433, 'n_words': 627, 'path': 'AlphabetSoupCharity_Optimzation_ipynb.ipynb', 'repo_name': 'akrakowsky/Module_21', 'size': '7919'}