2017-09-06 241 views
1

快問問傢伙!神經網絡(簡單)

開始學習機器學習有一天,偶然發現神經網絡,並在這裏有一個簡單的實現。我很好奇爲什麼我沒有輸出打印,因爲代碼沒有錯誤。

import numpy as np 


class NN(): 
    def _init_(self): 
     # Seed random number generator, so it generates the same number 
     # every time program runs 
     np.random.seed(1) 

     # Model single neuron, with 3 input connections and 1 output connection 
     # Assign random weights to a 3x1 matrix, with values in range -1 to 1 
     # and mean of 0 
     self.synaptic_weights = 2 * np.random.random((3, 1)) - 1 

    # Describes an s shaped curve we pass the weighted sum of the inputs 
    # through this function to normalise them between 0 and 1 
    def __sigmoid(self, x): 
     return 1/(1 + np.exp(-x)) 

    # Gradient of the sigmoid curve 
    def __sigmoid_derivative(self, x): 
     return x * (1 - x) 

    def train(self, training_set_input, training_set_output, number_of_training_iterations): 
     for iteration in np.xrange(number_of_training_iterations): 
      # pass training set through neural net 
      output = self.predict(training_set_input) 

      error = training_set_output - output 

      # multiply error by input and again by the gradient of the sigmoid curve 
      adjustment = np.dot(training_set_input.T, error * self.__sigmoid_derivative(output)) 

      # Adjust the weights 
      self.synaptic_weights += adjustment 

    def predict(self, inputs): 
     # Pass inputs through neural network (single neuron) 
     return self.__sigmoid(np.dot(inputs, self.synaptic_weights)) 


if __name__ == "__NN__": 
    # init single neuron neural network 
    nn = NN() 
    weightz = nn.synaptic_weights 
    new_predict = nn.predict(np.array[1, 0, 0]) 

    print("Random starting synaptic weights") 
    print(weightz) 

    # T flips the matrix vertically 
    training_set_input = np.array([0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]) 
    training_set_output = np.array([0, 1, 0, 0]).T 

    # train network using training set 
    # do it 10,000 times and make small adjustments each time 
    nn.train(training_set_input, training_set_output, 10000) 

    print("New starting synaptic weights") 
    print(weightz) 

    # test 
    print("Predicting") 
    print(new_predict) 

對不起,只是試圖找出問題所在。 保存文件爲NN.py 非常感謝!

+0

你是否聲稱沒有錯誤,但是你的'print'調用沒有工作?你是否證實'__name__'是你認爲的? –

+0

謝謝!!! :) – restores

回答

1

顯然,__name__不是等於"__NN__"。相反,它等於"__main__"

從文檔:

__name__屬性必須設置到模塊的完全限定名稱。該名稱用於唯一標識導入系統中的模塊。