import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageTk
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import threading
# Create the main application window
class PerceptronApp:
def __init__(self, root):
self.root = root
self.root.title("Perceptron Image Classifier")
# Variables to hold data and model parameters
self.dataset = None
self.weights = None
self.learning_rate = 0.1
self.epochs = 10
self.loss_history = []
# GUI components
self.create_widgets()
def create_widgets(self):
# Frame for file loading
frame_top = tk.Frame(self.root)
frame_top.pack()
# Button to load CSV file
self.btn_load_csv = tk.Button(frame_top, text="Load CSV File", command=self.load_csv)
self.btn_load_csv.grid(row=0, column=0, padx=5, pady=5)
# Button to load weights file
self.btn_load_weights = tk.Button(frame_top, text="Load Weights", command=self.load_weights)
self.btn_load_weights.grid(row=0, column=1, padx=5, pady=5)
# Canvas for image display
self.canvas = tk.Canvas(self.root, width=320, height=320)
self.canvas.pack()
# Button to start training
self.btn_train = tk.Button(self.root, text="Train Perceptron", command=self.start_training)
self.btn_train.pack(pady=5)
# Frame for metrics
frame_metrics = tk.Frame(self.root)
frame_metrics.pack()
self.label_accuracy = tk.Label(frame_metrics, text="Accuracy: N/A")
self.label_accuracy.pack(anchor=tk.W)
self.label_precision = tk.Label(frame_metrics, text="Precision: N/A")
self.label_precision.pack(anchor=tk.W)
self.label_recall = tk.Label(frame_metrics, text="Recall: N/A")
self.label_recall.pack(anchor=tk.W)
# Figure for loss plot
self.figure = plt.Figure(figsize=(5, 3), dpi=100)
self.ax = self.figure.add_subplot(111)
self.ax.set_title("Loss over Epochs")
self.ax.set_xlabel("Epoch")
self.ax.set_ylabel("Loss")
self.canvas_plot = FigureCanvasTkAgg(self.figure, master=self.root)
self.canvas_plot.get_tk_widget().pack()
# Button to save loss plot
self.btn_save_plot = tk.Button(self.root, text="Save Loss Plot", command=self.save_loss_plot)
self.btn_save_plot.pack(pady=5)
def load_csv(self):
# Open file dialog to select CSV file
file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
if file_path:
try:
# Load CSV file into pandas DataFrame
self.dataset = pd.read_csv(file_path)
messagebox.showinfo("Success", "CSV file loaded successfully.")
# Display the first image
self.display_image(0)
except Exception as e:
messagebox.showerror("Error", f"Failed to load CSV file.\n{e}")
def load_weights(self):
# Open file dialog to select weights file
file_path = filedialog.askopenfilename(filetypes=[("NumPy files", "*.npy")])
if file_path:
try:
# Load weights from .npy file
self.weights = np.load(file_path)
messagebox.showinfo("Success", "Weights loaded successfully.")
except Exception as e:
messagebox.showerror("Error", f"Failed to load weights.\n{e}")
def display_image(self, index):
# Extract image data from DataFrame
image_data = self.dataset.iloc[index, 2:].values.reshape(32, 32).astype(np.uint8) * 255
# Convert to PIL Image and resize
image = Image.fromarray(image_data).resize((320, 320))
self.photo = ImageTk.PhotoImage(image)
# Display image on canvas
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)
def start_training(self):
if self.dataset is None:
messagebox.showwarning("Warning", "Please load a dataset first.")
return
# Start training in a new thread to keep GUI responsive
threading.Thread(target=self.train_perceptron).start()
def train_perceptron(self):
# Initialize weights if not loaded
if self.weights is None:
self.weights = np.zeros(self.dataset.shape[1] - 2)
# Prepare data
X = self.dataset.iloc[:, 2:].values
y = self.dataset['class'].values
y = np.where(y == y[0], 1, -1) # Convert to binary labels
# Training loop
self.loss_history = []
for epoch in range(self.epochs):
total_loss = 0
for xi, target in zip(X, y):
# Calculate output
output = np.dot(xi, self.weights)
# Update weights using Hebbian learning rule
self.weights += self.learning_rate * xi * target
# Calculate loss (simple squared error)
loss = (target - output) ** 2
total_loss += loss
# Append average loss
avg_loss = total_loss / len(y)
self.loss_history.append(avg_loss)
# Update loss plot
self.update_loss_plot()
# Evaluate model
self.evaluate_model(X, y)
def update_loss_plot(self):
# Clear previous plot
self.ax.clear()
self.ax.set_title("Loss over Epochs")
self.ax.set_xlabel("Epoch")
self.ax.set_ylabel("Loss")
# Plot loss history
self.ax.plot(self.loss_history, marker='o')
self.canvas_plot.draw()
def evaluate_model(self, X, y):
# Predict outputs
outputs = np.dot(X, self.weights)
predictions = np.where(outputs >= 0, 1, -1)
# Calculate metrics
accuracy = np.mean(predictions == y)
precision = np.sum((predictions == 1) & (y == 1)) / np.sum(predictions == 1)
recall = np.sum((predictions == 1) & (y == 1)) / np.sum(y == 1)
# Update metrics labels
self.label_accuracy.config(text=f"Accuracy: {accuracy:.2f}")
self.label_precision.config(text=f"Precision: {precision:.2f}")
self.label_recall.config(text=f"Recall: {recall:.2f}")
# Check if multi-layer perceptron is needed
if accuracy < 0.95:
messagebox.showinfo("Info", "Accuracy below 0.95. Switching to Multi-layer Perceptron.")
self.train_mlp(X, y)
def train_mlp(self, X, y):
# Simple implementation of a multi-layer perceptron with one hidden layer
input_size = X.shape[1]
hidden_size = 64
output_size = 1
# Initialize weights
np.random.seed(1)
W1 = 2 * np.random.random((input_size, hidden_size)) - 1
W2 = 2 * np.random.random((hidden_size, output_size)) - 1
# Training loop
for epoch in range(self.epochs):
# Forward propagation
layer0 = X
layer1 = self.sigmoid(np.dot(layer0, W1))
layer2 = self.sigmoid(np.dot(layer1, W2))
# Error calculation
layer2_error = y.reshape(-1, 1) - layer2
# Backpropagation
layer2_delta = layer2_error * self.sigmoid_derivative(layer2)
layer1_error = layer2_delta.dot(W2.T)
layer1_delta = layer1_error * self.sigmoid_derivative(layer1)
# Update weights
W2 += layer1.T.dot(layer2_delta) * self.learning_rate
W1 += layer0.T.dot(layer1_delta) * self.learning_rate
# Calculate loss
loss = np.mean(np.square(layer2_error))
self.loss_history.append(loss)
# Update loss plot
self.update_loss_plot()
# Evaluate MLP model
predictions = np.where(layer2 >= 0.5, 1, -1)
accuracy = np.mean(predictions.flatten() == y)
precision = np.sum((predictions == 1) & (y.reshape(-1, 1) == 1)) / np.sum(predictions == 1)
recall = np.sum((predictions == 1) & (y.reshape(-1, 1) == 1)) / np.sum(y == 1)
# Update metrics labels
self.label_accuracy.config(text=f"Accuracy: {accuracy:.2f}")
self.label_precision.config(text=f"Precision: {precision:.2f}")
self.label_recall.config(text=f"Recall: {recall:.2f}")
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def save_loss_plot(self):
# Open file dialog to save plot
file_path = filedialog.asksaveasfilename(defaultextension=".png")
if file_path:
self.figure.savefig(file_path)
messagebox.showinfo("Success", "Loss plot saved successfully.")
# Main entry point
if __name__ == "__main__":
root = tk.Tk()
app = PerceptronApp(root)
root.mainloop()
Explanation of the Program:
-
Imports:
tkinter and related modules are used for creating the GUI.
numpy and pandas are used for numerical computations and data handling.
matplotlib is used for plotting the loss function.
threading is used to keep the GUI responsive during training.
-
PerceptronApp Class:
- Initializes the main application window and GUI components.
- Handles loading of the CSV dataset and weights.
- Displays the selected image from the dataset.
- Implements the training logic for the single-layer perceptron using Hebbian learning.
- Updates the loss plot in real-time during training.
- Calculates and displays classification metrics (Accuracy, Precision, Recall).
- Switches to a multi-layer perceptron (MLP) if the desired accuracy is not achieved.
- Provides functionality to save the loss plot as an image file.
-
Training Functions:
train_perceptron: Implements the Hebbian learning rule for a single-layer perceptron.
evaluate_model: Calculates metrics and checks if MLP is needed.
train_mlp: Implements a basic MLP with one hidden layer and backpropagation.
-
Utility Functions:
sigmoid and sigmoid_derivative: Activation function and its derivative for MLP.
-
GUI Functions:
create_widgets: Sets up all GUI components.
load_csv and load_weights: Load dataset and weights from files.
display_image: Visualizes an image from the dataset.
update_loss_plot: Updates the loss function plot after each epoch.
save_loss_plot: Saves the loss plot to an image file.
Note:
- This program assumes that the CSV file has the structure described: an
id column, a class column, and 1024 columns representing the 32x32 pixel values of the image.
- The images are expected to be in binary format (0 and 1), representing black and white pixels.
- The Hebbian learning rule used here is a simple implementation for demonstration purposes.
- The MLP implemented is basic and may need adjustments for larger datasets or more complex tasks.
- The program uses threading to ensure the GUI remains responsive during the training process.
Instructions to Run the Program:
- Save the script to a file, for example,
perceptron_gui.py.
- Install the required libraries if not already installed:
pip install numpy pandas matplotlib pillow
- Run the program:
python perceptron_gui.py
- Use the GUI to load your CSV dataset and optional weights.
- Click "Train Perceptron" to start the training process.
- View the metrics and loss plot. Save the loss plot if desired.
Comments:
- Each part of the program is commented to explain its functionality.
- Adjust the learning rate and epochs as needed for your specific dataset.
- Ensure that your CSV data is properly formatted to avoid errors during loading and training.