本文主要向大家介绍了机器学习入门之菜鸟之路——机器学习之非线性回归个人理解及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.930135Iteration 99989 / cost:3.930135Iteration 99990 / cost:3.930135Iteration 99991 / cost:3.930135Iteration 99992 / cost:3.930135Iteration 99993 / cost:3.930135Iteration 99994 / cost:3.930135Iteration 99995 / cost:3.930135Iteration 99996 / cost:3.930135Iteration 99997 / cost:3.930135Iteration 99998 / cost:3.930135Iteration 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是
只是创建了一个transpose方法,并没有真的给x转置。加上括号就好了。再打印xTrain就能正常显示转置后的x了
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标人工智能机器学习频道!