2025-02-08 13:36:03 +04:00

405 KiB
Raw Blame History

Начало лабораторной работы №7

In [119]:
import pandas as pd
df = pd.read_csv("..//static//csv//ndtv_data_final.csv")
print(df.columns)
display(df.head())
Index(['Unnamed: 0', 'Name', 'Brand', 'Model', 'Battery capacity (mAh)',
       'Screen size (inches)', 'Touchscreen', 'Resolution x', 'Resolution y',
       'Processor', 'RAM (MB)', 'Internal storage (GB)', 'Rear camera',
       'Front camera', 'Operating system', 'Wi-Fi', 'Bluetooth', 'GPS',
       'Number of SIMs', '3G', '4G/ LTE', 'Price'],
      dtype='object')
Unnamed: 0 Name Brand Model Battery capacity (mAh) Screen size (inches) Touchscreen Resolution x Resolution y Processor ... Rear camera Front camera Operating system Wi-Fi Bluetooth GPS Number of SIMs 3G 4G/ LTE Price
0 0 OnePlus 7T Pro McLaren Edition OnePlus 7T Pro McLaren Edition 4085 6.67 Yes 1440 3120 8 ... 48.0 16.0 Android Yes Yes Yes 2 Yes Yes 58998
1 1 Realme X2 Pro Realme X2 Pro 4000 6.50 Yes 1080 2400 8 ... 64.0 16.0 Android Yes Yes Yes 2 Yes Yes 27999
2 2 iPhone 11 Pro Max Apple iPhone 11 Pro Max 3969 6.50 Yes 1242 2688 6 ... 12.0 12.0 iOS Yes Yes Yes 2 Yes Yes 106900
3 3 iPhone 11 Apple iPhone 11 3110 6.10 Yes 828 1792 6 ... 12.0 12.0 iOS Yes Yes Yes 2 Yes Yes 62900
4 4 LG G8X ThinQ LG G8X ThinQ 4000 6.40 Yes 1080 2340 8 ... 12.0 32.0 Android Yes Yes Yes 1 No No 49990

5 rows × 22 columns

Создание лингвистических переменных

Входные переменные: Battery capacity (mAh) (емкость батареи) и RAM (MB) (объем оперативной памяти).
Выходная переменная: Price (цена).

In [120]:
import numpy as np
from skfuzzy import control as ctrl

data = pd.read_csv("..//static//csv//ndtv_data_final.csv")

# Инициализация лингвистических переменных
battery_capacity = ctrl.Antecedent(np.arange(data['Battery capacity (mAh)'].min(), data['Battery capacity (mAh)'].max(), 100), "battery_capacity")
ram = ctrl.Antecedent(np.arange(data['RAM (MB)'].min(), data['RAM (MB)'].max(), 100), "ram")
price = ctrl.Consequent(np.arange(data['Price'].min(), data['Price'].max(), 10), "price")

Формирование нечетких переменных для лингвистических переменных и их визуализация

In [121]:
import skfuzzy as fuzz

battery_capacity['low'] = fuzz.zmf(battery_capacity.universe, 2000, 3000)
battery_capacity['average'] = fuzz.trapmf(battery_capacity.universe, [2000, 3000, 4000, 5000])
battery_capacity['high'] = fuzz.smf(battery_capacity.universe, 4000, 5000)

ram['low'] = fuzz.zmf(ram.universe, 1000, 2000)
ram['average'] = fuzz.trapmf(ram.universe, [1000, 2000, 4000, 6000])
ram['high'] = fuzz.smf(ram.universe, 4000, 6000)

price['low'] = fuzz.zmf(price.universe, 10000, 20000)
price['average'] = fuzz.trapmf(price.universe, [10000, 20000, 40000, 60000])
price['high'] = fuzz.smf(price.universe, 40000, 60000)

battery_capacity.view()
ram.view()
price.view()
d:\ULSTU\AIM2\AIM-PIbd-32-Puchkina-A-A\aimenv\Lib\site-packages\skfuzzy\control\fuzzyvariable.py:125: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
  fig.show()
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image

Формирование и визуализация базы нечетких правил

In [122]:
# Нечеткие правила
rule1 = ctrl.Rule(battery_capacity["low"] & ram["low"], price["low"])
rule2 = ctrl.Rule(battery_capacity["low"] & ram["average"], price["low"])
rule3 = ctrl.Rule(battery_capacity["low"] & ram["high"], price["average"])
rule4 = ctrl.Rule(battery_capacity["average"] & ram["low"], price["low"])
rule5 = ctrl.Rule(battery_capacity["average"] & ram["average"], price["average"])
rule6 = ctrl.Rule(battery_capacity["average"] & ram["high"], price["high"])
rule7 = ctrl.Rule(battery_capacity["high"] & ram["low"], price["average"])
rule8 = ctrl.Rule(battery_capacity["high"] & ram["average"], price["high"])
rule9 = ctrl.Rule(battery_capacity["high"] & ram["high"], price["high"])
rule1.view()
Out[122]:
(<Figure size 640x480 with 1 Axes>, <Axes: >)
No description has been provided for this image

Создание нечеткой системы и добавление нечетких правил в базу знаний нечеткой системы

In [123]:
price_ctrl = ctrl.ControlSystem(
    [
        rule1,
        rule2,
        rule3,
        rule4,
        rule5,
        rule6,
        rule7,
        rule8,
        rule9,
    ]
)

# Создание симулятора нечеткой системы
price_sim = ctrl.ControlSystemSimulation(price_ctrl)

Пример расчета выходной переменной influx на основе входных переменных level и flow
Система также формирует подробный журнал выполнения процесса нечеткого логического вывода

In [124]:
price_sim.input['battery_capacity'] = 4000
price_sim.input['ram'] = 2000
price_sim.compute()

price_sim.print_state()

price_sim.output["price"]
=============
 Antecedents 
=============
Antecedent: battery_capacity        = 4000
  - low                             : 0.0
  - average                         : 0.991
  - high                            : 0.00017999999999999998
Antecedent: ram                     = 2000
  - low                             : 0.0016588799999999997
  - average                         : 0.9769599999999999
  - high                            : 0.0

=======
 Rules 
=======
RULE #0:
  IF battery_capacity[low] AND ram[low] THEN price[low]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[low]                                  : 0.0
  - ram[low]                                               : 0.0016588799999999997
                        battery_capacity[low] AND ram[low] = 0.0
  Activation (THEN-clause):
                                                price[low] : 0.0

RULE #1:
  IF battery_capacity[low] AND ram[average] THEN price[low]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[low]                                  : 0.0
  - ram[average]                                           : 0.9769599999999999
                    battery_capacity[low] AND ram[average] = 0.0
  Activation (THEN-clause):
                                                price[low] : 0.0

RULE #2:
  IF battery_capacity[low] AND ram[high] THEN price[average]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[low]                                  : 0.0
  - ram[high]                                              : 0.0
                       battery_capacity[low] AND ram[high] = 0.0
  Activation (THEN-clause):
                                            price[average] : 0.0

RULE #3:
  IF battery_capacity[average] AND ram[low] THEN price[low]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[average]                              : 0.991
  - ram[low]                                               : 0.0016588799999999997
                    battery_capacity[average] AND ram[low] = 0.0016588799999999997
  Activation (THEN-clause):
                                                price[low] : 0.0016588799999999997

RULE #4:
  IF battery_capacity[average] AND ram[average] THEN price[average]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[average]                              : 0.991
  - ram[average]                                           : 0.9769599999999999
                battery_capacity[average] AND ram[average] = 0.9769599999999999
  Activation (THEN-clause):
                                            price[average] : 0.9769599999999999

RULE #5:
  IF battery_capacity[average] AND ram[high] THEN price[high]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[average]                              : 0.991
  - ram[high]                                              : 0.0
                   battery_capacity[average] AND ram[high] = 0.0
  Activation (THEN-clause):
                                               price[high] : 0.0

RULE #6:
  IF battery_capacity[high] AND ram[low] THEN price[average]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[high]                                 : 0.00017999999999999998
  - ram[low]                                               : 0.0016588799999999997
                       battery_capacity[high] AND ram[low] = 0.00017999999999999998
  Activation (THEN-clause):
                                            price[average] : 0.00017999999999999998

RULE #7:
  IF battery_capacity[high] AND ram[average] THEN price[high]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[high]                                 : 0.00017999999999999998
  - ram[average]                                           : 0.9769599999999999
                   battery_capacity[high] AND ram[average] = 0.00017999999999999998
  Activation (THEN-clause):
                                               price[high] : 0.00017999999999999998

RULE #8:
  IF battery_capacity[high] AND ram[high] THEN price[high]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[high]                                 : 0.00017999999999999998
  - ram[high]                                              : 0.0
                      battery_capacity[high] AND ram[high] = 0.0
  Activation (THEN-clause):
                                               price[high] : 0.0


==============================
 Intermediaries and Conquests 
==============================
Consequent: price                    = 32933.17210826396
  low:
    Accumulate using accumulation_max : 0.0016588799999999997
  average:
    Accumulate using accumulation_max : 0.9769599999999999
  high:
    Accumulate using accumulation_max : 0.00017999999999999998

Out[124]:
np.float64(32933.17210826396)

Визуализация функции принадлежности для выходной переменной influx / Функция получена в процессе аккумуляции и используется для дефаззификации значения выходной переменной influx

In [125]:
price.view(sim=price_sim)
No description has been provided for this image

Пример решения задачи регрессии на основе нечеткого логического вывода

Загрузка данных

In [126]:
import pandas as pd

data_train = pd.read_csv("..//static//csv//ndtv_data_final.csv", sep=",")
data_test = pd.read_csv("..//static//csv//ndtv_data_final.csv", sep=",")

display(data_train.head(3))
display(data_test.head(3))
Unnamed: 0 Name Brand Model Battery capacity (mAh) Screen size (inches) Touchscreen Resolution x Resolution y Processor ... Rear camera Front camera Operating system Wi-Fi Bluetooth GPS Number of SIMs 3G 4G/ LTE Price
0 0 OnePlus 7T Pro McLaren Edition OnePlus 7T Pro McLaren Edition 4085 6.67 Yes 1440 3120 8 ... 48.0 16.0 Android Yes Yes Yes 2 Yes Yes 58998
1 1 Realme X2 Pro Realme X2 Pro 4000 6.50 Yes 1080 2400 8 ... 64.0 16.0 Android Yes Yes Yes 2 Yes Yes 27999
2 2 iPhone 11 Pro Max Apple iPhone 11 Pro Max 3969 6.50 Yes 1242 2688 6 ... 12.0 12.0 iOS Yes Yes Yes 2 Yes Yes 106900

3 rows × 22 columns

Unnamed: 0 Name Brand Model Battery capacity (mAh) Screen size (inches) Touchscreen Resolution x Resolution y Processor ... Rear camera Front camera Operating system Wi-Fi Bluetooth GPS Number of SIMs 3G 4G/ LTE Price
0 0 OnePlus 7T Pro McLaren Edition OnePlus 7T Pro McLaren Edition 4085 6.67 Yes 1440 3120 8 ... 48.0 16.0 Android Yes Yes Yes 2 Yes Yes 58998
1 1 Realme X2 Pro Realme X2 Pro 4000 6.50 Yes 1080 2400 8 ... 64.0 16.0 Android Yes Yes Yes 2 Yes Yes 27999
2 2 iPhone 11 Pro Max Apple iPhone 11 Pro Max 3969 6.50 Yes 1242 2688 6 ... 12.0 12.0 iOS Yes Yes Yes 2 Yes Yes 106900

3 rows × 22 columns

Инициализация лингвистических переменных и автоматическое формирование нечетких переменных

In [127]:
data = pd.read_csv("..//static//csv//ndtv_data_final.csv")

# Инициализация нечетких переменных
battery_capacity = ctrl.Antecedent(data["Battery capacity (mAh)"].sort_values().unique(), "battery_capacity")
ram = ctrl.Antecedent(data["RAM (MB)"].sort_values().unique(), "ram")
price = ctrl.Consequent(np.arange(0, 100001, 1000), "price")

battery_capacity.automf(3, variable_type="quant")
battery_capacity.view()
ram.automf(3, variable_type="quant")
ram.view()
price.automf(5, variable_type="quant")
price.view()
d:\ULSTU\AIM2\AIM-PIbd-32-Puchkina-A-A\aimenv\Lib\site-packages\skfuzzy\control\fuzzyvariable.py:125: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
  fig.show()
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image

Нечеткие правила

In [128]:
rule1 = ctrl.Rule(
    battery_capacity["low"] & ram["low"],
    price["low"],
)
rule2 = ctrl.Rule(
    battery_capacity["average"] & ram["low"],
    price["low"],
)
rule3 = ctrl.Rule(
    battery_capacity["high"] & ram["low"],
    price["average"],
)

rule4 = ctrl.Rule(
    battery_capacity["low"] & ram["average"],
    price["low"],
)
rule5 = ctrl.Rule(
    battery_capacity["average"] & ram["average"],
    price["average"],
)
rule6 = ctrl.Rule(
    battery_capacity["high"] & ram["average"],
    price["high"],
)

rule7 = ctrl.Rule(
    battery_capacity["low"] & ram["high"],
    price["average"],
)
rule8 = ctrl.Rule(
    battery_capacity["average"] & ram["high"],
    price["high"],
)
rule9 = ctrl.Rule(
    battery_capacity["high"] & ram["high"],
    price["high"],
)

Создание нечеткой системы

In [129]:
fuzzy_rules = [
    rule1,
    rule2,
    rule3,
    rule4,
    rule5,
    rule6,
    rule7,
    rule8,
    rule9,
]

price_cntrl = ctrl.ControlSystem(fuzzy_rules)

sim = ctrl.ControlSystemSimulation(price_cntrl)

fuzzy_rules
Out[129]:
[IF battery_capacity[low] AND ram[low] THEN price[low]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF battery_capacity[average] AND ram[low] THEN price[low]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF battery_capacity[high] AND ram[low] THEN price[average]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF battery_capacity[low] AND ram[average] THEN price[low]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF battery_capacity[average] AND ram[average] THEN price[average]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF battery_capacity[high] AND ram[average] THEN price[high]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF battery_capacity[low] AND ram[high] THEN price[average]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF battery_capacity[average] AND ram[high] THEN price[high]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax,
 IF battery_capacity[high] AND ram[high] THEN price[high]
 	AND aggregation function : fmin
 	OR aggregation function  : fmax]

Пример использования полученной нечеткой системы

In [130]:
example_row = data.iloc[3]  # Используем строку в качестве примера

sim.input["battery_capacity"] = example_row["Battery capacity (mAh)"]
sim.input["ram"] = example_row["RAM (MB)"]

sim.compute()

sim.print_state()
display(sim.output["price"])
=============
 Antecedents 
=============
Antecedent: battery_capacity        = 3110
  - low                             : 0.15831663326653306
  - average                         : 0.8416833667334669
  - high                            : 0.0
Antecedent: ram                     = 4000
  - low                             : 0.34048257372654156
  - average                         : 0.6595174262734584
  - high                            : 0.0

=======
 Rules 
=======
RULE #0:
  IF battery_capacity[low] AND ram[low] THEN price[low]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[low]                                  : 0.15831663326653306
  - ram[low]                                               : 0.34048257372654156
                        battery_capacity[low] AND ram[low] = 0.15831663326653306
  Activation (THEN-clause):
                                                price[low] : 0.15831663326653306

RULE #1:
  IF battery_capacity[average] AND ram[low] THEN price[low]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[average]                              : 0.8416833667334669
  - ram[low]                                               : 0.34048257372654156
                    battery_capacity[average] AND ram[low] = 0.34048257372654156
  Activation (THEN-clause):
                                                price[low] : 0.34048257372654156

RULE #2:
  IF battery_capacity[high] AND ram[low] THEN price[average]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[high]                                 : 0.0
  - ram[low]                                               : 0.34048257372654156
                       battery_capacity[high] AND ram[low] = 0.0
  Activation (THEN-clause):
                                            price[average] : 0.0

RULE #3:
  IF battery_capacity[low] AND ram[average] THEN price[low]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[low]                                  : 0.15831663326653306
  - ram[average]                                           : 0.6595174262734584
                    battery_capacity[low] AND ram[average] = 0.15831663326653306
  Activation (THEN-clause):
                                                price[low] : 0.15831663326653306

RULE #4:
  IF battery_capacity[average] AND ram[average] THEN price[average]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[average]                              : 0.8416833667334669
  - ram[average]                                           : 0.6595174262734584
                battery_capacity[average] AND ram[average] = 0.6595174262734584
  Activation (THEN-clause):
                                            price[average] : 0.6595174262734584

RULE #5:
  IF battery_capacity[high] AND ram[average] THEN price[high]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[high]                                 : 0.0
  - ram[average]                                           : 0.6595174262734584
                   battery_capacity[high] AND ram[average] = 0.0
  Activation (THEN-clause):
                                               price[high] : 0.0

RULE #6:
  IF battery_capacity[low] AND ram[high] THEN price[average]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[low]                                  : 0.15831663326653306
  - ram[high]                                              : 0.0
                       battery_capacity[low] AND ram[high] = 0.0
  Activation (THEN-clause):
                                            price[average] : 0.0

RULE #7:
  IF battery_capacity[average] AND ram[high] THEN price[high]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[average]                              : 0.8416833667334669
  - ram[high]                                              : 0.0
                   battery_capacity[average] AND ram[high] = 0.0
  Activation (THEN-clause):
                                               price[high] : 0.0

RULE #8:
  IF battery_capacity[high] AND ram[high] THEN price[high]
	AND aggregation function : fmin
	OR aggregation function  : fmax

  Aggregation (IF-clause):
  - battery_capacity[high]                                 : 0.0
  - ram[high]                                              : 0.0
                      battery_capacity[high] AND ram[high] = 0.0
  Activation (THEN-clause):
                                               price[high] : 0.0


==============================
 Intermediaries and Conquests 
==============================
Consequent: price                    = 40755.45920618248
  lower:
    Accumulate using accumulation_max : None
  low:
    Accumulate using accumulation_max : 0.34048257372654156
  average:
    Accumulate using accumulation_max : 0.6595174262734584
  high:
    Accumulate using accumulation_max : 0.0
  higher:
    Accumulate using accumulation_max : None

np.float64(40755.45920618248)

Функция для автоматизации вычисления целевой переменной Y на основе вектора признаков X

In [131]:
print(data_train.columns)
Index(['Unnamed: 0', 'Name', 'Brand', 'Model', 'Battery capacity (mAh)',
       'Screen size (inches)', 'Touchscreen', 'Resolution x', 'Resolution y',
       'Processor', 'RAM (MB)', 'Internal storage (GB)', 'Rear camera',
       'Front camera', 'Operating system', 'Wi-Fi', 'Bluetooth', 'GPS',
       'Number of SIMs', '3G', '4G/ LTE', 'Price'],
      dtype='object')
In [132]:
def fuzzy_pred(row):
    sim.input["battery_capacity"] = row["Battery capacity (mAh)"]
    sim.input["ram"] = row["RAM (MB)"]
    sim.compute()
    return sim.output["price"]

Тестирование нечеткой системы на обучающей выборке

In [133]:
result_train = data_train.copy()
result_train["Predicted Price"] = result_train.apply(fuzzy_pred, axis=1)

result_train.head(15)
Out[133]:
Unnamed: 0 Name Brand Model Battery capacity (mAh) Screen size (inches) Touchscreen Resolution x Resolution y Processor ... Front camera Operating system Wi-Fi Bluetooth GPS Number of SIMs 3G 4G/ LTE Price Predicted Price
0 0 OnePlus 7T Pro McLaren Edition OnePlus 7T Pro McLaren Edition 4085 6.67 Yes 1440 3120 8 ... 16.0 Android Yes Yes Yes 2 Yes Yes 58998 75000.000000
1 1 Realme X2 Pro Realme X2 Pro 4000 6.50 Yes 1080 2400 8 ... 16.0 Android Yes Yes Yes 2 Yes Yes 27999 55792.501783
2 2 iPhone 11 Pro Max Apple iPhone 11 Pro Max 3969 6.50 Yes 1242 2688 6 ... 12.0 iOS Yes Yes Yes 2 Yes Yes 106900 46614.283392
3 3 iPhone 11 Apple iPhone 11 3110 6.10 Yes 828 1792 6 ... 12.0 iOS Yes Yes Yes 2 Yes Yes 62900 40755.459206
4 4 LG G8X ThinQ LG G8X ThinQ 4000 6.40 Yes 1080 2340 8 ... 32.0 Android Yes Yes Yes 1 No No 49990 55792.501783
5 5 OnePlus 7T OnePlus 7T 3800 6.55 Yes 1080 2400 8 ... 16.0 Android Yes Yes No 2 Yes Yes 34930 59015.272109
6 6 OnePlus 7T Pro OnePlus 7T Pro 4085 6.67 Yes 1440 3120 8 ... 16.0 Android Yes Yes Yes 2 Yes Yes 52990 59015.272109
7 7 Samsung Galaxy Note 10+ Samsung Galaxy Note 10+ 4300 6.80 Yes 1440 3040 8 ... 10.0 Android Yes Yes Yes 2 Yes Yes 79699 75000.000000
8 8 Asus ROG Phone 2 Asus ROG Phone 2 6000 6.59 Yes 1080 2340 8 ... 24.0 Android Yes Yes Yes 1 Yes Yes 37999 75000.000000
9 9 Xiaomi Redmi K20 Pro Xiaomi Redmi K20 Pro 4000 6.39 Yes 1080 2340 8 ... 20.0 Android Yes Yes Yes 2 No No 23190 55792.501783
10 10 Oppo K3 Oppo K3 3765 6.50 Yes 1080 2340 8 ... 16.0 Android Yes Yes Yes 2 Yes Yes 23990 53251.486942
11 11 Realme X Realme X 3765 6.53 Yes 1080 2340 8 ... 16.0 Android Yes Yes Yes 2 Yes Yes 14999 44322.761836
12 12 Xiaomi Redmi K20 Xiaomi Redmi K20 4000 6.39 Yes 1080 2340 8 ... 20.0 Android Yes Yes Yes 2 Yes Yes 19282 55792.501783
13 13 OnePlus 7 Pro OnePlus 7 Pro 4000 6.67 Yes 1440 3120 8 ... 16.0 Android Yes Yes Yes 2 Yes Yes 39995 55792.501783
14 14 Oppo Reno 10x Zoom Oppo Reno 10x Zoom 4065 6.60 Yes 1080 2340 8 ... 16.0 Android Yes Yes Yes 2 Yes Yes 36990 56431.899431

15 rows × 23 columns

Тестирование нечеткой системы на тестовой выборке

In [135]:
result_test = data_test.copy()

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

result_test
Out[135]:
Unnamed: 0 Name Brand Model Battery capacity (mAh) Screen size (inches) Touchscreen Resolution x Resolution y Processor ... Front camera Operating system Wi-Fi Bluetooth GPS Number of SIMs 3G 4G/ LTE Price Predicted Price
0 0 OnePlus 7T Pro McLaren Edition OnePlus 7T Pro McLaren Edition 4085 6.67 Yes 1440 3120 8 ... 16.0 Android Yes Yes Yes 2 Yes Yes 58998 75000.000000
1 1 Realme X2 Pro Realme X2 Pro 4000 6.50 Yes 1080 2400 8 ... 16.0 Android Yes Yes Yes 2 Yes Yes 27999 55792.501783
2 2 iPhone 11 Pro Max Apple iPhone 11 Pro Max 3969 6.50 Yes 1242 2688 6 ... 12.0 iOS Yes Yes Yes 2 Yes Yes 106900 46614.283392
3 3 iPhone 11 Apple iPhone 11 3110 6.10 Yes 828 1792 6 ... 12.0 iOS Yes Yes Yes 2 Yes Yes 62900 40755.459206
4 4 LG G8X ThinQ LG G8X ThinQ 4000 6.40 Yes 1080 2340 8 ... 32.0 Android Yes Yes Yes 1 No No 49990 55792.501783
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
1354 1354 Intex Aqua A2 Intex Aqua A2 1500 4.00 Yes 480 800 4 ... 0.3 Android Yes Yes Yes 2 Yes No 2599 27649.663226
1355 1355 Videocon Infinium Z51 Nova+ Videocon Infinium Z51 Nova+ 2000 5.00 Yes 480 854 4 ... 5.0 Android Yes Yes Yes 2 Yes No 2940 30578.211284
1356 1356 Intex Aqua Y4 Intex Aqua Y4 1700 4.50 Yes 480 854 2 ... 2.0 Android Yes Yes No 2 Yes No 2999 27750.249507
1357 1357 iBall Andi4 B20 iBall Andi4 B20 1250 4.00 Yes 480 800 1 ... 0.3 Android Yes Yes Yes 2 Yes No 2498 26169.615853
1358 1358 iBall Andi Avonte 5 iBall Andi Avonte 5 2150 5.00 Yes 480 854 4 ... 0.0 Android Yes Yes Yes 2 Yes No 3999 30880.178199

1359 rows × 23 columns

Оценка результатов на основе метрик для задачи регрессии

In [138]:
import math
from sklearn import metrics

rmetrics = {}

rmetrics["RMSE_train"] = math.sqrt(
    metrics.mean_squared_error(result_train["Price"], result_train["Predicted Price"])
)

rmetrics["RMSE_test"] = math.sqrt(
    metrics.mean_squared_error(result_test["Price"], result_test["Predicted Price"])
)

rmetrics["RMAE_test"] = math.sqrt(
    metrics.mean_absolute_error(result_test["Price"], result_test["Predicted Price"])
)

rmetrics["R2_test"] = metrics.r2_score(
    result_test["Price"], result_test["Predicted Price"]
)

rmetrics
Out[138]:
{'RMSE_train': 28568.780129367737,
 'RMSE_test': 28568.780129367737,
 'RMAE_test': 165.28156612336826,
 'R2_test': -3.2533731852277636}