简体   繁体   English

我自己的线性回归

[英]My own linear regression

I have some data:我有一些数据:

x_data = 0.603 + np.array(range(1,5))
y_data = np.array([22.8,78.6,129.7,181.3,])3

now I want to create my own function for linear regression:现在我想为线性回归创建我自己的函数:

import numpy as np
import sympy as sp

def linear_fit(xi,yi):
    a = sp.Symbol("a")
    b = sp.Symbol("b")
    data = np.transpose(np.array([xi,yi]))
    res_sum = sum(np.array([(a * i + b - j)**2 for i, j in data]))

I am not sure how to derivate this sum and then how to solve the equations for "a" and "b".我不知道如何推导这个和,然后如何求解“a”和“b”的方程。 And I wonder if there is a better way to define linear regression instead of using sympy.我想知道是否有更好的方法来定义线性回归而不是使用 sympy。

I like that spirit to make your own regression model instead of using other libraries.我喜欢这种制作自己的回归模型而不是使用其他库的精神。 You can try this code i wrote and update it as you wish.你可以试试我写的这段代码,并根据需要更新它。

import numpy as np
import time
"""
m is the coeficient and b0 is the y intercrept(the y obstacle in the y-axis) and 
x_pred is the predicting data
in this model we predict the y by x so we should feed some xs to the data and some ys 
and then we predict the y to the given x
"""
class Linear:
     m = 0;#the coef
     b0 = 0;#the y-intercrept
     def train(x,y):#train data set simply we do is fit the xs to the ys
         global b0;
         global m;
         pred = [];
         c = 0;
         m_x = np.mean(x);#mean of x
         m_y = np.mean(y);#mean of y
         s = len(x); #length of x
         num,den = 0,0;#the denominator and the numerator
         for i in range(s):
             num += (x[i]-m_x)*(y[i]-m_y);#numerator #find m; m= (x[i]m_x(y[i]m_y)/(x[i]-m_x)**2 -->do this for s number of times(the number of xs in the data set) do this for number of xs in the data set
         den += (x[i]-m_x)**2;#denominator
         m = num/den;#find m; m= (x[i]-m_x)*(y[i]-m_y)/(x[i]-m_x)**2  
         b0 = m_y-(m*m_x);#find b0(the y-intercrept)
         return pred;

    def predict(x_pred):#predict model
        global b0,m;
        x_test = m*x_pred+b0;#y = m*x+b is the predicting equation
        print("y={}*{}+{}".format(m,x,b0));
        return x_test;
y = [3,6,9];
x = [5,10,15];
train = Linear.train(x,y);
p1 = Linear.predict(5);
print("y is:",p1);

This is all YOURS!!!!这都是你的!!!! -From TOEKNEEHARSH -来自 TOEKNEEHARSH

In short, you need to implement all the functions for computing the hypothesis, the cost and the gradient, and then combine them to create your model.简而言之,您需要实现所有用于计算假设、成本和梯度的函数,然后将它们组合起来创建您的模型。

You can take a look at this notebook implemented from scratch using NumPy .你可以看看这个使用NumPy从头开始实现的笔记本。

Although this notebook implements Logistic Regression and not Linear Regression, you can get a fair idea about how to implement Linear Regression.虽然本笔记本实现的是逻辑回归而不是线性回归,但您可以对如何实现线性回归有一个大致的了解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM