1
from numpy import exp, array, random, dot, matrix, asarray
class NeuralNetwork():
def __init__(self):
random.seed(1)
self.synaptic_weights = 2 * random.random((3, 1)) - 1 # init weight from -1 to 1
def __sigmoid(self, x):
return 1/(1 + exp(-x))
def __sigmoid_derivative(self, x):
return x * (1 - x)
def train(self, train_input, train_output, iter):
for i in range(iter):
output = self.think(train_input)
error = train_output - output
adjustment = dot(train_input.T, error * self.__sigmoid_derivative(output))
self.synaptic_weights += adjustment
def think(self, inputs):
return self.__sigmoid(dot(inputs, self.synaptic_weights))
neural_network = NeuralNetwork()
train = matrix([[0, 0, 1, 0],[1, 1, 1, 1],[1, 0, 1, 1],[0, 1, 1, 0]])
train_input = asarray(train[:, 0:3])
train_output = asarray(train[:,3])
neural_network.train(train_input, train_output, 10000)
该代码是一个基本的神经网络。当我使用asarray
转换训练集时它运行良好,但它不起作用矩阵本身。这似乎矩阵不能计算sigmoid_derivative和终端显示ValueError: shapes (4,1) and (4,1) not aligned: 1 (dim 1) != 4 (dim 0)
计算工作在numpy的阵列而不是在numpy的矩阵
为什么矩阵没有在代码工作?
'np.matrix'是'np.array'(ndarray)的一个子类,看起来有点像MATLAB矩阵。它始终是2d,并使用'*'作为'dot'产品。如果你真的不需要使用它,坚持'数组。 x *(1-x)是元素乘积还是矩阵(点)乘积。除非'x'是正方形,否则会产生尺寸问题。 – hpaulj
因为'矩阵'会尝试使用矩阵乘法而不是元素乘法? – mgilson