Skip to content

Instantly share code, notes, and snippets.

@celsowm
Created November 11, 2023 22:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celsowm/d50c568008a9f1cec63bdc879f8aefb5 to your computer and use it in GitHub Desktop.
Save celsowm/d50c568008a9f1cec63bdc879f8aefb5 to your computer and use it in GitHub Desktop.
neural_network_scratch_with_hidden_layer.py
import numpy as np
import pandas as pd
# Função de ativação sigmoid e sua derivada
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_der(x):
return sigmoid(x) * (1 - sigmoid(x))
# Ler o arquivo CSV
df = pd.read_csv('diabetes.csv')
# Extrair os dados para feature_set e labels
feature_set = df.drop('diabetico', axis=1).values
labels = df['diabetico'].values.reshape(-1, 1)
np.random.seed(42)
# Pesos da camada de entrada para a camada oculta (3 entradas, 4 neurônios na camada oculta)
weights_input_hidden = np.random.rand(3, 4)
bias_hidden = np.random.rand(4) # Viés da camada oculta
# Pesos da camada oculta para a camada de saída (4 neurônios na camada oculta, 1 saída)
weights_hidden_output = np.random.rand(4, 1)
bias_output = np.random.rand(1) # Viés da camada de saída
lr = 0.05 #learning rate (taxa de aprendizado)
# Função para feed_forward em uma camada
def feed_forward(inputs, weights, bias):
return sigmoid(np.dot(inputs, weights) + bias)
def update_weights(weights, inputs, z_delta, lr):
weights -= lr * np.dot(inputs.T, z_delta)
return weights
def update_bias(bias, z_delta, lr):
bias -= lr * np.sum(z_delta)
return bias
for epoch in range(20000):
# feed_forward
z_hidden = feed_forward(feature_set, weights_input_hidden, bias_hidden)
z_output = feed_forward(z_hidden, weights_hidden_output, bias_output)
# Backpropagation
error = z_output - labels
dcost_dpred = error
dpred_dz = sigmoid_der(z_output)
z_delta = dcost_dpred * dpred_dz
# Cálculo do erro na camada oculta usando os pesos da camada de saída
dcost_dhidden = np.dot(z_delta, weights_hidden_output.T)
dhidden_dz = sigmoid_der(z_hidden)
z_delta_hidden = dcost_dhidden * dhidden_dz
# Gradiente Descendente: Atualização dos pesos e viés da camada de saída
weights_hidden_output = update_weights(weights_hidden_output, z_hidden, z_delta, lr)
bias_output = update_bias(bias_output, z_delta, lr)
# Gradiente Descendente: Atualização dos pesos e viés da camada oculta
weights_input_hidden = update_weights(weights_input_hidden, feature_set, z_delta_hidden, lr)
bias_hidden = update_bias(bias_hidden, z_delta_hidden, lr)
# Predição
single_point = np.array([0, 1, 0]) #ou [1, 0, 0]
z_hidden = feed_forward(single_point, weights_input_hidden, bias_hidden)
result = feed_forward(z_hidden, weights_hidden_output, bias_output)
limiar = 0.5
resultado = 1 if result[0] > limiar else 0
print(resultado)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment