脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 初学者指南:使用Numpy、Keras和PyTorch实现简单的线性回归

初学者指南:使用Numpy、Keras和PyTorch实现简单的线性回归

2021-11-09 20:49deephub Python

机器学习是人工智能的一门子科学,其中计算机和机器通常学会在没有人工干预或显式编程的情况下自行执行特定任务(当然,首先要对他们进行训练)。

初学者指南:使用Numpy、Keras和PyTorch实现简单的线性回归

不同类型的机器学习技术可以划分到不同类别,如图 1 所示。方法的选择取决于问题的类型(分类、回归、聚类)、数据的类型(图像、图形、时间系列、音频等等)以及方法本身的配置(调优)。

初学者指南:使用Numpy、Keras和PyTorch实现简单的线性回归

在本文中,我们将使用 Python 中最著名的三个模块来实现一个简单的线性回归模型。 使用 Python 的原因是它易于学习和应用。 我们将使用的三个模块是:

1- Numpy:可以用于数组、矩阵、多维矩阵以及与它们相关的所有操作。

2- Keras:TensorFlow 的高级接口。 它也用于支持和实现深度学习模型和浅层模型。 它是由谷歌工程师开发的。

3- PyTorch:基于 Torch 的深度学习框架。 它是由 Facebook 开发的。

所有这些模块都是开源的。 Keras 和 PyTorch 都支持使用 GPU 来加快执行速度。

以下部分介绍线性回归的理论和概念。 如果您已经熟悉理论并且想要实践部分,可以跳过到下一部分。

线性回归

它是一种数学方法,可以将一条线与基础数据拟合。 它假设输出和输入之间存在线性关系。 输入称为特征或解释变量,输出称为目标或因变量。 输出变量必须是连续的。 例如,价格、速度、距离和温度。 以下等式在数学上表示线性回归模型:

Y = W*X + B

如果把这个方程写成矩阵形式。 Y 是输出矩阵,X 是输入矩阵,W 是权重矩阵,B 是偏置向量。 权重和偏置是线性回归参数。 有时权重和偏置分别称为斜率和截距。

训练该模型的第一步是随机初始化这些参数。 然后它使用输入的数据来计算输出。 通过测量误差将计算出的输出与实际输出进行比较,并相应地更新参数。并重复上述步骤。该误差称为 L2 范数(误差平方和),由下式给出:

初学者指南:使用Numpy、Keras和PyTorch实现简单的线性回归

计算误差的函数又被称作损失函数,它可以有不同的公式。 i 是数据样本数,y 是预测输出,t 是真实目标。 根据以下等式中给出的梯度下降规则更新参数:

初学者指南:使用Numpy、Keras和PyTorch实现简单的线性回归
初学者指南:使用Numpy、Keras和PyTorch实现简单的线性回归

在这里,(希腊字母 eta)是学习率,它指定参数的更新步骤(更新速度)。 (希腊字母 delta)只是预测输出和真实输出之间的差异。 i 代表迭代(所谓的轮次)。 L(W) 是损失函数相对于权重的梯度(导数)。 关于学习率的价值,有一点值得一提。 较小的值会导致训练速度变慢,而较大的值会导致围绕局部最小值或发散(无法达到损失函数的局部最小值)的振荡。 图 2 总结了以上所有内容。

初学者指南:使用Numpy、Keras和PyTorch实现简单的线性回归

现在让我们深入了解每个模块并将上面的方法实现。

Numpy 实现

我们将使用 Google Colab 作为我们的 IDE(集成开发环境),因为它功能强大,提供了所有必需的模块,无需安装(部分模块除外),并且可以免费使用。

为了简化实现,我们将考虑具有单个特征和偏置 (y = w1*x1 + b) 的线性关系。

让我们首先导入 Numpy 模块来实现线性回归模型和 Matplotlib 进行可视化。

  1. #Numpyisneededtobuildthemodel
  2. importnumpyasnp
  3. #Importthemodulematplotlibforvisualizingthedata
  4. importmatplotlib.pyplotasplt

我们需要一些数据来处理。 数据由一个特征和一个输出组成。 对于特征生成,我们将从随机均匀分布中生成 1000 个样本。

  1. #Weusethislinetomakethecodereproducible(togetthesameresultswhenrunning)
  2. np.random.seed(42)
  3. #First,weshoulddeclareavariablecontainingthesizeofthetrainingsetwewanttogenerate
  4. observations=1000
  5. #Letusassumewehavethefollowingrelationship
  6. #y=13x+2
  7. #yistheoutputandxistheinputorfeature
  8. #Wegeneratethefeaturerandomly,drawingfromanuniformdistribution.Thereare3argumentsofthismethod(low,high,size).
  9. #Thesizeofxisobservationsby1.Inthiscase:1000x1.
  10. x=np.random.uniform(low=-10,high=10,size=(observations,1))
  11. #Letusprinttheshapeofthefeaturevector
  12. print(x.shape)

为了生成输出(目标),我们将使用以下关系:

  1. Y=13*X+2+噪声

这就是我们将尝试使用线性回归模型来估计的。 权重值为 13,偏置为 2。噪声变量用于添加一些随机性。

  1. np.random.seed(42)
  2. #Weaddasmallnoisetoourfunctionformorerandomness
  3. noise=np.random.uniform(-1,1,(observations,1))
  4. #Producethetargetsaccordingtothef(x)=13x+2+noisedefinition.
  5. #Thisisasimplelinearrelationshipwithoneweightandbias.
  6. #Inthisway,wearebasicallysaying:theweightis13andthebiasis2.
  7. targets=13*x+2+noise
  8. #Checktheshapeofthetargetsjustincase.Itshouldbenxm,wherenisthenumberofsamples
  9. #andmisthenumberofoutputvariables,so1000x1.
  10. print(targets.shape)

让我们绘制生成的数据。

  1. #Plotxandtargets
  2. plt.plot(x,targets)
  3. #Addlabelstoxaxisandyaxis
  4. plt.ylabel('Targets')
  5. plt.xlabel('Input')
  6. #Addtitletothegraph
  7. plt.title('Data')
  8. #Showtheplot
  9. plt.show()

图 3 显示了这种线性关系:

初学者指南:使用Numpy、Keras和PyTorch实现简单的线性回归

对于模型训练,我们将从参数的一些初始值开始。 它们是从给定范围内的随机均匀分布生成的。 您可以看到这些值与真实值相差甚远。

  1. np.random.seed(42)
  2. #Wewillinitializetheweightsandbiasesrandomlywithinasmallinitialrange.
  3. #init_rangeisthevariablethatwillmeasurethat.
  4. init_range=0.1
  5. #Weightsareofsizekxm,wherekisthenumberofinputvariablesandmisthenumberofoutputvariables
  6. #Inourcase,theweightsmatrixis1x1,sincethereisonlyoneinput(x)andoneoutput(y)
  7. weights=np.random.uniform(low=-init_range,high=init_range,size=(1,1))
  8. #Biasesareofsize1sincethereisonly1output.Thebiasisascalar.
  9. biases=np.random.uniform(low=-init_range,high=init_range,size=1)
  10. #Printtheweightstogetasenseofhowtheywereinitialized.
  11. #Youcanseethattheyarefarfromtheactualvalues.
  12. print(weights)
  13. print(biases)
  14. [[-0.02509198]]
  15. [0.09014286]

我们还为我们的训练设置了学习率。 我们选择了 0.02 的值。 这里可以通过尝试不同的值来探索性能。 我们有了数据,初始化了参数,并设置了学习率,已准备好开始训练过程。 我们通过将 epochs 设置为 100 来迭代数据。在每个 epoch 中,我们使用初始参数来计算新输出并将它们与实际输出进行比较。 损失函数用于根据前面提到的梯度下降规则更新参数。 新更新的参数用于下一次迭代。 这个过程会不断重复,直到达到 epoch 数。 可以有其他停止训练的标准,但我们今天不讨论它。

  1. #Setsomesmalllearningrate
  2. #0.02isgoingtoworkquitewellforourexample.Onceagain,youcanplayaroundwithit.
  3. #ItisHIGHLYrecommendedthatyouplayaroundwithit.
  4. learning_rate=0.02
  5. #Weiterateoverourtrainingdataset100times.Thatworkswellwithalearningrateof0.02.
  6. #Wecalltheseiterationepochs.
  7. #Letusdefineavariabletostorethelossofeachepoch.
  8. losses=[]
  9. foriinrange(100):
  10. #Thisisthelinearmodel:y=xw+bequation
  11. outputs=np.dot(x,weights)+biases
  12. #Thedeltasarethedifferencesbetweentheoutputsandthetargets
  13. #Notethatdeltashereisavector1000x1
  14. deltas=outputs-targets
  15. #WeareconsideringtheL2-normlossasourlossfunction(regressionproblem),butdividedby2.
  16. #Moreover,wefurtherdivideitbythenumberofobservationstotakethemeanoftheL2-norm.
  17. loss=np.sum(deltas**2)/2/observations
  18. #Weprintthelossfunctionvalueateachstepsowecanobservewhetheritisdecreasingasdesired.
  19. print(loss)
  20. #Addthelosstothelist
  21. losses.append(loss)
  22. #Anothersmalltrickistoscalethedeltasthesamewayasthelossfunction
  23. #Inthiswayourlearningrateisindependentofthenumberofsamples(observations).
  24. #Again,thisdoesn'tchangeanythinginprinciple,itsimplymakesiteasiertopickasinglelearningrate
  25. #thatcanremainthesameifwechangethenumberoftrainingsamples(observations).
  26. deltas_scaled=deltas/observations
  27. #Finally,wemustapplythegradientdescentupdaterules.
  28. #Theweightsare1x1,learningrateis1x1(scalar),inputsare1000x1,anddeltas_scaledare1000x1
  29. #Wemusttransposetheinputssothatwegetanallowedoperation.
  30. weights=weights-learning_rate*np.dot(x.T,deltas_scaled)
  31. biases=biases-learning_rate*np.sum(deltas_scaled)
  32. #Theweightsareupdatedinalinearalgebraicway(amatrixminusanothermatrix)
  33. #Thebiases,however,arejustasinglenumberhere,sowemusttransformthedeltasintoascalar.
  34. #Thetwolinesarebothconsistentwiththegradientdescentmethodology.

我们可以观察每个轮次的训练损失。

  1. #Plotepochsandlosses
  2. plt.plot(range(100),losses)
  3. #Addlabelstoxaxisandyaxis
  4. plt.ylabel('loss')
  5. plt.xlabel('epoch')
  6. #Addtitletothegraph
  7. plt.title('Training')
  8. #Showtheplot
  9. #Thecurveisdecreasingineachepoch,whichiswhatweneed
  10. #Afterseveralepochs,wecanseethatthecurveisflattened.
  11. #Thismeansthealgorithmhasconvergedandhencetherearenosignificantupdates
  12. #orchangesintheweightsorbiases.
  13. plt.show()

正如我们从图 4 中看到的,损失在每个 epoch 中都在减少。 这意味着模型越来越接近参数的真实值。 几个 epoch 后,损失没有显着变化。 这意味着模型已经收敛并且参数不再更新(或者更新非常小)。

初学者指南:使用Numpy、Keras和PyTorch实现简单的线性回归

此外,我们可以通过绘制实际输出和预测输出来验证我们的模型在找到真实关系方面的指标。

  1. #Weprinttherealandpredictedtargetsinordertoseeiftheyhavealinearrelationship.
  2. #Thereisalmostatotalmatchbetweentherealtargetsandpredictedtargets.
  3. #Thisisagoodsignalofthesuccessofourmachinelearningmodel.
  4. plt.plot(outputs,targets,'bo')
  5. plt.xlabel('Predicted')
  6. plt.ylabel('Real')
  7. plt.show()
  8. #Weprinttheweightsandthebiases,sowecanseeiftheyhaveconvergedtowhatwewanted.
  9. #Weknowthattherealweightis13andthebiasis2
  10. print(weights,biases)

这将生成如图 5 所示的图形。我们甚至可以打印最后一个 epoch 之后的参数值。 显然,更新后的参数与实际参数非常接近。

  1. [[13.09844702]][1.73587336]
初学者指南:使用Numpy、Keras和PyTorch实现简单的线性回归

Numpy 实现线性回归模型就是这样。

Keras 实现

我们首先导入必要的模块。 TensorFlow 是这个实现的核心。 它是构建模型所必需的。 Keras 是 TensorFlow 的抽象,以便于使用。

  1. #Numpyisneededtogeneratethedata
  2. importnumpyasnp
  3. #Matplotlibisneededforvisualization
  4. importmatplotlib.pyplotasplt
  5. #TensorFlowisneededformodelbuild
  6. importtensorflowastf

为了生成数据(特征和目标),我们使用了 Numpy 中生成数据的代码。 我们添加了一行来将 Numpy 数组保存在一个文件中,以防我们想将它们与其他模型一起使用(可能不需要,但添加它不会有什么坏处)。

  1. np.savez('TF_intro',inputs=x,targets=targets)

Keras 有一个 Sequential 的类。 它用于堆叠创建模型的层。 由于我们只有一个特征和输出,因此我们将只有一个称为密集层的层。 这一层负责线性变换 (W*X +B),这是我们想要的模型。 该层有一个称为神经元的计算单元用于输出计算,因为它是一个回归模型。 对于内核(权重)和偏置初始化,我们在给定范围内应用了均匀随机分布(与 Numpy 中相同,但是在层内指定)。

  1. #Declareavariablewherewewillstoretheinputsizeofourmodel
  2. #Itshouldbeequaltothenumberofvariablesyouhave
  3. input_size=1
  4. #Declaretheoutputsizeofthemodel
  5. #Itshouldbeequaltothenumberofoutputsyou'vegot(forregressionsthat'susually1)
  6. output_size=1
  7. #Outlinethemodel
  8. #Welayoutthemodelin'Sequential'
  9. #Notethattherearenocalculationsinvolved-wearejustdescribingournetwork
  10. model=tf.keras.Sequential([
  11. #Each'layer'islistedhere
  12. #Themethod'Dense'indicates,ourmathematicaloperationtobe(xw+b)
  13. tf.keras.layers.Input(shape=(input_size,)),
  14. tf.keras.layers.Dense(output_size,
  15. #thereareextraargumentsyoucanincludetocustomizeyourmodel
  16. #inourcasewearejusttryingtocreateasolutionthatis
  17. #ascloseaspossibletoourNumPymodel
  18. #kernelhereisjustanothernamefortheweightparameter
  19. kernel_initializer=tf.random_uniform_initializer(minval=-0.1,maxval=0.1),
  20. bias_initializer=tf.random_uniform_initializer(minval=-0.1,maxval=0.1)
  21. )
  22. ])
  23. #Printthestructureofthemodel
  24. model.summary()

为了训练模型,keras提供 fit 的方法可以完成这项工作。 因此,我们首先加载数据,指定特征和标签,并设置轮次。 在训练模型之前,我们通过选择合适的优化器和损失函数来配置模型。 这就是 compile 的作用。 我们使用了学习率为 0.02(与之前相同)的随机梯度下降,损失是均方误差。

  1. #LoadthetrainingdatafromtheNPZ
  2. training_data=np.load('TF_intro.npz')
  3. #Wecanalsodefineacustomoptimizer,wherewecanspecifythelearningrate
  4. custom_optimizer=tf.keras.optimizers.SGD(learning_rate=0.02)
  5. #'compile'istheplacewhereyouselectandindicatetheoptimizersandtheloss
  6. #Ourlosshereisthemeansquareerror
  7. model.compile(optimizer=custom_optimizer,loss='mse')
  8. #finallywefitthemodel,indicatingtheinputsandtargets
  9. #iftheyarenototherwisespecifiedthenumberofepochswillbe1(asingleepochoftraining),
  10. #sothenumberofepochsis'kindof'mandatory,too
  11. #wecanplayaroundwithverbose;wepreferverbose=2
  12. model.fit(training_data['inputs'],training_data['targets'],epochs=100,verbose=2)

我们可以在训练期间监控每个 epoch 的损失,看看是否一切正常。 训练完成后,我们可以打印模型的参数。 显然,模型已经收敛了与实际值非常接近的参数值。

  1. #Extractingtheweightsandbiasesisachievedquiteeasily
  2. model.layers[0].get_weights()
  3. #Wecansavetheweightsandbiasesinseparatevariablesforeasierexamination
  4. #Notethattherecanbehundredsorthousandsofthem!
  5. weights=model.layers[0].get_weights()[0]
  6. bias=model.layers[0].get_weights()[1]
  7. bias,weights
  8. (array([1.9999999],dtype=float32),array([[13.1]],dtype=float32))

当您构建具有数千个参数和不同层的复杂模型时,TensorFlow 可以为您节省大量精力和代码行。 由于模型太简单,这里并没有显示keras的优势。

PyTorch 实现

我们导入 Torch。这是必须的,因为它将用于创建模型。

  1. #Numpyisneededfordatageneration
  2. importnumpyasnp
  3. #Pytorchisneededformodelbuild
  4. importtorch

数据生成部分未显示,因为它与前面使用的代码相同。 但是Torch 只处理张量(torch.Tensor)。所以需要将特征和目标数组都转换为张量。 最后,从这两个张量创建一个张量数据集。

  1. #TensorDatasetisneededtopreparethetrainingdatainformoftensors
  2. fromtorch.utils.dataimportTensorDataset
  3. #TorunthemodeloneithertheCPUorGPU(ifavailable)
  4. device='cuda'iftorch.cuda.is_available()else'cpu'
  5. #Sincetorchdealswithtensors,weconvertthenumpyarraysintotorchtensors
  6. x_tensor=torch.from_numpy(x).float()
  7. y_tensor=torch.from_numpy(targets).float()
  8. #Combinethefeaturetensorandtargettensorintotorchdataset
  9. train_data=TensorDataset(x_tensor,y_tensor)

模型的创建很简单。 与keras类似,Sequential 类用于创建层堆栈。 我们只有一个线性层(keras叫密集层),一个输入和一个输出。 模型的参数使用定义的函数随机初始化。 为了配置模型,我们设置了学习率、损失函数和优化器。 还有其他参数需要设置,这里不做介绍。

  1. #Initializetheseedtomakethecodereproducible
  2. torch.manual_seed(42)
  3. #Thisfunctionisformodel'sparametersinitialization
  4. definit_weights(m):
  5. ifisinstance(m,torch.nn.Linear):
  6. torch.nn.init.uniform_(m.weight,a=-0.1,b=0.1)
  7. torch.nn.init.uniform_(m.bias,a=-0.1,b=0.1)
  8. #DefinethemodelusingSequentialclass
  9. #Itcontainsonlyasinglelinearlayerwithoneinputandoneoutput
  10. model=torch.nn.Sequential(torch.nn.Linear(1,1)).to(device)
  11. #Initializethemodel'sparametersusingthedefinedfunctionfromabove
  12. model.apply(init_weights)
  13. #Printthemodel'sparameters
  14. print(model.state_dict())
  15. #Specifythelearningrate
  16. lr=0.02
  17. #Thelossfunctionisthemeansquarederror
  18. loss_fn=torch.nn.MSELoss(reduction='mean')
  19. #Theoptimizeristhestochasticgradientdescentwithacertainlearningrate
  20. optimizer=torch.optim.SGD(model.parameters(),lr=lr)

我们将使用小批量梯度下降训练模型。 DataLoader 负责从训练数据集创建批次。 训练类似于keras的实现,但使用不同的语法。 关于 Torch训练有几点补充:

1- 模型和批次必须在同一设备(CPU 或 GPU)上。

2- 模型必须设置为训练模式。

3- 始终记住在每个 epoch 之后将梯度归零以防止累积(对 epoch 的梯度求和),这会导致错误的值。

  1. #DataLoaderisneededfordatabatching
  2. fromtorch.utils.dataimportDataLoader
  3. #Trainingdatasetisconvertedintobatchesofsize16sampleseach.
  4. #Shufflingisenabledforrandomizingthedata
  5. train_loader=DataLoader(train_data,batch_size=16,shuffle=True)
  6. #Afunctionfortrainingthemodel
  7. #Itisafunctionofafunction(Howfancy)
  8. defmake_train_step(model,optimizer,loss_fn):
  9. deftrain_step(x,y):
  10. #Setthemodeltotrainingmode
  11. model.train()
  12. #Feedforwardthemodelwiththedata(features)toobtainthepredictions
  13. yhat=model(x)
  14. #Calculatethelossbasedonthepredictedandactualtargets
  15. loss=loss_fn(y,yhat)
  16. #Performthebackpropagationtofindthegradients
  17. loss.backward()
  18. #Updatetheparameterswiththecalculatedgradients
  19. optimizer.step()
  20. #Setthegradientstozerotopreventaccumulation
  21. optimizer.zero_grad()
  22. returnloss.item()
  23. returntrain_step
  24. #Callthetrainingfunction
  25. train_step=make_train_step(model,optimizer,loss_fn)
  26. #Tostorethelossofeachepoch
  27. losses=[]
  28. #Settheepochsto100
  29. epochs=100
  30. #Runthetrainingfunctionineachepochonthebatchesofthedata
  31. #Thisiswhywehavetwoforloops
  32. #Outerloopforepochs
  33. #Innerloopforiteratingthroughthetrainingdatabatches
  34. forepochinrange(epochs):
  35. #Toaccumulatethelossesofallbatcheswithinasingleepoch
  36. batch_loss=0
  37. forx_batch,y_batchintrain_loader:
  38. x_batch=x_batch.to(device)
  39. y_batch=y_batch.to(device)
  40. loss=train_step(x_batch,y_batch)
  41. batch_loss=batch_loss+loss
  42. #63isnotamagicnumber.Itisthenumberofbatchesinthetrainingset
  43. #wehave1000samplesandthebatchsizeis16(definedintheDataLoader)
  44. #1000/16=63
  45. epoch_loss=batch_loss/63
  46. losses.append(epoch_loss)
  47. #Printtheparametersafterthetrainingisdone
  48. print(model.state_dict())
  49. OrderedDict([('0.weight',tensor([[13.0287]],device='cuda:0')),('0.bias',tensor([2.0096],device='cuda:0'))])

作为最后一步,我们可以绘制 epoch 上的训练损失以观察模型的性能。 如图 6 所示。

初学者指南:使用Numpy、Keras和PyTorch实现简单的线性回归

完成。 让我们总结一下到目前为止我们学到的东西。

总结

线性回归被认为是最容易实现和解释的机器学习模型之一。 在本文中,我们使用 Python 中的三个不同的流行模块实现了线性回归。 还有其他模块可用于创建。 例如,Scikitlearn。

原文链接:https://www.toutiao.com/a7028008744260780558/

延伸 · 阅读

精彩推荐