├── Modelt.py ├── app.py ├── heart_disease_autoencoder.h5 └── prediction_log.txt /Modelt.py: -------------------------------------------------------------------------------- 1 | # Import Necessary Libraries 2 | import tensorflow as tf 3 | from keras.models import Model 4 | from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D 5 | from sklearn.model_selection import train_test_split 6 | import numpy as np 7 | import matplotlib.pyplot as plt 8 | import os 9 | from skimage.transform import resize 10 | 11 | # Load and Preprocess Dataset 12 | def load_images(image_dir, target_size=(224, 224)): 13 | """ 14 | Load and preprocess images from a directory. 15 | :param image_dir: Path to the directory containing images. 16 | :param target_size: Target size for resizing images. 17 | :return: Preprocessed images as a NumPy array. 18 | """ 19 | images = [] 20 | for filename in os.listdir(image_dir): 21 | if filename.endswith(".jpg") or filename.endswith(".png"): 22 | img = plt.imread(os.path.join(image_dir, filename)) 23 | img_resized = resize(img, target_size, anti_aliasing=True) 24 | images.append(img_resized) 25 | images = np.array(images) 26 | images = images / 255.0 # Normalize pixel values 27 | return images 28 | 29 | # Path to dataset 30 | image_path = r'C:\Users\mutha\Desktop\Heart\data' 31 | 32 | # Load images 33 | images = load_images(image_path) 34 | 35 | # Split data into training and validation sets 36 | x_train, x_val = train_test_split(images, test_size=0.2, random_state=42) 37 | 38 | # Define Autoencoder Model 39 | def create_autoencoder(input_shape): 40 | """ 41 | Create an autoencoder model for one-class classification. 42 | :param input_shape: Shape of input images. 43 | :return: Compiled autoencoder model. 44 | """ 45 | input_img = Input(shape=input_shape) 46 | 47 | # Encoder 48 | x = Conv2D(32, (3, 3), activation='relu', padding='same')(input_img) 49 | x = MaxPooling2D((2, 2), padding='same')(x) 50 | x = Conv2D(64, (3, 3), activation='relu', padding='same')(x) 51 | encoded = MaxPooling2D((2, 2), padding='same')(x) 52 | 53 | # Decoder 54 | x = Conv2D(64, (3, 3), activation='relu', padding='same')(encoded) 55 | x = UpSampling2D((2, 2))(x) 56 | x = Conv2D(32, (3, 3), activation='relu', padding='same')(x) 57 | x = UpSampling2D((2, 2))(x) 58 | decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x) 59 | 60 | autoencoder = Model(input_img, decoded) 61 | autoencoder.compile(optimizer='adam', loss='mse') 62 | return autoencoder 63 | 64 | # Define input shape 65 | input_shape = (224, 224, 3) # Adjust dimensions based on your images 66 | 67 | # Create the autoencoder 68 | autoencoder = create_autoencoder(input_shape) 69 | 70 | # Train the Autoencoder 71 | history = autoencoder.fit( 72 | x_train, x_train, 73 | validation_data=(x_val, x_val), 74 | epochs=20, # Adjust as needed 75 | batch_size=32, # Adjust as needed 76 | verbose=1 77 | ) 78 | 79 | # Save the Model 80 | model_save_path = r"C:\Users\mutha\Desktop\Heart\heart_disease_autoencoder.h5" 81 | autoencoder.save(model_save_path) 82 | print(f"Model saved as {model_save_path}") 83 | 84 | # Evaluate the Model 85 | loss = autoencoder.evaluate(x_val, x_val) 86 | print(f"Validation Loss: {loss:.4f}") 87 | 88 | # Visualize Reconstruction Performance 89 | def visualize_reconstruction(model, images, n=5): 90 | """ 91 | Visualize the reconstruction of the autoencoder. 92 | :param model: Trained autoencoder model. 93 | :param images: Validation images. 94 | :param n: Number of samples to visualize. 95 | """ 96 | reconstructed = model.predict(images[:n]) 97 | plt.figure(figsize=(10, 4)) 98 | for i in range(n): 99 | # Original image 100 | plt.subplot(2, n, i + 1) 101 | plt.imshow(images[i]) 102 | plt.title("Original") 103 | plt.axis('off') 104 | 105 | # Reconstructed image 106 | plt.subplot(2, n, i + 1 + n) 107 | plt.imshow(reconstructed[i]) 108 | plt.title("Reconstructed") 109 | plt.axis('off') 110 | plt.show() 111 | 112 | visualize_reconstruction(autoencoder, x_val) 113 | 114 | # Anomaly Detection: Compute Reconstruction Error 115 | def compute_reconstruction_error(model, images): 116 | """ 117 | Compute reconstruction error for each image. 118 | :param model: Trained autoencoder model. 119 | :param images: Images to compute reconstruction error on. 120 | :return: Reconstruction errors. 121 | """ 122 | reconstructed = model.predict(images) 123 | errors = np.mean(np.square(images - reconstructed), axis=(1, 2, 3)) 124 | return errors 125 | 126 | # Compute reconstruction errors 127 | errors = compute_reconstruction_error(autoencoder, x_val) 128 | threshold = np.percentile(errors, 95) # Set threshold for anomaly detection 129 | print(f"Threshold for anomaly detection: {threshold:.4f}") 130 | 131 | # Detect anomalies (e.g., non-heart disease images) 132 | anomalies = errors > threshold 133 | print(f"Number of anomalies detected: {np.sum(anomalies)}") 134 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, jsonify, render_template 2 | import numpy as np 3 | import tensorflow as tf 4 | from PIL import Image 5 | import logging 6 | import traceback 7 | 8 | 9 | app = Flask(__name__) 10 | logging.basicConfig(level=logging.DEBUG) 11 | 12 | try: 13 | model = tf.keras.models.load_model(r'C:\Users\mutha\Desktop\Heart\heart_disease_autoencoder.h5') 14 | except Exception as e: 15 | logging.error(f"Model loading error: {e}") 16 | model = None 17 | 18 | def preprocess_image(image, target_size=(224, 224)): 19 | try: 20 | image = image.resize(target_size, Image.Resampling.LANCZOS) 21 | image_array = np.array(image) 22 | 23 | if image_array.ndim == 2: 24 | image_array = np.stack((image_array,) * 3, axis=-1) 25 | 26 | image_array = image_array / 255.0 27 | image_array = np.expand_dims(image_array, axis=0) 28 | 29 | return image_array 30 | except Exception as e: 31 | logging.error(f"Image preprocessing error: {e}") 32 | return None 33 | 34 | @app.route("/") 35 | def home(): 36 | return render_template("index.html") 37 | 38 | @app.route("/predict", methods=["POST"]) 39 | def predict(): 40 | try: 41 | # Validate file 42 | if "file" not in request.files: 43 | return jsonify({"error": "No file uploaded"}) 44 | 45 | file = request.files["file"] 46 | if file.filename == "": 47 | return jsonify({"error": "No file selected"}) 48 | 49 | # Open and preprocess image 50 | image = Image.open(file).convert("RGB") 51 | image = image.resize((224, 224)) 52 | image_array = np.array(image) / 255.0 53 | image_array = np.expand_dims(image_array, axis=0) 54 | 55 | # Predict 56 | prediction = model.predict(image_array) 57 | 58 | # For autoencoders, calculate reconstruction error 59 | reconstruction_error = np.mean(np.abs(prediction - image_array)) 60 | 61 | # Threshold for heart disease detection 62 | label = "Heart Disease" if 0.20 < reconstruction_error < 0.30 else "No Heart Disease" 63 | 64 | return jsonify({ 65 | "prediction": label, 66 | "confidence": float(reconstruction_error) 67 | }) 68 | 69 | except Exception as e: 70 | return jsonify({"error": str(e)}) 71 | 72 | if __name__ == "__main__": 73 | app.run(debug=True) -------------------------------------------------------------------------------- /heart_disease_autoencoder.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ajis-mohamed/Design-project/49abce358542be17bb17fa130153bd18dcc0b1c2/heart_disease_autoencoder.h5 -------------------------------------------------------------------------------- /prediction_log.txt: -------------------------------------------------------------------------------- 1 | 2024-12-02 10:41:13,451 - INFO: Model loaded successfully 2 | 2024-12-02 10:41:13,481 - INFO: WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. 3 | * Running on all addresses (0.0.0.0) 4 | * Running on http://127.0.0.1:5000 5 | * Running on http://192.168.9.165:5000 6 | 2024-12-02 10:41:13,481 - INFO: Press CTRL+C to quit 7 | 2024-12-02 10:41:13,500 - INFO: * Restarting with watchdog (windowsapi) 8 | 2024-12-02 10:41:19,259 - INFO: Model loaded successfully 9 | 2024-12-02 10:41:19,277 - WARNING: * Debugger is active! 10 | 2024-12-02 10:41:19,282 - INFO: * Debugger PIN: 313-684-670 11 | 2024-12-02 10:41:20,533 - INFO: * Detected change in 'c:\\Users\\mutha\\Desktop\\Heart\\app.py', reloading 12 | 2024-12-02 10:41:20,542 - INFO: * Detected change in 'c:\\Users\\mutha\\Desktop\\Heart\\app.py', reloading 13 | 2024-12-02 10:41:20,543 - INFO: * Detected change in 'c:\\Users\\mutha\\Desktop\\Heart\\app.py', reloading 14 | 2024-12-02 10:41:22,482 - INFO: * Restarting with watchdog (windowsapi) 15 | 2024-12-02 10:41:33,090 - INFO: Model loaded successfully 16 | 2024-12-02 10:41:33,113 - INFO: WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. 17 | * Running on all addresses (0.0.0.0) 18 | * Running on http://127.0.0.1:5000 19 | * Running on http://192.168.9.165:5000 20 | 2024-12-02 10:41:33,113 - INFO: Press CTRL+C to quit 21 | 2024-12-02 10:41:33,130 - INFO: * Restarting with watchdog (windowsapi) 22 | 2024-12-02 10:41:38,606 - INFO: Model loaded successfully 23 | 2024-12-02 10:41:38,625 - WARNING: * Debugger is active! 24 | 2024-12-02 10:41:38,629 - INFO: * Debugger PIN: 313-684-670 25 | 2024-12-02 10:41:38,659 - INFO: 127.0.0.1 - - [02/Dec/2024 10:41:38] "GET / HTTP/1.1" 200 - 26 | 2024-12-02 10:42:36,391 - INFO: * Detected change in 'c:\\Users\\mutha\\Desktop\\Heart\\app.py', reloading 27 | 2024-12-02 10:42:36,421 - INFO: * Detected change in 'c:\\Users\\mutha\\Desktop\\Heart\\app.py', reloading 28 | 2024-12-02 10:42:38,455 - INFO: * Restarting with watchdog (windowsapi) 29 | 2024-12-02 10:42:44,525 - INFO: Model loaded successfully 30 | 2024-12-02 10:43:43,014 - INFO: Model loaded successfully 31 | --------------------------------------------------------------------------------