neuroph簡単なセンサテスト

3264 ワード

これはセンサがANDルールを学ぶ例で、NEUのSampleから写したものです.
まずTrainingSetを定義し、2つのパラメータはそれぞれ入力ベクトルSIZEと出力ベクトルSIZEを表し、コードを見る.

 /**
         * Creates an instance of new empty training set
         * 
         * @param inputVectorSize
         * @param outputVectorSize
         */
        public TrainingSet(int inputVectorSize, int outputVectorSize) {
		this.elements = new Vector<TrainingElement>();
                this.inputVectorSize = inputVectorSize;
                this.outputVectorSize = outputVectorSize;
	}


次に、入力レイヤのメタ数と出力のメタ数を表すセンサを定義します.コード:

/**
	 * Creates new Perceptron with specified number of neurons in input and
	 * output layer, with Step trqansfer function
	 * 
	 * @param inputNeuronsCount
	 *            number of neurons in input layer
	 * @param outputNeuronsCount
	 *            number of neurons in output layer
	 */
	public Perceptron(int inputNeuronsCount, int outputNeuronsCount) {
		this.createNetwork(inputNeuronsCount, outputNeuronsCount, TransferFunctionType.STEP);
	}

次に、現在のスレッドで学習プロセスを開始します.非同期で実行する必要がある場合、learnInNewThreadは需要を満たすために提供される.
トレーニングネットワーク
出力を確認します.


public void testPerceptron() {
        TrainingSet trainingSet = new TrainingSet(2, 1);
        trainingSet.addElement(new SupervisedTrainingElement(new double[]{0, 0}, new double[]{0}));
        trainingSet.addElement(new SupervisedTrainingElement(new double[]{0, 1}, new double[]{0}));
        trainingSet.addElement(new SupervisedTrainingElement(new double[]{1, 0}, new double[]{0}));
        trainingSet.addElement(new SupervisedTrainingElement(new double[]{1, 1}, new double[]{1}));

        NeuralNetwork myPerceptron = new Perceptron(2, 1);
        myPerceptron.learnInSameThread(trainingSet);
        System.out.println("Testing trained perceptron");
        neuralNetwork(myPerceptron, trainingSet);
        myPerceptron.save("mySamplePerceptron.nnet");
        
        
        NeuralNetwork loadedPerceptron = NeuralNetwork.load("mySamplePerceptron.nnet");
        System.out.println("Testing loaded perceptron");
        neuralNetwork(loadedPerceptron, trainingSet);
	}
	
	
	
	private void neuralNetwork(NeuralNetwork neuralNet, TrainingSet trainingSet) {
	
	    for(TrainingElement trainingElement : trainingSet.trainingElements()) {
	        neuralNet.setInput(trainingElement.getInput());
	        neuralNet.calculate();
	        Vector<Double> networkOutput = neuralNet.getOutput();
	
	        double d1 = trainingElement.getInput().get(0);
	        double d2 = trainingElement.getInput().get(1);
	        
	        double result = networkOutput.get(0);
	        
	        boolean b1 = d1 == 1.0;
	        boolean b2 = d2 == 1.0;
	        
	        boolean r1 = result == 1.0;
	        
	        assertEquals(b1 & b2, r1);
	    }
	}