Demystify Neural Network. Implement A Simple NN using PYTHON Functions. Tensorflow/keras VS Python-Code...??
Steps:
Problem We will be working on is a binary classification problem in which we will be predicting whether a person going to opt for insurance or not depending on his/her age and affordability.
Lets start...
import numpy as np
import tensorflow as tf
from tensorflow import keras
import pandas as pd
from matplotlib import pyplot as plt
%matplotlib inline
df = pd.read_csv("insurance_data.csv")
df.head()
Dataset has three columns age(10-90) , affordability(0/1), insurance(0/1).
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df[['age','affordibility']],df.bought_insurance,test_size=0.2, random_state=25)
X_train_scaled = X_train.copy()
X_train_scaled['age'] = X_train_scaled['age'] / 100
X_test_scaled = X_test.copy()
X_test_scaled['age'] = X_test_scaled['age'] / 100
model = keras.Sequential([
keras.layers.Dense(1, input_shape=(2,), activation='sigmoid', kernel_initializer='ones', bias_initializer='zeros')
])
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
model.fit(X_train_scaled, y_train, epochs=5000)
model.evaluate(X_test_scaled,y_test)
1/1 [==============================] - 0s 1ms/step - loss: 0.3550 - accuracy: 1.0000
[0.35497748851776123, 1.0]
#lets predict
model.predict(X_test_scaled)
array([[0.7054848 ],
[0.35569546],
[0.16827849],
[0.47801173],
[0.7260697 ],
[0.8294984 ]], dtype=float32)
#lets compare prediction with actual values
y_test
2 1
10 0
21 0
11 0
14 1
9 1
Name: bought_insurance, dtype: int64
#Now get the value of weights and bias from the model
coef, intercept = model.get_weights()
coef, intercept
(array([[5.060867 ],
[1.4086502]], dtype=float32),
array([-2.9137027], dtype=float32))
Now lets mimic using simple python code and math.
领英推荐
def sigmoid_numpy(X):
return 1/(1+np.exp(-X))
def log_loss(y_true, y_predicted):
epsilon = 1e-15
y_predicted_new = [max(i,epsilon) for i in y_predicted]
y_predicted_new = [min(i,1-epsilon) for i in y_predicted_new]
y_predicted_new = np.array(y_predicted_new)
return -np.mean(y_true*np.log(y_predicted_new)+(1-y_true)*np.log(1-y_predicted_new))
def gradient_descent(age, affordability, y_true, epochs, loss_thresold):
w1 = w2 = 1
bias = 0
rate = 0.5
n = len(age)
for i in range(epochs):
weighted_sum = w1 * age + w2 * affordability + bias
y_predicted = sigmoid_numpy(weighted_sum)
loss = log_loss(y_true, y_predicted)
w1d = (1/n)*np.dot(np.transpose(age),(y_predicted-y_true))
w2d = (1/n)*np.dot(np.transpose(affordability),(y_predicted-y_true))
bias_d = np.mean(y_predicted-y_true)
w1 = w1 - rate * w1d
w2 = w2 - rate * w2d
bias = bias - rate * bias_d
print (f'Epoch:{i}, w1:{w1}, w2:{w2}, bias:{bias}, loss:{loss}')
if loss<=loss_thresold:
break
return w1, w2, bias
gradient_descent(X_train_scaled['age'],X_train_scaled['affordibility'],y_train,1000, 0.4631)
def sigmoid(x):
import math
return 1 / (1 + math.exp(-x))
def prediction_function(age, affordibility):
weighted_sum = coef[0]*age + coef[1]*affordibility + intercept
return sigmoid(weighted_sum)
prediction_function(.47, 1)
We can use above two functions for prediction.
Thank You