MII_Salin_Oleg_PIbd-33/lec2.ipynb
2024-10-22 18:54:39 +04:00

24 KiB
Raw Blame History

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

In [1]:
import pandas as pd

df = pd.read_csv("data/car_price_prediction.csv", index_col="ID")

df.info()

df["Leatherinterior"] = df["Leatherinterior"].apply(
    lambda x: 1 if x == 'Yes' else 0,
)

print(df.shape)

df.head()
<class 'pandas.core.frame.DataFrame'>
Index: 19237 entries, 45654403 to 45813273
Data columns (total 17 columns):
 #   Column           Non-Null Count  Dtype  
---  ------           --------------  -----  
 0   Price            19237 non-null  int64  
 1   Levy             19237 non-null  object 
 2   Manufacturer     19237 non-null  object 
 3   Model            19237 non-null  object 
 4   Prodyear         19237 non-null  int64  
 5   Category         19237 non-null  object 
 6   Leatherinterior  19237 non-null  object 
 7   Fueltype         19237 non-null  object 
 8   Engine volume    19237 non-null  object 
 9   Mileage          19237 non-null  object 
 10  Cylinders        19237 non-null  float64
 11  Gear box type    19237 non-null  object 
 12  Drive wheels     19237 non-null  object 
 13  Doors            19237 non-null  object 
 14  Wheel            19237 non-null  object 
 15  Color            19237 non-null  object 
 16  Airbags          19237 non-null  int64  
dtypes: float64(1), int64(3), object(13)
memory usage: 2.6+ MB
(19237, 17)
Out[1]:
Price Levy Manufacturer Model Prodyear Category Leatherinterior Fueltype Engine volume Mileage Cylinders Gear box type Drive wheels Doors Wheel Color Airbags
ID
45654403 13328 1399 LEXUS RX 450 2010 Jeep 1 Hybrid 3.5 186005 km 6.0 Automatic 4x4 04-May Left wheel Silver 12
44731507 16621 1018 CHEVROLET Equinox 2011 Jeep 0 Petrol 3 192000 km 6.0 Tiptronic 4x4 04-May Left wheel Black 8
45774419 8467 - HONDA FIT 2006 Hatchback 0 Petrol 1.3 200000 km 4.0 Variator Front 04-May Right-hand drive Black 2
45769185 3607 862 FORD Escape 2011 Jeep 1 Hybrid 2.5 168966 km 4.0 Automatic 4x4 04-May Left wheel White 0
45809263 11726 446 HONDA FIT 2014 Hatchback 1 Petrol 1.3 91901 km 4.0 Automatic Front 04-May Left wheel Silver 4

Получение сведений о пропущенных данных

Типы пропущенных данных:

  • None - представление пустых данных в Python
  • NaN - представление пустых данных в Pandas
  • '' - пустая строка
In [2]:
# Количество пустых значений признаков
print(df.isnull().sum())

print()

# Есть ли пустые значения признаков
print(df.isnull().any())

print()

# Процент пустых значений признаков
for i in df.columns:
    null_rate = df[i].isnull().sum() / len(df) * 100
    if null_rate > 0:
        print(f"{i} процент пустых значений: %{null_rate:.2f}")
Price              0
Levy               0
Manufacturer       0
Model              0
Prodyear           0
Category           0
Leatherinterior    0
Fueltype           0
Engine volume      0
Mileage            0
Cylinders          0
Gear box type      0
Drive wheels       0
Doors              0
Wheel              0
Color              0
Airbags            0
dtype: int64

Price              False
Levy               False
Manufacturer       False
Model              False
Prodyear           False
Category           False
Leatherinterior    False
Fueltype           False
Engine volume      False
Mileage            False
Cylinders          False
Gear box type      False
Drive wheels       False
Doors              False
Wheel              False
Color              False
Airbags            False
dtype: bool

In [3]:
# fillna_df = df.fillna(0)

# print(fillna_df.shape)

# print(fillna_df.isnull().any())

# # Замена пустых данных на 0
# df["AgeFillNA"] = df["Age"].fillna(0)

# # Замена пустых данных на медиану
# df["AgeFillMedian"] = df["Age"].fillna(df["Age"].median())

# df.tail()
In [4]:
# df["AgeCopy"] = df["Age"]

# # Замена данных сразу в DataFrame без копирования
# df.fillna({"AgeCopy": 0}, inplace=True)

# df.tail()

Удаление наблюдений с пропусками

In [5]:
# dropna_df = df.dropna()

# print(dropna_df.shape)

# print(fillna_df.isnull().any())

Создание выборок данных

Библиотека scikit-learn

https://scikit-learn.org/stable/index.html

No description has been provided for this image
In [6]:
# Функция для создания выборок
from sklearn.model_selection import train_test_split


def split_stratified_into_train_val_test(
    df_input,
    stratify_colname="y",
    frac_train=0.6,
    frac_val=0.15,
    frac_test=0.25,
    random_state=None,
):
    """
    Splits a Pandas dataframe into three subsets (train, val, and test)
    following fractional ratios provided by the user, where each subset is
    stratified by the values in a specific column (that is, each subset has
    the same relative frequency of the values in the column). It performs this
    splitting by running train_test_split() twice.

    Parameters
    ----------
    df_input : Pandas dataframe
        Input dataframe to be split.
    stratify_colname : str
        The name of the column that will be used for stratification. Usually
        this column would be for the label.
    frac_train : float
    frac_val   : float
    frac_test  : float
        The ratios with which the dataframe will be split into train, val, and
        test data. The values should be expressed as float fractions and should
        sum to 1.0.
    random_state : int, None, or RandomStateInstance
        Value to be passed to train_test_split().

    Returns
    -------
    df_train, df_val, df_test :
        Dataframes containing the three splits.
    """

    if frac_train + frac_val + frac_test != 1.0:
        raise ValueError(
            "fractions %f, %f, %f do not add up to 1.0"
            % (frac_train, frac_val, frac_test)
        )

    if stratify_colname not in df_input.columns:
        raise ValueError("%s is not a column in the dataframe" % (stratify_colname))

    X = df_input  # Contains all columns.
    y = df_input[
        [stratify_colname]
    ]  # Dataframe of just the column on which to stratify.

    # Split original dataframe into train and temp dataframes.
    df_train, df_temp, y_train, y_temp = train_test_split(
        X, y, stratify=y, test_size=(1.0 - frac_train), random_state=random_state
    )

    # Split the temp dataframe into val and test dataframes.
    relative_frac_test = frac_test / (frac_val + frac_test)
    df_val, df_test, y_val, y_test = train_test_split(
        df_temp,
        y_temp,
        stratify=y_temp,
        test_size=relative_frac_test,
        random_state=random_state,
    )

    assert len(df_input) == len(df_train) + len(df_val) + len(df_test)

    return df_train, df_val, df_test
In [7]:
# Вывод распределения количества наблюдений по меткам (классам)
print(df.Leatherinterior.value_counts())

data = df[["Leatherinterior", "Price", "Airbags"]].copy()

df_train, df_val, df_test = split_stratified_into_train_val_test(
    data,
    stratify_colname="Leatherinterior",
    frac_train=0.60,
    frac_val=0.20,
    frac_test=0.20,
)

print("Обучающая выборка: ", df_train.shape)
print(df_train.Leatherinterior.value_counts())

print("Контрольная выборка: ", df_val.shape)
print(df_val.Leatherinterior.value_counts())

print("Тестовая выборка: ", df_test.shape)
print(df_test.Leatherinterior.value_counts())
Leatherinterior
1    13954
0     5283
Name: count, dtype: int64
Обучающая выборка:  (11542, 3)
Leatherinterior
1    8372
0    3170
Name: count, dtype: int64
Контрольная выборка:  (3847, 3)
Leatherinterior
1    2791
0    1056
Name: count, dtype: int64
Тестовая выборка:  (3848, 3)
Leatherinterior
1    2791
0    1057
Name: count, dtype: int64
In [8]:
from imblearn.over_sampling import ADASYN

ada = ADASYN()

print("Обучающая выборка: ", df_train.shape)
print(df_train.Leatherinterior.value_counts())

X_resampled, y_resampled = ada.fit_resample(df_train, df_train["Leatherinterior"])  # type: ignore
df_train_adasyn = pd.DataFrame(X_resampled)

print("Обучающая выборка после oversampling: ", df_train_adasyn.shape)
print(df_train_adasyn.Leatherinterior.value_counts())

df_train_adasyn
Обучающая выборка:  (11542, 3)
Leatherinterior
1    8372
0    3170
Name: count, dtype: int64
Обучающая выборка после oversampling:  (16585, 3)
Leatherinterior
1    8372
0    8213
Name: count, dtype: int64
Out[8]:
Leatherinterior Price Airbags
0 1 12231 8
1 1 18817 10
2 1 15053 4
3 1 470 0
4 1 19914 6
... ... ... ...
16580 0 13015 4
16581 0 8799 2
16582 0 2057 2
16583 0 2000 2
16584 0 1910 1

16585 rows × 3 columns