<jupyter_start><jupyter_text>Creating an ANN using PyTorch<jupyter_code>import pandas as pd
df = pd.read_csv('diabetes.csv')
df.head()
df.isnull().sum()
import pandas.util.testing as tm
import seaborn as sns
import numpy as np

df['Outcome'] = np.where(df['Outcome']==1, "Diabetic", "No Diabetic")
df.head()
sns.pairplot(df, hue="Outcome")
df = pd.read_csv('diabetes.csv')
X = df.drop('Outcome', axis=1).values
y = df['Outcome'].values
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)<jupyter_output><empty_output><jupyter_text>Creating Tensors<jupyter_code># Libraries from PyTorch

import torch
import torch.nn as nn
import torch.nn.functional as F
# Creating Tensors

# All the independent features have to be converted into a Float Tensors
X_train = torch.FloatTensor(X_train)
X_test = torch.FloatTensor(X_test)

y_train = torch.LongTensor(y_train)
y_test = torch.LongTensor(y_test)<jupyter_output><empty_output><jupyter_text>Creating Model with PyTorch<jupyter_code>df.shape
# Always have to define a class when creating a model (2 Functions)

class ANN_Model(nn.Module):
  
  def __init__(self, input_features=8, hidden1=20, hidden2=20, out_features=2):
    super().__init__()
    self.f_connected1=nn.Linear(input_features, hidden1)
    self.f_connected2=nn.Linear(hidden1, hidden2)
    self.out = nn.Linear(hidden2, out_features)
  def forward(self, x):
    x=F.relu(self.f_connected1(x))
    x=F.relu(self.f_connected2(x))
    x=self.out(x)
    return x
# Instantiate my ANN_Model

torch.manual_seed(20)
model=ANN_Model()
model.parameters
# Backward Propogation -- Define the Loss Function and also define the Optimizer

loss_function = nn.CrossEntropyLoss()     # -- For MultiClass problem
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
epochs = 500
final_losses = []
for i in range(epochs):
  i = i + 1
  y_pred = model.forward(X_train)
  loss = loss_function(y_pred, y_train)
  final_losses.append(loss)

  if i%10 == 1:
    print("Epoch number: {} and the loss is: {}".format(i, loss.item()))
  
  optimizer.zero_grad()
  loss.backward()
  optimizer.step()
# Plotting the loss function

import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(range(epochs), final_losses)
plt.ylabel('Loss')
plt.xlabel('Epoch')<jupyter_output><empty_output><jupyter_text>Prediction from the ANN Model<jupyter_code>predictions = []

with torch.no_grad():
  for i, data in enumerate(X_test):
    y_pred = model(data)
    predictions.append(y_pred.argmax().item())
    print(y_pred.argmax().item())
predictions
from sklearn.metrics import confusion_matrix

cm = confusion_matrix(y_test, predictions)
print(cm)
plt.figure(figsize=(10, 6))
sns.heatmap(cm, annot=True)
plt.xlabel('Actual Values')
plt.ylabel('Predicted Values')
from sklearn.metrics import accuracy_score
score = accuracy_score(y_test, predictions)
print(score)<jupyter_output>0.7987012987012987<jupyter_text>Saving the Model<jupyter_code>torch.save(model, 'diabetes.pt')
model = torch.load('diabetes.pt')
model.eval()<jupyter_output><empty_output><jupyter_text>Prediction of New Data Point<jupyter_code>list(df.iloc[0, :-1])
lst1 = [6.0, 135.0, 72.0, 40.0, 0.0, 23.6, 0.627, 45.0]
new_data = torch.tensor(lst1)
with torch.no_grad():
  print(model(new_data))
  print(model(new_data).argmax().item())<jupyter_output>tensor([1.5731, 0.9671])
0
{'fraction_non_alphanumeric': 0.1330005871990605, 'fraction_numerical': 0.0273047563123899, 'mean_word_length': 5.92479674796748, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '192364', 'license': 'MIT', 'n_tokens_mistral': 1346, 'n_tokens_neox': 1272, 'n_words': 263, 'path': 'ANN using PyTorch/ANN_using_PyTorch_on_Pima_Diabetes_Kaggle.ipynb', 'repo_name': 'aryamanak10/Data-Science-Learning', 'size': '3406'}