我想知道是否有关于为涉及多个变量输入的分类问题找到最佳权重的最佳方法的任何建议。我目前不清楚如何在 tensorflow 或 pytorch 中使用神经网络或多元非线性回归来做到这一点。我正在尝试优化的公式如下,以便为我的数据 [x0, x1, x2, x3] 找到最佳 [w0, w1]。
y = (1 + w0 * x0 + w1 * x1) / (1 + w0 * x2 + w1 * x3)
我不清楚方法和建议会很好
要优化
pytorch
中的多个变量,您可以创建一个tensor
,长度为您拥有的变量数。确保您的tensor
通过设置autograd
启用了requires_grad = True
,Pytorch中的神经网络默认将此设置为True
,但常规张量默认将其设置为False
。然后使用张量的索引作为变量创建损失函数,并像对普通神经网络一样使用梯度下降。这是一个例子:
import torch
from torch.optim import SGD
# Initialize weights.
w = torch.randn(2, requires_grad=True)
optimizer = SGD([w], lr=0.01)
# Let's assume we have some data.
# These should be replaced with your actual data.
x0, x1, x2, x3 = torch.randn(4)
y_target = torch.randn(1)
for i in range(1000): # Number of optimization steps.
optimizer.zero_grad()
# Compute y according to the given formula.
y = (1 + w[0] * x0 + w[1] * x1) / (1 + w[0] * x2 + w[1] * x3)
# Make y the same shape as y_target
# (there will be a warning otherwise because y is a scalar)
y = y.unsqueeze(0)
# Compute the loss. Here we use mean squared error (MSE) loss.
loss = torch.nn.functional.mse_loss(y, y_target)
# Backpropagation.
loss.backward()
# Update the weights.
optimizer.step()
if i % 100 == 0: # Print loss every 100 steps.
print(f'Iteration {i}, Loss {loss.item()}')
print(f'Optimized weights: {w.data}')