<jupyter_start><jupyter_text>Preprocessing<jupyter_code># 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.
url = "https://raw.githubusercontent.com/dmtiblin/UR--Deep-Learning-Assignment/main/Resources/charity_data.csv"
application_df = pd.read_csv(url)
application_df.head()
# Drop the non-beneficial ID columns, 'EIN' and 'NAME'.
df = application_df.drop(['EIN','NAME'], axis = 1)
df.head()
# Determine the number of unique values in each column.
df.nunique()
# Look at APPLICATION_TYPE value counts for binning
df['APPLICATION_TYPE'].value_counts()
# 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()
# Look at CLASSIFICATION value counts for binning
class_list = df['CLASSIFICATION'].value_counts()
class_list_df = pd.DataFrame(class_list)
class_list_df
# You may find it helpful to look at CLASSIFICATION value counts >1
df['CLASSIFICATION'].value_counts().loc[lambda x : x>1]

# 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()
df.dtypes
# Convert categorical data to numeric with `pd.get_dummies`
encoded_df = pd.get_dummies(df)
encoded_df.head()

len(encoded_df.columns)
# 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)
# 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)<jupyter_output><empty_output><jupyter_text>Compile, Train and Evaluate the Model<jupyter_code># 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()
# Compile the model
nn_model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])


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

# 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])
# 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}")
# 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")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10189627598811972, 'fraction_numerical': 0.01553575508339045, 'mean_word_length': 6.072697899838449, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 11, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '216365', 'license': 'ADSL', 'n_tokens_mistral': 1496, 'n_tokens_neox': 1421, 'n_words': 381, 'path': 'charity_funding_predictor.ipynb', 'repo_name': 'dmtiblin/UR-Deep-Learning-Challenge', 'size': '4377'}