Reset checkboxes after button 'Diagnosa' is clicked

import operator
#import json
import numpy as np
import pandas as pd
import streamlit as st
import requests
#from sklearn.metrics import accuracy_score
from sklearn.base import BaseEstimator, ClassifierMixin
from streamlit_option_menu import option_menu
from streamlit_lottie import st_lottie
from st_aggrid import AgGrid, JsCode
from st_aggrid.grid_options_builder import GridOptionsBuilder
#from streamlit.components.v1 import html

st.set_page_config(page_title=“Sistem Pakar”, page_icon=“:chicken:”, layout=“wide”)

class FuzzyKNN(BaseEstimator, ClassifierMixin):
def init(self, k=5, plot=False):
self.k = k
self.plot = plot

def fit(self, X, y=None):
    self._check_params(X, y)
    self.X = X
    self.y = y
    self.xdim = len(self.X[0])
    self.n = len(y)
    classes = list(set(y))
    classes.sort()
    self.classes = classes
    self.df = pd.DataFrame(self.X)
    self.df['y'] = self.y
    self.memberships = self._compute_memberships()
    self.df['membership'] = self.memberships
    self.fitted_ = True
    return self

def predict(self, X):
    if self.fitted_ is None:
        raise Exception('predict() called before fit()')
    else:
        m = 2
        y_pred = []
        self.top_memberships = []
        top_memberships = []  # Menyimpan 5 nilai keanggotaan terbesar untuk ditampilkan
        for x in X:
            neighbors = self._find_k_nearest_neighbors(pd.DataFrame.copy(self.df), x)
            votes = {}
            memberships = {}  # Menyimpan nilai keanggotaan untuk setiap kelas
            for c in self.classes:
                den = 0
                for n in range(self.k):
                    dist = np.linalg.norm(x - neighbors.iloc[n, 0:self.xdim])
                    den += 1 / (dist ** (2 / (m - 1)))
                neighbors_votes = []
                for n in range(self.k):
                    dist = np.linalg.norm(x - neighbors.iloc[n, 0:self.xdim])
                    num = (neighbors.iloc[n].membership[c]) / (dist ** (2 / (m - 1)))
                    vote = num / den
                    neighbors_votes.append(vote)
                votes[c] = np.sum(neighbors_votes)
                memberships[c] = np.sum(neighbors_votes)  # Simpan nilai keanggotaan

            # Menyimpan 5 nilai keanggotaan terbesar
            top_5_memberships = sorted(memberships.items(), key=lambda x: x[1], reverse=True)[:5]
            self.top_memberships.append(top_5_memberships)

            pred = max(votes.items(), key=operator.itemgetter(1))[0]
            y_pred.append(pred)

        # Menampilkan 5 nilai keanggotaan terbesar untuk setiap data uji
        for i, top_5 in enumerate(top_memberships):
            st.write(f"\n5 Nilai Keanggotaan Terbesar pada Data Uji ke-{i + 1}:")
            for c, value in top_5:
                st.write(f"{c}: {value}")

        return y_pred       

def _find_k_nearest_neighbors(self, df, x):
    X = df.iloc[:, 0:self.xdim].values
    df['distances'] = [np.linalg.norm(X[i] - x) for i in range(self.n)]
    df.sort_values(by='distances', ascending=True, inplace=True)
    neighbors = df.iloc[0:self.k]
    return neighbors

def _get_counts(self, neighbors):
    groups = neighbors.groupby('y')
    counts = {group[1]['y'].iloc[0]: group[1].count()[0] for group in groups}
    return counts

def _compute_memberships(self):
    memberships = []
    for i in range(self.n):
        x = self.X[i]
        y = self.y[i]
        neighbors = self._find_k_nearest_neighbors(pd.DataFrame.copy(self.df), x)
        counts = self._get_counts(neighbors)
        membership = dict()
        for c in self.classes:
            try:
                uci = 0.49 * (counts[c] / self.k)
                if c == y:
                    uci += 0.51
                membership[c] = uci
            except:
                membership[c] = 0
        memberships.append(membership)
    return memberships

def _check_params(self, X, y):
    if type(self.k) != int:
        raise Exception('"k" should have type int')
    if self.k >= len(y):
        raise Exception('"k" should be less than the number of feature sets')
    if self.k % 2 == 0:
        raise Exception('"k" should be odd')
    if type(self.plot) != bool:
        raise Exception('"plot" should have type bool')

Memuat data latih dari file CSV

train_data = pd.read_csv(‘data_setfix.csv’)
train_features = train_data.iloc[:, :-1].values
train_labels = train_data.iloc[:, -1].values

Mendapatkan nama kolom/gejala dari data latih

column_names = train_data.columns.tolist()

if selected == “Diagnosa”:
st.title(f"Menu yang dipilih {selected}“)
st.write(”“”
# Diagnosa Penyakit
Pilih gejala dengan centang checkbox sesuai dengan kondisi ayam yang diternak
“”")
# Membagi gejala menjadi beberapa kolom dalam satu baris
num_columns = 3
gejala = [column_names[i:i+num_columns] for i in range(0, len(column_names)-1, num_columns)]

# Membuat inputan gejala menggunakan checkbox dengan nama kolom yang sesuai
input_data = []
for col_group in gejala:
    cols = st.columns(len(col_group))
    for i, col_name in enumerate(col_group):
        input_data.append(cols[i].checkbox(col_name))

# Konversi inputan gejala ke array numpy
input_array = np.array(input_data, dtype=np.float64).reshape(1, -1)

# Melatih classifier Fuzzy k-NN
k = 5
classifier = FuzzyKNN(k=k)
classifier.fit(train_features, train_labels)

if st.button('Diagnosa'):
    # Menguji classifier menggunakan data uji
    predictions = classifier.predict(input_array)

    # Menampilkan hasil prediksi
    result = predictions[0]
    st.subheader(f"Hasil diagnosa untuk gejala yang dimasukkan: Diagnosa = {result}")

    # Menampilkan solusi atau saran berdasarkan hasil prediksi
    if result in solutions:
        st.write("---")
        st.subheader("\nSolusi atau Saran:")
        st.info(solutions[result])
    else:
        st.subheader("\nTidak ditemukan solusi untuk penyakit yang didiagnosa.")
    
    # Menampilkan tabel gejala yang dicentang saat menekan tombol prediksi
    checked_symptoms = [column_names[i] for i in range(len(column_names) - 1) if input_array[0][i] == 1]
    if checked_symptoms:
        st.write("---")
        st.subheader("\nGejala yang Dicentang:")
        for i, symptom in enumerate(checked_symptoms, start=1):
            st.info(f"{i}. {symptom}")
    else:
        st.subheader("\nTidak ada gejala yang dicentang.")
        

    for i, top_5 in enumerate(classifier.top_memberships):
        st.write("---")
        st.subheader(f"\n5 Nilai Keanggotaan Terbesar :")
        st.write("*Catatan : semakin mendekati nilai 1 semakin akurat*")
        for c, value in top_5:
            st.info(f"{c}: {value:.2f}")


    neighbors = classifier._find_k_nearest_neighbors(pd.DataFrame.copy(classifier.df), input_array.flatten())
    st.write("---")
    st.subheader("\n5 Nilai Jarak Euclidean Terdekat :")
    for index, row in neighbors.iterrows():
        # Calculate the membership value in percentage
        membership = (row['distances'])
        st.info(f"{row['y']}: {membership:.2f}")