菜鸟之路——机器学习之非线性回归个人理解及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)/m13         theta=theta-alpha*graient14     return theta15 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]=121         x[i][1] = i22         y[i]=(i+bias)+random.uniform(0,1)*variance23     return x,y24 25 X,Y=getData(100,25,10)26 print("X:",X)27 print("Y:",Y)28 29 numIterations=10000030 alpha=0.000531 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了

菜鸟之路——机器学习之非线性回归个人理解及python实现

评论关闭