RecursionError: maximum recursion depth exceeded while calling a Python object

Hi I have problem in my program, problem is:
Recursion Error: maximum recursion depth exceeded while calling a Python object

Screenshot_2020-08-28 apps · Streamlit


# import libray

import streamlit as st

import os

import pandas as pd

import numpy as np

import uuid

from IPython.display import Image

import pydot

import graphviz 

eps = np.finfo(float).eps

from numpy import log2 as log

st.subheader("Sistem Penentuan Pola Serangan Menggunakan Algoritma ID3")



Sistem ini merupakan keluaran dari penelitian yang dilakukan, sistem ini

dibagun menggunakan bahsa python dengan menggunakan framework streamlit. 

Sistem ini bertujuan untuk mengolah data serangan siber menggunakan 

teknik data mining dengan menggunakan algoritma ID3, untuk menemukan pola serangan siber 



st.sidebar.title("Selamat Datang Analis")

st.sidebar.markdown("Ikuti Langkah dibawah ini untuk menjalakan perangkat lunak:")

st.sidebar.subheader("Pengolahan Data")

# Pilih data

def pilih_data(folder_path='/home/muslim/sppssiber/data'):

    filenames = os.listdir(folder_path)

    selected_filename = st.sidebar.selectbox('Pilih dataset', filenames)

    return os.path.join(folder_path, selected_filename)

dapil = pilih_data()

st.sidebar.markdown('Data yang dipilih: `%s`' % dapil)

# lihat data

def lihat_data(datapilih):

    data = pd.read_csv(dapil)

    return data

df = lihat_data(dapil)

if st.sidebar.checkbox('Tampil Data'):

    st.subheader('Berikut adalah data training yang dipilih:')


# pemprosesan data

# hitung entropy target attribut

def hitung_enropyAT(df):

    Class = df.keys()[-1] 

    entropy = 0

    values = df[Class].unique()

    for value in values:

        fraction = df[Class].value_counts()[value]/len(df[Class])

        entropy += -fraction*np.log2(fraction)

    return entropy

# hitung entropy attribut

def hitung_entropyA(df,attribute):

        Class = df.keys()[-1]   

        target_variables = df[Class].unique()  

        variables = df[attribute].unique()

        entropy2 = 0

        for variable in variables:

            entropy = 0

            for target_variable in target_variables:

                    num = len(df[attribute][df[attribute]==variable][df[Class] ==target_variable])

                    den = len(df[attribute][df[attribute]==variable])

                    fraction = num/(den+eps)

                    entropy += -fraction*log(fraction+eps)

            fraction2 = den/len(df)

            entropy2 += -fraction2*entropy

        return abs(entropy2)

# hitung information gain

def hitung_ig(df):

    IG = []

    for key in df.keys()[:-1]:


    return df.keys()[:-1][np.argmax(IG)]

# bentuk struktur pohon

def bentuk_st(df, node, value):


    return df[df[node] == value].reset_index(drop=True)

# membangun pohon

def bangun_dt(df,tree=None): 


    Class = df.keys()[-1]  

    node = hitung_ig(df)

    attValue = np.unique(df[node])


    if tree is None:                    


        tree[node] = {}

    for value in attValue:


        stpohon = bentuk_st(df,node,value)

        clValue,counts = np.unique(stpohon['Target'],return_counts=True)                        


        if len(counts)==1:

            tree[node][value] = clValue[0]                                                    


            tree[node][value] = bangun_dt(stpohon)

    return tree

tree = bangun_dt(df)

# visualisasi pohon

def visualisasi_pohon(graph, dictionary, parent_node=None):

    for k in dictionary.keys():

        if parent_node is not None:         

            from_name = parent_node.get_name().replace("\"", "") + '_' + str(k)

            from_label = str(k)

            obj_dict = {}


            if 'True' in from_label:

                node_from = pydot.Node(from_name, color='white', style='filled',fillcolor='green', label=from_label)

            elif 'False' in from_label:

                node_from = pydot.Node(from_name, color='white', style='filled',fillcolor='red', label=from_label)


                node_from = pydot.Node(from_name, label=from_label)


            graph.add_edge( pydot.Edge(parent_node, node_from) )

            if isinstance(dictionary[k], dict):

                visualisasi_pohon(graph, dictionary[k], node_from)


                to_name = str(uuid.uuid4()) + '_' + str(dictionary[k])

                to_label = str(dictionary[k])

                node_to = pydot.Node(to_name, label=to_label, shape='box')


                graph.add_edge(pydot.Edge(node_from, node_to))



            from_name =  str(k)

            from_label = str(k)

            node_from = pydot.Node(from_name, label=from_label)

            visualisasi_pohon(graph, dictionary[k], node_from)

# simpan pohon

def simpan_pohon(tree, name):

    graph = pydot.Dot(graph_type='digraph')

    visualisasi_pohon(graph, tree)


if st.sidebar.button('Proses Data'):

    loading = st.sidebar.text('Data sedang diproses...')



    loading.text('Data berhasil diproses.. cek hasil di direktori')

st.subheader("Cek Pola Serangan")

at1 = st.text_input('Protokol')

at2 = st.text_input('Negara')

at3 = st.text_input('Class Ip')

# cek pola serangan

def cek_pola(cekdata,tree):


    for nodes in tree.keys():        


        value = cekdata[nodes]

        tree = tree[nodes][value]

        pola = 0


        if type(tree) is dict:

            pola = cek_pola(cekdata, tree)


            pola = tree



    return pola

if st.button('Cek pola data'):

    data = {'Protokol':at1,'Negara':at2,'Ip':at3,}

    cekdata = pd.Series(data)

    port = cek_pola(cekdata,tree)


    st.write('Jika ada koneksi dengan protokol:',at1,'dengan negara penyerang:',at2,'kelas ip yang digunakan:',at3,'maka port yang diserang:',port)

Hi @Ahmad_Muslim -

Can you post the code you are running?

I have posted the code

I’m guessing, but the fact that you are recursively calling cek_pola is the likely issue. Since I’m not familiar with tree/graph processing, I cannot suggest a solution.

Quick fix ( I dont recommend this ) would be to set max_recursion_depth to something higher.

import sys

As @randyzwitch has mentioned the error is in your traversal method cek_pola, How about you change the traversal to iterative?

Its untested but you should be able to resolve your error by changing your function to this,

def cek_pola(cekdata,tree):
    stack = [tree]

    while stack:
        current_node = stack.pop()
        for nodes in tree.keys():        
            value = cekdata[nodes]
            tree = current_node[nodes][value]
            pola = 0

            if type(current_node) is dict:
                pola = tree

    return pola

Hope it helps ! :slight_smile:

functin cek_pola is solved but function bangun_dt showing error Recursion Error: maximum recursion depth exceeded while calling a Python object

You need to change that function to iterative tree traversal as well using similar approach.

can you created for me, i don’t understand