Untitled
unknown
plain_text
2 years ago
1.2 kB
7
Indexable
import pandas as pd
dt = {'Outlook': {'Overcast': 'Yes', 'Rain': {'Wind': {'Strong': 'No', 'Weak': 'Yes'}}, 'Sunny': {'Temperature': {'Cool': 'Yes', 'Hot': 'No', 'Mild': 'No'}}}}
dt = {'Odour': {'a': 'e', 'c': 'p', 'n': {'spore_print_color': {'b': 'No', 'Weak': 'Yes'}}, 'Sunny': {'Temperature': {'Cool': 'Yes', 'Hot': 'No', 'Mild': 'No'}}}}
df = pd.DataFrame(data=[['Sunny', 'Mild', 'Normal', 'Strong', 'Yes']],columns=['Outlook', 'Temperature', 'Humidity', 'Wind', 'Decision'])
print(df)
def fun(d, t):
"""
d -- decision tree dictionary
t -- testing examples in form of pandas dataframe
"""
res = []
for _, e in t.iterrows():
res.append(predict(d, e))
return res
def predict(d, e):
"""
d -- decision tree dictionary
e -- a testing example in form of pandas series
"""
current_node = list(d.keys())[0]
current_branch = d[current_node][e[current_node]]
# if leaf node value is string then its a decision
if isinstance(current_branch, str):
return current_branch
# else use that node as new searching subtree
else:
return predict(current_branch, e)
print(fun(dt, df))
Editor is loading...
Leave a Comment