.. методом МНК
Этот код строит простую модель линейной регрессии на основе метода OLS, чтобы предсказать рост сына, учитывая рост отца.
Шаг 1 — Импорт необходимых библиотек
import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline import math from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn import metrics
Шаг 2 — Чтение набора данных; разделить данные обучения/тестирования
dataset = pd.read_csv(‘father_son_heights.csv’) dataset.head()
x = dataset[‘Father’].values.reshape(-1,1) y = dataset[‘Son’].values.reshape(-1,1) x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3,random_state=0)
Шаг 3 — Визуализируйте набор данных
plt.scatter(x, y) plt.xlabel(‘Height: Father’) plt.ylabel(‘Height: Son’) plt.show()
Шаг 4 — Построить модель; получить перехват и коэффициент
# Generate a Linear Regression model & fit training data lm = LinearRegression() lm.fit(x_train,y_train) textstr = ‘’ textstr = textstr + ‘Coefficient value obtained: ‘ + str(lm.coef_ ) textstr = textstr + ‘\nIntercept value obtained: ‘ + str(lm.intercept_ ) print(textstr)
Шаг 5 — Постройте прогноз y против x
x_ht_samples = np.linspace(x.min(), x.max(), num=50) plt.scatter(x, y, color=’g’) # Scatter-plot of x & y as in Step 3 plt.xlabel(‘Height: Father’) plt.ylabel(‘Height: Son’) y_ht_prediction = lm.predict(x_ht_samples.reshape(-1,1)) plt.plot(x_ht_samples, y_ht_prediction, color=’r’, linewidth=3) plt.show()