# 梯度下降算法以及其Python实现

 1 2 import numpy as np from numpy import genfromtxt

 1 2 dataPath = r“E:learninghouse.csv” dataSet = genfromtxt(dataPath, delimiter=‘,’)

 1 2 3 4 5 6 def getData(dataSet):     m, n = np.shape(dataSet)     trainData = np.ones((m, n))     trainData[:,:–1] = dataSet[:,:–1]     trainLabel = dataSet[:,–1]     return trainData, trainLabel

 1 2 3 4 5 6 7 8 def batchGradientDescent(x, y, theta, alpha, m, maxIterations):     xTrains = x.transpose()     for i in range(0, maxIterations):         hypothesis = np.dot(x, theta)         loss = hypothesis – y         gradient = np.dot(xTrains, loss) / m         theta = theta – alpha * gradient     return theta

x为自变量训练集，y为自变量对应的因变量训练集；theta为待求解的权重值，需要事先进行初始化；alpha是学习率；m为样本总数；maxIterations为最大迭代次数；

 1 2 3 4 5 trainData, trainLabel = getData(dataSet) m, n = np.shape(trainData) theta = np.ones(n) alpha = 0.05 maxIteration = 1000

 1 theta = batchGradientDescent(trainData, trainLabel, theta, alpha, m, maxIteration)

 1 2 3 4 5 6 def predict(x, theta):     m, n = np.shape(x)     xTest = np.ones((m, n+1))     xTest[:, :–1] = x     yPre = np.dot(xTest, theta)     return yPre

x为待预测值的自变量，thta为已经求解出的权重值，yPre为预测结果

 1 2 x = np.array([[3.1, 5.5], [3.3, 5.9], [3.5, 6.3], [3.7, 6.7], [3.9, 7.1]]) print predict(x, theta)

 1 [9.49608552  10.19523475  10.89438398  11.59353321  12.29268244]

 1 [ 9.49997917  10.19997464  10.89997012  11.59996559  12.29996106]

 1 [ 9.5  10.2  10.9  11.6  12.3]

1.权重的更新低于某个阈值；
2.预测的错误率低于某个阈值；
3.达到预设的最大循环次数；

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 #coding=utf-8   import numpy as np import random from numpy import genfromtxt   def getData(dataSet):     m, n = np.shape(dataSet)     trainData = np.ones((m, n))     trainData[:,:–1] = dataSet[:,:–1]     trainLabel = dataSet[:,–1]     return trainData, trainLabel   def batchGradientDescent(x, y, theta, alpha, m, maxIterations):     xTrains = x.transpose()     for i in range(0, maxIterations):         hypothesis = np.dot(x, theta)         loss = hypothesis – y         # print loss         gradient = np.dot(xTrains, loss) / m         theta = theta – alpha * gradient     return theta   def predict(x, theta):     m, n = np.shape(x)     xTest = np.ones((m, n+1))     xTest[:, :–1] = x     yP = np.dot(xTest, theta)     return yP   dataPath = r“E:learninghouse.csv” dataSet = genfromtxt(dataPath, delimiter=‘,’) trainData, trainLabel = getData(dataSet) m, n = np.shape(trainData) theta = np.ones(n) alpha = 0.1 maxIteration = 5000 theta = batchGradientDescent(trainData, trainLabel, theta, alpha, m, maxIteration) x = np.array([[3.1, 5.5], [3.3, 5.9], [3.5, 6.3], [3.7, 6.7], [3.9, 7.1]]) print predict(x, theta)