using this code:
import numpy as np
import seaborn as sns
import pandas as pd
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
class NeuralNetwork:
def init(self, x, y, hidden_neurons=20):
# Initialize parameters
self.input = x
self.weights1 = np.random.rand(self.input.shape[1], hidden_neurons)
self.bias1 = np.random.rand(1, hidden_neurons)
self.weights2 = np.random.rand(hidden_neurons, 1)
self.bias2 = np.random.rand(1, 1)
self.y = y
self.output = np.zeros(self.y.shape)
code
Assistant
User
can you implement the said suggestions/improvements?
Assistant
User
Assistant
def feedforward(self):
# Perform feedforward operation
self.layer1 = sigmoid(np.dot(self.input, self.weights1) + self.bias1)
self.output = sigmoid(np.dot(self.layer1, self.weights2) + self.bias2)
def backprop(self):
# Perform backpropagation
error = self.y - self.output
# Calculate gradients for weights and biases based on error
d_weights2 = np.dot(self.layer1.T, (2 * error * sigmoid_derivative(self.output)))
d_bias2 = np.sum(2 * error * sigmoid_derivative(self.output), axis=0, keepdims=True)
d_layer1 = np.dot(2 * error * sigmoid_derivative(self.output), self.weights2.T)
d_weights1 = np.dot(self.input.T, (d_layer1 * sigmoid_derivative(self.layer1)))
d_bias1 = np.sum(d_layer1 * sigmoid_derivative(self.layer1), axis=0, keepdims=True)
# Update parameters
self.weights1 += d_weights1
self.bias1 += d_bias1
self.weights2 += d_weights2
self.bias2 += d_bias2
def train(self, epochs=1000):
# Train the neural network for a given number of epochs
for epoch in range(epochs):
self.feedforward()
self.backprop()
def predict(self, X):
# Function to perform prediction using the neural network
self.input = X
self.feedforward()
return self.output
Function to create and train the network
def create_and_train_nn(X_train, y_train, hidden_neurons, epochs=1000):
y_train_np = y_train.to_numpy().reshape(-1, 1) # Convert Series to numpy array and reshape
nn = NeuralNetwork(X_train, y_train_np, hidden_neurons=hidden_neurons)
nn.train(epochs=epochs)
return nn
for config, result in results.items():
print(f"Results for {config} Hidden Neurons:")
print("Accuracy:", result["Accuracy"])
print("Confusion Matrix:\n", result["Confusion Matrix"])
print("Classification Report:\n", result["Classification Report"])
print()
are the tasks accomplished?:
Background and Dataset
The garment industry is one of the key examples of the industrial globalization of this modern era. There are many manual operations in this business, which requires a lot of effort. Employee performance in terms of production and delivery in clothing manufacturing enterprises is a major factor in meeting the enormous demand for textile products around the world. Hence, monitoring, evaluating, and forecasting the productivity performance of the factory work teams is highly desired by the decision-makers in the garment business.
In this study, you will use Productivity Prediction of Garment Employees dataset to classify it as satisfactory or unsatisfactory productivity.
The dataset consists of 1197 instances and 15 features. For dataset description see UCI Machine Learning Library at:
https://archive.ics.uci.edu/dataset/597/productivity+prediction+of+garment+employees
This study consists of two parts:
• Part 1 is about implementing and training a multilayer feedforward neural network to classify productivity data as satisfactory or unsatisfactory.
• Part 2 is about applying computational intelligence techniques to classify the data based on various features.
Part 1 Tasks
A. Dataset Preparation
2.1 The original class label (actual_productivity) is a continuous variable. You must first transform it to a discrete variable so that you can apply Binary Classification on it. Visualize the distribution of features and classes, normalize the data, and divide it into training and test sets.
B. Developing ANN from Scratch
2.2 Construct a 3-layers feedforward network with X input neurons, 20 hidden neurons, and Y output neurons. You must identify the values of X and Y yourself (Hint: Lecture # 3 ANN architecture design). Identify an appropriate activation function and justify your choice.
2.3 Write a computer program using a high-level programming language of your choice (Python with NumPy or C/C++ or Java) to train and test the neural network using the Backpropagation algorithm from scratch WITHOUT using any machine learning library.
C. Performance Evaluation
2.4 Evaluate the NN using state-of-the-art evaluation metrics.
D. Performance Comparison
2.5 Train a new neural network classifier with 10 hidden neurons and evaluate its performance. Repeat the process for training and testing neural network classifier with 30 hidden neurons.
2.6 Contrast the differences and compare among the performance of three trained neural network classifiers (i.e., with 20, 10 and 30 hidden neurons). Justify your observations.
The code provided in the question handles many of the tasks outlined in Part 1 of the project, specifically in the realm of Dataset Preparation, Developing an ANN from Scratch, Performance Evaluation, and Performance Comparison. Let's review each of the tasks from Part 1 based on the supplied Python code:
Part 1 Tasks Review:
A. Dataset Preparation
2.1:
The continuous variable actual_productivity has been successfully transformed into a binary class productivity_class using a threshold of 0.5. This step is key for binary classification.
The distribution of features and classes is displayed using a Seaborn count plot.
Data normalization is done using StandardScaler which scales the dataset such that it has a mean of zero and a standard deviation of one, suitable for input into the neural network.
The dataset is split into training and test sets with 80-20 ratio, adhering to typical practices in machine learning for training and validation.
B. Developing ANN from Scratch
2.2:
The multilayer feedforward neural network is configured with variable numbers of input neurons (X features after one-hot encoding and scaling), 20 hidden neurons as a starting point, and 1 output neuron since this is a binary classification problem.
The sigmoid function is used as the activation function. This choice is appropriate for binary classification problems because its output ranges between 0 and 1, ideal for modeling probability-like outputs.
2.3:
The neural network is implemented from scratch using NumPy, a high-level programming library in Python. This implementation covers initialization, feedforward computation, backpropagation for learning the weights, and a training loop that iterates through the specified number of epochs.
C. Performance Evaluation
2.4:
The performance of the neural network is evaluated using accuracy, confusion matrix, and classification report. These metrics provide a comprehensive understanding of the classifier's performance including aspects like precision, recall, F1-score, and support along with overall accuracy.
D. Performance Comparison
2.5 & 2.6:
The neural network is tested with different configurations of hidden neurons (10, 20, 30).
For each configuration, performance metrics are recorded and printed, allowing for a comparative analysis between different configurations.
Points Addressed:
Background and Dataset are well-described in the introduction.
Part 1 tasks A through D are mostly accomplished through the provided code, demonstrating dataset preparation, neural network implementation, and performance evaluation.
Suggestions/Improvements:
Justification for Activation Functions: While the sigmoid activation function is used, you might include specific justifications for its choice beyond the range benefit, such as its ability to provide clear binary outputs enabling effective classification.
Error Handling and Validation: Incorporate checks or validations, especially when handling data transformations and neural network predictions.
Feature Engineering: Before transforming and using the data, inspect and possibly engineer the features to ensure they are suitable for neural network processing, potentially improving the model's performance.
Enhanced Learning Parameter Tuning: Might explore variations in learning rate, weight initialization strategies, or regularization methods to optimize network performance.
Overall, the tasks are methodically tackled, but always room for enhancement especially in tuning and expanding the neural network model's robustness and handling edge cases or outliers in dataset preparation.
To implement the suggestions for improvements and expand on the neural network developed earlier, we can perform the following enhancements:
Justify and Possibly Diversify Activation Functions: Though the sigmoid function is well-suited for binary classification, experimenting with other activation functions such as ReLU for hidden layers might improve training efficiency and help avoid issues like vanishing gradients.
Error Handling and Validation: This includes checking for null values, ensuring data types are correct, and verifying the range of input data.
Feature Engineering: It involves inspecting the features more closely, checking correlations, and perhaps considering dimensionality reduction or feature selection techniques.
Tuning Learning Parameters: Introduce aspects like learning rate adjustments, better weight initialization, and methods like regularization to make the neural network less prone to overfitting.
Here is the code that considers these improvements:
Adjusted Neural Network Implementation with Improvements
python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# Assuming the dataset has been cleaned and preprocessed
# Reading the dataset and preparing as before
df = pd.read_csv("garments_worker_productivity.csv")
df["productivity_class"] = (df["actual_productivity"] >= 0.5).astype(int)
X = pd.get_dummies(df.drop(["actual_productivity", "productivity_class"], axis=1))
y = df["productivity_class"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
class NeuralNetwork:
def __init__(self, layer_sizes, activation=np.tanh):
self.activation = activation
self.weights = [np.random.randn(size[0], size[1]) * np.sqrt(2 / size[0]) for size in zip(layer_sizes[:-1], layer_sizes[1:])]
self.biases = [np.random.randn(1, size) for size in layer_sizes[1:]]
def feedforward(self, X):
self.activations = [X]
for w, b in zip(self.weights, self.biases):
z = np.dot(self.activations[-1], w) + b
a = self.activation(z)
self.activations.append(a)
# Sigmoid on the output layer for binary classification
self.activations[-1] = 1 / (1 + np.exp(-self.activations[-1]))
return self.activations[-1]
def backprop(self, X, y):
delta = self.activations[-1] - y
dW = [np.dot(self.activations[-2].T, delta)]
dB = [np.sum(delta, axis=0, keepdims=True)]
for i in range(len(self.weights) - 1, 0, -1):
delta = np.dot(delta, self.weights[i].T) * (1 - self.activations[i]**2) # derivative of tanh
dW.append(np.dot(self.activations[i-1].T, delta))
dB.append(np.sum(delta, axis=0, keepdims=True))
# Reverse to match weights and biases order
dW.reverse()
dB.reverse()
# Update weights and biases
for i in range(len(self.weights)):
self.weights[i] -= learning_rate * dW[i]
self.biases[i] -= learning_rate * dB[i]
def train(self, X, y, epochs, learning_rate):
y = y.reshape(-1, 1) # making sure y is the right shape
for epoch in range(epochs):
self.feedforward(X)
self.backprop(X, y)
# Train the network with improved functionalities
layer_sizes = [X_train_scaled.shape[1], 20, 1] # Input layer, one hidden layer, one output layer
nn = NeuralNetwork(layer_sizes, activation=np.tanh)
nn.train(X_train_scaled, y_train.to_numpy(), epochs=1500, learning_rate=0.01)
# Evaluate the network
preds = nn.feedforward(X_test_scaled) > 0.5
accuracy = accuracy_score(y_test, preds.flatten())
conf_mat = confusion_matrix(y_test, preds.flatten())
class_report = classification_report(y_test, preds.flatten())
print("Accuracy:", accuracy)
print("Confusion Matrix:\n", conf_mat)
print("Classification Report:\n", class_report)
Explanation of Enhancements:
Activation Function: In the example, I used tanh for the hidden layers which can sometimes help in faster convergence during training compared to sigmoid for hidden layers.
Weight Initialization: I used He initialization (np.sqrt(2/size[0])) which is more appropriate for layers using ReLU family functions but generally better than simple random normal for deep networks.
Learning Rate and Weight Update: The learning rate is explicitly utilized in the backpropagation step.
This example enables a starting point for more nuanced handling, performance tuning, and perhaps deeper feature engineering going forward.
import numpy as np
import seaborn as sns
import pandas as pd
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
class NeuralNetwork:
def init(self, x, y, hidden_neurons=20):
# Initialize parameters
self.input = x
self.weights1 = np.random.rand(self.input.shape[1], hidden_neurons)
self.bias1 = np.random.rand(1, hidden_neurons)
self.weights2 = np.random.rand(hidden_neurons, 1)
self.bias2 = np.random.rand(1, 1)
self.y = y
self.output = np.zeros(self.y.shape)
code
def feedforward(self):
# Perform feedforward operation
self.layer1 = sigmoid(np.dot(self.input, self.weights1) + self.bias1)
self.output = sigmoid(np.dot(self.layer1, self.weights2) + self.bias2)
def backprop(self):
# Perform backpropagation
error = self.y - self.output
# Calculate gradients for weights and biases based on error
d_weights2 = np.dot(self.layer1.T, (2 * error * sigmoid_derivative(self.output)))
d_bias2 = np.sum(2 * error * sigmoid_derivative(self.output), axis=0, keepdims=True)
d_layer1 = np.dot(2 * error * sigmoid_derivative(self.output), self.weights2.T)
d_weights1 = np.dot(self.input.T, (d_layer1 * sigmoid_derivative(self.layer1)))
d_bias1 = np.sum(d_layer1 * sigmoid_derivative(self.layer1), axis=0, keepdims=True)
# Update parameters
self.weights1 += d_weights1
self.bias1 += d_bias1
self.weights2 += d_weights2
self.bias2 += d_bias2
def train(self, epochs=1000):
# Train the neural network for a given number of epochs
for epoch in range(epochs):
self.feedforward()
self.backprop()
def predict(self, X):
# Function to perform prediction using the neural network
self.input = X
self.feedforward()
return self.output
Function to create and train the network
def create_and_train_nn(X_train, y_train, hidden_neurons, epochs=1000):
y_train_np = y_train.to_numpy().reshape(-1, 1) # Convert Series to numpy array and reshape
nn = NeuralNetwork(X_train, y_train_np, hidden_neurons=hidden_neurons)
nn.train(epochs=epochs)
return nn
for config, result in results.items():
print(f"Results for {config} Hidden Neurons:")
print("Accuracy:", result["Accuracy"])
print("Confusion Matrix:\n", result["Confusion Matrix"])
print("Classification Report:\n", result["Classification Report"])
print()
how can i make this code more efficient whilst maintaining everything
To enhance the efficiency of the provided neural network code while maintaining its core functionality, we can consider the following modifications and improvements:
Vectorization of Network Layers: Rather than iterating through each layer manually, we'll create a mechanism to handle any number of layers dynamically. This approach simplifies network extension and maintenance.
Improved Weight Initialization: Use better strategies like He or Glorot initialization depending on the activation function used to prevent issues such as vanishing or exploding gradients.
Avoid Redundant Computations: Store values that are reused, such as the results of activation functions during forward pass, to avoid recalculating them in the backward pass.
Structured Learning Rate: Implement a structured approach to adjust the learning rate dynamically during training, such as learning rate decay or adaptive learning rate techniques.
Utility Functions: Use utility functions for common operations to keep the code modular and easier to read and maintain.
Error Handling: Implement error checks and input validation to make the code robust against inconsistent input data.
Here is the revised code:
python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
def initialize_weights(layer_sizes):
weights = {}
for i, layer_size in enumerate(layer_sizes[:-1]):
weights[f"W{i+1}"] = np.random.randn(layer_sizes[i], layer_sizes[i+1]) * np.sqrt(2. / layer_sizes[i])
weights[f"b{i+1}"] = np.zeros((1, layer_sizes[i+1]))
return weights
class NeuralNetwork:
def __init__(self, layer_sizes):
self.layer_sizes = layer_sizes
self.weights = initialize_weights(layer_sizes)
def feedforward(self, X):
activations = [X]
for i in range(len(self.layer_sizes) - 1):
W = self.weights[f"W{i+1}"]
b = self.weights[f"b{i+1}"]
z = np.dot(activations[-1], W) + b
a = sigmoid(z) if i < len(self.layer_sizes) - 2 else sigmoid(z)
activations.append(a)
return activations
def backprop(self, X, y, activations, learning_rate):
deltas = {}
# Output layer error
deltas[f"delta{len(self.layer_sizes)-1}"] = (activations[-1] - y) * sigmoid_derivative(activations[-1])
# Propagate error backwards
for i in range(len(self.layer_sizes) - 2, 0, -1):
delta = deltas[f"delta{i+1}"]
W = self.weights[f"W{i+1}"]
a = activations[i]
deltas[f"delta{i}"] = np.dot(delta, W.T) * sigmoid_derivative(a)
# Update weights and biases
for i in range(len(self.layer_sizes) - 1):
W_name = f"W{i+1}"
b_name = f"b{i+1}"
delta = deltas[f"delta{i+1}"]
self.weights[W_name] -= learning_rate * np.dot(activations[i].T, delta)
self.weights[b_name] -= learning_rate * np.sum(delta, axis=0, keepdims=True)
def train(self, X, y, epochs, learning_rate):
for epoch in range(epochs):
activations = self.feedforward(X)
self.backprop(X, y, activations, learning_rate)
def predict(self, X):
activations = self.feedforward(X)
return activations[-1]
# Assuming data preparation and splitting as before
# Create and configure the Neural Network
layer_sizes = [X_train_scaled.shape[1], 20, 1] # Example layer configuration
nn = NeuralNetwork(layer_sizes)
nn.train(X_train_scaled, y_train.values.reshape(-1, 1), epochs=1500, learning_rate=0.01)
# Prediction and Evaluation
preds = nn.predict(X_test_scaled) > 0.5
accuracy = accuracy_score(y_test, preds.flatten())
conf_mat = confusion_matrix(y_test, preds.flatten())
class_report = classification_report(y_test, preds.flatten())
print("Accuracy:", accuracy)
print("Confusion Matrix:\n", conf_mat)
print("Classification Report:\n", class_report)
Key Enhancements in the Revised Code:
Generalized Weight Initialization and Network Layers: Facilitates the easy extension or modification of the network topology.
Error Handling and Validation: While not explicitly shown, you can add checks for data consistency, shapes, and NaN values as required.
Modular Operations: Functions are used to segment operations logically, making the network easier to understand and modify.
These changes aim to strike a balance between efficient execution, readability, and maintainability, ensuring the network is not only functional but also robust against diverse datasets and easy to adapt for future modifications.