19 KiB
Raw Permalink Blame History

Вот как можно переделать текст под ваш датасет, учитывая его особенности:

Регрессия

  • Прогнозирование цены бриллианта: Цель: Используя такие параметры, как караты, огранка, цвет, чистота, глубина, таблица, размеры (x, y, z), можно предсказать цену бриллиантов.

Классификация

  • Распределение бриллиантов по категориям чистоты: Цель: Распределить бриллианты по различным категориям чистоты (например, IF, VVS1, VVS2 и т.д.) с использованием данных о каратах, огранке, цвете, глубине, таблице и размерах.
In [1]:
import pandas as pd
from sklearn import set_config

set_config(transform_output="pandas")

random_state = 9

file_path = 'data/Diamonds Prices2022.csv'
df = pd.read_csv(file_path)

# Функция для преобразования типа огранки (cut)
def Cut_Type(value):
    if value == "Fair":
        return 0
    elif value == "Good":
        return 1
    elif value == "Very Good":
        return 2
    elif value == "Premium":
        return 3
    elif value == "Ideal":
        return 4

df['Cut_Type'] = df['cut'].map(Cut_Type)

df
Out[1]:
Unnamed: 0 carat cut color clarity depth table price x y z Cut_Type
0 1 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43 4
1 2 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31 3
2 3 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31 1
3 4 0.29 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63 3
4 5 0.31 Good J SI2 63.3 58.0 335 4.34 4.35 2.75 1
... ... ... ... ... ... ... ... ... ... ... ... ...
53938 53939 0.86 Premium H SI2 61.0 58.0 2757 6.15 6.12 3.74 3
53939 53940 0.75 Ideal D SI2 62.2 55.0 2757 5.83 5.87 3.64 4
53940 53941 0.71 Premium E SI1 60.5 55.0 2756 5.79 5.74 3.49 3
53941 53942 0.71 Premium F SI1 59.8 62.0 2756 5.74 5.73 3.43 3
53942 53943 0.70 Very Good E VS2 60.5 59.0 2757 5.71 5.76 3.47 2

53943 rows × 12 columns

In [2]:
from sklearn.utils import resample
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn import metrics
from imblearn.over_sampling import RandomOverSampler
from imblearn.under_sampling import RandomUnderSampler
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, RandomForestClassifier, GradientBoostingClassifier
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import SGDClassifier, SGDRegressor
from sklearn.metrics import (
    precision_score, recall_score, accuracy_score, roc_auc_score, f1_score,
    matthews_corrcoef, cohen_kappa_score, confusion_matrix
)
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
import numpy as np
import featuretools as ft
from sklearn.metrics import accuracy_score, classification_report

# Загрузка данных
df = pd.read_csv("data/Diamonds Prices2022.csv")

# Определение целевых переменных
# Для задачи классификации я буду использовать 'cut' как целевую переменную
X = df.drop('cut', axis=1)  # Убираем target переменную
y_class = df['cut']  # Задача классификации (например, классификация по типу огранки)
y_reg = df['price']  # Задача регрессии (например, предсказание цены бриллианта)

# Преобразование категориальных переменных
categorical_features = ['color', 'clarity']
numerical_features = ['carat', 'depth', 'table', 'x', 'y', 'z']

# Создание ColumnTransformer с обработкой неизвестных категорий
preprocessor = ColumnTransformer(
    transformers=[
        ('num', StandardScaler(), numerical_features),
        ('cat', OneHotEncoder(handle_unknown='ignore'), categorical_features)])  # Используем handle_unknown='ignore'

# Разделение данных на обучающую и тестовую выборки
X_train, X_test, y_class_train, y_class_test, y_reg_train, y_reg_test = train_test_split(X, y_class, y_reg, test_size=0.2, random_state=42)

def estimate_bias_variance(model, X, y):
    predictions = np.array([model.fit(X, y).predict(X) for _ in range(1000)])
    bias = np.mean((y - np.mean(predictions, axis=0)) ** 2)
    variance = np.mean(np.var(predictions, axis=0))
    return bias, variance

# Просмотр обучающих и тестовых данных
print("X_train", X_train.head())
print("y_class_train", y_class_train.head())

print("X_test", X_test.head())
print("y_class_test", y_class_test.head())
X_train        Unnamed: 0  carat color clarity  depth  table  price     x     y     z
9159         9160   1.01     E     SI2   60.0   60.0   4540  6.57  6.49  3.92
14131       14132   1.10     H     VS2   62.5   58.0   5729  6.59  6.54  4.10
15757       15758   1.50     E     SI2   61.5   65.0   6300  7.21  7.17  4.42
24633       24634   1.53     E     SI1   61.3   59.0  12968  7.40  7.35  4.52
49831       49832   0.84     D     SI2   64.5   60.0   2167  5.92  5.84  3.79
y_class_train 9159     Very Good
14131      Premium
15757         Good
24633      Premium
49831         Fair
Name: cut, dtype: object
X_test        Unnamed: 0  carat color clarity  depth  table  price     x     y     z
1388         1389   0.24     G    VVS1   62.1   56.0    559  3.97  4.00  2.47
19841       19842   1.21     F     VS2   62.9   54.0   8403  6.78  6.82  4.28
41647       41648   0.50     E     SI1   61.7   68.0   1238  5.09  5.03  3.12
41741       41742   0.50     D     SI2   62.8   56.0   1243  5.06  5.03  3.17
17244       17245   1.55     E     SI2   62.3   55.0   6901  7.44  7.37  4.61
y_class_test 1388         Ideal
19841    Very Good
41647         Fair
41741        Ideal
17244        Ideal
Name: cut, dtype: object
In [3]:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix

# Загрузка данных
file_path = 'data/Diamonds Prices2022.csv'
df = pd.read_csv(file_path)

# Очистка столбцов от пробелов
df.columns = df.columns.str.strip()

# Проверка столбцов
print(df.columns)

# Определение признаков и целевой переменной
# Задача классификации: будем предсказывать 'cut' (тип огранки)
X = df.drop('cut', axis=1)  # Убираем целевую переменную
y_class = df['cut']  # Целевая переменная для классификации

# Преобразование категориальных признаков в числовые
X = pd.get_dummies(X, drop_first=True)  # Преобразуем категориальные признаки в числовые, исключая первую категорию

# Разделение на обучающую и тестовую выборки
X_train, X_test, y_train, y_test = train_test_split(X, y_class, test_size=0.2, random_state=42)

# Масштабирование данных
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# Обучение модели
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)

# Прогнозирование
y_pred = model.predict(X_test_scaled)

# Оценка модели
print(classification_report(y_test, y_pred))
print(confusion_matrix(y_test, y_pred))
Index(['Unnamed: 0', 'carat', 'cut', 'color', 'clarity', 'depth', 'table',
       'price', 'x', 'y', 'z'],
      dtype='object')
              precision    recall  f1-score   support

        Fair       0.91      0.87      0.89       328
        Good       0.77      0.69      0.73      1000
       Ideal       0.82      0.92      0.87      4316
     Premium       0.73      0.81      0.77      2734
   Very Good       0.66      0.47      0.55      2411

    accuracy                           0.77     10789
   macro avg       0.78      0.75      0.76     10789
weighted avg       0.76      0.77      0.76     10789

[[ 286   31    1    7    3]
 [  19  686   18   58  219]
 [   6   10 3982  157  161]
 [   0   11  312 2219  192]
 [   2  154  527  589 1139]]