LMS算法(Least mean square)

转载:https://blog.csdn.net/caimouse/article/details/60322886

LMS算法可认为是机器学习里面最基本也比较有用的算法,神经网络中对参数的学习使用的就是LMS的思想,在通信信号处理领域LMS也非常常见,比如自适应滤波器。

其它就是利用梯度下降的算法来实现的,具体推导如下:

最后这条公式,就是LMS算法的实现基础,可以使用python代码实现如下:

 

 
import numpy as np
import random
from matplotlib import pyplot as plt
# m是点的数量
def gradient descent(x, y, theta, alpha, m, numIterations):

    #矩阵转置
    xTrans = x.transpose()

    cost = None

    for i in range(0, numIterations):


        #点积

        hypothesis = np.dot(x, theta)


        #计算最小平方数
     loss = hypothesis - y        

        cost = np.sum(loss ** 2) / (2 * m)


        #print("Iteration %d | Cost: %f" % (i, cost))

        # 计算梯度

        gradient = np.dot(xTrans, loss) / m


        # 更新值

        theta = theta - alpha * gradient


    print("Iteration %d | Cost: %f" % (numIterations, cost))   

    return theta


def genData(numPoints, bias, variance):


    x = np.zeros(shape=(numPoints, 2))


    y = np.zeros(shape=numPoints)

  # 构造一条直线左右的点


    for i in range(0, numPoints):


        # 偏移

      x[i][0] = 1

    x[i][1] = i

    # 目标值


        y[i] = bias + i * variance  + random.uniform(0, 1) * 15

    return x, y


def plotModel(x, y, w):    

    plt.plot(x[:,1], y, "x")   

  plt.plot(x[:,1], [i+j  for i, j in x * w], "r-") 


    plt.show()

# 生成 100个点,截距为6, 斜率为0.8

x, y = genData(50, 6, 0.8)
#获取x矩阵的行列
m, n = np.shape(x)
#迭代次数

numIterations = 100000

#学习步伐

alpha = 0.00005

#计算回归参数

theta = np.ones(n)
print(theta)

theta = gradientDescent(x, y, theta, alpha, m, numIterations)

print(theta)

plotModel(x, y, theta)



输出结果如下:

 

从这个代码里,可以理解前面学习梯度的作用,以及梯度求解,就是最优化的方法。通过这个例子,也明白了什么叫做LMS算法,以及它的实现方法,同时也可以理解TensorFlow梯度优化器的原理,为什么需要不断对它进行迭代运行,以及更新梯度和应用梯度的过程。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值