Python 神经网络中不需要的 [Nan] 输出

Unwanted [Nan] output in Python neural network

这里是新手。刚从 JS 切换到 Python 来构建神经网络,但从中得到 [Nan] 输出。

奇怪的是我的 sigmoid 函数。似乎没有遇到任何溢出,但衍生物导致混乱。

import numpy as np

def sigmoid(x):
  return x*(1-x)
  return 1/(1 + np.exp(-x))

#The function- 2

def Sigmoid_Derivative(x):
    return x * (1-x)

Training_inputs = np.array([[0,0,1], 
                            [1,1,1], 
                            [1,0,1], 
                            [0,1,1]])

Training_outputs = np.array([[0, 1, 1, 0]]).T

np.random.seed(1)

synaptic_weights = np.random.random((3, 1)) - 1

print ("Random starting synaptic weight:")
print (synaptic_weights)

for iteration in range(20000):
  Input_Layer = Training_inputs

  Outputs = sigmoid(np.dot(Input_Layer, synaptic_weights)) 

  erorr = Training_outputs - Outputs

  adjustments = erorr * Sigmoid_Derivative(Outputs)

  synaptic_weights += np.dot(Input_Layer.T, adjustments)

# The print declaration----------  
print ("Synaptic weights after trainig:")
print (synaptic_weights)

print ("Outputs after training: ")
print (Outputs)

这是错误信息。我不知道为什么它会溢出,因为权重似乎很小 enough.BTW 请给出简单的解决方案 python 因为我是新手 :--

Random starting synaptic weight:
[[-0.582978  ]
 [-0.27967551]
 [-0.99988563]]
/home/neel/Documents/VS-Code_Projects/Machine_Lrn(PY)/tempCodeRunnerFile.py:10: RuntimeWarning: overflow encountered in multiply
  return x * (1-x)
Synaptic weights after trainig:
[[nan]
 [nan]
 [nan]]
Outputs after training: 
[[nan]
 [nan]
 [nan]
 [nan]]

您的代码至少有 两个 个问题。

首先是在你的 sigmoid 函数中莫名其妙地使用了 2 return 语句,应该是:

def sigmoid(x):
  return 1/(1 + np.exp(-x))

x=0 (0.5) 给出了正确的结果,对于大 x:

则为 1
sigmoid(0)
# 0.5
sigmoid(20)
# 0.99999999793884631

你的(错误的)乙状结肠:

def your_sigmoid(x):
  return x*(1-x)
  return 1/(1 + np.exp(-x))

容易导致溢出:

your_sigmoid(20)
# -380

另一个问题是你的导数是错误的;应该是:

def Sigmoid_Derivative(x):
    return sigmoid(x) * (1-sigmoid(x))

参见Derivative of sigmoid function thread at Math.SE, as well as the discussion here