fuzzy-rules-generator/density_fuzzy.ipynb
2024-11-01 11:04:05 +04:00

220 KiB

In [7]:
import pandas as pd

density_train = pd.read_csv("data/density_train.csv", sep=";", decimal=",")
density_test = pd.read_csv("data/density_test.csv", sep=";", decimal=",")

display(density_train.head(3))
display(density_test.head(3))
T Al2O3 TiO2 Density
0 20 0.0 0.0 1.06250
1 25 0.0 0.0 1.05979
2 35 0.0 0.0 1.05404
T Al2O3 TiO2 Density
0 30 0.00 0.0 1.05696
1 55 0.00 0.0 1.04158
2 25 0.05 0.0 1.08438
In [8]:
import numpy as np
from skfuzzy import control as ctrl
import skfuzzy as fuzz

# temp = ctrl.Antecedent(np.arange(20, 70, 1), "temp")
# al = ctrl.Antecedent(np.arange(0, 0.3, 0.001), "al")
# ti = ctrl.Antecedent(np.arange(0, 0.3, 0.001), "ti")
# density = ctrl.Consequent(np.arange(1, 1.3, 0.00001), "density")

temp = ctrl.Antecedent(density_train["T"].sort_values().unique(), "temp")
al = ctrl.Antecedent(density_train["Al2O3"].sort_values().unique(), "al")
ti = ctrl.Antecedent(density_train["TiO2"].sort_values().unique(), "ti")
density = ctrl.Consequent(np.arange(1.03, 1.22, 0.0001), "density")

temp.automf(3, variable_type="quant")
temp.view()
al.automf(3, variable_type="quant")
al.view()
ti.automf(3, variable_type="quant")
ti.view()
density.automf(3, variable_type="quant")
# density["low"] = fuzz.trimf(density.universe, [1.03, 1.06, 1.09])
# density["average"] = fuzz.trimf(density.universe, [1.06, 1.14, 1.18])
# density["high"] = fuzz.trimf(density.universe, [1.09, 1.18, 1.22])
density.view()
c:\Users\user\Projects\python\fuzzy\.venv\Lib\site-packages\skfuzzy\control\fuzzyvariable.py:125: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
  fig.show()
In [9]:
rule11 = ctrl.Rule(
    temp["low"] & al["low"] & ti["low"],
    density["low"],
)
rule12 = ctrl.Rule(
    temp["average"] & al["low"] & ti["low"],
    density["low"],
)
rule13 = ctrl.Rule(
    temp["high"] & al["low"] & ti["low"],
    density["low"],
)

rule21 = ctrl.Rule(
    temp["low"] & al["average"] & ti["low"],
    density["average"],
)
rule22 = ctrl.Rule(
    temp["average"] & al["average"] & ti["low"],
    density["low"],
)
rule23 = ctrl.Rule(
    temp["high"] & al["average"] & ti["low"],
    density["low"],
)

rule31 = ctrl.Rule(
    temp["low"] & al["high"] & ti["low"],
    density["high"],
)
rule32 = ctrl.Rule(
    temp["low"] & al["high"] & ti["low"],
    density["high"],
)
rule33 = ctrl.Rule(
    temp["high"] & al["high"] & ti["low"],
    density["average"],
)

rule41 = ctrl.Rule(
    temp["low"] & al["low"] & ti["average"],
    density["average"],
)
rule42 = ctrl.Rule(
    temp["average"] & al["low"] & ti["average"],
    density["average"],
)
rule43 = ctrl.Rule(
    temp["high"] & al["low"] & ti["average"],
    density["low"],
)

rule51 = ctrl.Rule(
    temp["low"] & al["low"] & ti["high"],
    density["high"],
)
rule52 = ctrl.Rule(
    temp["average"] & al["low"] & ti["high"],
    density["high"],
)
rule53 = ctrl.Rule(
    temp["high"] & al["low"] & ti["high"],
    density["average"],
)
In [10]:
fuzzy_rules = [
    rule11,
    rule12,
    rule13,
    rule21,
    rule22,
    rule23,
    rule31,
    rule32,
    rule33,
    rule41,
    rule42,
    rule43,
    rule51,
    rule52,
    rule53,
]

density_cntrl = ctrl.ControlSystem(fuzzy_rules)

sim = ctrl.ControlSystemSimulation(density_cntrl)

fuzzy_rules
Out[10]:
[IF (temp[low] AND al[low]) AND ti[low] THEN density[low]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[average] AND al[low]) AND ti[low] THEN density[low]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[high] AND al[low]) AND ti[low] THEN density[low]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[low] AND al[average]) AND ti[low] THEN density[average]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[average] AND al[average]) AND ti[low] THEN density[low]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[high] AND al[average]) AND ti[low] THEN density[low]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[low] AND al[high]) AND ti[low] THEN density[high]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[low] AND al[high]) AND ti[low] THEN density[high]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[high] AND al[high]) AND ti[low] THEN density[average]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[low] AND al[low]) AND ti[average] THEN density[average]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[average] AND al[low]) AND ti[average] THEN density[average]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[high] AND al[low]) AND ti[average] THEN density[low]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[low] AND al[low]) AND ti[high] THEN density[high]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[average] AND al[low]) AND ti[high] THEN density[high]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF (temp[high] AND al[low]) AND ti[high] THEN density[average]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax]
In [11]:
sim.input["temp"] = 20
sim.input["al"] = 0.3
sim.input["ti"] = 0.0
sim.compute()
sim.print_state()
display(sim.output["density"])
=============
 Antecedents 
=============
Antecedent: temp                    = 20
  - low                             : 1.0
  - average                         : 0.0
  - high                            : 0.0
Antecedent: al                      = 0.3
  - low                             : 0.0
  - average                         : 0.0
  - high                            : 1.0
Antecedent: ti                      = 0.0
  - low                             : 1.0
  - average                         : 0.0
  - high                            : 0.0

=======
 Rules 
=======
RULE #0:
  IF (temp[low] AND al[low]) AND ti[low] THEN density[low]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[low]                                              : 1.0
  - al[low]                                                : 0.0
  - ti[low]                                                : 1.0
                       (temp[low] AND al[low]) AND ti[low] = 0.0
  Activation (THEN-clause):
                                              density[low] : 0.0

RULE #1:
  IF (temp[average] AND al[low]) AND ti[low] THEN density[low]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[average]                                          : 0.0
  - al[low]                                                : 0.0
  - ti[low]                                                : 1.0
                   (temp[average] AND al[low]) AND ti[low] = 0.0
  Activation (THEN-clause):
                                              density[low] : 0.0

RULE #2:
  IF (temp[high] AND al[low]) AND ti[low] THEN density[low]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[high]                                             : 0.0
  - al[low]                                                : 0.0
  - ti[low]                                                : 1.0
                      (temp[high] AND al[low]) AND ti[low] = 0.0
  Activation (THEN-clause):
                                              density[low] : 0.0

RULE #3:
  IF (temp[low] AND al[average]) AND ti[low] THEN density[average]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[low]                                              : 1.0
  - al[average]                                            : 0.0
  - ti[low]                                                : 1.0
                   (temp[low] AND al[average]) AND ti[low] = 0.0
  Activation (THEN-clause):
                                          density[average] : 0.0

RULE #4:
  IF (temp[average] AND al[average]) AND ti[low] THEN density[low]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[average]                                          : 0.0
  - al[average]                                            : 0.0
  - ti[low]                                                : 1.0
               (temp[average] AND al[average]) AND ti[low] = 0.0
  Activation (THEN-clause):
                                              density[low] : 0.0

RULE #5:
  IF (temp[high] AND al[average]) AND ti[low] THEN density[low]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[high]                                             : 0.0
  - al[average]                                            : 0.0
  - ti[low]                                                : 1.0
                  (temp[high] AND al[average]) AND ti[low] = 0.0
  Activation (THEN-clause):
                                              density[low] : 0.0

RULE #6:
  IF (temp[low] AND al[high]) AND ti[low] THEN density[high]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[low]                                              : 1.0
  - al[high]                                               : 1.0
  - ti[low]                                                : 1.0
                      (temp[low] AND al[high]) AND ti[low] = 1.0
  Activation (THEN-clause):
                                             density[high] : 1.0

RULE #7:
  IF (temp[low] AND al[high]) AND ti[low] THEN density[high]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[low]                                              : 1.0
  - al[high]                                               : 1.0
  - ti[low]                                                : 1.0
                      (temp[low] AND al[high]) AND ti[low] = 1.0
  Activation (THEN-clause):
                                             density[high] : 1.0

RULE #8:
  IF (temp[high] AND al[high]) AND ti[low] THEN density[average]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[high]                                             : 0.0
  - al[high]                                               : 1.0
  - ti[low]                                                : 1.0
                     (temp[high] AND al[high]) AND ti[low] = 0.0
  Activation (THEN-clause):
                                          density[average] : 0.0

RULE #9:
  IF (temp[low] AND al[low]) AND ti[average] THEN density[average]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[low]                                              : 1.0
  - al[low]                                                : 0.0
  - ti[average]                                            : 0.0
                   (temp[low] AND al[low]) AND ti[average] = 0.0
  Activation (THEN-clause):
                                          density[average] : 0.0

RULE #10:
  IF (temp[average] AND al[low]) AND ti[average] THEN density[average]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[average]                                          : 0.0
  - al[low]                                                : 0.0
  - ti[average]                                            : 0.0
               (temp[average] AND al[low]) AND ti[average] = 0.0
  Activation (THEN-clause):
                                          density[average] : 0.0

RULE #11:
  IF (temp[high] AND al[low]) AND ti[average] THEN density[low]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[high]                                             : 0.0
  - al[low]                                                : 0.0
  - ti[average]                                            : 0.0
                  (temp[high] AND al[low]) AND ti[average] = 0.0
  Activation (THEN-clause):
                                              density[low] : 0.0

RULE #12:
  IF (temp[low] AND al[low]) AND ti[high] THEN density[high]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[low]                                              : 1.0
  - al[low]                                                : 0.0
  - ti[high]                                               : 0.0
                      (temp[low] AND al[low]) AND ti[high] = 0.0
  Activation (THEN-clause):
                                             density[high] : 0.0

RULE #13:
  IF (temp[average] AND al[low]) AND ti[high] THEN density[high]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[average]                                          : 0.0
  - al[low]                                                : 0.0
  - ti[high]                                               : 0.0
                  (temp[average] AND al[low]) AND ti[high] = 0.0
  Activation (THEN-clause):
                                             density[high] : 0.0

RULE #14:
  IF (temp[high] AND al[low]) AND ti[high] THEN density[average]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - temp[high]                                             : 0.0
  - al[low]                                                : 0.0
  - ti[high]                                               : 0.0
                     (temp[high] AND al[low]) AND ti[high] = 0.0
  Activation (THEN-clause):
                                          density[average] : 0.0


==============================
 Intermediaries and Conquests 
==============================
Consequent: density                  = 1.1882499824468897
  low:
    Accumulate using accumulation_max : 0.0
  average:
    Accumulate using accumulation_max : 0.0
  high:
    Accumulate using accumulation_max : 1.0

np.float64(1.1882499824468897)
In [12]:
def fuzzy_pred(row):
    sim.input["temp"] = row["T"]
    sim.input["al"] = row["Al2O3"]
    sim.input["ti"] = row["TiO2"]
    sim.compute()
    return sim.output["density"]
In [13]:
result_train = density_train.copy()

result_train["DensityPred"] = result_train.apply(fuzzy_pred, axis=1)

result_train.head(15)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[13], line 3
      1 result_train = density_train.copy()
----> 3 result_train["DensityPred"] = result_train.apply(fuzzy_pred, axis=1)
      5 result_train.head(15)

File c:\Users\user\Projects\python\fuzzy\.venv\Lib\site-packages\pandas\core\frame.py:10374, in DataFrame.apply(self, func, axis, raw, result_type, args, by_row, engine, engine_kwargs, **kwargs)
  10360 from pandas.core.apply import frame_apply
  10362 op = frame_apply(
  10363     self,
  10364     func=func,
   (...)
  10372     kwargs=kwargs,
  10373 )
> 10374 return op.apply().__finalize__(self, method="apply")

File c:\Users\user\Projects\python\fuzzy\.venv\Lib\site-packages\pandas\core\apply.py:916, in FrameApply.apply(self)
    913 elif self.raw:
    914     return self.apply_raw(engine=self.engine, engine_kwargs=self.engine_kwargs)
--> 916 return self.apply_standard()

File c:\Users\user\Projects\python\fuzzy\.venv\Lib\site-packages\pandas\core\apply.py:1063, in FrameApply.apply_standard(self)
   1061 def apply_standard(self):
   1062     if self.engine == "python":
-> 1063         results, res_index = self.apply_series_generator()
   1064     else:
   1065         results, res_index = self.apply_series_numba()

File c:\Users\user\Projects\python\fuzzy\.venv\Lib\site-packages\pandas\core\apply.py:1081, in FrameApply.apply_series_generator(self)
   1078 with option_context("mode.chained_assignment", None):
   1079     for i, v in enumerate(series_gen):
   1080         # ignore SettingWithCopy here in case the user mutates
-> 1081         results[i] = self.func(v, *self.args, **self.kwargs)
   1082         if isinstance(results[i], ABCSeries):
   1083             # If we have a view on v, we need to make a copy because
   1084             #  series_generator will swap out the underlying data
   1085             results[i] = results[i].copy(deep=False)

Cell In[12], line 6, in fuzzy_pred(row)
      4 sim.input["ti"] = row["TiO2"]
      5 sim.compute()
----> 6 return sim.output["density"]

KeyError: 'density'
In [19]:
result_test = density_test.copy()

result_test["DensityPred"] = result_test.apply(fuzzy_pred, axis=1)

result_test
Out[19]:
T Al2O3 TiO2 Density DensityPred
0 30 0.00 0.00 1.05696 1.060000
1 55 0.00 0.00 1.04158 1.060000
2 25 0.05 0.00 1.08438 1.096363
3 30 0.05 0.00 1.08112 1.097343
4 35 0.05 0.00 1.07781 1.097343
5 40 0.05 0.00 1.07446 1.088627
6 60 0.05 0.00 1.06053 1.060000
7 35 0.30 0.00 1.17459 1.159583
8 65 0.30 0.00 1.14812 1.126222
9 45 0.00 0.05 1.07424 1.096363
10 50 0.00 0.05 1.07075 1.096363
11 55 0.00 0.05 1.06721 1.097343
12 20 0.00 0.30 1.22417 1.163333
13 30 0.00 0.30 1.21310 1.161428
14 40 0.00 0.30 1.20265 1.162778
15 60 0.00 0.30 1.18265 1.141253
16 70 0.00 0.30 1.17261 1.126667
In [10]:
import math
from sklearn import metrics


rmetrics = {}
rmetrics["RMSE_train"] = math.sqrt(
    metrics.mean_squared_error(result_train["Density"], result_train["DensityPred"])
)
rmetrics["RMSE_test"] = math.sqrt(
    metrics.mean_squared_error(result_test["Density"], result_test["DensityPred"])
)
rmetrics["RMAE_test"] = math.sqrt(
    metrics.mean_absolute_error(result_test["Density"], result_test["DensityPred"])
)
rmetrics["R2_test"] = metrics.r2_score(
    result_test["Density"], result_test["DensityPred"]
)

rmetrics
Out[10]:
{'RMSE_train': 0.024131296333542294,
 'RMSE_test': 0.03056470202709202,
 'RMAE_test': 0.16058558998263095,
 'R2_test': 0.7532040538162098}