Melhore o código abaixo em 100%

```
import tkinter as tk
from tkinter import messagebox, simpledialog
from PIL import Image, ImageDraw, ImageTk
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
import pickle
import os

class DrawingApp:
    def __init__(self, master):
        self.master = master
        self.master.title("Desenho, Identificação e Geração")

        self.canvas = tk.Canvas(master, width=280, height=280, bg="white")
        self.canvas.pack()

        self.canvas.bind("<B1-Motion>", self.paint)

        self.entry = tk.Entry(master)
        self.entry.pack()

        self.identify_button = tk.Button(master, text="Identificar", command=self.identify)
        self.identify_button.pack()

        self.teach_button = tk.Button(master, text="Ensinar", command=self.teach)
        self.teach_button.pack()

        self.save_button = tk.Button(master, text="Salvar", command=self.save_model)
        self.save_button.pack()

        self.load_button = tk.Button(master, text="Carregar", command=self.load_model)
        self.load_button.pack()

        self.clear_button = tk.Button(master, text="Limpar", command=self.clear_canvas)
        self.clear_button.pack()

        self.generate_button = tk.Button(master, text="Gerar", command=self.generate)
        self.generate_button.pack()

        self.image = Image.new("L", (280, 280), color="white")
        self.draw = ImageDraw.Draw(self.image)

        self.model = KNeighborsClassifier(n_neighbors=3)
        self.classes = []
        self.X = []
        self.y = []

    def paint(self, event):
        x1, y1 = (event.x - 1), (event.y - 1)
        x2, y2 = (event.x + 1), (event.y + 1)
        self.canvas.create_oval(x1, y1, x2, y2, fill="black", width=5)
        self.draw.line([x1, y1, x2, y2], fill="black", width=5)

    def clear_canvas(self):
        self.canvas.delete("all")
        self.image = Image.new("L", (280, 280), color="white")
        self.draw = ImageDraw.Draw(self.image)

    def preprocess_image(self):
        img = self.image.resize((28, 28))
        img_array = np.array(img).flatten() / 255.0
        return img_array

    def identify(self):
        if len(self.classes) == 0:
            messagebox.showinfo("Aviso", "Primeiro ensine algumas classes!")
            return

        img_array = self.preprocess_image()
        prediction = self.model.predict([img_array])
        predicted_class = self.classes[prediction[0]]
        messagebox.showinfo("Identificação", f"Acredito que seja um(a): {predicted_class}")

    def teach(self):
        class_name = self.entry.get()
        if not class_name:
            messagebox.showinfo("Aviso", "Por favor, insira um nome para a classe!")
            return

        if class_name not in self.classes:
            self.classes.append(class_name)

        img_array = self.preprocess_image()
        self.X.append(img_array)
        self.y.append(self.classes.index(class_name))

        self.model.fit(self.X, self.y)
        messagebox.showinfo("Ensino", f"Aprendi que isso é um(a): {class_name}")

    def save_model(self):
        with open("drawing_model.pkl", "wb") as f:
            pickle.dump((self.model, self.classes, self.X, self.y), f)
        messagebox.showinfo("Salvar", "Modelo salvo com sucesso!")

    def load_model(self):
        if os.path.exists("drawing_model.pkl"):
            with open("drawing_model.pkl", "rb") as f:
                self.model, self.classes, self.X, self.y = pickle.load(f)
            messagebox.showinfo("Carregar", "Modelo carregado com sucesso!")
        else:
            messagebox.showinfo("Aviso", "Nenhum modelo salvo encontrado!")

    def generate(self):
        if len(self.classes) == 0:
            messagebox.showinfo("Aviso", "Primeiro ensine algumas classes!")
            return

        class_name = simpledialog.askstring("Gerar", "Qual classe você quer gerar?")
        if class_name not in self.classes:
            messagebox.showinfo("Aviso", "Classe não encontrada!")
            return

        class_index = self.classes.index(class_name)
        class_samples = [x for x, y in zip(self.X, self.y) if y == class_index]
        
        if len(class_samples) == 0:
            messagebox.showinfo("Aviso", "Não há amostras para esta classe!")
            return

        # Calcular a média das amostras
        average_sample = np.mean(class_samples, axis=0)
        
        # Converter de volta para uma imagem
        img_array = (average_sample * 255).astype(np.uint8).reshape((28, 28))
        img = Image.fromarray(img_array)
        img = img.resize((280, 280))
        
        # Mostrar a imagem gerada
        self.show_generated_image(img)

    def show_generated_image(self, img):
        top = tk.Toplevel()
        top.title("Imagem Gerada")
        
        canvas = tk.Canvas(top, width=280, height=280)
        canvas.pack()

        img_tk = ImageTk.PhotoImage(img)
        canvas.create_image(0, 0, anchor="nw", image=img_tk)
        canvas.image = img_tk  # Keep a reference!

root = tk.Tk()
app = DrawingApp(root)
root.mainloop()
```