Python中的简单线性回归

卡齐(Kazi Nazmul Haque Shezan)

我正在尝试实现此算法以查找单个变量的截距和斜率:

线性回归算法

这是我的Python代码,用于更新截距和斜率。但这并没有收敛。RSS是随着迭代而不是减少而增加的,经过一轮迭代后,它变得无限了。我在执行算法时没有发现任何错误,如何解决此问题?我也附上了csv文件。这是代码。

import pandas as pd
import numpy as np

#Defining gradient_decend
#This Function takes X value, Y value and vector of w0(intercept),w1(slope)
#INPUT FEATURES=X(sq.feet of house size)
#TARGET VALUE=Y (Price of House)
#W=np.array([w0,w1]).reshape(2,1)
#W=[w0,
#    w1]

def gradient_decend(X,Y,W):
    intercept=W[0][0]
    slope=W[1][0]

    #Here i will get a list
    #list is like this
    #gd=[sum(predicted_value-(intercept+slope*x)),
    #     sum(predicted_value-(intercept+slope*x)*x)]
    gd=[sum(y-(intercept+slope*x) for x,y in zip(X,Y)),
        sum(((y-(intercept+slope*x))*x) for x,y in zip(X,Y))]
    return np.array(gd).reshape(2,1)

#Defining Resudual sum of squares
def RSS(X,Y,W):
    return sum((y-(W[0][0]+W[1][0]*x))**2 for x,y in zip(X,Y))


#Reading Training Data
training_data=pd.read_csv("kc_house_train_data.csv")

#Defining fixed parameters
#Learning Rate
n=0.0001
iteration=1500
#Intercept
w0=0
#Slope
w1=0

#Creating 2,1 vector of w0,w1 parameters
W=np.array([w0,w1]).reshape(2,1)

#Running gradient Decend
for i in range(iteration):
     W=W+((2*n)*    (gradient_decend(training_data["sqft_living"],training_data["price"],W)))
     print RSS(training_data["sqft_living"],training_data["price"],W)

是CSV文件。

卡齐(Kazi Nazmul Haque Shezan)

我已经解决了自己的问题!

这是解决的方法。

import numpy as np
import pandas as pd
import math
from sys import stdout

#function Takes the pandas dataframe, Input features list and the target column name
def get_numpy_data(data, features, output):

    #Adding a constant column with value 1 in the dataframe.
    data['constant'] = 1    
    #Adding the name of the constant column in the feature list.
    features = ['constant'] + features
    #Creating Feature matrix(Selecting columns and converting to matrix).
    features_matrix=data[features].as_matrix()
    #Target column is converted to the numpy array
    output_array=np.array(data[output])
    return(features_matrix, output_array)

def predict_outcome(feature_matrix, weights):
    weights=np.array(weights)
    predictions = np.dot(feature_matrix, weights)
    return predictions

def errors(output,predictions):
    errors=predictions-output
    return errors

def feature_derivative(errors, feature):
    derivative=np.dot(2,np.dot(feature,errors))
    return derivative


def regression_gradient_descent(feature_matrix, output, initial_weights, step_size, tolerance):
    converged = False
    #Initital weights are converted to numpy array
    weights = np.array(initial_weights)
    while not converged:
        # compute the predictions based on feature_matrix and weights:
        predictions=predict_outcome(feature_matrix,weights)
        # compute the errors as predictions - output:
        error=errors(output,predictions)
        gradient_sum_squares = 0 # initialize the gradient
        # while not converged, update each weight individually:
        for i in range(len(weights)):
            # Recall that feature_matrix[:, i] is the feature column associated with weights[i]
            feature=feature_matrix[:, i]
            # compute the derivative for weight[i]:
            #predict=predict_outcome(feature,weights[i])
            #err=errors(output,predict)
            deriv=feature_derivative(error,feature)
            # add the squared derivative to the gradient magnitude
            gradient_sum_squares=gradient_sum_squares+(deriv**2)
            # update the weight based on step size and derivative:
            weights[i]=weights[i] - np.dot(step_size,deriv)

        gradient_magnitude = math.sqrt(gradient_sum_squares)
        stdout.write("\r%d" % int(gradient_magnitude))
        stdout.flush()
        if gradient_magnitude < tolerance:
            converged = True
    return(weights)


#Example of Implementation
#Importing Training and Testing Data
# train_data=pd.read_csv("kc_house_train_data.csv")
# test_data=pd.read_csv("kc_house_test_data.csv")

# simple_features = ['sqft_living', 'sqft_living15']
# my_output= 'price'
# (simple_feature_matrix, output) = get_numpy_data(train_data, simple_features, my_output)
# initial_weights = np.array([-100000., 1., 1.])
# step_size = 7e-12
# tolerance = 2.5e7
# simple_weights = regression_gradient_descent(simple_feature_matrix, output,initial_weights, step_size,tolerance)
# print simple_weights

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Python多重简单线性回归

来自分类Dev

从R中的数据框运行多个简单的线性回归

来自分类Dev

使用python进行线性回归的简单预测

来自分类Dev

Spark中的分组线性回归

来自分类Dev

Python中的多元线性回归-MATLAB中mvregress的模拟?

来自分类Dev

简单线性回归上的Tensorflow

来自分类Dev

theano中的线性回归

来自分类Dev

如何使用scikit-learn在Python中打印简单线性回归的截距和斜率?

来自分类Dev

使用lapply存储在列表中的简单线性回归的摘要统计量

来自分类Dev

线性回归脚本在Python中不起作用

来自分类Dev

简单线性依赖

来自分类Dev

在Tensorflow-Probability中具有DenseVariational层的简单线性回归模型返回:TypeError:'NoneType'对象不可调用

来自分类Dev

Swift中的简单线性插值

来自分类Dev

如何在R中的财务数据xts对象上绘制简单滚动线性回归?

来自分类Dev

为什么这种带有梯度下降的简单线性回归不起作用?

来自分类Dev

在Python中线性回归失败,因变量中的值较大

来自分类Dev

python线性回归实现

来自分类Dev

Python中的简单Logistic回归错误

来自分类Dev

训练模型以预测简单线性函数

来自分类Dev

statsmodel.formula.api python中的线性回归

来自分类Dev

简单线性回归未能在张量流中收敛

来自分类Dev

在 Python 中实现线性回归

来自分类Dev

“数组不是python函数”在keras中构建简单线性模型时出错

来自分类Dev

从关于数据的简单线性回归模型的参数得出什么结论

来自分类Dev

python中带有向量的线性回归

来自分类Dev

如何在 Minitab 中运行非线性回归宏(简单的语法错误)?

来自分类Dev

多元线性回归 Python statsmodel 在输出中显示 predictorVariable[Tx]

来自分类Dev

python自动统计线性回归

来自分类Dev

如何在使用简单线性回归的同时在 spyder 中摆脱“预期值错误,二维数组改为一维数组”

Related 相关文章

  1. 1

    Python多重简单线性回归

  2. 2

    从R中的数据框运行多个简单的线性回归

  3. 3

    使用python进行线性回归的简单预测

  4. 4

    Spark中的分组线性回归

  5. 5

    Python中的多元线性回归-MATLAB中mvregress的模拟?

  6. 6

    简单线性回归上的Tensorflow

  7. 7

    theano中的线性回归

  8. 8

    如何使用scikit-learn在Python中打印简单线性回归的截距和斜率?

  9. 9

    使用lapply存储在列表中的简单线性回归的摘要统计量

  10. 10

    线性回归脚本在Python中不起作用

  11. 11

    简单线性依赖

  12. 12

    在Tensorflow-Probability中具有DenseVariational层的简单线性回归模型返回:TypeError:'NoneType'对象不可调用

  13. 13

    Swift中的简单线性插值

  14. 14

    如何在R中的财务数据xts对象上绘制简单滚动线性回归?

  15. 15

    为什么这种带有梯度下降的简单线性回归不起作用?

  16. 16

    在Python中线性回归失败,因变量中的值较大

  17. 17

    python线性回归实现

  18. 18

    Python中的简单Logistic回归错误

  19. 19

    训练模型以预测简单线性函数

  20. 20

    statsmodel.formula.api python中的线性回归

  21. 21

    简单线性回归未能在张量流中收敛

  22. 22

    在 Python 中实现线性回归

  23. 23

    “数组不是python函数”在keras中构建简单线性模型时出错

  24. 24

    从关于数据的简单线性回归模型的参数得出什么结论

  25. 25

    python中带有向量的线性回归

  26. 26

    如何在 Minitab 中运行非线性回归宏(简单的语法错误)?

  27. 27

    多元线性回归 Python statsmodel 在输出中显示 predictorVariable[Tx]

  28. 28

    python自动统计线性回归

  29. 29

    如何在使用简单线性回归的同时在 spyder 中摆脱“预期值错误,二维数组改为一维数组”

热门标签

归档