gmustafa413 commited on
Commit
43e4d9f
·
verified ·
1 Parent(s): c848d6b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -0
app.py CHANGED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import streamlit as st
3
+ import tensorflow as tf
4
+ from tensorflow import keras
5
+ import numpy as np
6
+ from PIL import Image
7
+ import matplotlib.pyplot as plt
8
+ from sklearn.model_selection import train_test_split
9
+
10
+ # Load CIFAR-10 dataset
11
+ (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
12
+
13
+ # Normalize pixel values to [0, 1]
14
+ x_train, x_test = x_train / 255.0, x_test / 255.0
15
+
16
+ # Split training data into training and validation sets
17
+ x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.2, random_state=42)
18
+
19
+ # Define a simple CNN model
20
+ def create_model():
21
+ model = keras.models.Sequential([
22
+ keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
23
+ keras.layers.MaxPooling2D((2, 2)),
24
+ keras.layers.Conv2D(64, (3, 3), activation='relu'),
25
+ keras.layers.MaxPooling2D((2, 2)),
26
+ keras.layers.Conv2D(128, (3, 3), activation='relu'),
27
+ keras.layers.Flatten(),
28
+ keras.layers.Dense(128, activation='relu'),
29
+ keras.layers.Dense(10, activation='softmax')
30
+ ])
31
+ return model
32
+
33
+ # Check if the model is already saved
34
+ import os
35
+ if not os.path.exists("cifar10_cnn_model.h5"):
36
+ # Create and compile the model
37
+ model = create_model()
38
+ model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
39
+
40
+ # Train the model
41
+ st.write("Training the model...")
42
+ history = model.fit(x_train, y_train, epochs=100, validation_data=(x_val, y_val)) # Reduced epochs for quick testing
43
+
44
+ # Save the model
45
+ model.save("cifar10_cnn_model.h5")
46
+ st.write("Model saved as 'cifar10_cnn_model.h5'")
47
+ else:
48
+ # Load the pre-trained model
49
+ st.write("Loading pre-trained model...")
50
+ model = keras.models.load_model("cifar10_cnn_model.h5")
51
+
52
+ # Class names for CIFAR-10 dataset
53
+ class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
54
+
55
+ # Streamlit app title
56
+ st.title("Image Detection System")
57
+
58
+ # Upload image
59
+ uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
60
+
61
+ if uploaded_file is not None:
62
+ # Display the uploaded image
63
+ image = Image.open(uploaded_file)
64
+ st.image(image, caption="Uploaded Image", use_column_width=True)
65
+
66
+ # Preprocess the image
67
+ image = image.resize((32, 32)) # Resize to match CIFAR-10 input size
68
+ image = np.array(image) / 255.0 # Normalize pixel values
69
+ image = np.expand_dims(image, axis=0) # Add batch dimension
70
+
71
+ # Make prediction
72
+ predictions = model.predict(image)
73
+ predicted_class = np.argmax(predictions)
74
+ confidence = np.max(predictions) * 100
75
+
76
+ # Display results
77
+ st.write(f"**Prediction:** {class_names[predicted_class]}")
78
+ st.write(f"**Confidence:** {confidence:.2f}%")
79
+ model.save("cifar10_cnn_model.keras")