zoukankan      html  css  js  c++  java
  • 菜鸟之路——机器学习之非线性回归个人理解及python实现

    关键词:

    梯度下降:就是让数据顺着梯度最大的方向,也就是函数导数最大的放下下降,使其快速的接近结果。

    Cost函数等公式太长,不在这打了。网上多得是。

    这个非线性回归说白了就是缩小版的神经网络。

    python实现:

     1 import numpy as np
     2 import random
     3 
     4 def graientDescent(x,y,theta,alpha,m,numIterations):#梯度下降算法
     5     xTrain =x.transpose()
     6     for i in range(0,numIterations):#重复多少次
     7         hypothesis=np.dot(x,theta)          #h函数
     8         loss=hypothesis-y
     9 
    10         cost=np.sum(loss**2) / (2*m)
    11         print("Iteration %d / cost:%f"%(i,cost))
    12         graient=np.dot(xTrain,loss)/m
    13         theta=theta-alpha*graient
    14     return theta
    15 
    16 def getData(numPoints,bias,variance):#自己生成待处理数据
    17     x=np.zeros(shape=(numPoints,2))
    18     y=np.zeros(shape=numPoints)
    19     for i in range(0,numPoints):
    20         x[i][0]=1
    21         x[i][1] = i
    22         y[i]=(i+bias)+random.uniform(0,1)*variance
    23     return x,y
    24 
    25 X,Y=getData(100,25,10)
    26 print("X:",X)
    27 print("Y:",Y)
    28 
    29 numIterations=100000
    30 alpha=0.0005
    31 theta=np.ones(X.shape[1])
    32 theta=graientDescent(X,Y,theta,alpha,X.shape[0],numIterations)
    33 print(theta)

    运行结果:

    ......输出数据太多,只截取后面十几行

    Iteration 99988 / cost:3.930135
    Iteration 99989 / cost:3.930135
    Iteration 99990 / cost:3.930135
    Iteration 99991 / cost:3.930135
    Iteration 99992 / cost:3.930135
    Iteration 99993 / cost:3.930135
    Iteration 99994 / cost:3.930135
    Iteration 99995 / cost:3.930135
    Iteration 99996 / cost:3.930135
    Iteration 99997 / cost:3.930135
    Iteration 99998 / cost:3.930135
    Iteration 99999 / cost:3.930135
    [30.54541676 0.99982553]

    其中遇到一个错误。

    TypeError: unsupported operand type(s) for *: 'builtin_function_or_method' and 'float'

    因为我第五行xTrain =x.transpose()。刚开始没加括号。直接用的xTrain =x.transpose

    打印一下xTrain是

    <built-in method transpose of numpy.ndarray object at 0x00000219C1D14850>

    只是创建了一个transpose方法,并没有真的给x转置。加上括号就好了。再打印xTrain就能正常显示转置后的x了

  • 相关阅读:
    PHP垃圾回收深入理解
    PHP的运行机制与原理(底层)
    SSO单点登录-简单实现
    HBuilder 打包流程
    PHP实现多继承的效果(tarits)
    mysql explain用法和结果的含义
    mysql分区功能详细介绍,以及实例
    MySQL分表、分区

    椒图
  • 原文地址:https://www.cnblogs.com/albert-yzp/p/9565800.html
Copyright © 2011-2022 走看看