2017-09-06 245 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__属性必须设置到模块的完全限定名称。该名称用于唯一标识导入系统中的模块。