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'は、MATLAB行列のように見える' np.array'(ndarray)のサブクラスです。常に2dであり、 'dot'プロダクトに' * 'を使います。あなたが本当にそれを使用する必要がない場合は、 '配列で固執してください。 'x *(1 - x)'は要素積、または行列(ドット)積による要素です。 'x'が正方形でなければ次元の問題が起こるでしょう。 – hpaulj
'matrix'は要素ごとの乗算ではなく行列乗算を使用しようとしていますか? – mgilson