Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在PyTorch中绘制神经网络的决策边界_Python_Matplotlib_Neural Network_Pytorch - Fatal编程技术网

Python 在PyTorch中绘制神经网络的决策边界

Python 在PyTorch中绘制神经网络的决策边界,python,matplotlib,neural-network,pytorch,Python,Matplotlib,Neural Network,Pytorch,我一直在尝试绘制我的神经网络的决策边界,我使用输出层中的sigmoid函数进行二元分类,但没有成功,我发现许多帖子讨论了scikit学习分类器的决策边界的绘制,而不是PyTorch中构建的神经网络。 下面是我的神经网络: class NeuralNetwork(torch.nn.Module): def __init__(self): super(NeuralNetwork, self).__init__() self.fc1 = torch.nn.Linear(23, 16

我一直在尝试绘制我的神经网络的决策边界,我使用输出层中的sigmoid函数进行二元分类,但没有成功,我发现许多帖子讨论了scikit学习分类器的决策边界的绘制,而不是PyTorch中构建的神经网络。 下面是我的神经网络:

class NeuralNetwork(torch.nn.Module):
  def __init__(self):
    super(NeuralNetwork, self).__init__()
    self.fc1 = torch.nn.Linear(23, 16)
    self.fc2 = torch.nn.Linear(16, 14)
    self.fc3 = torch.nn.Linear(14, 10)
    self.fc4 = torch.nn.Linear(10, 5)
    self.fc5 = torch.nn.Linear(5, 1)

  def forward(self, x):
    x = torch.relu(self.fc1(x))
    x = torch.relu(self.fc2(x))
    x = torch.relu(self.fc3(x))
    x = torch.relu(self.fc4(x))
    x = torch.sigmoid(self.fc5(x))
    return x

model = NeuralNetwork().double()

CUDA = torch.cuda.is_available()
if CUDA:
  model.cuda()

criterion = torch.nn.BCELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(), lr=1e-2, momentum=0.9)

model_1.train()

Precision = []
Cost = []

for epoch in range(10001):

  if CUDA:
    inputs = X_train.cuda()
    label = Y_train.cuda()
  else:
    inputs = X_train
    label = Y_train

  prediction = model_1(inputs)
  loss = criterion(prediction, label)
  accuracy = ((prediction > 0.5) == label).float().mean().item()

  Cost.append(loss.item())
  Precision.append(accuracy)

  if epoch % 1000 == 0 or epoch == 30000:
    print("Epoch:", epoch, ",", "Loss:", loss.item(), ",", "Accuracy:", accuracy)

  # Backpropagation process
  optimizer.zero_grad()
  loss.backward()
  optimizer.step()

model_1.eval()

X_test = torch.from_numpy(X[27000:,:])
Y_test = torch.from_numpy(y[27000:,:]).double()

with torch.no_grad():

  y_pred = model_1(X_test)
  print("Accuracy: ", ((y_pred > 0.5) == Y_test).float().mean().item())
以下是我试图生成类似图的尝试:

但不幸的是,我得到了以下错误:

TypeError                                 Traceback (most recent call last)

<ipython-input-52-fb941749621a> in <module>()
  1 f, ax = plt.subplots(figsize=(8, 6))
  2 contour = ax.contourf(xx, yy, probs, 25, cmap="RdBu",
----> 3                       vmin=0, vmax=1)
  4 ax_c = f.colorbar(contour)
  5 ax_c.set_label("$P(y = 1)$")

5 frames

/usr/local/lib/python3.6/dist-packages/matplotlib/contour.py in _check_xyz(self, args, kwargs)
1549             raise TypeError("Input z must be a 2D array.")
1550         elif z.shape[0] < 2 or z.shape[1] < 2:
-> 1551             raise TypeError("Input z must be at least a 2x2 array.")
1552         else:
1553             Ny, Nx = z.shape

TypeError: Input z must be at least a 2x2 array.
TypeError回溯(最近一次调用)
在()
1 f,ax=plt.子批次(图尺寸=(8,6))
2轮廓=最大轮廓f(xx,yy,probs,25,cmap=“RdBu”,
---->3 vmin=0,vmax=1)
4 ax_c=f.色条(轮廓)
5 ax_c.set_标签($P(y=1)$)
5帧
/usr/local/lib/python3.6/dist-packages/matplotlib/contour.py in_check_xyz(self、args、kwargs)
1549 raise TypeError(“输入z必须是2D数组”)
1550 elif z.shape[0]<2或z.shape[1]<2:
->1551 raise TypeError(“输入z必须至少是2x2数组。”)
1552其他:
1553 Ny,Nx=z形
TypeError:输入z必须至少是2x2数组。
我将非常感谢你的帮助,提前谢谢

TypeError                                 Traceback (most recent call last)

<ipython-input-52-fb941749621a> in <module>()
  1 f, ax = plt.subplots(figsize=(8, 6))
  2 contour = ax.contourf(xx, yy, probs, 25, cmap="RdBu",
----> 3                       vmin=0, vmax=1)
  4 ax_c = f.colorbar(contour)
  5 ax_c.set_label("$P(y = 1)$")

5 frames

/usr/local/lib/python3.6/dist-packages/matplotlib/contour.py in _check_xyz(self, args, kwargs)
1549             raise TypeError("Input z must be a 2D array.")
1550         elif z.shape[0] < 2 or z.shape[1] < 2:
-> 1551             raise TypeError("Input z must be at least a 2x2 array.")
1552         else:
1553             Ny, Nx = z.shape

TypeError: Input z must be at least a 2x2 array.