from sklearn.linear_model import LogisticRegression from sklearn.datasets import fetch_openml from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import joblib # Load the MNIST dataset mnist = fetch_openml('mnist_784', version=1) # Normalize the data X = mnist.data / 255.0 y = mnist.target.astype(int) # Split the data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) # Train the logistic regression model model = LogisticRegression(solver='lbfgs', max_iter=1000, multi_class='multinomial') model.fit(X_train, y_train) # Evaluate the model y_pred = model.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f'Accuracy: {accuracy * 100:.2f}%') # Save the model joblib.dump(model, 'logistic_regression_model.pkl') import tkinter as tk from tkinter import * import numpy as np from PIL import Image, ImageDraw, ImageOps import joblib # Load the trained model (make sure you have a trained model saved as 'logistic_regression_model.pkl') model = joblib.load('logistic_regression_model.pkl') class App(tk.Tk): def __init__(self): super().__init__() self.title('Handwritten Digit Recognition') self.canvas = tk.Canvas(self, width=200, height=200, bg='white') self.canvas.pack() self.button_predict = tk.Button(self, text='Predict', command=self.predict) self.button_predict.pack() self.button_clear = tk.Button(self, text='Clear', command=self.clear) self.button_clear.pack() self.label_result = tk.Label(self, text='Draw a digit and click Predict') self.label_result.pack() self.canvas.bind('', self.paint) self.image = Image.new('L', (200, 200), color=255) self.draw = ImageDraw.Draw(self.image) def paint(self, event): x1, y1 = (event.x - 2), (event.y - 2) # Adjust the size to make the line thinner x2, y2 = (event.x + 2), (event.y + 2) # Adjust the size to make the line thinner self.canvas.create_oval(x1, y1, x2, y2, fill='black', width=2) # Adjust the width to make the line thinner self.draw.ellipse([x1, y1, x2, y2], fill='black') def clear(self): self.canvas.delete('all') self.image = Image.new('L', (200, 200), color=255) self.draw = ImageDraw.Draw(self.image) self.label_result.config(text='Draw a digit and click Predict') def predict(self): # Resize and invert the image image = self.image.resize((28, 28)) image = ImageOps.invert(image) image = np.array(image) # Normalize the image data to [0, 1] range image = image.astype('float32') / 255 # Flatten the image image = image.flatten() # Predict the digit prediction = model.predict([image]) digit = prediction[0] # Display the prediction self.label_result.config(text=f'Predicted Digit: {digit}') # Create and run the application if __name__ == '__main__': app = App() app.mainloop()