Atayaz/grape_transfer_resnet
0
1# grape_transfer_resnet.py2 3import streamlit as st4import numpy as np5import os6import cv27import matplotlib.pyplot as plt8 9from tensorflow.keras.preprocessing.image import ImageDataGenerator10from tensorflow.keras.applications import ResNet5011from tensorflow.keras.models import Model12from tensorflow.keras.layers import Dense, GlobalAveragePooling2D13from tensorflow.keras.optimizers import Adam14from tensorflow.keras.callbacks import EarlyStopping15 16st.title("Grape Disease Detection (ResNet50 Transfer Learning)")17 18data_dir = "Final Training Data"19img_size = (224, 224)20batch_size = 3221epochs = 122 23datagen = ImageDataGenerator(24 rescale=1./255,25 rotation_range=20,26 zoom_range=0.2,27 width_shift_range=0.2,28 height_shift_range=0.2,29 horizontal_flip=True,30 validation_split=0.231)32 33train_data = datagen.flow_from_directory(34 data_dir,35 target_size=img_size,36 batch_size=batch_size,37 class_mode='categorical',38 subset='training'39)40 41val_data = datagen.flow_from_directory(42 data_dir,43 target_size=img_size,44 batch_size=batch_size,45 class_mode='categorical',46 subset='validation'47)48 49base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))50for layer in base_model.layers:51 layer.trainable = False52 53x = base_model.output54x = GlobalAveragePooling2D()(x)55x = Dense(128, activation='relu')(x)56output = Dense(train_data.num_classes, activation='softmax')(x)57model = Model(inputs=base_model.input, outputs=output)58 59model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])60 61early_stop = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)62history = model.fit(train_data, epochs=epochs, validation_data=val_data, callbacks=[early_stop])63model.save("grape_resnet_model.h5")64 65# Grafik66st.subheader("Model Accuracy & Loss")67fig, ax = plt.subplots(1, 2, figsize=(12, 4))68ax[0].plot(history.history['accuracy'], label='Train Acc')69ax[0].plot(history.history['val_accuracy'], label='Val Acc')70ax[0].legend()71ax[0].set_title('Accuracy')72 73ax[1].plot(history.history['loss'], label='Train Loss')74ax[1].plot(history.history['val_loss'], label='Val Loss')75ax[1].legend()76ax[1].set_title('Loss')77st.pyplot(fig)78 79# Tahmin80st.subheader("Bir Görsel Yükle ve Tahmin Et")81uploaded_file = st.file_uploader("Görsel seç...", type=["jpg", "jpeg", "png"])82if uploaded_file:83 file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)84 img = cv2.imdecode(file_bytes, 1)85 img_resized = cv2.resize(img, img_size)86 img_norm = img_resized / 255.087 img_input = np.expand_dims(img_norm, axis=0)88 89 pred = model.predict(img_input)90 class_idx = np.argmax(pred)91 class_label = list(train_data.class_indices.keys())[class_idx]92 93 st.image(img, channels="BGR", caption="Yüklenen Görsel", width=250)94 st.success(f"Tahmin: {class_label}")95 