Лучшая часть этого блога заключается в том, что вы можете использовать эту реализацию как для простой, так и для множественной линейной регрессии с использованием градиентного спуска, просто изменив свои входные данные с одиночной на множественную переменную.
Первое, что вам нужно знать о линейной регрессии:
Алгоритм:
- Подготовьте данные в виде (x_train, x_test, y_train, y_test)
- Структура гипотезы (линейное представление) y = theta0 + (theta1 * x)
- Определите функцию стоимости: J (theta0, theta1) (#formula упомянута на изображении) 1/2 добавляется просто для упрощения производной, когда вы берете производную функции стоимости, которую получают 2 в степени отменяется множителем 1/2. Это не имеет значения, Если вы даже не делите эти 2 и не делите на 1/2, то вы просто усиливаете скаляр (одно число) на 2, тогда как все, что вам нужно, это базовый количество (которое представляет собой скорость изменения или крутизну), в ML следует отметить одну вещь: изучение линейной величины является простым и занимает меньше времени, тогда как усиление на 2 может в дальнейшем привести к дополнительному шагу, который похож на просьбу модели адаптироваться к чему-то дополнительному.
- Определить вычислительные градиенты: производные # формула, указанная на изображении
- Определить градиентный спуск: (x, y, итерации, скорость обучения)
Определить массив cost_history
Инициализировать случайные значения theta_coeff
compute_gradients wrt theta_coeff
Обновить theta_coeff
Рассчитать новую стоимость и сохранить - Прогноз: установить значение Learning_rate
Определить переменную смещения
Использовать гипотезу с new_inputs
7. Рассчитайте RMSE и R2_Score:
Выполнение
Мы собираемся сначала сгенерировать набор данных:
import numpy as np import pandas as pd from sklearn.datasets import make_regression from sklearn.model_selection import train_test_split X, y= make_regression(n_samples=300, n_features=2, noise=20, bias=5) data = pd.DataFrame(np.column_stack((X, y)),columns=['a', 'b', 'y']) train_dataset, test_dataset = train_test_split(data, test_size=0.2, shuffle=True) train_dataset.to_csv('train_dataset.csv',index=False) test_dataset.to_csv('test_dataset.csv',index=False)
Теперь реализуем простой LR по алгоритму:
#prepare Data import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline train_data = pd.read_csv('train_dataset.csv') test_data = pd.read_csv('test_dataset.csv') x= train_data['a'].values y= train_data['y'].values x_test= test_data['a'].values y_test= test_data['y'].values
Определите гипотезу:
def hypothesis(theta_coeff,x): ''' parameters: theta_coeff (array)= coefficient of function (1 X num_of_theta_coeff) x = input data/variables (num_of_samples X 1) return: predicted values for each example rows in inputs (1 X num_of_inputs) ''' return x.dot(theta_coeff)
Определите функцию затрат:
def cost_function_mse(theta_coeff, x, y): ''' parameters: theta_coeff (array)= coefficient of function (1 X num_of_theta_coeff) x = input data/variables (num_of_samples X 1) y = input data/variables (num_of_samples X 1) return: Computes cost of using theta_coeff as coefficients for Linear Representation wrt to training data ''' predicted_y = hypothesis(theta_coeff,x) return np.sum((predicted_y - y)** 2) / (2*len(x))
Определите вычислительные градиенты:
def compute_gradients(theta_coeff, x, y): ''' parameters: theta_coeff (array)= coefficient of function (1 X num_of_theta_coeff) x = input data/variables (num_of_samples X 1) y = input data/variables (num_of_samples X 1) return: Array of computed gradients for each of the coefficients (1 x num_of_coefficients) ''' predicted_y = hypothesis(theta_coeff,x) coeff_gradients = np.sum((predicted_y - y) * x.T,axis=1) /(len(x)) return coeff_gradients
Определить градиентный спуск
def gradient_descent(x, y, iterations, learning_rate): ''' parameters: x = input data/variables (num_of_samples X 1) y = input data/variables (num_of_samples X 1) iterations(int) = number of iterations/epochs learning_rate(int): alpha or learning rate which controls the descent return: Array of computed gradients for each of the coefficients (1 x num_of_coefficients) ''' # Container to cost history as the descent progresses cost_history = [] theta_coeff = np.array([0] * x.shape[1]) for iteration in range(iterations): # Compute gradient wrt. old theta_coeff coeff_gradients = compute_gradients(theta_coeff, x, y) #update theta_coeff theta_coeff = theta_coeff - (learning_rate * coeff_gradients) #store the new cost cost = cost_function_mse(theta_coeff, x, y) cost_history.append(cost) return theta_coeff, cost_history
Установить скорость обучения и переменную смещения
alpha = 0.0001 #learning_rate bias_variable = np.ones(len(x))#bias variables x_train = np.column_stack([bias_variable, x]) best_theta_coeff, cost_history = gradient_descent(x_train, y, 25000, alpha) plt.plot(cost_history)
Определите прогноз получения:
def get_predictions(theta_coeff, x_input): bias_variable = np.ones(len(x_input))#bias variables new_x_input = np.column_stack([bias_variable, x_input])# Plug input along with bias_variable preds = hypothesis(theta_coeff, new_x_input)# Compute output values with new coefficients return preds
Рассчитайте RMSE и R2_Score
def rmse(y, y_pred): rmse = np.sqrt(np.sum((y-y_pred)**2)/len(y)) return rmse def r2_score(y, y_pred): mean_y =np.mean(y) SE_line_variation = np.sum((y - y_pred)** 2) #Unexplained variation in y wrt -> fitted line SE_total_variation = np.sum((y - mean_y)** 2) #Unexplained max possible variation in y wrt->Mean return 1 - (SE_line_variation/SE_total_variation) y_pred_train = get_predictions(best_theta_coeff, x) y_pred_test = get_predictions(best_theta_coeff, x_test)
Оценка тренировочного набора
print(f"RMSE= {rmse(y, y_pred_train)}") print(f"R2_score = {r2_score(y, y_pred_train)}") RMSE= 63.354472973417906 R2_score = 0.6092364075248261
Оценка тестового набора
print(f"RMSE= {rmse(test_data['y'].values, y_pred_test)}") print(f"R2_score = {r2_score(test_data['y'].values, y_pred_test)}") RMSE= 62.21722128800 R2_score = 0.6574969344382422
Для переменной с несколькими входами вам просто нужно изменить входную переменную:
x= train_data[['a','b']].values y= train_data['y'].values x_test= test_data[['a','b']].values y_test= test_data['y'].values
Найдите набор данных и код здесь: https://github.com/Gauravhulmukh/All_ml_algorithm_from_scratch/tree/master/Linear%20Regression
Есть вопросы? Нужна помощь ? Свяжитесь со мной!
Электронная почта: [email protected]
LinkedIn: https://www.linkedin.com/in/gaurav-hulmukh-932648166/
Instagram: https://www.instagram.com/gauravhulmukh/