Created
November 12, 2023 01:59
-
-
Save celsowm/65ea78ee4e530e041ec3094dcb7424d7 to your computer and use it in GitHub Desktop.
neural_network_pytorch.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import torch | |
import torch.nn as nn | |
import pandas as pd | |
# Ler o arquivo CSV | |
df = pd.read_csv('diabetes.csv') | |
# Extrair os dados para feature_set e labels | |
feature_set = torch.tensor(df.drop('diabetico', axis=1).values, dtype=torch.float32) | |
labels = torch.tensor(df['diabetico'].values, dtype=torch.float32) | |
class NeuralNetwork(nn.Module): | |
def __init__(self): | |
super(NeuralNetwork, self).__init__() | |
self.hidden = nn.Linear(3, 4) | |
self.output = nn.Linear(4, 1) | |
self.sigmoid = nn.Sigmoid() | |
def forward(self, x): | |
x = self.sigmoid(self.hidden(x)) | |
x = self.sigmoid(self.output(x)) | |
return x | |
model = NeuralNetwork() | |
criterion = nn.BCELoss() # Binary Cross Entropy Loss | |
optimizer = torch.optim.SGD(model.parameters(), lr=0.05) # Stochastic Gradient Descent | |
for epoch in range(20000): | |
optimizer.zero_grad() # Zera os gradientes | |
output = model(feature_set) | |
loss = criterion(output, labels.view(-1, 1)) # Calcula a perda | |
loss.backward() # Propagação para trás | |
optimizer.step() # Atualização dos pesos | |
# Predição | |
single_point = torch.tensor([[0, 1, 0]], dtype=torch.float32) # ou [[1, 0, 0]] | |
result = model(single_point) | |
threshold = 0.5 | |
prediction = 1 if result.item() > threshold else 0 | |
print(prediction) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment