pred_analytics/lec2.ipynb
2025-01-13 14:42:39 +04:00

30 KiB
Raw Permalink Blame History

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

In [1]:
import pandas as pd

df = pd.read_csv("data/titanic.csv", index_col="PassengerId")

df.info()

display(df.shape)

df.head()
<class 'pandas.core.frame.DataFrame'>
Index: 891 entries, 1 to 891
Data columns (total 11 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   Survived  891 non-null    int64  
 1   Pclass    891 non-null    int64  
 2   Name      891 non-null    object 
 3   Sex       891 non-null    object 
 4   Age       714 non-null    float64
 5   SibSp     891 non-null    int64  
 6   Parch     891 non-null    int64  
 7   Ticket    891 non-null    object 
 8   Fare      891 non-null    float64
 9   Cabin     204 non-null    object 
 10  Embarked  889 non-null    object 
dtypes: float64(2), int64(4), object(5)
memory usage: 83.5+ KB
(891, 11)
Out[1]:
Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
PassengerId
1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S
5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S

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

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

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

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

# Процент пустых значений признаков
for i in df.columns:
    null_rate = df[i].isnull().sum() / len(df) * 100
    if null_rate > 0:
        display(f"{i} процент пустых значений: %{null_rate:.2f}")
Survived      0
Pclass        0
Name          0
Sex           0
Age         177
SibSp         0
Parch         0
Ticket        0
Fare          0
Cabin       687
Embarked      2
dtype: int64
Survived    False
Pclass      False
Name        False
Sex         False
Age          True
SibSp       False
Parch       False
Ticket      False
Fare        False
Cabin        True
Embarked     True
dtype: bool
'Age процент пустых значений: %19.87'
'Cabin процент пустых значений: %77.10'
'Embarked процент пустых значений: %0.22'
In [3]:
fillna_df = df.fillna(0)

display(fillna_df.shape)

display(fillna_df.isnull().any())

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

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

df.tail()
(891, 11)
Survived    False
Pclass      False
Name        False
Sex         False
Age         False
SibSp       False
Parch       False
Ticket      False
Fare        False
Cabin       False
Embarked    False
dtype: bool
Out[3]:
Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked AgeFillNA AgeFillMedian
PassengerId
887 0 2 Montvila, Rev. Juozas male 27.0 0 0 211536 13.00 NaN S 27.0 27.0
888 1 1 Graham, Miss. Margaret Edith female 19.0 0 0 112053 30.00 B42 S 19.0 19.0
889 0 3 Johnston, Miss. Catherine Helen "Carrie" female NaN 1 2 W./C. 6607 23.45 NaN S 0.0 28.0
890 1 1 Behr, Mr. Karl Howell male 26.0 0 0 111369 30.00 C148 C 26.0 26.0
891 0 3 Dooley, Mr. Patrick male 32.0 0 0 370376 7.75 NaN Q 32.0 32.0
In [4]:
df["AgeCopy"] = df["Age"]

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

df.tail()
Out[4]:
Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked AgeFillNA AgeFillMedian AgeCopy
PassengerId
887 0 2 Montvila, Rev. Juozas male 27.0 0 0 211536 13.00 NaN S 27.0 27.0 27.0
888 1 1 Graham, Miss. Margaret Edith female 19.0 0 0 112053 30.00 B42 S 19.0 19.0 19.0
889 0 3 Johnston, Miss. Catherine Helen "Carrie" female NaN 1 2 W./C. 6607 23.45 NaN S 0.0 28.0 0.0
890 1 1 Behr, Mr. Karl Howell male 26.0 0 0 111369 30.00 C148 C 26.0 26.0 26.0
891 0 3 Dooley, Mr. Patrick male 32.0 0 0 370376 7.75 NaN Q 32.0 32.0 32.0

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

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

display(dropna_df.shape)

display(fillna_df.isnull().any())
(183, 14)
Survived    False
Pclass      False
Name        False
Sex         False
Age         False
SibSp       False
Parch       False
Ticket      False
Fare        False
Cabin       False
Embarked    False
dtype: bool

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

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

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

No description has been provided for this image
In [6]:
# Вывод распределения количества наблюдений по меткам (классам)
from src.utils import split_stratified_into_train_val_test


display(df.Pclass.value_counts())
display()

data = df[["Pclass", "Survived", "AgeFillMedian"]].copy()

df_train, df_val, df_test, y_train, y_val, y_test = split_stratified_into_train_val_test(
   data, stratify_colname="Pclass", frac_train=0.60, frac_val=0.20, frac_test=0.20
)

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

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

display("Тестовая выборка: ", df_test.shape)
display(df_test.Pclass.value_counts())
Pclass
3    491
1    216
2    184
Name: count, dtype: int64
'Обучающая выборка: '
(534, 3)
Pclass
3    294
1    130
2    110
Name: count, dtype: int64
'Контрольная выборка: '
(178, 3)
Pclass
3    98
1    43
2    37
Name: count, dtype: int64
'Тестовая выборка: '
(179, 3)
Pclass
3    99
1    43
2    37
Name: count, dtype: int64
In [1]:
from imblearn.over_sampling import ADASYN

ada = ADASYN()

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

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

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

df_train_adasyn
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[1], line 5
      1 from imblearn.over_sampling import ADASYN
      3 ada = ADASYN()
----> 5 display("Обучающая выборка: ", df_train.shape)
      6 display(df_train.Pclass.value_counts())
      8 X_resampled, y_resampled = ada.fit_resample(df_train, df_train["Pclass"]) # type: ignore

NameError: name 'df_train' is not defined