1.梯度下降
梯度下降是一种优化算法,可以根据损失函数的梯度方向来调整模型的参数,从而最小化损失函数。在机器学习和深度学习中,梯度下降是一种广泛使用的方法,可以用来训练神经网络等模型。梯度下降有多种形式,包括批量梯度下降、随机梯度下降和小批量梯度下降等。
2.反向传播
反向传播是一种用于训练神经网络的算法,通过计算误差和权重梯度来更新神经网络中的权重值。简单来说,反向传播将计算误差的过程从输出层反向传播到输入层,以便对每个神经元的权重进行调整,从而提高神经网络的准确性。反向传播的理解和应用对于理解和开发神经网络至关重要,它已经成为了当今人工智能领域中最为广泛使用的算法之一。
3.计算图
计算图是用来表示计算过程的一种图形化语言,它将计算过程分解成一个个操作节点和数据节点,并将它们以图形的形式连接起来。在人工智能领域中,计算图被广泛应用于深度学习模型的训练和推理过程中。深度学习模型的计算过程可以看作是由多个神经网络层组成的计算图,在训练过程中,计算图将输入数据和模型参数作为节点,通过不断地前向传播和反向传播过程,实现模型参数的更新和优化。在推理过程中,计算图将输入数据作为节点,通过前向传播过程,得到模型的输出结果。
4.使用Numpy编程实现例题
5.使用PyTorch的Backward()编程实现例题
import torch
# prepare dataset
x_data = torch.tensor([[1.0], [2.0], [3.0]])
y_data = torch.tensor([[2.0], [4.0], [6.0]])
#design model using class
"""
our model class should be inherit from nn.Module, which is base class for all neural network modules.
member methods __init__() and forward() have to be implemented
class nn.linear contain two member Tensors: weight and bias
class nn.Linear has implemented the magic method __call__(),which enable the instance of the class can
be called just like a function.Normally the forward() will be called
"""
class LinearModel(torch.nn.Module):
def __init__(self):
super(LinearModel, self).__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
y_pred = self.linear(x)
return y_pred
model = LinearModel()
# construct loss and optimizer
# criterion = torch.nn.MSELoss(size_average = False)
criterion = torch.nn.MSELoss(reduction = 'sum')
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01) # model.parameters()
# training cycle forward, backward, update
for epoch in range(100):
y_pred = model(x_data) # forward:predict
loss = criterion(y_pred, y_data) # forward: loss
print(epoch, loss.item())
optimizer.zero_grad() # the grad computer by .backward() will be accumulated. so before backward, remember set the grad to zero
loss.backward() # backward: autograd,
optimizer.step() # update
print('w = ', model.linear.weight.item())
print('b = ', model.linear.bias.item())
x_test = torch.tensor([[4.0]])
y_test = model(x_test)
print('y_pred = ', y_test.data)