Trains the classifier with the given instance.

@param instance    the new training instance to include in the model
518775
@Override
    public void trainOnInstanceImpl(Instance instance) {

        if (m_weights == null) {
            m_weights = new DoubleVector();
            m_velocity = new DoubleVector();
            m_bias = 0;

            m_weights.setValue(instance.numAttributes(), 0);
            m_velocity.setValue(instance.numAttributes(), 0);
        }

        if (instance.classIsMissing()) {
            return;
        }
   
        double z = dotProd(instance, m_weights, instance.classIndex()) + m_bias;

        double y;
        double dldz;

        if (instance.classAttribute().isNominal()) {
            y = (instance.classValue() == 0) ? 0 : 1;
            
            if (m_loss == LOGLOSS) {
                double yhat = 1.0 / (1.0 + Math.exp(-z));
                dldz = (yhat - y);
            }
            else {
                y = y * 2 - 1;
                
                if(y * z < 1.0)
                {
                    dldz = -y;
                }
                else
                {
                    dldz = 0;
                }
            }
        }
        else {
            y = instance.classValue();
            dldz = z - y;
        }

        int n = instance.numValues();
        DoubleVector gradients = new DoubleVector();
        gradients.setValue(instance.numAttributes(), 0);

        for(int i = 0; i < n; i++)
        {
            int idx = instance.index(i);
            gradients.setValue(idx, instance.valueSparse(i) * dldz + (m_lambda / (m_t + m_epsilon)) * m_weights.getValue(idx));
        }

        //Weight update for the bias
        double biasGradient = dldz;
        m_biasVelocity += biasGradient * biasGradient;
        m_bias -= (m_learningRate / (Math.sqrt(m_biasVelocity) + m_epsilon)) * biasGradient;

        for(int i = 0; i < m_weights.numValues(); i++) {
            //Weight update
            double g = gradients.getValue(i);
            m_velocity.addToValue(i, g * g);
            m_weights.addToValue(i, -(m_learningRate / (Math.sqrt(m_velocity.getValue(i)) + m_epsilon)) * g);
        }

        m_t += 1.0;
    }
579181
private ClassifierKS getPreviousClassifier(Classifier classifier,
            List<Instance> instances) {
        ExecutorService threadPool = Executors.newFixedThreadPool(this.threadSizeOption.getValue());
        int SIZE = this.classifiers.size();
        Map<Integer, Future<Double>> futures = new HashMap<>();
        for (int i = 0; i < SIZE; i++) {
            ClassifierKS cs = this.classifiers.get(i);
            if (cs != null) {
                if (cs.getClassifier() != classifier) {
                    StatisticalTest st = (StatisticalTest) getPreparedClassOption(this.statisticalTestOption);
                    StatisticalTest temp = (StatisticalTest) st.copy();
                    temp.set(instances, cs.getInstances());
                    futures.put(i, threadPool.submit(temp));
                }
            } else {
                break;
            }
        }
        ClassifierKS cks = null;
        int qtd = this.quantityClassifiersTestOption.getValue();
        double maxPValue = this.similarityBetweenDistributionsOption.getValue();
        try {
            for (int i = 0; i < SIZE && qtd > 0; i++) {
                Future<Double> f = futures.get(i);
                if (f != null) {
                    double p = f.get();
                    if (p < maxPValue) {
                        maxPValue = p;
                        cks = this.classifiers.get(i);
                        qtd--;
                    }
                }
            }
        } catch (InterruptedException e) {
            System.out.println("Processing interrupted.");
        } catch (ExecutionException e) {
            throw new RuntimeException("Error computing statistical test.", e);
        }
        threadPool.shutdownNow();
        return cks;
    }
1260225
protected void initializeTraining(){
        if(!initializedTraining) {
            if(trainingConfig == null) {
                throw new ND4JIllegalStateException("Please specify a training config with setTrainingConfig");
            }
            //First: infer the variables to be optimized if required
            if(trainingConfig.getTrainableParams() == null || trainingConfig.getTrainableParams().size() == 0) {
                //Variable is trainable if it's not the output of some function
                //TODO also - should be floating point type
                List<String> trainVarList = new ArrayList<>();
                for(Variable var : variables.values()){
                    SDVariable v = var.getVariable();
                    String n = v.getVarName();
                    if(variables.get(n).getOutputOfOp() == null &&       //Is a leaf (not the output of a function)
                            !isPlaceHolder(n) &&                                //and not a placeholder
                            !variables.get(n).getVariable().isConstant() &&     //and not a constant
                            (trainingConfig.getDataSetFeatureMapping() == null || !trainingConfig.getDataSetFeatureMapping().contains(n))   &&  //and not an input (this really should be a placeholder, but we can't guarantee that...)
                            (trainingConfig.getDataSetLabelMapping() == null || !trainingConfig.getDataSetLabelMapping().contains(n))   &&      //and not a label (this really should be a placeholder, but we can't guarantee that...)
                            (trainingConfig.getDataSetFeatureMaskMapping() == null || !trainingConfig.getDataSetFeatureMaskMapping().contains(n))   &&  //and not a feature mask (this really should be a placeholder, but we can't guarantee that...)
                            (trainingConfig.getDataSetLabelMaskMapping() == null || !trainingConfig.getDataSetLabelMaskMapping().contains(n))){  //and not a label input (this really should be a placeholder, but we can't guarantee that...)
                        trainVarList.add(n);
                    }
                }

                trainingConfig.setTrainableParams(trainVarList);
                log.info("Inferred trainable variables: {}", trainVarList);
            }

            //Allocate updater state
            long numTrainableParams = 0;
            DataType dt = null;             //TODO support mixed precision variables - https://github.com/deeplearning4j/deeplearning4j/issues/6992
            for(String s : trainingConfig.getTrainableParams()) {
                SDVariable v = variables.get(s).getVariable();
                Preconditions.checkState(v != null, "No variable found for trainable parameter name \"%s\"", s);

                INDArray arr = v.getArr();
                Preconditions.checkState(arr != null, "No array found for trainable parameter \"%s\"", s);
                numTrainableParams += arr.length();
                if(dt == null)
                    dt = arr.dataType();
            }

            long updaterStateSize = trainingConfig.getUpdater().stateSize(numTrainableParams);

            if(updaterStateSize > 0) {
                try(MemoryWorkspace ws = Nd4j.getMemoryManager().scopeOutOfWorkspaces()) {
                    updaterState = Nd4j.createUninitialized(dt, 1, updaterStateSize);
                }
            }

            long viewSoFar = 0;
            updaterViews = new HashMap<>();
            updaterMap = new HashMap<>();
            for(String s : trainingConfig.getTrainableParams()) {
                long thisSize = trainingConfig.getUpdater().stateSize(variables.get(s).getVariable().getArr().length());
                INDArray view = (updaterStateSize == 0 || thisSize == 0 ? null :
                        updaterState.get(NDArrayIndex.interval(0, 1), NDArrayIndex.interval(viewSoFar, viewSoFar + thisSize)));

                updaterViews.put(s, view);
                updaterMap.put(s, trainingConfig.getUpdater().instantiate(view, true));
                viewSoFar += thisSize;
            }

            initializedTraining = true;
        }
    }
820882
@Override
	public void trainOnInstance(Instance inst) {
		// Update class statistics with weights
		int classIndex = (int) inst.classValue();
		Double weight = this.classInstances.get(classIndex);
		if (weight == null)
			weight = 0.;
		this.classInstances.put(classIndex, weight + inst.weight());
		
		// Get the class prototype
		Double classPrototype = this.classPrototypes.get(classIndex);
		if (classPrototype == null)
			classPrototype = 1.;
		
		// Iterate over the attributes of the given instance
		for (int attributePosition = 0; attributePosition < inst
				.numAttributes(); attributePosition++) {
			// Get the attribute index - Dense -> 1:1, Sparse is remapped
			int attributeID = inst.index(attributePosition);
			// Skip class attribute
			if (attributeID == inst.classIndex())
				continue;
			// Get the attribute observer for the current attribute
			GaussianNumericAttributeClassObserver obs = this.attributeObservers
					.get(attributeID);
			// Lazy init of observers, if null, instantiate a new one
			if (obs == null) {
				// FIXME: At this point, we model everything as a numeric
				// attribute
				obs = new GaussianNumericAttributeClassObserver();
				this.attributeObservers.put(attributeID, obs);
			}
			
			// Get the probability density function under the current model
			GaussianEstimator obs_estimator = obs.getEstimator(classIndex);
			if (obs_estimator != null) {
				// Fetch the probability that the feature value is zero
				double probDens_zero_current = obs_estimator.probabilityDensity(0);
				classPrototype -= probDens_zero_current;
			}
			
			// FIXME: Sanity check on data values, for now just learn
			// Learn attribute value for given class
			obs.observeAttributeClass(inst.valueSparse(attributePosition),
					(int) inst.classValue(), inst.weight());
			
			// Update obs_estimator to fetch the pdf from the updated model
			obs_estimator = obs.getEstimator(classIndex);
			// Fetch the probability that the feature value is zero
			double probDens_zero_updated = obs_estimator.probabilityDensity(0);
			// Update the class prototype
			classPrototype += probDens_zero_updated;
		}
		// Store the class prototype
		this.classPrototypes.put(classIndex, classPrototype);
		// Count another training instance
		this.instancesSeen++;
	}
688571
public static void setInstanceProvider(SpringInstanceProvider provider) {
		if(instanceProvider != null)return;
		instanceProvider = provider;
		initialized.set(true);
	}
255751
def train(self, record):
        
        self.n += 1
        class_attr = self.tree.data.class_attribute_name
        class_value = record[class_attr]
        
        # Update class statistics.
        is_con = self.tree.data.is_continuous_class
        if is_con:
            # For a continuous class.
            self._class_cdist += class_value
        else:
            # For a discrete class.
            self._class_ddist.add(class_value)
        
        # Update attribute statistics.
        for an, av in iteritems(record):
            if an == class_attr:
                continue
            self._attr_value_counts[an][av] += 1
            self._attr_value_count_totals[an] += 1
            if is_con:
                self._attr_value_cdist[an][av] += class_value
            else:
                self._attr_class_value_counts[an][av][class_value] += 1
        
        # Decide if branch should split on an attribute.
        if self.ready_to_split:
            self.attr_name = self.get_best_splitting_attr()
            self.tree.leaf_count -= 1
            for av in self._attr_value_counts[self.attr_name]:
                self._branches[av] = Node(tree=self.tree)
                self.tree.leaf_count += 1
            
        # If we've split, then propagate the update to appropriate sub-branch.
        if self.attr_name:
            key = record[self.attr_name]
            del record[self.attr_name]
            self._branches[key].train(record)
292020
public static void setInstance(OkHttpClient client) throws GuildWars2Exception {
		if (instance != null)
			throw new GuildWars2Exception(ErrorCode.Other, "Instance already initialized");
		instance = new GuildWars2(client);
	}
274176
@SuppressWarnings("rawtypes")
    public void evaluateInstanceList(TransducerTrainer tt, InstanceList data,
            String description) {
        Transducer model = tt.getTransducer();
        int numCorrectTokens, totalTokens;
        int[] numTrueSegments, numPredictedSegments, numCorrectSegments;
        int allIndex = segmentStartTags.length;
        numTrueSegments = new int[allIndex + 1];
        numPredictedSegments = new int[allIndex + 1];
        numCorrectSegments = new int[allIndex + 1];

        totalTokens = numCorrectTokens = 0;
        for (int n = 0; n < numTrueSegments.length; n++)
            numTrueSegments[n] = numPredictedSegments[n] = numCorrectSegments[n] = 0;
        for (int i = 0; i < data.size(); i++) {
            Instance instance = data.get(i);
            Sequence input = (Sequence) instance.getData();
            // String tokens = null;
            // if (instance.getSource() != null)
            // tokens = (String) instance.getSource().toString();
            Sequence trueOutput = (Sequence) instance.getTarget();
            assert (input.size() == trueOutput.size());
            Sequence predOutput = model.transduce(input);
            assert (predOutput.size() == trueOutput.size());
            int trueStart, predStart; // -1 for non-start, otherwise index into
                                      // segmentStartTag

            boolean hasIncorrect = false;
            StringBuilder sentencePrint = new StringBuilder();

            for (int j = 0; j < trueOutput.size(); j++) {
                totalTokens++;
                if (trueOutput.get(j).equals(predOutput.get(j))) {
                    numCorrectTokens++;
                    if (printMissclassified)
                        sentencePrint.append(getText(input, j) + " ");

                } else if (printMissclassified) {// not predicted correctly
                    hasIncorrect = true;
                    sentencePrint.append("{{" + getText(input, j) + "}} ");
                }

                trueStart = predStart = -1;
                // Count true segment starts
                for (int n = 0; n < segmentStartTags.length; n++) {
                    if (segmentStartTags[n].equals(trueOutput.get(j))) {
                        numTrueSegments[n]++;
                        numTrueSegments[allIndex]++;
                        trueStart = n;
                        break;
                    }
                }
                // Count predicted segment starts
                for (int n = 0; n < segmentStartTags.length; n++) {
                    if (segmentStartTags[n].equals(predOutput.get(j))) {
                        numPredictedSegments[n]++;
                        numPredictedSegments[allIndex]++;
                        predStart = n;
                    }
                }
                if (trueStart != -1 && trueStart == predStart) {
                    // Truth and Prediction both agree that the same segment
                    // tag-type is starting now
                    int m;
                    boolean trueContinue = false;
                    boolean predContinue = false;
                    for (m = j + 1; m < trueOutput.size(); m++) {
                        trueContinue = segmentContinueTags[predStart]
                                .equals(trueOutput.get(m));
                        predContinue = segmentContinueTags[predStart]
                                .equals(predOutput.get(m));
                        if (!trueContinue || !predContinue) {
                            if (trueContinue == predContinue) {
                                // They agree about a segment is ending somehow
                                numCorrectSegments[predStart]++;
                                numCorrectSegments[allIndex]++;
                            }
                            break;
                        }
                    }
                    // for the case of the end of the sequence
                    if (m == trueOutput.size()) {
                        if (trueContinue == predContinue) {
                            numCorrectSegments[predStart]++;
                            numCorrectSegments[allIndex]++;
                        }
                    }
                }
            }
            if (hasIncorrect && printMissclassified)
                System.out.println(sentencePrint.toString());
        }

        tokenAccuracy = ((double) numCorrectTokens) / totalTokens;
        for (int n = 0; n < numCorrectSegments.length; n++) {
            if (!(n < allIndex)) {// only "OVERALL"
                precision = numPredictedSegments[n] == 0 ? 1
                        : ((double) numCorrectSegments[n])
                                / numPredictedSegments[n];
                recall = numTrueSegments[n] == 0 ? 1
                        : ((double) numCorrectSegments[n]) / numTrueSegments[n];
                f1 = recall + precision == 0.0 ? 0.0
                        : (2.0 * recall * precision) / (recall + precision);
            }
        }
    }
941422
public void trainOnInstanceImpl(Instance inst) {
		accumulatedError= Math.abs(this.prediction(inst)-inst.classValue())*inst.weight() + fadingFactor*accumulatedError;
		nError=inst.weight()+fadingFactor*nError;
		// Initialise Perceptron if necessary   
		if (this.initialisePerceptron == true) {
			//Initialize numericAttributesIndex
			LinkedList<Integer> numericIndices= new LinkedList<Integer>();
			for (int i = 0; i < inst.numAttributes(); i++)
				if(inst.attribute(i).isNumeric() && i!=inst.classIndex())
					numericIndices.add(i);
			numericAttributesIndex=new int[numericIndices.size()];
			int j=0;
			for(Integer index : numericIndices)
				numericAttributesIndex[j++]=index;

			this.fadingFactor=this.fadingFactorOption.getValue();
			this.initialisePerceptron = false; // not in resetLearningImpl() because it needs Instance!
			this.weightAttribute = new double[numericAttributesIndex.length+1];
			for (int i = 0; i < numericAttributesIndex.length+1; i++) {
				//if (inst.attribute(i).isNumeric())
				weightAttribute[i] = 2 * this.classifierRandom.nextDouble() - 1;
			}
			// Update Learning Rate
			learningRatio = learningRatioOption.getValue();
			this.learningRateDecay = learningRateDecayOption.getValue();

		}

		// Update attribute statistics
		this.perceptronInstancesSeen+=inst.weight();
		this.perceptronYSeen+=inst.weight();


		for(int j = 0; j < numericAttributesIndex.length; j++)
		{
			int instAttIndex = modelAttIndexToInstanceAttIndex(numericAttributesIndex[j], inst);
			double value=inst.value(instAttIndex);
			perceptronattributeStatistics.addToValue(j, value*inst.weight());	
			squaredperceptronattributeStatistics.addToValue(j, value*value*inst.weight());
		}
		double value=inst.classValue();
		this.perceptronsumY += value*inst.weight();
		this.squaredperceptronsumY += value * value*inst.weight();

		if(constantLearningRatioDecayOption.isSet()==false){
			learningRatio = learningRatioOption.getValue() / (1+ perceptronInstancesSeen*learningRateDecay); 
		}

		//double prediction = this.updateWeights(inst,learningRatio);
		//accumulatedError= Math.abs(prediction-inst.classValue()) + fadingFactor*accumulatedError;


		this.updateWeights(inst,learningRatio);

	}
778414
protected void releaseInstance(T instance) throws IOException {
    AtomicInteger currentCount = providedVsCount.get(instance);
    if(currentCount != null) {
      if(currentCount.decrementAndGet() < 0) {
        currentCount.incrementAndGet();
        throw new IllegalArgumentException("Given instance of " + instance.getClass().getName() + " is not managed by this provider");
      }
    } else {
      throw new IllegalArgumentException("Given instance of " + instance.getClass().getName() + " is not managed by this provider");
    }

    if(instantiated.remove(instance) && instance instanceof Closeable) {
      ((Closeable)instance).close();
    }
  }
1152146
def do_execute(self):
        
        if isinstance(self.input.payload, Instances):
            inst = None
            data = self.input.payload
        else:
            inst = self.input.payload
            data = inst.dataset

        retrain = False
        if (self._header is None) or (self._header.equal_headers(data) is not None) or (inst is None):
            retrain = True
            self._header = Instances.template_instances(data, 0)

        if retrain or (self._model is None):
            cls = self.resolve_option("setup")
            if isinstance(cls, Classifier):
                self._model = Classifier.make_copy(cls)
            elif isinstance(cls, Clusterer):
                self._model = Clusterer.make_copy(cls)
            elif isinstance(cls, Associator):
                self._model = Associator.make_copy(cls)
            else:
                return "Unhandled class: " + classes.get_classname(cls)

        if retrain:
            if inst is not None:
                data = Instances.template_instances(data, 1)
                data.add_instance(inst)
            if isinstance(self._model, Classifier):
                self._model.build_classifier(data)
            elif isinstance(self._model, Clusterer):
                self._model.build_clusterer(data)
            elif isinstance(self._model, Associator):
                self._model.build_associations(data)
        else:
            if isinstance(self._model, Classifier):
                self._model.update_classifier(inst)
            elif isinstance(self._model, Clusterer):
                self._model.update_clusterer(inst)
            else:
                return "Cannot train incrementally: " + classes.get_classname(self._model)

        cont = ModelContainer(model=self._model, header=self._header)
        self._output.append(Token(cont))
        return None
11131
public static void deleteInstanceResources( Instance instance )	throws IOException {
		File dir = InstanceHelpers.findInstanceDirectoryOnAgent( instance );
		Utils.deleteFilesRecursively( dir );
	}
1152877
@Override
    public void trainOnInstanceImpl(Instance inst) {
        if (this.reset == true) {
            this.m_numClasses = inst.numClasses();
            double laplace = this.laplaceCorrectionOption.getValue();
            int numAttributes = inst.numAttributes();

            m_probOfClass = new double[m_numClasses];
            Arrays.fill(m_probOfClass, laplace);

            m_classTotals = new double[m_numClasses];
            Arrays.fill(m_classTotals, laplace * numAttributes);

            m_wordTotalForClass = new DoubleVector[m_numClasses];
            for (int i = 0; i< m_numClasses; i++) {
                //Arrays.fill(wordTotal, laplace);
                m_wordTotalForClass[i] = new DoubleVector();
            }
            this.reset = false;
        }
        // Update classifier
        int classIndex = inst.classIndex();
        int classValue = (int) inst.classValue();//value(classIndex);

        double w = inst.weight();
        m_probOfClass[classValue] += w;

        m_classTotals[classValue] += w * totalSize(inst);
        double total = m_classTotals[classValue];

        for (int i = 0; i < inst.numValues(); i++) {
            int index = inst.index(i);
            if (index != classIndex && !inst.isMissing(i)) {
                //m_wordTotalForClass[index][classValue] += w * inst.valueSparse(i);
                double laplaceCorrection = 0.0;
                if (m_wordTotalForClass[classValue].getValue(index)== 0) {
                    laplaceCorrection = this.laplaceCorrectionOption.getValue();
                }
                m_wordTotalForClass[classValue].addToValue(index, w * inst.valueSparse(i) + laplaceCorrection);
            }
        }
    }
613640
@Override
    public void trainOnInstanceImpl(Instance instance) {

        if (m_weights == null) {
            int length;
             if (instance.classAttribute().isNominal()) {
                 length = instance.numClasses();
             } else {
                 length = 1;
             }
            m_weights = new DoubleVector[length];
            m_bias = new double[length];
            for (int i = 0; i < m_weights.length; i++){
                m_weights[i] = new DoubleVector(); 
                m_bias[i] = 0.0;
            }
        }
        for (int i = 0; i < m_weights.length; i++){
                this.trainOnInstanceImpl(instance, i); 
            }
        m_t++;
    }
333645
public TPredict[] classify(InstanceSet instances, int n) {
		TPredict[] ress = new TPredict[instances.size()];
		for(int i=0;i<instances.size();i++){
			ress[i] = classify(instances.get(i), n);
		}
		return ress;
	}
294605
def register(self, cls, instance):
        
        if not issubclass(cls, DropletInterface):
            raise TypeError('Given class is not a NAZInterface subclass: %s'
                            % cls)

        if not isinstance(instance, cls):
            raise TypeError('Given instance does not implement the class: %s'
                            % instance)

        if instance.name in self.INSTANCES_BY_NAME:
            if self.INSTANCES_BY_NAME[instance.name] != instance:
                raise ValueError('Given name is registered '
                                 'by other instance: %s' % instance.name)

        self.INSTANCES_BY_INTERFACE[cls].add(instance)
        self.INSTANCES_BY_NAME[instance.name] = instance
71949
private void trainOnInstanceImpl(Instance inst) {
		if(this.treeRoot == null){
			this.treeRoot = newLearningNode(this.parallelismHint);
			this.activeLeafNodeCount = 1;
                        
		}
		FoundNode foundNode = this.treeRoot.filterInstanceToLeaf(inst, null, -1);
                trainOnInstanceImpl(foundNode, inst);
        }