二元函数梯度下降法python实现

想求二元函数的梯度下降迭代结果,但是报错了。代码思路没问题,数组使用不是很明白。

img

grad是个元组,你把它当个函数在调用
如果它是个frame,那后面也应该是方括号而不是圆括号
或者你其实是想调用grad_2

你把数据截图发给我

  • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/7526098
  • 我还给你找了一篇非常好的博客,你可以看看是否有帮助,链接:用python实现求信息增益,进行特征选择。(可以同时适用于二值离散型和连续型的属性)
  • 除此之外, 这篇博客: 通过python程序,采用牛顿法和梯度下降法求解多元一次函数的线性回归方程中的 梯度下降法求解二元一次线性回归方程 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • import pandas as pd
    import numpy as np
    from matplotlib import pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    data=np.genfromtxt('C:\\Users\\ll\\Desktop\\作业六2题.csv',delimiter=',')   #导入数据
    
    x_data=data[:,:-1]
    y_data=data[:,2]
    #定义学习率、斜率、截据a
    #设方程为y=theta1x1+theta2x2+theta0
    lr=0.00001
    theta0=0
    theta1=0
    theta2=0
    #定义最大迭代次数,因为梯度下降法是在不断迭代更新k与b
    epochs=10000
    #定义最小二乘法函数-损失函数(代价函数)
    def compute_error(theta0,theta1,theta2,x_data,y_data):
        totalerror=0
        for i in range(0,len(x_data)):#定义一共有多少样本点
            totalerror=totalerror+(y_data[i]-(theta1*x_data[i,0]+theta2*x_data[i,1]+theta0))**2
        return totalerror/float(len(x_data))/2
    #梯度下降算法求解参数
    def gradient_descent_runner(x_data,y_data,theta0,theta1,theta2,lr,epochs):
        m=len(x_data)
        for i in range(epochs):
            theta0_grad=0
            theta1_grad=0
            theta2_grad=0
            for j in range(0,m):
                theta0_grad-=(1/m)*(-(theta1*x_data[j,0]+theta2*x_data[j,1]+theta2)+y_data[j])
                theta1_grad-=(1/m)*x_data[j,0]*(-(theta1*x_data[j,0]+theta2*x_data[j,1]+theta0)+y_data[j])
                theta2_grad-=(1/m)*x_data[j,1]*(-(theta1*x_data[j,0]+theta2*x_data[j,1]+theta0)+y_data[j])
            theta0=theta0-lr*theta0_grad
            theta1=theta1-lr*theta1_grad
            theta2=theta2-lr*theta2_grad
        return theta0,theta1,theta2
    #进行迭代求解
    theta0,theta1,theta2=gradient_descent_runner(x_data,y_data,theta0,theta1,theta2,lr,epochs)
    print('结果:')
    print('迭代次数:{0} 学习率:{1}  a0={2},a1={3},a2={4},代价函数为{5}'.format(epochs,lr,theta0,theta1,theta2,compute_error(theta0,theta1,theta2,x_data,y_data)))
    print("多元线性回归方程为:y=",theta1,"X1",theta2,"X2+",theta0)
    #画图
    ax=plt.figure().add_subplot(111,projection='3d')
    ax.scatter(x_data[:,0],x_data[:,1],y_data,c='r',marker='o')
    x0=x_data[:,0]
    x1=x_data[:,1]
    #生成网格矩阵
    x0,x1=np.meshgrid(x0,x1)
    z=theta0+theta1*x0+theta2*x1
    #画3d图
    ax.plot_surface(x0,x1,z)
    ax.set_xlabel('area')
    ax.set_ylabel('distance')
    ax.set_zlabel("monney")
    plt.show()
    
    结果:
    迭代次数:10000 学习率:1e-05  a0=5.3774162274868,a1=45.0533119768975,a2=-0.19626929358281256,代价函数为366.7314528822914
    多元线性回归方程为:y= 45.0533119768975 X1 -0.19626929358281256 X2+ 5.3774162274868
    

    在这里插入图片描述

  • 您还可以看一下 王进老师的跟着王进老师学开发Python篇第二季:基础强化篇课程中的 案例演示:找出相同手机号码小节, 巩固相关知识点

目测你的函数名是 grad_2 不是 grad,你修改下。