Родитель
3a49868256
Сommit
0fc82df61a
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
@ -0,0 +1,65 @@
|
||||
import numpy as np
|
||||
from sklearn.datasets import load_iris
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sb
|
||||
import pingouin as pg
|
||||
from scipy import stats
|
||||
|
||||
# Датасет Ирисы Фишера
|
||||
iris = load_iris()
|
||||
#iris_pd=pd.DataFrame(data=np.c_[iris['data'], iris['target']], columns=iris['feature_names'] + ['target'])
|
||||
iris_pd=pd.DataFrame(data=np.c_[iris['data']], columns=iris['feature_names'])
|
||||
|
||||
# Формирование выборок по признакам
|
||||
x1 = np.array(iris_pd['sepal length (cm)']) # первый признак - длина чашелистика
|
||||
x2 = np.array(iris_pd['sepal width (cm)']) # второй признак - ширина чашелистика
|
||||
x3 = np.array(iris_pd['petal length (cm)']) # третий признак - длина лепестка
|
||||
x4 = np.array(iris_pd['petal width (cm)']) # четвертый признак - ширина лепестка
|
||||
|
||||
# Проверка на нормальность по критерию К-С
|
||||
print('Тест Колмогорова-Смирнова. Уровень значимости a = 0.05')
|
||||
|
||||
for col in iris['feature_names']:
|
||||
x = iris_pd[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='less').pvalue
|
||||
if pvalue > 0.05: result = 'H0 не должна быть отвергнута'
|
||||
else: result = 'H0 должна быть отвергнута'
|
||||
print('Для {}: p-value: {}, так что {}'.format(col, pvalue, result))
|
||||
|
||||
# Построение диаграммы Тьюки
|
||||
fig1, axes = plt.subplots(1, 3, figsize=(20, 4))
|
||||
axes[0].boxplot([x1,x2,x3,x4], tick_labels = ['Sepal Length', 'Sepal Width', 'Petal Length', 'Petal Width'])
|
||||
axes[0].set_title('Диаграмма Тьюки')
|
||||
|
||||
|
||||
# Построение тепловой карты парных коэффициентов корреляции
|
||||
corrMatrix = iris_pd.corr()
|
||||
axes[1].set_title('Тепловая карта парных коэфф. корреляции')
|
||||
sb.heatmap(corrMatrix, annot=True, linewidths=0.5, xticklabels = False, yticklabels = False, ax = axes[1])
|
||||
|
||||
|
||||
# Построение тепловой карты частных коэффициентов корреляции
|
||||
pCorrMatrix = iris_pd.pcorr()
|
||||
axes[2].set_title('Тепловая карта частных коэфф. корреляции')
|
||||
sb.heatmap(pCorrMatrix, annot=True, linewidths=0.5, xticklabels = False, yticklabels = False, ax = axes[2])
|
||||
|
||||
|
||||
# Построение гистограмм по выборкам
|
||||
fig2, axes = plt.subplots(2, 2, figsize=(10, 7))
|
||||
|
||||
axes[0,0].hist(x1)
|
||||
axes[0,0].set_title('Гисотграмма по значениям X1')
|
||||
|
||||
axes[0,1].hist(x2)
|
||||
axes[0,1].set_title('Гисотграмма по значениям X2')
|
||||
|
||||
axes[1,0].hist(x3)
|
||||
axes[1,0].set_title('Гисотграмма по значениям X3')
|
||||
|
||||
axes[1,1].hist(x4)
|
||||
axes[1,1].set_title('Гисотграмма по значениям X4')
|
||||
|
||||
plt.show()
|
||||
@ -0,0 +1,107 @@
|
||||
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())
|
||||
@ -0,0 +1,102 @@
|
||||
import numpy as np
|
||||
from sklearn.datasets import load_iris
|
||||
from sklearn.linear_model import LinearRegression
|
||||
from sklearn.metrics import r2_score
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sb
|
||||
import pingouin as pg
|
||||
from scipy import stats
|
||||
|
||||
# Датасет Ирисы Фишера
|
||||
iris = load_iris()
|
||||
iris_pd=pd.DataFrame(data=np.c_[iris['data'], iris['target']], columns=iris['feature_names'] + ['target'])
|
||||
|
||||
# Формирование выборок по признакам
|
||||
x1 = np.array(iris_pd['sepal length (cm)']) # первый признак - длина чашелистика
|
||||
x2 = np.array(iris_pd['sepal width (cm)']) # второй признак - ширина чашелистика
|
||||
x3 = np.array(iris_pd['petal length (cm)']) # третий признак - длина лепестка
|
||||
x4 = np.array(iris_pd['petal width (cm)']) # четвертый признак - ширина лепестка
|
||||
|
||||
# Пусть X4 - выходные переменные, а X3 - входные переменные, так как они коррелируют сильнее остальных комбинаций
|
||||
fig, axes = plt.subplots(2, 2, figsize=(10, 10))
|
||||
|
||||
axes[0,0].scatter(x3, x4)
|
||||
axes[0,0].set_title('Зависимость X4 от X3')
|
||||
|
||||
axes[0,1].scatter(x3, x4)
|
||||
axes[0,1].set_title('Предсказанные значения')
|
||||
|
||||
|
||||
|
||||
# Парная регрессия
|
||||
N = 150
|
||||
K = 2
|
||||
lr = LinearRegression().fit(x3.reshape(-1,1), x4)
|
||||
|
||||
#line_x3 = np.linspace(min(x3), max(x3),150)
|
||||
line_y1 = lr.predict(x3.reshape(-1,1))
|
||||
axes[0,0].plot(x3, line_y1, color='red', linewidth=2)
|
||||
|
||||
line_x3_pred = np.linspace(min(x3), 2*max(x3), 150)
|
||||
line_y1_pred = lr.predict(line_x3_pred.reshape(-1,1))
|
||||
axes[0,1].plot(line_x3_pred, line_y1_pred, color='red', linewidth=2)
|
||||
|
||||
meanY = np.mean(x4)
|
||||
Qreg = np.sum((line_y1 - meanY)**2)
|
||||
Qtotal = np.sum((x4 - meanY)**2)
|
||||
Qint = np.sum((x4 - line_y1)**2)
|
||||
Sreg = (1/(K-1))*Qreg
|
||||
Stotal = (1/(N-1))*Qtotal
|
||||
Sint = (1/(N-K))*Qint
|
||||
|
||||
print(np.dot(x4 - line_y1, line_y1))
|
||||
|
||||
print('Парная регрессия. Коэффициент детерминации: ', r2_score(x4,line_y1))
|
||||
print('Скорр. коэффициент детерминации: ', 1 - (1 - r2_score(x4,line_y1)*(149/147)))
|
||||
print('Множ. коэффициент корреляции: ', np.sqrt(r2_score(x4,line_y1)))
|
||||
print('Стандартная ошибка регрессии: ', np.sqrt(Qint/147))
|
||||
|
||||
# Множественная регрессия
|
||||
N = 150
|
||||
K = 4
|
||||
X = np.vstack((x1, x2, x3)).T
|
||||
mr = LinearRegression().fit(X, x4)
|
||||
|
||||
line_x1 = np.linspace(min(x1), max(x1), 150)
|
||||
line_x2 = np.linspace(min(x2), max(x2), 150)
|
||||
line_x3 = np.linspace(min(x3), max(x3), 150)
|
||||
|
||||
line_y2 = mr.coef_[0] * line_x1 + mr.coef_[1] * line_x2 + mr.coef_[2] * line_x3 + mr.intercept_
|
||||
axes[0,0].plot(line_x3, line_y2, color='green', linewidth=2)
|
||||
|
||||
line_x1_pred = np.linspace(min(x1), 2*max(x1), 150)
|
||||
line_x2_pred = np.linspace(min(x2), 2*max(x2), 150)
|
||||
line_x3_pred = np.linspace(min(x3), 2*max(x3), 150)
|
||||
line_y2_pred = mr.coef_[0] * line_x1_pred + mr.coef_[1] * line_x2_pred + mr.coef_[2] * line_x3_pred + mr.intercept_
|
||||
axes[0,1].plot(line_x3_pred, line_y2_pred, color='green', linewidth=2)
|
||||
|
||||
Qreg = np.sum((line_y2 - meanY)**2)
|
||||
Qint = np.sum((x4 - line_y2)**2)
|
||||
Sreg = (1/(K-1))*Qreg
|
||||
Stotal = (1/(N-1))*Qtotal
|
||||
Sint = (1/(N-K))*Qint
|
||||
|
||||
print('Множ. регресиия. Коэффициент детерминации: ', r2_score(x4,line_y2))
|
||||
print('Скорр. коэффициент детерминации: ', 1 - (1 - r2_score(x4,line_y2)*(149/147)))
|
||||
print('Множ. коэффициент корреляции: ', np.sqrt(r2_score(x4,line_y2)))
|
||||
print('Стандартная ошибка регрессии: ', np.sqrt(Qint/147))
|
||||
|
||||
# График остатков
|
||||
residuals1 = x4 - line_y1
|
||||
residuals2 = x4 - line_y2
|
||||
|
||||
axes[1,0].scatter([i for i in range(1,151)], residuals1)
|
||||
axes[1,0].set_title('Парная регрессия. График остатков')
|
||||
|
||||
axes[1,1].scatter([i for i in range(1,151)], residuals2)
|
||||
axes[1,1].set_title('Множ. регрессия. График остатков')
|
||||
|
||||
|
||||
plt.show()
|
||||
|
||||
@ -0,0 +1,118 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn.linear_model import LinearRegression
|
||||
from sklearn.metrics import r2_score
|
||||
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)
|
||||
|
||||
# === ПАРНАЯ РЕГРЕССИЯ ===
|
||||
# Выходная переменная — вес, входная — рост
|
||||
X_single = df['Height(inches)'].values.reshape(-1, 1)
|
||||
y = df['Weight(pounds)'].values
|
||||
|
||||
lr = LinearRegression().fit(X_single, y)
|
||||
y_pred_single = lr.predict(X_single)
|
||||
res_single = y - y_pred_single
|
||||
|
||||
# Визуализация
|
||||
fig1, axes = plt.subplots(1, 3, figsize=(15, 5))
|
||||
fig1.suptitle('Парная регрессия')
|
||||
|
||||
# 1. Линия регрессии
|
||||
axes[0].scatter(df['Height(inches)'], df['Weight(pounds)'], color='blue', alpha=0.6)
|
||||
axes[0].plot(df['Height(inches)'], y_pred_single, color='red', linewidth=2)
|
||||
axes[0].set_xlabel('Height (inches)')
|
||||
axes[0].set_ylabel('Weight (pounds)')
|
||||
axes[0].set_title('Линейная зависимость')
|
||||
|
||||
# 2. Остатки
|
||||
axes[1].scatter(y_pred_single, res_single, color='green', alpha=0.6)
|
||||
axes[1].axhline(y=0, color='red', linestyle='--')
|
||||
axes[1].set_xlabel('Предсказанные значения')
|
||||
axes[1].set_ylabel('Остатки')
|
||||
axes[1].set_title('Анализ остатков')
|
||||
|
||||
# 3. Гистограмма остатков
|
||||
axes[2].hist(res_single, bins=15, color='gray', edgecolor='black')
|
||||
axes[2].set_xlabel('Остатки')
|
||||
axes[2].set_ylabel('Количество точек')
|
||||
axes[2].set_title('Распределение остатков')
|
||||
|
||||
# Метрики
|
||||
Qreg = np.sum((y_pred_single - y.mean()) ** 2)
|
||||
Qres = np.sum((y - y_pred_single) ** 2)
|
||||
Qtotal = np.sum((y - y.mean()) ** 2)
|
||||
|
||||
R2 = r2_score(y, y_pred_single)
|
||||
AdjR2 = 1 - (1 - R2) * (115 - 1) / (115 - 1 - 1)
|
||||
R = np.sqrt(R2)
|
||||
StdErr = np.sqrt(Qres / (115 - 2))
|
||||
|
||||
print('\n=== Парная регрессия ===')
|
||||
print('Коэффициент детерминации R²:', round(R2, 4))
|
||||
print('Скорректированный R²:', round(AdjR2, 4))
|
||||
print('Множественный коэффициент корреляции R:', round(R, 4))
|
||||
print('Стандартная ошибка регрессии:', round(StdErr, 4))
|
||||
print('Коэффициенты модели (b0 + b1*x):', lr.intercept_, lr.coef_)
|
||||
|
||||
# === МНОЖЕСТВЕННАЯ РЕГРЕССИЯ ===
|
||||
# Кодируем категориальный признак Position в числовой формат
|
||||
position_mapping = {pos: i for i, pos in enumerate(df['Position'].unique())}
|
||||
df['Position_num'] = df['Position'].map(position_mapping)
|
||||
|
||||
# Входные переменные — позиция, рост и возраст
|
||||
X_multi = df[['Position_num', 'Height(inches)', 'Age']].values
|
||||
|
||||
mr = LinearRegression().fit(X_multi, y)
|
||||
y_pred_multi = mr.predict(X_multi)
|
||||
res_multi = y - y_pred_multi
|
||||
|
||||
# Визуализация
|
||||
fig2, axes = plt.subplots(1, 2, figsize=(12, 5))
|
||||
fig2.suptitle('Множественная регрессия')
|
||||
|
||||
# Остатки
|
||||
axes[0].scatter(y_pred_multi, res_multi, color='purple', alpha=0.6)
|
||||
axes[0].axhline(y=0, color='red', linestyle='--')
|
||||
axes[0].set_xlabel('Предсказанные значения')
|
||||
axes[0].set_ylabel('Остатки')
|
||||
axes[0].set_title('Анализ остатков')
|
||||
|
||||
# Гистограмма остатков
|
||||
axes[1].hist(res_multi, bins=15, color='orange', edgecolor='black')
|
||||
axes[1].set_xlabel('Остатки')
|
||||
axes[1].set_ylabel('Количество точек')
|
||||
axes[1].set_title('Распределение остатков')
|
||||
|
||||
# Метрики
|
||||
Qreg_m = np.sum((y_pred_multi - y.mean()) ** 2)
|
||||
Qres_m = np.sum((y - y_pred_multi) ** 2)
|
||||
|
||||
R2_m = r2_score(y, y_pred_multi)
|
||||
AdjR2_m = 1 - (1 - R2_m) * (115 - 1) / (115 - 3 - 1)
|
||||
R_m = np.sqrt(R2_m)
|
||||
StdErr_m = np.sqrt(Qres_m / (115 - 3 - 1))
|
||||
|
||||
print('\n=== Множественная регрессия ===')
|
||||
print('Коэффициент детерминации R²:', round(R2_m, 4))
|
||||
print('Скорректированный R²:', round(AdjR2_m, 4))
|
||||
print('Множественный коэффициент корреляции R:', round(R_m, 4))
|
||||
print('Стандартная ошибка регрессии:', round(StdErr_m, 4))
|
||||
print('Коэффициенты модели:', mr.intercept_, mr.coef_)
|
||||
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
# === КРАТКИЕ ВЫВОДЫ ===
|
||||
print('\n=== ВЫВОДЫ ===')
|
||||
print('1. Парная регрессия показывает умеренную связь между ростом и весом (R ≈', round(R, 2), ').')
|
||||
print('2. Множественная регрессия с учётом возраста и позиции улучшает качество модели (R² выше).')
|
||||
print('3. Остатки распределены примерно нормально, значимых выбросов немного.')
|
||||
print('4. Наиболее информативные переменные: рост и возраст.')
|
||||
|
||||
|
||||
|
||||
@ -0,0 +1,67 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.datasets import load_iris
|
||||
from sklearn.linear_model import LinearRegression
|
||||
from statsmodels.stats.stattools import durbin_watson
|
||||
from scipy import stats
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# === Датасет Ирисы Фишера ===
|
||||
iris = load_iris()
|
||||
iris_pd = pd.DataFrame(data=np.c_[iris['data'], iris['target']],
|
||||
columns=iris['feature_names'] + ['target'])
|
||||
|
||||
# === Признаки и целевая переменная ===
|
||||
x1 = iris_pd['sepal length (cm)'].values
|
||||
x2 = iris_pd['sepal width (cm)'].values
|
||||
x3 = iris_pd['petal length (cm)'].values
|
||||
x4 = iris_pd['petal width (cm)'].values # целевая переменная
|
||||
|
||||
# === Парная регрессия: x3 -> x4 ===
|
||||
lr = LinearRegression().fit(x3.reshape(-1,1), x4)
|
||||
y_pred1 = lr.predict(x3.reshape(-1,1))
|
||||
residuals1 = x4 - y_pred1
|
||||
|
||||
# === Множественная регрессия: x1,x2,x3 -> x4 ===
|
||||
X = np.vstack((x1, x2, x3)).T
|
||||
mr = LinearRegression().fit(X, x4)
|
||||
y_pred2 = mr.predict(X)
|
||||
residuals2 = x4 - y_pred2
|
||||
|
||||
# === Графики остатков ===
|
||||
fig, axes = plt.subplots(1, 2, figsize=(12,5))
|
||||
axes[0].hist(residuals1, bins=15, color='lightblue', edgecolor='black')
|
||||
axes[0].set_title('Остатки парной регрессии')
|
||||
axes[1].hist(residuals2, bins=15, color='lightgreen', edgecolor='black')
|
||||
axes[1].set_title('Остатки множественной регрессии')
|
||||
plt.show()
|
||||
|
||||
# === Проверка нормальности остатков (Shapiro-Wilk) ===
|
||||
print("=== Проверка нормальности остатков ===")
|
||||
for i, res in enumerate([residuals1, residuals2], start=1):
|
||||
stat, p = stats.shapiro(res)
|
||||
print(f"Регрессия {i}: Статистика Шапиро–Уилка = {stat:.4f}, p-value = {p:.4f}")
|
||||
if p > 0.05:
|
||||
print("→ Остатки распределены нормально (H0 не отвергается).")
|
||||
else:
|
||||
print("→ Остатки не распределены нормально (H0 отвергается).")
|
||||
|
||||
# === Статистика Дурбина–Уотсона ===
|
||||
from statsmodels.stats.stattools import durbin_watson
|
||||
print("\n=== Статистика Дурбина–Уотсона ===")
|
||||
dw1 = durbin_watson(residuals1)
|
||||
dw2 = durbin_watson(residuals2)
|
||||
print(f"Парная регрессия: DW = {dw1:.4f}")
|
||||
print(f"Множественная регрессия: DW = {dw2:.4f}")
|
||||
|
||||
# Интерпретация
|
||||
def interpret_dw(dw):
|
||||
if dw < 1.5:
|
||||
return "→ Положительная автокорреляция остатков."
|
||||
elif dw > 2.5:
|
||||
return "→ Отрицательная автокорреляция остатков."
|
||||
else:
|
||||
return "→ Остатки независимы (автокорреляции нет)."
|
||||
|
||||
print("Парная регрессия:", interpret_dw(dw1))
|
||||
print("Множественная регрессия:", interpret_dw(dw2))
|
||||
@ -0,0 +1,66 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.linear_model import LinearRegression
|
||||
from statsmodels.stats.stattools import durbin_watson
|
||||
from scipy import stats
|
||||
import seaborn as sns
|
||||
import matplotlib.pyplot as plt
|
||||
import statsmodels.api as sm
|
||||
|
||||
# === Загружаем данные ===
|
||||
columns = ['Position', 'Height(inches)', 'Weight(pounds)', 'Age']
|
||||
df = pd.read_csv('SOCR_Data_MLB_HeightsWeights.txt', sep='\t', nrows=115, usecols=columns)
|
||||
|
||||
# Кодируем категориальный признак "Position"
|
||||
df['Position_num'] = pd.factorize(df['Position'])[0]
|
||||
|
||||
# === Множественная регрессия (Weight = f(Position, Height, Age)) ===
|
||||
X = df[['Position_num', 'Height(inches)', 'Age']]
|
||||
y = df['Weight(pounds)']
|
||||
|
||||
model = LinearRegression().fit(X, y)
|
||||
y_pred = model.predict(X)
|
||||
|
||||
# === Остатки ===
|
||||
res2 = y - y_pred
|
||||
|
||||
# === Проверка нормальности остатков ===
|
||||
print('=== Проверка нормальности остатков ===')
|
||||
shapiro_stat, shapiro_p = stats.shapiro(res2)
|
||||
print(f"Статистика Шапиро–Уилка: {shapiro_stat:.4f}, p-value = {shapiro_p:.4f}")
|
||||
if shapiro_p > 0.05:
|
||||
print("→ Остатки распределены нормально (нет оснований отвергнуть H₀).")
|
||||
else:
|
||||
print("→ Остатки не распределены нормально (отвергаем H₀).")
|
||||
|
||||
# === Графики остатков ===
|
||||
plt.figure(figsize=(12, 5))
|
||||
|
||||
# Гистограмма
|
||||
plt.subplot(1, 2, 1)
|
||||
sns.histplot(res2, bins=20, kde=True, color='lightblue', edgecolor='black')
|
||||
plt.title('Гистограмма остатков')
|
||||
plt.xlabel('Остатки')
|
||||
|
||||
# QQ-график
|
||||
plt.subplot(1, 2, 2)
|
||||
sm.qqplot(res2, line='s', ax=plt.gca())
|
||||
plt.title('QQ-график остатков')
|
||||
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
# === Статистика Дурбина–Уотсона ===
|
||||
dw_stat = durbin_watson(res2)
|
||||
|
||||
# Явный вывод для отчёта
|
||||
print('\n=== Статистика Дурбина–Уотсона ===')
|
||||
print(f"Значение статистики Дурбина–Уотсона: {dw_stat:.4f}")
|
||||
|
||||
# Интерпретация
|
||||
if dw_stat < 1.5:
|
||||
print("→ Наблюдается положительная автокорреляция остатков.")
|
||||
elif dw_stat > 2.5:
|
||||
print("→ Наблюдается отрицательная автокорреляция остатков.")
|
||||
else:
|
||||
print("→ Автокорреляция остатков отсутствует (остатки независимы).")
|
||||
@ -0,0 +1,45 @@
|
||||
import numpy as np
|
||||
from sklearn.datasets import load_iris
|
||||
from sklearn.linear_model import LinearRegression
|
||||
from sklearn.metrics import mean_squared_error, r2_score
|
||||
from sklearn.model_selection import train_test_split
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# Датасет Ирисы Фишера
|
||||
iris = load_iris()
|
||||
iris_pd=pd.DataFrame(data=np.c_[iris['data'], iris['target']], columns=iris['feature_names'] + ['target'])
|
||||
|
||||
# Формирование выборок по признакам
|
||||
x1 = np.array(iris_pd['sepal length (cm)']) # первый признак - длина чашелистика
|
||||
x2 = np.array(iris_pd['sepal width (cm)']) # второй признак - ширина чашелистика
|
||||
x3 = np.array(iris_pd['petal length (cm)']) # третий признак - длина лепестка
|
||||
x4 = np.array(iris_pd['petal width (cm)']) # четвертый признак - ширина лепестка
|
||||
|
||||
X = np.column_stack((x1, x2, x3))
|
||||
|
||||
# Разделение на обучающую и тестовую выборки
|
||||
X_train, X_test, y_train, y_test = train_test_split(X, x4, test_size=0.25, random_state=42)
|
||||
|
||||
|
||||
|
||||
model = LinearRegression()
|
||||
model.fit(X_train, y_train)
|
||||
|
||||
y_pred = model.predict(X_test)
|
||||
|
||||
mse = mean_squared_error(y_test, y_pred)
|
||||
rmse = np.sqrt(mse)
|
||||
r2 = r2_score(y_test, y_pred)
|
||||
|
||||
print(f"Среднеквадратичное отклонение (СКO): {rmse:.2f}")
|
||||
print(f"Коэффициент детерминации (R²): {r2:.2f}")
|
||||
|
||||
residuals = y_test - y_pred
|
||||
|
||||
plt.scatter(y_pred, residuals)
|
||||
plt.axhline(y=0, color='red', linestyle='--')
|
||||
plt.xlabel('Предсказанные значения')
|
||||
plt.ylabel('Остаточные ошибки')
|
||||
plt.title('График остатков')
|
||||
plt.show()
|
||||
@ -0,0 +1,56 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.linear_model import LinearRegression
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.metrics import mean_squared_error, r2_score
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sns
|
||||
|
||||
# === Загружаем данные ===
|
||||
columns = ['Position', 'Height(inches)', 'Weight(pounds)', 'Age']
|
||||
df = pd.read_csv('SOCR_Data_MLB_HeightsWeights.txt', sep='\t', nrows=115, usecols=columns)
|
||||
|
||||
# Кодируем категориальный признак "Position"
|
||||
df['Position_num'] = pd.factorize(df['Position'])[0]
|
||||
|
||||
# === Признаки и целевая переменная ===
|
||||
X = df[['Position_num', 'Height(inches)', 'Age']]
|
||||
y = df['Weight(pounds)']
|
||||
|
||||
# === Разделение выборки на обучающую и тестовую ===
|
||||
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
|
||||
|
||||
# === Обучение модели ===
|
||||
model = LinearRegression()
|
||||
model.fit(X_train, y_train)
|
||||
|
||||
# === Предсказание ===
|
||||
y_pred = model.predict(X_test)
|
||||
|
||||
# === Оценка точности ===
|
||||
mse = mean_squared_error(y_test, y_pred)
|
||||
rmse = np.sqrt(mse)
|
||||
r2 = r2_score(y_test, y_pred)
|
||||
|
||||
print("=== Оценка качества модели ===")
|
||||
print(f"СКО (RMSE): {rmse:.4f}")
|
||||
print(f"Коэффициент детерминации (R^2): {r2:.4f}")
|
||||
|
||||
# === График ошибок ===
|
||||
errors = y_test - y_pred
|
||||
|
||||
plt.figure(figsize=(10, 5))
|
||||
sns.histplot(errors, bins=15, kde=True, color='lightcoral', edgecolor='black')
|
||||
plt.title('Гистограмма ошибок предсказания')
|
||||
plt.xlabel('Ошибка (y_true - y_pred)')
|
||||
plt.ylabel('Частота')
|
||||
plt.show()
|
||||
|
||||
# === Визуализация предсказанного vs реального значения ===
|
||||
plt.figure(figsize=(8, 6))
|
||||
plt.scatter(y_test, y_pred, color='blue', edgecolor='k')
|
||||
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--', lw=2)
|
||||
plt.xlabel('Истинные значения')
|
||||
plt.ylabel('Предсказанные значения')
|
||||
plt.title('Предсказанные vs Истинные значения')
|
||||
plt.show()
|
||||
|
После Ширина: | Высота: | Размер: 194 KiB |
Двоичный файл не отображается.
Двоичный файл не отображается.
Загрузка…
Ссылка в новой задаче