Tuesday, April 12, 2022

Dive into linear regression via gradient descent Python

 Линейная регрессия с использованием градиентного спуска

Градиентный спуск — один из наиболее распространенных методов, используемых для оптимизации различных выпуклых функций в машинном обучении. Поскольку мы знаем, что функция стоимости аналогична функции стоимости (с разницей в 1/2 раза), данной в методе наименьших квадратов, мы будем использовать градиентный спуск для решения проблемы. Мы должны минимизировать функцию стоимости, чтобы найти значение Theta на линии регрессии.

Метод градиентного спуска можно представить следующим образом:

































*******

Code 1

*******

(.env) [boris@fedora35server LINEAREGRS]$ cat gradientDesc1.py

import numpy as np

from matplotlib import pyplot as plt

from PIL import Image

# Function for cost function

def cost(z,theta,y):

    m,n=z.shape;

    htheta = z.dot(theta.transpose())

    cost = ((htheta - y)**2).sum()/(2.0 * m)

    return cost;


def gradient_descent(z,theta,alpha,y,itr):

    cost_arr=[]

    m,n=z.shape;

    count=0;

    htheta = z.dot(theta.transpose())

    while count<itr:

        htheta = z.dot(theta.transpose())

        a=(alpha/m)

        # Using temporary variables for simultaneous updation of variables

        temp0=theta[0,0]-a*(htheta-y).sum();

        temp1=theta[0,1]-a*((htheta-y)*(z[::,1:])).sum();

        theta[0,0]=temp0;

        theta[0,1]=temp1;

        cost_arr.append(float(cost(z,theta,y)));

        count+=1;

    cost_log = np.array(cost_arr);

    plt.plot(np.linspace(0, itr, itr, endpoint=True), cost_log)

    plt.xlabel("No. of iterations")

    plt.ylabel("Error Function value")

    # plt.show()

    fig = plt.gcf()

    fig.savefig('fig1.jpg')

    return theta;


x = np.array([[0], [1],[2], [3], [4], [5], [6], [7], [8], [9]]) 

y = np.array([[11], [13], [12], [15], [17], [18], [18], [19], [20], [22]]) 

m,n=x.shape;

z=np.ones((m,n+1),dtype=int);

z[::,1:]=x;

theta=np.array([[21,2]],dtype=float)

theta_minimised=gradient_descent(z,theta,0.01,y,10000)

print("theta_minimised =",theta_minimised)

new_x=np.array([1,11])

predicted_y=new_x.dot(theta_minimised.transpose())

print(round(predicted_y[0],4))

im = Image.open('fig1.jpg')

im.show()
















Код из https://www.educative.io/edpresso/a-deep-dive-into-linear-regression-3-way-implementation

изменен ( не прнинципиально, мне так удобней )




1 comment: