Pytorch学习笔记之通过numpy实现线性拟合

通过使用numpy库编写简单的Gradient Descent数据位于附件之中

import torch
from torch import autograd
import numpy as np
import matplotlib.pyplot as plt
'''torch关于求导的简单运用'''
# x = torch.tensor(1.)
# a = torch.tensor(1.,requires_grad=True)
# b = torch.tensor(2.,requires_grad=True)
# c = torch.tensor(3.,requires_grad=True)
#
# y = a**2*x + b*x + c
#
# print('before',a.grad,b.grad,c.grad)
# grads = autograd.grad(y,[a,b,c])
# print('after',grads[0],grads[1],grads[2])
"""函数名:Loss_Function(损失函数)  """        #首先明确此次通过偏导想求拟合的直线方程为y = w*x + b
"""参数名:b:拟合曲线的biase(偏移量)"""
"""      w:拟合曲线x的系数          """
"""      points:待拟合数据         """
"""返回值:返回值为平方损失函数的均值   """
def Loss_Function(b,w,points):
    Totle_value = 0
    for i in range(len(points)):            #通过for循环达到求解对应b,w下的损失函数的值的目的
        x = points[i,0]
        y = points[i,1]
        Totle_value += ((w*x + b) - y)**2   #损失之的求解,其中w*x + b为预测值,y为真实值,计算在当前w,b下每个预测值偏离实际值之和
                                            #平方损失函数
    return Totle_value/float(len(points))

"""函数名:Grad_Function(梯度函数)         """
"""参数名:b_current:拟合曲线的biase(偏移量)"""
"""      w_current:拟合曲线x的系数          """
"""      points:待拟合数据                 """
"""      learning_rate:学习率             """
"""返回值:当前b,w值下update后新的b,w值      """
def Grad_Function(b_current,w_current,learning_rate,points):   #本次函数中用到的是普通的Gradient Descent(梯度下降)
                                                               #所以对应的公式为w = w - *learningrate
    b_gradent = 0                            #设定当前梯度为0
    w_gradent = 0
    N = float(len(points))                   #确定数据个数
    for i in range(0,len(points)):
        x = points[i,0]
        y = points[i,1]
        b_gradent += -(2/N)*(y - (w_current*x + b_current))       #求解b方向上梯度值,即loss函数对b的偏导值
        w_gradent += -(2/N)*x*(y - (w_gradent*x + b_current))     #求解w方向上梯度值,即loss函数对w的偏导值
    new_b = b_current - b_gradent*learning_rate                 #求解update之后的b的值
    new_w = w_current - w_gradent*learning_rate                 #求解update之后的b的值
    return [new_b,new_w]


"""函数名:Loop_Grad(梯度函数循环函数)         """
"""参数名:b_start:拟合曲线的biase(偏移量)    """
"""      w_start:拟合曲线x的系数              """
"""      points:待拟合数据                   """
"""      learning_rate:学习率               """
"""      num_interation:步进次数             """
"""返回值:num_iteration次之后的b和w值          """

def Loop_Grad(points,b_start,w_start,learning_rate,num_iteration):
    b = b_start
    w = w_start
    x = range(-100,100,1)
    for i in range(0,num_iteration):
        b,w = Grad_Function(b,w,learning_rate,np.array(points))
        print(b,w)
    y = w * x + b
    plt.plot(x, y)
    plt.show()
    return [b,w]

"""函数名:Run          """
"""函数功能:实现步进求解 """
def Run():
    points = np.genfromtxt("D:\DataData\Pytorch\Pytorch_learn_by_dragen1860\datasets\l3_data.csv",delimiter=",")
    learning_rate = 0.01
    init_b = 3
    init_w = 4
    num_iteration = 100
    print('Running...')
    [b,w] = Loop_Grad(points/100,init_b,init_w,learning_rate,num_iteration)
    # print("b",b)
    print("After {0} iterations b = {1},w = {2},error = {3}".
            format(num_iteration,b,w,Loss_Function(b,w,points/100)))


if __name__ == '__main__':
    Run()

 

本此使用的是简单的梯度下降的方法求拟合曲线,所以一共通过三个函数实现功能,首先第一个是损失函数Loss_function,第二个需要的函数为梯度下降求解函数,第三个函数为梯度步进函数,梯度步进的函数主要是通过对梯度下降函数的循环来达到求得最佳解。

本次学习过程中遇到的问题,在进行梯度计算时,update两次之后发生数据溢出现象,但是并未找到处理方式,因此采取最简单的方法,将所有数据全部缩小100倍处理,若有大佬看出哪里有问题请指出,先说一声谢谢。

附件为数据集https://download.csdn.net/download/qq_42191909/12986863

你可能感兴趣的:(pytorch,深度学习,pytorch)