Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
107 строки
4.6 KiB
Python
107 строки
4.6 KiB
Python
import numpy as np
|
|
import pandas as pd
|
|
import matplotlib.pyplot as plt
|
|
import seaborn as sb
|
|
import pingouin as pg
|
|
from scipy import stats
|
|
|
|
# Датасет "Рост-Вес-Возраст-Позиция"
|
|
columns = ['Position', 'Height(inches)', 'Weight(pounds)', 'Age']
|
|
|
|
df = pd.read_csv('SOCR_Data_MLB_HeightsWeights.txt', sep='\t', nrows=115, usecols=columns)
|
|
|
|
# Построение диаграммы Тьюки только для числовых признаков
|
|
fig1, axes = plt.subplots(2, 2, figsize=(10, 10))
|
|
fig1.suptitle('Диаграммы Тьюки по признакам')
|
|
|
|
# Используем только числовые столбцы для boxplot
|
|
numeric_columns = ['Height(inches)', 'Weight(pounds)', 'Age']
|
|
|
|
# Первый subplot оставляем пустым или убираем
|
|
axes[0,0].remove() # убираем первый subplot
|
|
axes[0,1].boxplot(df['Height(inches)'])
|
|
axes[0,1].set_xticklabels(['Height(inches)'])
|
|
axes[0,1].set_title('Рост (дюймы)')
|
|
|
|
axes[1,0].boxplot(df['Weight(pounds)'])
|
|
axes[1,0].set_xticklabels(['Weight(pounds)'])
|
|
axes[1,0].set_title('Вес (фунты)')
|
|
|
|
axes[1,1].boxplot(df['Age'])
|
|
axes[1,1].set_xticklabels(['Age'])
|
|
axes[1,1].set_title('Возраст')
|
|
|
|
# Альтернативный вариант: построить boxplot для Position как категориального признака
|
|
fig1_pos, ax_pos = plt.subplots(figsize=(8, 6))
|
|
position_counts = df['Position'].value_counts()
|
|
ax_pos.bar(position_counts.index, position_counts.values)
|
|
ax_pos.set_title('Распределение по позициям')
|
|
ax_pos.set_xlabel('Позиция')
|
|
ax_pos.set_ylabel('Количество')
|
|
plt.xticks(rotation=45)
|
|
|
|
fig2, axes = plt.subplots(1, 2, figsize=(12, 5))
|
|
fig2.suptitle('Тепловые карты')
|
|
|
|
# Для корреляции преобразуем Position в числовой формат
|
|
df_numeric = df.copy()
|
|
# Создаем числовое представление позиций для корреляции
|
|
position_mapping = {pos: i for i, pos in enumerate(df['Position'].unique())}
|
|
df_numeric['Position_num'] = df['Position'].map(position_mapping)
|
|
|
|
# Построение тепловой карты парных коэффициентов корреляции
|
|
corrMatrix = df_numeric[['Position_num', 'Height(inches)', 'Weight(pounds)', 'Age']].corr()
|
|
axes[0].set_title('Тепловая карта парных коэфф. корреляции')
|
|
sb.heatmap(corrMatrix, annot=True, linewidths=0.5, ax=axes[0])
|
|
|
|
|
|
# Построение тепловой карты частных коэффициентов корреляции
|
|
try:
|
|
pCorrMatrix = df_numeric[['Position_num', 'Height(inches)', 'Weight(pounds)', 'Age']].pcorr()
|
|
axes[1].set_title('Тепловая карта частных коэфф. корреляции')
|
|
sb.heatmap(pCorrMatrix, annot=True, linewidths=0.5, ax=axes[1])
|
|
except:
|
|
axes[1].set_title('Частная корреляция недоступна')
|
|
print("Метод pcorr() недоступен")
|
|
|
|
|
|
print('Тест Колмогорова-Смирнова. Уровень значимости a = 0.05')
|
|
|
|
# Тест только для числовых признаков
|
|
for col in numeric_columns:
|
|
x = df[col]
|
|
x_mean, std = np.mean(x), np.std(x, ddof=1)
|
|
x_std = (x - x_mean)/std
|
|
pvalue = stats.kstest(x_std, "norm", alternative='two-sided').pvalue
|
|
if pvalue > 0.05:
|
|
result = 'H0 не должна быть отвергнута'
|
|
else:
|
|
result = 'H0 должна быть отвергнута'
|
|
print('Для {}: p-value: {:.4f}, так что {}'.format(col, pvalue, result))
|
|
|
|
# Построение гистограмм
|
|
fig3, axes = plt.subplots(2, 2, figsize=(10, 7))
|
|
|
|
# Гистограмма для Position (как категориальный признак)
|
|
position_counts = df['Position'].value_counts()
|
|
axes[0,0].bar(position_counts.index, position_counts.values)
|
|
axes[0,0].set_title('Распределение по позициям')
|
|
axes[0,0].tick_params(axis='x', rotation=45)
|
|
|
|
axes[0,1].hist(df['Height(inches)'], bins=15, alpha=0.7, edgecolor='black')
|
|
axes[0,1].set_title('Гистограмма роста')
|
|
|
|
axes[1,0].hist(df['Weight(pounds)'], bins=15, alpha=0.7, edgecolor='black')
|
|
axes[1,0].set_title('Гистограмма веса')
|
|
|
|
axes[1,1].hist(df['Age'], bins=15, alpha=0.7, edgecolor='black')
|
|
axes[1,1].set_title('Гистограмма возраста')
|
|
|
|
plt.tight_layout()
|
|
plt.show()
|
|
|
|
# Дополнительная информация о данных
|
|
print("\nИнформация о данных:")
|
|
print(df.info())
|
|
print("\nПервые 5 строк:")
|
|
print(df.head()) |