Implement a Neural Network using Pytorch
ANSWER
To accomplish this task, you’ll need to follow these steps:
- Import necessary libraries.
- Load and preprocess the dataset.
- Split the data into training and testing sets.
- Create a neural network using PyTorch.
- Train the neural network.
- Evaluate the model on the testing data and report the accuracy.
- Print the predicted decisions alongside the real labels.
Here’s a step-by-step implementation in Python using PyTorch:
import torch
import torch.nn as nn
import torch.optim as optim
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
# Step 2: Load and preprocess the dataset
data = pd.read_csv('CC_data.csv')
# Assuming that the target column is named 'approved' and all other columns are predictors
X = data.drop('approved', axis=1).values
y = data['approved'].values
# Standardize the data
scaler = StandardScaler()
X = scaler.fit_transform(X)
# Step 3: Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Step 4: Create a neural network using PyTorch
class NeuralNetwork(nn.Module):
def __init__(self, input_size, hidden_size):
super(NeuralNetwork, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
out = self.sigmoid(out)
return out
# Step 5: Train the neural network
input_size = X_train.shape[1]
hidden_size = 64 # Adjust this as needed
model = NeuralNetwork(input_size, hidden_size)
criterion = nn.BCELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
num_epochs = 100 # You may need to adjust this
for epoch in range(num_epochs):
inputs = torch.tensor(X_train, dtype=torch.float32)
labels = torch.tensor(y_train, dtype=torch.float32).view(-1, 1)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (epoch + 1) % 10 == 0:
print(f'Epoch [{epoch + 1}/{num_epochs}], Loss: {loss.item()}')
# Step 6: Evaluate the model on the testing data
model.eval()
with torch.no_grad():
test_inputs = torch.tensor(X_test, dtype=torch.float32)
predicted_probabilities = model(test_inputs)
predicted_labels = (predicted_probabilities > 0.5).float().numpy()
accuracy = accuracy_score(y_test, predicted_labels)
print(f'Test Accuracy: {accuracy * 100:.2f}%')
# Step 7: Print the predicted decisions alongside real labels
for i in range(len(X_test)):
print(f'Real: {y_test[i]}, Predicted: {predicted_labels[i][0]}')
Make sure to adjust the hyperparameters like hidden_size
, num_epochs
, and the architecture of the neural network as needed to achieve at least 80% accuracy on the training data.
QUESTION
Description
Credit Card Approval. On one of the first lectures, a credit card approval
record with multiple predictors was used as an example to show the use-
fulness of learning from data. Here you will have the chance to create
your own Neural Network based on CC data.csv. The data contains 15
predictors, and one response (approved or denied). You’ll randomly split
your data into training and testing with a 80/20 ratio.
(a) Implement a Neural Network using Pytorch with the following spec-
ifications:
? Input layer: Number of neurons as number of inputs (15).
? Second layer: fully connected layer with N neurons.
? Set the number of neurons for the second layer N , and the num-
ber of epochs, to obtain an accuracy of at least 80% in the train-
ing data.
(b) Evaluate the model with the testing data, report the accuracy; com-
pute and print the predicted decision for every input of the testing
data (approved or denied) alongside with the real labels.