【Python】纯代码通过神经网络实现线性回归的拟合
生活随笔
收集整理的這篇文章主要介紹了
【Python】纯代码通过神经网络实现线性回归的拟合
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
參考鏈接中的文章,有錯(cuò)誤,我給更正了。
并且原文中是需要數(shù)據(jù)集文件的,我直接給替換成了一個(gè)數(shù)組,采用直接賦值的方式。
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as pltclass SimpleDataReader(object):def __init__(self, data_file):self.train_file_name = data_fileself.num_train = 0self.XTrain = Noneself.YTrain = None# read data from filedef ReadData(self):# data = np.load(self.train_file_name)# self.XTrain = data["data"]# self.YTrain = data["label"]self.XTrain = np.array([0.95, 3, 4, 5.07, 6.03, 8.21, 8.85, 12.02, 15], dtype=float)self.YTrain = np.array([5.1, 8.7, 11.5, 13, 15.3, 18, 21, 26.87, 32.5], dtype=float)self.num_train = self.XTrain.shape[0]#end if# get batch training datadef GetSingleTrainSample(self, iteration):x = self.XTrain[iteration]y = self.YTrain[iteration]return x, ydef GetWholeTrainSamples(self):return self.XTrain, self.YTrainclass NeuralNet(object):def __init__(self, eta):self.eta = etaself.w = 0self.b = 0def __forward(self, x):z = x * self.w + self.breturn zdef __backward(self, x,y,z):dz = z - y # 原錯(cuò)誤為:dz = x * (z - y)db = dzdw = dzreturn dw, dbdef __update(self, dw, db):self.w = self.w - self.eta * dwself.b = self.b - self.eta * dbdef train(self, dataReader):for i in range(dataReader.num_train):# get x and y value for one samplex,y = dataReader.GetSingleTrainSample(i)# get z from x,yz = self.__forward(x)# calculate gradient of w and bdw, db = self.__backward(x, y, z)# update w,bself.__update(dw, db)# end fordef inference(self, x):return self.__forward(x)if __name__ == '__main__':# read datasdr = SimpleDataReader('ch04.npz')sdr.ReadData()# create neteta = 0.1net = NeuralNet(eta)net.train(sdr)# resultprint("w=%f,b=%f" %(net.w, net.b))# 繪圖部分trainX,trainY = sdr.GetWholeTrainSamples()fig = plt.figure()ax = fig.add_subplot(111)# 繪制散點(diǎn)圖ax.scatter(trainX,trainY)# 繪制線性回歸x = np.arange(0, 15, 0.01)f = np.vectorize(net.inference, excluded=['x'])plt.plot(x,f(x),color='red')# 顯示圖表plt.show()Ref:
總結(jié)
以上是生活随笔為你收集整理的【Python】纯代码通过神经网络实现线性回归的拟合的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【UAV】光流模块、测量速度、快速入门及
- 下一篇: 【UAV】气压计 SPL06