<jupyter_start><jupyter_text>**Import Libraries**<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd<jupyter_output><empty_output><jupyter_text>**Read Data**<jupyter_code>#!gdown --id 1jPZntVYySpJX0fAlizKU2WcKFoWORWHR #Only if using google colab
df = pd.read_excel('restoran.xlsx')
pelayanan,makanan = df['pelayanan'].values,df['makanan'].values
df.describe()
fig = plt.subplots(1,1, figsize=(10,5))
plt.plot(pelayanan, makanan, 'o')
plt.title('Scatter Plot Data Restoran', fontsize=30)
plt.xlabel('Kualitas Pelayanan', fontsize=17)
plt.ylabel('Kualitas Makanan', fontsize=17)
plt.savefig('scatter.png')<jupyter_output><empty_output><jupyter_text>**Linguistic Range**<jupyter_code>pelayanan_label = ['LOW', 'MED', 'HIGH', 'SUPER']
makanan_label = ['HORRIBLE', 'ORDINARY', 'TASTY', 'SPLENDID']
target_label = ['UNRECOMMENDED', 'CONSIDERED', 'RECOMMENDED', 'HIGHLY RECOMMENDED']

m_diff = 0.5
m_cut = [5, 7, 9, 10]
p_diff = 5
p_cut = [50, 70, 90, 100]
t_diff = 5
t_cut = [30, 60, 80, 100]

makanan_point = [[0, m_cut[0]-m_diff, m_cut[0]],
                    [m_cut[0]-m_diff, m_cut[0], m_cut[1]-m_diff, m_cut[1]],
                    [m_cut[1]-m_diff, m_cut[1], m_cut[2]-m_diff, m_cut[2]],
                    [m_cut[2]-m_diff, m_cut[2], m_cut[3]]
                   ]
pelayanan_point = [[0, p_cut[0]-p_diff, p_cut[0]],
                    [p_cut[0]-p_diff, p_cut[0], p_cut[1]-p_diff, p_cut[1]],
                    [p_cut[1]-p_diff, p_cut[1], p_cut[2]-p_diff, p_cut[2]],
                    [p_cut[2]-p_diff, p_cut[2], p_cut[3]]
                   ]
target_point = [[0, t_cut[0] - t_diff, t_cut[0]],
                [t_cut[0] - t_diff, t_cut[0], t_cut[1] - t_diff, t_cut[1]],
                [t_cut[1]-t_diff, t_cut[1], t_cut[2]-t_diff, t_cut[2]],
                [t_cut[2]-t_diff, t_cut[2], t_cut[3]]
                ]
target_point_sugeno = t_cut

print ('makanan_point = ', makanan_point,'','pelayanan_point = ', pelayanan_point,'','target_point = ', target_point, sep='\n')<jupyter_output>makanan_point = 
[[0, 4.5, 5], [4.5, 5, 6.5, 7], [6.5, 7, 8.5, 9], [8.5, 9, 10]]

pelayanan_point = 
[[0, 45, 50], [45, 50, 65, 70], [65, 70, 85, 90], [85, 90, 100]]

target_point = 
[[0, 25, 30], [25, 30, 55, 60], [55, 60, 75, 80], [75, 80, 100]]<jupyter_text>**Calculate Membership Function**<jupyter_code>def down(x, a, b):
  return -(x-b)/(b-a)
def up(x, a, b):
  return (x-b)/(b-a)<jupyter_output><empty_output><jupyter_text>**Membership Function Makanan**<jupyter_code>def fx_horrible_makanan(x):
  p = makanan_point[0]
  if (x <= p[1]):
    return 1
  elif (p[1] < x < p[2]):
    return down(x, p[1], p[2])
  else:
    return 0

def fx_ordinary_makanan(x):
    p = makanan_point[1]
    if (p[0] < x < p[1]):
        return up(x, p[0], p[1])
    elif (p[1] <= x <= p[2]):
        return 1
    elif (p[2] < x <= p[3]):
        return down(x, p[2], p[3])
    else:
        return 0

def fx_tasty_makanan(x):
    p = makanan_point[2]
    if (p[0] < x < p[1]):
        return up(x, p[0], p[1])
    elif (p[1] <= x <= p[2]):
        return 1
    elif (p[2] < x <= p[3]):
        return down(x, p[2], p[3])
    else:
        return 0

def fx_splendid_makanan(x):
    p = makanan_point[3]
    if (x >= p[1]):
        return 1
    elif (p[0] < x < p[1]):
        return up(x, p[0], p[1])
    else:
        return 0<jupyter_output><empty_output><jupyter_text>**Membership Function Pelayanan**<jupyter_code>def fx_low_pelayanan(x):
    p = pelayanan_point[0]
    if (x <= p[1]):
        return 1
    elif (p[1] < x < p[2]):
        return down(x, p[1], p[2])
    else:
        return 0

def fx_med_pelayanan(x):
    p = pelayanan_point[1]
    if (p[0] < x < p[1]):
        return up(x, p[0], p[1])
    elif (p[1] <= x <= p[2]):
        return 1
    elif (p[2] < x <= p[3]):
        return down(x, p[2], p[3])
    else:
        return 0

def fx_high_pelayanan(x):
    p = pelayanan_point[2]
    if (p[0] < x < p[1]):
        return up(x, p[0], p[1])
    elif (p[1] <= x <= p[2]):
        return 1
    elif (p[2] < x <= p[3]):
        return down(x, p[2], p[3])
    else:
        return 0

def fx_super_pelayanan(x):
    p = pelayanan_point[3]
    if (x >= p[1]):
        return 1
    elif (p[0] < x < p[1]):
        return up(x, p[0], p[1])
    else:
        return 0<jupyter_output><empty_output><jupyter_text>**Plot Membership Function**<jupyter_code>x = np.arange(0,11,1)
x2 = np.arange(0,110,10)
fig, ax = plt.subplots(1,2,figsize=(18, 4))
ax[0].plot(x,[fx_horrible_makanan(y) for y in x], label='horrible')
ax[0].plot(x,[fx_ordinary_makanan(y) for y in x], label='ordinary',color='r')
ax[0].plot(x,[fx_tasty_makanan(y) for y in x], label='tasty')
ax[0].plot(x,[fx_splendid_makanan(y) for y in x], label='splendid')
ax[0].set_title('Makanan')
ax[0].legend(loc='center left')
ax[1].plot(x2,[fx_low_pelayanan(y) for y in x2], label='low')
ax[1].plot(x2,[fx_med_pelayanan(y) for y in x2], label='medium',color='r')
ax[1].plot(x2,[fx_high_pelayanan(y) for y in x2], label='high')
ax[1].plot(x2,[fx_super_pelayanan(y) for y in x2], label='super')
ax[1].set_title('Pelayanan')
ax[1].legend(loc='center left')
fig.suptitle('Membership function')
plt.plot()<jupyter_output><empty_output><jupyter_text>**Fuzzification**<jupyter_code>def fuzzification():
  fuzzyset_makanan, fuzzyset_pelayanan = [], []
  for i in makanan:
    temp = [[makanan_label[0], fx_horrible_makanan(i)],
            [makanan_label[1], fx_ordinary_makanan(i)],
            [makanan_label[2], fx_tasty_makanan(i)],
            [makanan_label[3], fx_splendid_makanan(i)]]
    fuzzyset_makanan.append(temp)
  
  for i in pelayanan:
    temp = [[pelayanan_label[0], fx_low_pelayanan(i)],
            [pelayanan_label[1], fx_med_pelayanan(i)],
            [pelayanan_label[2], fx_high_pelayanan(i)],
            [pelayanan_label[3], fx_super_pelayanan(i)]]
    fuzzyset_pelayanan.append(temp)

  return fuzzyset_makanan, fuzzyset_pelayanan<jupyter_output><empty_output><jupyter_text>**Inference Rule**<jupyter_code>rule = [[0, 0, 0, 0],[0, 1, 1, 1],[0, 1, 2, 3],[0, 2, 2, 3]]
df_rule = pd.DataFrame(rule, index = makanan_label, columns = pelayanan_label).replace({0:target_label[0],1:target_label[1],2:target_label[2],3:target_label[3]})
df_rule
def inference(x, y):
    results = []
    for i in range(len(x)):
        classes = {}
        for mak in x[i]:
            for pel in y[i]:
                key = df_rule[pel[0]][mak[0]]
                value = min(pel[1],mak[1])
                if key not in classes.keys():
                    classes[key] = value
                else:
                    classes[key] = max(value, classes[key])
        results.append(classes)
    return results<jupyter_output><empty_output><jupyter_text>**Membership Function Target**<jupyter_code>def fx_unrecommended(x):
    p = target_point[0]
    if (x <= p[1]):
        return 1
    elif (p[1] < x < p[2]):
        return down(x, p[1], p[2])
    else:
        return 0

def fx_considered(x):
    p = target_point[1]
    if (p[0] < x < p[1]):
        return up(x, p[0], p[1]) 
    elif (p[1] <= x <= p[2]):
        return 1
    elif (p[2] < x <= p[3]):
        return down(x, p[2], p[3])
    else:
        return 0
        
def fx_recommended(x):
    p = target_point[2]
    if (p[0] < x < p[1]):
        return up(x, p[0], p[1]) 
    elif (p[1] <= x <= p[2]):
        return 1
    elif (p[2] < x <= p[3]):
        return down(x, p[2], p[3])
    else:
        return 0

def fx_highly_recommended(x):
    p = target_point[3]
    if x >= p[1]:
        return 1
    elif (p[0] < x < p[1]):
        return up(x, p[0], p[1])
    else:
        return 0<jupyter_output><empty_output><jupyter_text>**Plot Membership Function Target**<jupyter_code>x3 = np.arange(0,110,10)
fig, ax = plt.subplots(1, 2, figsize=(20, 4))
ax[0].plot(x3, [fx_unrecommended(y) for y in x3], label='unrecommended', color='b')
ax[0].plot(x3, [fx_considered(y) for y in x3], label='considered',color='r')
ax[0].plot(x3, [fx_recommended(y) for y in x3], label='recommended', color='orange')
ax[0].plot(x3, [fx_highly_recommended(y) for y in x3], label='highly recommended', color='g')
ax[0].set_title('Mamdani rules')
ax[0].legend(loc='center left', fontsize=8)
ax[1].vlines(x = target_point_sugeno[0], ymin = 0, ymax = 1, label='unrecommended', color='b')
ax[1].vlines(x = target_point_sugeno[1], ymin = 0, ymax = 1, label='considered',color='r')
ax[1].vlines(x = target_point_sugeno[2], ymin = 0, ymax = 1, label='recommended', color ='orange')
ax[1].vlines(x = target_point_sugeno[3], ymin = 0, ymax = 1, label='highly recommended', color='g')
ax[1].vlines(0,0,1,visible=False)
ax[1].set_title('Sugeno rules')
ax[1].legend(loc='center left', fontsize=8)
fig.suptitle('Defuzzification rules')
plt.plot()
plt.savefig('defuzzification_rules.png')<jupyter_output><empty_output><jupyter_text>**Defuzzification**<jupyter_code>def defuzzification(inferences,style):
    score = []
    for i in inferences :
        if style == 'mamdani':
            μB = []
            points = np.arange(5,100,5)
            for p in points:
                unrecommend = i['UNRECOMMENDED'] if fx_unrecommended(p) > 0 else 0
                consider = i['CONSIDERED'] if fx_considered(p) > 0 else 0
                recommend = i['RECOMMENDED'] if fx_recommended(p) > 0 else 0
                highly_recommend = i['HIGHLY RECOMMENDED'] if fx_highly_recommended(p) > 0 else 0
                μB.append(max(unrecommend, consider, recommend, highly_recommend))
            zμB = [μB[i] * points[i] for i in range(len(points))]
            z = sum(zμB)/sum(μB)
            score.append(z)
        elif style == 'sugeno':
            p = target_point_sugeno
            unrecommend = i['UNRECOMMENDED'] 
            consider = i['CONSIDERED'] 
            recommend = i['RECOMMENDED']
            highly_recommend = i['HIGHLY RECOMMENDED']
            μB = (unrecommend * p[0] + consider * p[1] + recommend * p[2] + highly_recommend * p[3])
            z = μB / (unrecommend + consider + recommend + highly_recommend) if μB> 0 else 0
            score.append(z)
        else :
            score = np.zeros(len(inferences))
            print('not supported yet')
    return score<jupyter_output><empty_output><jupyter_text>**Main Program**<jupyter_code>style = str(input())
if (style != 'mamdani' and style != 'sugeno'):
  raise NameError('style must be mamdani or sugeno')

fuzzyset_makanan, fuzzyset_pelayanan = fuzzification()
x = inference(fuzzyset_makanan,fuzzyset_pelayanan)
score = defuzzification(x,style)
df['Score'] = score
output = df.sort_values(by=['Score', 'pelayanan'],ascending=False)
final = output['id'][:10]
filename = 'peringkat_'+style+'.xlsx'
final.to_excel(filename,header=True,index=False)
print('  method :',style)
final
sisa = output[10:]

fig, ax = plt.subplots(1,1, figsize=(10, 5))
ax.scatter(output['pelayanan'], output['makanan'], label='10 terbaik', color='r')
ax.scatter(sisa['pelayanan'], sisa['makanan'])
ax.set_title('Persebaran Data Hasil Fuzzy Logic', fontsize=25)
plt.xlabel('Kualitas Pelayanan', fontsize=17)
plt.ylabel('Kualitas Makanan', fontsize=17)
plt.legend()
plt.plot()
plt.savefig('scatter_hasil.png')<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup