idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
21,600
public ArrayList < DensityGrid > getNeighbours ( ) { ArrayList < DensityGrid > neighbours = new ArrayList < DensityGrid > ( ) ; DensityGrid h ; int [ ] hCoord = this . getCoordinates ( ) ; for ( int i = 0 ; i < this . dimensions ; i ++ ) { hCoord [ i ] = hCoord [ i ] - 1 ; h = new DensityGrid ( hCoord ) ; neighbours . add ( h ) ; hCoord [ i ] = hCoord [ i ] + 2 ; h = new DensityGrid ( hCoord ) ; neighbours . add ( h ) ; hCoord [ i ] = hCoord [ i ] - 1 ; } return neighbours ; }
Generates an Array List of neighbours for this density grid by varying each coordinate by one in either direction . Does not test whether the generated neighbours are valid as DensityGrid is not aware of the number of partitions in each dimension .
21,601
public double getInclusionProbability ( Instance instance ) { for ( int i = 0 ; i < this . dimensions ; i ++ ) { if ( ( int ) instance . value ( i ) != this . coordinates [ i ] ) return 0.0 ; } return 1.0 ; }
Provides the probability of the argument instance belonging to the density grid in question .
21,602
public void readBuffer ( List < String > algPath , List < String > algNames , List < Measure > measures ) { BufferedReader buffer = null ; for ( int i = 0 ; i < algPath . size ( ) ; i ++ ) { try { buffer = new BufferedReader ( new FileReader ( algPath . get ( i ) ) ) ; } catch ( FileNotFoundException ex ) { Logger . getLogger ( Stream . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } Algorithm algorithm = new Algorithm ( algNames . get ( i ) , measures , buffer , algPath . get ( i ) ) ; this . algorithm . add ( algorithm ) ; } }
Read each algorithm file .
21,603
protected void fireClusterChange ( long timestamp , String type , String message ) { if ( listeners != null && ! listeners . isEmpty ( ) ) { ClusterEvent event = new ClusterEvent ( this , timestamp , type , message ) ; Vector targets ; synchronized ( this ) { targets = ( Vector ) listeners . clone ( ) ; } Enumeration e = targets . elements ( ) ; while ( e . hasMoreElements ( ) ) { ClusterEventListener l = ( ClusterEventListener ) e . nextElement ( ) ; l . changeCluster ( event ) ; } } }
Fire a ClusterChangeEvent to all registered listeners
21,604
protected void notifyChangeListeners ( ) { ChangeEvent e = new ChangeEvent ( this ) ; for ( ChangeListener l : changeListeners ) { l . stateChanged ( e ) ; } }
Notifies all registered change listeners that the options have changed .
21,605
public void setGraph ( MeasureCollection [ ] measures , MeasureCollection [ ] stds , double [ ] variedParamValues , Color [ ] colors ) { this . variedParamValues = variedParamValues ; super . setGraph ( measures , stds , colors ) ; }
Draws a scatter graph based on the varied parameter and the measures .
21,606
private void scatter ( Graphics g , int i ) { int height = getHeight ( ) ; int width = getWidth ( ) ; int x = ( int ) ( ( ( this . variedParamValues [ i ] - this . lower_x_value ) / ( this . upper_x_value - this . lower_x_value ) ) * width ) ; double value = this . measures [ i ] . getLastValue ( this . measureSelected ) ; if ( Double . isNaN ( value ) ) { return ; } int y = ( int ) ( height - ( value / this . upper_y_value ) * height ) ; g . setColor ( this . colors [ i ] ) ; if ( this . isStandardDeviationPainted ) { int len = ( int ) ( ( this . measureStds [ i ] . getLastValue ( this . measureSelected ) / this . upper_y_value ) * height ) ; paintStandardDeviation ( g , len , x , y ) ; } g . fillOval ( x - DOT_SIZE / 2 , y - DOT_SIZE / 2 , DOT_SIZE , DOT_SIZE ) ; }
Paint a dot onto the panel .
21,607
public static MOAObject copy ( MOAObject obj ) { try { return ( MOAObject ) SerializeUtils . copyObject ( obj ) ; } catch ( Exception e ) { throw new RuntimeException ( "Object copy failed." , e ) ; } }
This method produces a copy of an object .
21,608
public static String get ( String property , String defaultValue ) { return PROPERTIES . getProperty ( property , defaultValue ) ; }
returns the value for the specified property if non - existent then the default value .
21,609
public static String [ ] getTabs ( ) { String [ ] result ; String tabs ; tabs = get ( "Tabs" , "moa.gui.ClassificationTabPanel,moa.gui.RegressionTabPanel,moa.gui.MultiLabelTabPanel,moa.gui.MultiTargetTabPanel,moa.gui.clustertab.ClusteringTabPanel,moa.gui.outliertab.OutlierTabPanel,moa.gui.ConceptDriftTabPanel,moa.gui.ALTabPanel,moa.gui.AuxiliarTabPanel,moa.gui.experimentertab.ExperimenterTabPanel" ) ; result = tabs . split ( "," ) ; return result ; }
returns an array with the classnames of all the additional panels to display as tabs in the GUI .
21,610
public static int getFrameWidth ( ) { int result ; String str ; str = get ( "FrameWidth" , "1200" ) ; try { result = Integer . parseInt ( str ) ; } catch ( Exception e ) { result = 1200 ; } return result ; }
Returns the width for the frame .
21,611
public static void main ( String [ ] args ) { Enumeration names ; String name ; Vector sorted ; System . out . println ( "\nMOA defaults:" ) ; names = PROPERTIES . propertyNames ( ) ; sorted = new Vector ( ) ; while ( names . hasMoreElements ( ) ) { sorted . add ( names . nextElement ( ) ) ; } Collections . sort ( sorted ) ; names = sorted . elements ( ) ; while ( names . hasMoreElements ( ) ) { name = names . nextElement ( ) . toString ( ) ; System . out . println ( "- " + name + ": " + PROPERTIES . getProperty ( name , "" ) ) ; } System . out . println ( ) ; }
only for testing - prints the content of the props file .
21,612
public static double inverseError ( double x ) { double z = Math . sqrt ( Math . PI ) * x ; double res = ( z ) / 2 ; double z2 = z * z ; double zProd = z * z2 ; res += ( 1.0 / 24 ) * zProd ; zProd *= z2 ; res += ( 7.0 / 960 ) * zProd ; zProd *= z2 ; res += ( 127 * zProd ) / 80640 ; zProd *= z2 ; res += ( 4369 * zProd ) / 11612160 ; zProd *= z2 ; res += ( 34807 * zProd ) / 364953600 ; zProd *= z2 ; res += ( 20036983 * zProd ) / 797058662400d ; return res ; }
Approximates the inverse error function . Clustream needs this .
21,613
protected void bicoUpdate ( double [ ] x ) { assert ( ! this . bufferPhase && this . numDimensions == x . length ) ; ClusteringTreeNode r = this . root ; int i = 1 ; while ( true ) { ClusteringTreeNode y = r . nearestChild ( x ) ; if ( r . hasNoChildren ( ) || y == null || Metric . distanceSquared ( x , y . getCenter ( ) ) > calcRSquared ( i ) ) { r . addChild ( new ClusteringTreeNode ( x , new ClusteringFeature ( x , calcR ( i ) ) ) ) ; this . rootCount ++ ; break ; } else { if ( y . getClusteringFeature ( ) . calcKMeansCosts ( y . getCenter ( ) , x ) <= this . T ) { y . getClusteringFeature ( ) . add ( 1 , x , Metric . distanceSquared ( x ) ) ; break ; } else { r = y ; i ++ ; } } } if ( this . rootCount > this . maxNumClusterFeatures ) { rebuild ( ) ; } }
Inserts a new point into the ClusteringFeature tree .
21,614
protected void rebuild ( ) { while ( this . rootCount > this . maxNumClusterFeatures ) { this . T *= 2.0 ; this . root . setThreshold ( calcRSquared ( 1 ) ) ; Queue < ClusteringTreeNode > Q = new LinkedList < ClusteringTreeNode > ( ) ; Q . addAll ( this . root . getChildren ( ) ) ; this . root . clearChildren ( ) ; this . rootCount = 0 ; while ( ! Q . isEmpty ( ) ) { ClusteringTreeNode x = Q . element ( ) ; Q . addAll ( x . getChildren ( ) ) ; x . clearChildren ( ) ; bicoCFUpdate ( x ) ; Q . remove ( ) ; } } }
If the number of ClusteringTreeNodes exceeds the maximum bound the global threshold T will be doubled and the tree will be rebuild with the new threshold .
21,615
protected void bicoCFUpdate ( ClusteringTreeNode x ) { ClusteringTreeNode r = this . root ; int i = 1 ; while ( true ) { ClusteringTreeNode y = r . nearestChild ( x . getCenter ( ) ) ; if ( r . hasNoChildren ( ) || y == null || Metric . distanceSquared ( x . getCenter ( ) , y . getCenter ( ) ) > calcRSquared ( i ) ) { x . setThreshold ( calcR ( i ) ) ; r . addChild ( x ) ; this . rootCount ++ ; break ; } else { if ( y . getClusteringFeature ( ) . calcKMeansCosts ( y . getCenter ( ) , x . getClusteringFeature ( ) ) <= this . T ) { y . getClusteringFeature ( ) . merge ( x . getClusteringFeature ( ) ) ; break ; } else { r = y ; i ++ ; } } } }
Inserts a ClusteringTreeNode into the ClusteringFeature tree .
21,616
public static void combSort11 ( double arrayToSort [ ] , int linkedArray [ ] ) { int switches , j , top , gap ; double hold1 ; int hold2 ; gap = arrayToSort . length ; do { gap = ( int ) ( gap / 1.3 ) ; switch ( gap ) { case 0 : gap = 1 ; break ; case 9 : case 10 : gap = 11 ; break ; default : break ; } switches = 0 ; top = arrayToSort . length - gap ; for ( int i = 0 ; i < top ; i ++ ) { j = i + gap ; if ( arrayToSort [ i ] > arrayToSort [ j ] ) { hold1 = arrayToSort [ i ] ; hold2 = linkedArray [ i ] ; arrayToSort [ i ] = arrayToSort [ j ] ; linkedArray [ i ] = linkedArray [ j ] ; arrayToSort [ j ] = hold1 ; linkedArray [ j ] = hold2 ; switches ++ ; } } } while ( switches > 0 || gap > 1 ) ; }
sorts the two given arrays .
21,617
public static void quickSort ( double [ ] arrayToSort , double [ ] linkedArray , int left , int right ) { if ( left < right ) { int middle = partition ( arrayToSort , linkedArray , left , right ) ; quickSort ( arrayToSort , linkedArray , left , middle ) ; quickSort ( arrayToSort , linkedArray , middle + 1 , right ) ; } }
performs quicksort .
21,618
public Instances kNearestNeighbours ( Instance target , int k ) throws Exception { checkMissing ( target ) ; MyHeap heap = new MyHeap ( k ) ; findNearestNeighbours ( target , m_Root , k , heap , 0.0 ) ; Instances neighbours = new Instances ( m_Instances , ( heap . size ( ) + heap . noOfKthNearest ( ) ) ) ; m_DistanceList = new double [ heap . size ( ) + heap . noOfKthNearest ( ) ] ; int [ ] indices = new int [ heap . size ( ) + heap . noOfKthNearest ( ) ] ; int i = indices . length - 1 ; MyHeapElement h ; while ( heap . noOfKthNearest ( ) > 0 ) { h = heap . getKthNearest ( ) ; indices [ i ] = h . index ; m_DistanceList [ i ] = h . distance ; i -- ; } while ( heap . size ( ) > 0 ) { h = heap . get ( ) ; indices [ i ] = h . index ; m_DistanceList [ i ] = h . distance ; i -- ; } m_DistanceFunction . postProcessDistances ( m_DistanceList ) ; for ( int idx = 0 ; idx < indices . length ; idx ++ ) { neighbours . add ( m_Instances . instance ( indices [ idx ] ) ) ; } return neighbours ; }
Returns the k nearest neighbours of the supplied instance . &gt ; k neighbours are returned if there are more than one neighbours at the kth boundary .
21,619
public void update ( Instance instance ) throws Exception { if ( m_Instances == null ) throw new Exception ( "No instances supplied yet. Have to call " + "setInstances(instances) with a set of Instances " + "first." ) ; addInstanceInfo ( instance ) ; addInstanceToTree ( instance , m_Root ) ; }
Adds one instance to the KDTree . This updates the KDTree structure to take into account the newly added training instance .
21,620
protected void checkMissing ( Instances instances ) throws Exception { for ( int i = 0 ; i < instances . numInstances ( ) ; i ++ ) { Instance ins = instances . instance ( i ) ; for ( int j = 0 ; j < ins . numValues ( ) ; j ++ ) { if ( ins . index ( j ) != ins . classIndex ( ) ) if ( ins . isMissingSparse ( j ) ) { throw new Exception ( "ERROR: KDTree can not deal with missing " + "values. Please run ReplaceMissingValues filter " + "on the dataset before passing it on to the KDTree." ) ; } } } }
Checks if there is any instance with missing values . Throws an exception if there is as KDTree does not handle missing values .
21,621
protected void checkMissing ( Instance ins ) throws Exception { for ( int j = 0 ; j < ins . numValues ( ) ; j ++ ) { if ( ins . index ( j ) != ins . classIndex ( ) ) if ( ins . isMissingSparse ( j ) ) { throw new Exception ( "ERROR: KDTree can not deal with missing " + "values. Please run ReplaceMissingValues filter " + "on the dataset before passing it on to the KDTree." ) ; } } }
Checks if there is any missing value in the given instance .
21,622
public Enumeration enumerateMeasures ( ) { Vector < String > newVector = new Vector < String > ( ) ; newVector . addElement ( "measureTreeSize" ) ; newVector . addElement ( "measureNumLeaves" ) ; newVector . addElement ( "measureMaxDepth" ) ; return newVector . elements ( ) ; }
Returns an enumeration of the additional measure names .
21,623
public double getMeasure ( String additionalMeasureName ) { if ( additionalMeasureName . compareToIgnoreCase ( "measureMaxDepth" ) == 0 ) { return measureMaxDepth ( ) ; } else if ( additionalMeasureName . compareToIgnoreCase ( "measureTreeSize" ) == 0 ) { return measureTreeSize ( ) ; } else if ( additionalMeasureName . compareToIgnoreCase ( "measureNumLeaves" ) == 0 ) { return measureNumLeaves ( ) ; } else { throw new IllegalArgumentException ( additionalMeasureName + " not supported (KDTree)" ) ; } }
Returns the value of the named measure .
21,624
public void centerInstances ( Instances centers , int [ ] assignments , double pc ) throws Exception { int [ ] centList = new int [ centers . numInstances ( ) ] ; for ( int i = 0 ; i < centers . numInstances ( ) ; i ++ ) centList [ i ] = i ; determineAssignments ( m_Root , centers , centList , assignments , pc ) ; }
Assigns instances to centers using KDTree .
21,625
protected void determineAssignments ( KDTreeNode node , Instances centers , int [ ] candidates , int [ ] assignments , double pc ) throws Exception { int [ ] owners = refineOwners ( node , centers , candidates ) ; if ( owners . length == 1 ) { for ( int i = node . m_Start ; i <= node . m_End ; i ++ ) { assignments [ m_InstList [ i ] ] = owners [ 0 ] ; } } else if ( ! node . isALeaf ( ) ) { determineAssignments ( node . m_Left , centers , owners , assignments , pc ) ; determineAssignments ( node . m_Right , centers , owners , assignments , pc ) ; } else { assignSubToCenters ( node , centers , owners , assignments ) ; } }
Assigns instances to the current centers called candidates .
21,626
protected int [ ] refineOwners ( KDTreeNode node , Instances centers , int [ ] candidates ) throws Exception { int [ ] owners = new int [ candidates . length ] ; double minDistance = Double . POSITIVE_INFINITY ; int ownerIndex = - 1 ; Instance owner ; int numCand = candidates . length ; double [ ] distance = new double [ numCand ] ; boolean [ ] inside = new boolean [ numCand ] ; for ( int i = 0 ; i < numCand ; i ++ ) { distance [ i ] = distanceToHrect ( node , centers . instance ( candidates [ i ] ) ) ; inside [ i ] = ( distance [ i ] == 0.0 ) ; if ( distance [ i ] < minDistance ) { minDistance = distance [ i ] ; ownerIndex = i ; } } owner = ( Instance ) centers . instance ( candidates [ ownerIndex ] ) . copy ( ) ; int index = 0 ; for ( int i = 0 ; i < numCand ; i ++ ) { if ( ( inside [ i ] ) || ( distance [ i ] == distance [ ownerIndex ] ) ) { owners [ index ++ ] = candidates [ i ] ; } else { Instance competitor = ( Instance ) centers . instance ( candidates [ i ] ) . copy ( ) ; if ( ! candidateIsFullOwner ( node , owner , competitor ) ) { owners [ index ++ ] = candidates [ i ] ; } } } int [ ] result = new int [ index ] ; for ( int i = 0 ; i < index ; i ++ ) result [ i ] = owners [ i ] ; return result ; }
Refines the ownerlist .
21,627
protected double distanceToHrect ( KDTreeNode node , Instance x ) throws Exception { double distance = 0.0 ; Instance closestPoint = ( Instance ) x . copy ( ) ; boolean inside ; inside = clipToInsideHrect ( node , closestPoint ) ; if ( ! inside ) distance = m_EuclideanDistance . distance ( closestPoint , x ) ; return distance ; }
Returns the distance between a point and an hyperrectangle .
21,628
protected boolean clipToInsideHrect ( KDTreeNode node , Instance x ) { boolean inside = true ; for ( int i = 0 ; i < m_Instances . numAttributes ( ) ; i ++ ) { if ( x . value ( i ) < node . m_NodeRanges [ i ] [ MIN ] ) { x . setValue ( i , node . m_NodeRanges [ i ] [ MIN ] ) ; inside = false ; } else if ( x . value ( i ) > node . m_NodeRanges [ i ] [ MAX ] ) { x . setValue ( i , node . m_NodeRanges [ i ] [ MAX ] ) ; inside = false ; } } return inside ; }
Finds the closest point in the hyper rectangle to a given point . Change the given point to this closest point by clipping of at all the dimensions to be clipped of . If the point is inside the rectangle it stays unchanged . The return value is true if the point was not changed so the the return value is true if the point was inside the rectangle .
21,629
public void assignSubToCenters ( KDTreeNode node , Instances centers , int [ ] centList , int [ ] assignments ) throws Exception { int numCent = centList . length ; if ( assignments == null ) { assignments = new int [ m_Instances . numInstances ( ) ] ; for ( int i = 0 ; i < assignments . length ; i ++ ) { assignments [ i ] = - 1 ; } } for ( int i = node . m_Start ; i <= node . m_End ; i ++ ) { int instIndex = m_InstList [ i ] ; Instance inst = m_Instances . instance ( instIndex ) ; int newC = m_EuclideanDistance . closestPoint ( inst , centers , centList ) ; assignments [ instIndex ] = newC ; } }
Assigns instances of this node to center . Center to be assign to is decided by the distance function .
21,630
public void setDistanceFunction ( DistanceFunction df ) throws Exception { if ( ! ( df instanceof EuclideanDistance ) ) throw new Exception ( "KDTree currently only works with " + "EuclideanDistanceFunction." ) ; m_DistanceFunction = m_EuclideanDistance = ( EuclideanDistance ) df ; }
sets the distance function to use for nearest neighbour search .
21,631
public int count ( ) { int count = ( clusteringFeature != null ) ? 1 : 0 ; for ( ClusteringTreeNode child : children ) { count += child . count ( ) ; } return count ; }
Counts the elements in tree with this node as the root .
21,632
public Clustering addToClustering ( Clustering clustering ) { if ( center != null && getClusteringFeature ( ) != null ) { clustering . add ( getClusteringFeature ( ) . toCluster ( ) ) ; } for ( ClusteringTreeNode child : children ) { child . addToClustering ( clustering ) ; } return clustering ; }
Adds all ClusterFeatures of the tree with this node as the root to a Clustering .
21,633
public List < double [ ] > addToClusteringCenters ( List < double [ ] > clustering ) { if ( center != null && getClusteringFeature ( ) != null ) { clustering . add ( getClusteringFeature ( ) . toClusterCenter ( ) ) ; } for ( ClusteringTreeNode child : children ) { child . addToClusteringCenters ( clustering ) ; } return clustering ; }
Adds all clustering centers of the ClusterFeatures of the tree with this node as the root to a List of points .
21,634
public void printClusteringCenters ( Writer stream ) throws IOException { if ( center != null && getClusteringFeature ( ) != null ) { getClusteringFeature ( ) . printClusterCenter ( stream ) ; } for ( ClusteringTreeNode child : children ) { child . printClusteringCenters ( stream ) ; } }
Writes all clustering centers of the ClusterFeatures of the tree with this node as the root to a given stream .
21,635
public ClusteringTreeNode nearestChild ( double [ ] pointA ) { assert ( this . center . length == pointA . length ) ; double minDistance = Double . POSITIVE_INFINITY ; ClusteringTreeNode min = null ; for ( ClusteringTreeNode node : this . getChildren ( ) ) { double d = Metric . distance ( pointA , node . getCenter ( ) ) ; if ( d < minDistance ) { minDistance = d ; min = node ; } } return min ; }
Searches for the nearest child node by comparing each representation .
21,636
public boolean addChild ( ClusteringTreeNode e ) { assert ( this . center . length == e . center . length ) ; return this . children . add ( e ) ; }
Adds a child node .
21,637
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 ; }
Searches for the classifier best suited for actual data . All statistical tests are performed in parallel .
21,638
protected void makeOlder ( long timeDifference , double negLambda ) { if ( timeDifference == 0 ) { return ; } assert ( negLambda < 0 ) ; assert ( timeDifference > 0 ) ; double weightFactor = Math . pow ( 2.0 , negLambda * timeDifference ) ; this . N *= weightFactor ; for ( int i = 0 ; i < LS . length ; i ++ ) { LS [ i ] *= weightFactor ; SS [ i ] *= weightFactor ; } }
Make this cluster older . This means multiplying weighted N LS and SS with a weight factor given by the time difference and the parameter negLambda .
21,639
protected void overwriteOldCluster ( ClusKernel other ) { this . totalN = other . totalN ; this . N = other . N ; assert ( LS . length == other . LS . length ) ; System . arraycopy ( other . LS , 0 , LS , 0 , LS . length ) ; assert ( SS . length == other . SS . length ) ; System . arraycopy ( other . SS , 0 , SS , 0 , SS . length ) ; }
Overwrites the LS SS and weightedN in this cluster to the values of the given cluster but adds N and classCount of the given cluster to this one . This function is useful when the weight of an entry becomes to small and we want to forget the information of the old points .
21,640
public double [ ] getVotesForInstance ( Instance inst ) { double vSTM [ ] ; double vLTM [ ] ; double vCM [ ] ; double v [ ] ; double distancesSTM [ ] ; double distancesLTM [ ] ; int predClassSTM = 0 ; int predClassLTM = 0 ; int predClassCM = 0 ; try { if ( this . stm . numInstances ( ) > 0 ) { distancesSTM = get1ToNDistances ( inst , this . stm ) ; int nnIndicesSTM [ ] = nArgMin ( Math . min ( distancesSTM . length , this . kOption . getValue ( ) ) , distancesSTM ) ; vSTM = getDistanceWeightedVotes ( distancesSTM , nnIndicesSTM , this . stm ) ; predClassSTM = this . getClassFromVotes ( vSTM ) ; distancesLTM = get1ToNDistances ( inst , this . ltm ) ; vCM = getCMVotes ( distancesSTM , this . stm , distancesLTM , this . ltm ) ; predClassCM = this . getClassFromVotes ( vCM ) ; if ( this . ltm . numInstances ( ) >= 0 ) { int nnIndicesLTM [ ] = nArgMin ( Math . min ( distancesLTM . length , this . kOption . getValue ( ) ) , distancesLTM ) ; vLTM = getDistanceWeightedVotes ( distancesLTM , nnIndicesLTM , this . ltm ) ; predClassLTM = this . getClassFromVotes ( vLTM ) ; } else { vLTM = new double [ inst . numClasses ( ) ] ; } int correctSTM = historySum ( this . stmHistory ) ; int correctLTM = historySum ( this . ltmHistory ) ; int correctCM = historySum ( this . cmHistory ) ; if ( correctSTM >= correctLTM && correctSTM >= correctCM ) { v = vSTM ; } else if ( correctLTM > correctSTM && correctLTM >= correctCM ) { v = vLTM ; } else { v = vCM ; } } else { v = new double [ inst . numClasses ( ) ] ; } this . stmHistory . add ( ( predClassSTM == inst . classValue ( ) ) ? 1 : 0 ) ; this . ltmHistory . add ( ( predClassLTM == inst . classValue ( ) ) ? 1 : 0 ) ; this . cmHistory . add ( ( predClassCM == inst . classValue ( ) ) ? 1 : 0 ) ; } catch ( Exception e ) { return new double [ inst . numClasses ( ) ] ; } return v ; }
Predicts the label of a given sample by using the STM LTM and the CM .
21,641
private void clusterDown ( ) { int classIndex = this . ltm . classIndex ( ) ; for ( int c = 0 ; c <= this . maxClassValue ; c ++ ) { List < double [ ] > classSamples = new ArrayList < > ( ) ; for ( int i = this . ltm . numInstances ( ) - 1 ; i > - 1 ; i -- ) { if ( this . ltm . get ( i ) . classValue ( ) == c ) { classSamples . add ( this . ltm . get ( i ) . toDoubleArray ( ) ) ; this . ltm . delete ( i ) ; } } if ( classSamples . size ( ) > 0 ) { for ( double [ ] sample : classSamples ) { if ( classIndex != 0 ) { sample [ classIndex ] = sample [ 0 ] ; } sample [ 0 ] = 1 ; } List < double [ ] > centroids = this . kMeans ( classSamples , Math . max ( classSamples . size ( ) / 2 , 1 ) ) ; for ( double [ ] centroid : centroids ) { double [ ] attributes = new double [ this . ltm . numAttributes ( ) ] ; System . arraycopy ( centroid , 0 , attributes , 1 , this . ltm . numAttributes ( ) - 1 ) ; if ( classIndex != 0 ) { attributes [ 0 ] = attributes [ classIndex ] ; } attributes [ classIndex ] = c ; Instance inst = new InstanceImpl ( 1 , attributes ) ; inst . setDataset ( this . ltm ) ; this . ltm . add ( inst ) ; } } } }
Performs classwise kMeans ++ clustering for given samples with corresponding labels . The number of samples is halved per class .
21,642
private void memorySizeCheck ( ) { if ( this . stm . numInstances ( ) + this . ltm . numInstances ( ) > this . maxSTMSize + this . maxLTMSize ) { if ( this . ltm . numInstances ( ) > this . maxLTMSize ) { this . clusterDown ( ) ; } else { int numShifts = this . maxLTMSize - this . ltm . numInstances ( ) + 1 ; for ( int i = 0 ; i < numShifts ; i ++ ) { this . ltm . add ( this . stm . get ( 0 ) . copy ( ) ) ; this . stm . delete ( 0 ) ; this . stmHistory . remove ( 0 ) ; this . ltmHistory . remove ( 0 ) ; this . cmHistory . remove ( 0 ) ; } this . clusterDown ( ) ; this . predictionHistories . clear ( ) ; for ( int i = 0 ; i < this . stm . numInstances ( ) ; i ++ ) { for ( int j = 0 ; j < this . stm . numInstances ( ) ; j ++ ) { this . distanceMatrixSTM [ i ] [ j ] = this . distanceMatrixSTM [ numShifts + i ] [ numShifts + j ] ; } } } } }
Makes sure that the STM and LTM combined doe not surpass the maximum size .
21,643
private void clean ( Instances cleanAgainst , Instances toClean , boolean onlyLast ) { if ( cleanAgainst . numInstances ( ) > this . kOption . getValue ( ) && toClean . numInstances ( ) > 0 ) { if ( onlyLast ) { cleanSingle ( cleanAgainst , ( cleanAgainst . numInstances ( ) - 1 ) , toClean ) ; } else { for ( int i = 0 ; i < cleanAgainst . numInstances ( ) ; i ++ ) { cleanSingle ( cleanAgainst , i , toClean ) ; } } } }
Removes distance - based all instances from the input samples that contradict those in the STM .
21,644
private double [ ] getDistanceWeightedVotes ( double distances [ ] , int [ ] nnIndices , Instances instances ) { double v [ ] = new double [ this . maxClassValue + 1 ] ; for ( int nnIdx : nnIndices ) { v [ ( int ) instances . instance ( nnIdx ) . classValue ( ) ] += 1. / Math . max ( distances [ nnIdx ] , 0.000000001 ) ; } return v ; }
Returns the distance weighted votes .
21,645
private int getClassFromVotes ( double votes [ ] ) { double maxVote = - 1 ; int maxVoteClass = - 1 ; for ( int i = 0 ; i < votes . length ; i ++ ) { if ( votes [ i ] > maxVote ) { maxVote = votes [ i ] ; maxVoteClass = i ; } } return maxVoteClass ; }
Returns the class with maximum vote .
21,646
private double getDistance ( Instance sample , Instance sample2 ) { double sum = 0 ; for ( int i = 0 ; i < sample . numInputAttributes ( ) ; i ++ ) { double diff = sample . valueInputAttribute ( i ) - sample2 . valueInputAttribute ( i ) ; sum += diff * diff ; } return Math . sqrt ( sum ) ; }
Returns the Euclidean distance .
21,647
private double [ ] get1ToNDistances ( Instance sample , Instances samples ) { double distances [ ] = new double [ samples . numInstances ( ) ] ; for ( int i = 0 ; i < samples . numInstances ( ) ; i ++ ) { distances [ i ] = this . getDistance ( sample , samples . get ( i ) ) ; } return distances ; }
Returns the Euclidean distance between one sample and a collection of samples in an 1D - array .
21,648
private void adaptHistories ( int numberOfDeletions ) { for ( int i = 0 ; i < numberOfDeletions ; i ++ ) { SortedSet < Integer > keys = new TreeSet < > ( this . predictionHistories . keySet ( ) ) ; this . predictionHistories . remove ( keys . first ( ) ) ; keys = new TreeSet < > ( this . predictionHistories . keySet ( ) ) ; for ( Integer key : keys ) { List < Integer > predHistory = this . predictionHistories . remove ( key ) ; this . predictionHistories . put ( key - keys . first ( ) , predHistory ) ; } } }
Removes predictions of the largest window size and shifts the remaining ones accordingly .
21,649
private double getHistoryErrorRate ( List < Integer > predHistory ) { double sumCorrect = 0 ; for ( Integer e : predHistory ) { sumCorrect += e ; } return 1. - ( sumCorrect / predHistory . size ( ) ) ; }
Calculates the achieved error rate of a history .
21,650
public static double distanceSquared ( double [ ] pointA ) { double distance = 0.0 ; for ( int i = 0 ; i < pointA . length ; i ++ ) { distance += pointA [ i ] * pointA [ i ] ; } return distance ; }
Calculates the squared Euclidean length of a point .
21,651
public static double distanceSquared ( double [ ] pointA , double [ ] pointB , int offsetB ) { assert ( pointA . length == pointB . length + offsetB ) ; double distance = 0.0 ; for ( int i = 0 ; i < pointA . length ; i ++ ) { double d = pointA [ i ] - pointB [ i + offsetB ] ; distance += d * d ; } return distance ; }
Calculates the squared Euclidean distance of two points . Starts at dimension offset + 1 of pointB .
21,652
public static double distance ( double [ ] pointA , double [ ] pointB , int offsetB ) { return Math . sqrt ( distanceSquared ( pointA , pointB , offsetB ) ) ; }
Calculates the Euclidean distance of two points . Starts at dimension offset + 1 of pointB .
21,653
public static double distanceWithDivisionSquared ( double [ ] pointA , double dA ) { double distance = 0.0 ; for ( int i = 0 ; i < pointA . length ; i ++ ) { double d = pointA [ i ] / dA ; distance += d * d ; } return distance ; }
Calculates the squared Euclidean length of a point divided by a scalar .
21,654
public static double distanceWithDivision ( double [ ] pointA , double dA , double [ ] pointB ) { return Math . sqrt ( distanceWithDivisionSquared ( pointA , dA , pointB ) ) ; }
Calculates the Euclidean distance of the first point divided by a scalar and another second point .
21,655
public static double dotProduct ( double [ ] pointA ) { double product = 0.0 ; for ( int i = 0 ; i < pointA . length ; i ++ ) { product += pointA [ i ] * pointA [ i ] ; } return product ; }
Calculates the dot product of the point with itself .
21,656
public static double dotProductWithAddition ( double [ ] pointA1 , double [ ] pointA2 , double [ ] pointB ) { assert ( pointA1 . length == pointA2 . length && pointA1 . length == pointB . length ) ; double product = 0.0 ; for ( int i = 0 ; i < pointA1 . length ; i ++ ) { product += ( pointA1 [ i ] + pointA2 [ i ] ) * pointB [ i ] ; } return product ; }
Calculates the dot product of the addition of the first and the second point with the third point .
21,657
public static double dotProductWithAddition ( double [ ] pointA1 , double [ ] pointA2 , double [ ] pointB1 , double [ ] pointB2 ) { assert ( pointA1 . length == pointA2 . length && pointB1 . length == pointB2 . length && pointA1 . length == pointB1 . length ) ; double product = 0.0 ; for ( int i = 0 ; i < pointA1 . length ; i ++ ) { product += ( pointA1 [ i ] + pointA2 [ i ] ) * ( pointB1 [ i ] + pointB2 [ i ] ) ; } return product ; }
Calculates the dot product of the addition of the first and the second point with the addition of the third and the fourth point .
21,658
public Instance samoaInstance ( weka . core . Instance inst ) { Instance samoaInstance ; if ( inst instanceof weka . core . SparseInstance ) { double [ ] attributeValues = new double [ inst . numValues ( ) ] ; int [ ] indexValues = new int [ inst . numValues ( ) ] ; for ( int i = 0 ; i < inst . numValues ( ) ; i ++ ) { if ( inst . index ( i ) != inst . classIndex ( ) ) { attributeValues [ i ] = inst . valueSparse ( i ) ; indexValues [ i ] = inst . index ( i ) ; } } samoaInstance = new SparseInstance ( inst . weight ( ) , attributeValues , indexValues , inst . numAttributes ( ) ) ; } else { samoaInstance = new DenseInstance ( inst . weight ( ) , inst . toDoubleArray ( ) ) ; } if ( this . samoaInstanceInformation == null ) { this . samoaInstanceInformation = this . samoaInstancesInformation ( inst . dataset ( ) ) ; } samoaInstance . setDataset ( samoaInstanceInformation ) ; if ( inst . classIndex ( ) >= 0 ) { samoaInstance . setClassValue ( inst . classValue ( ) ) ; } return samoaInstance ; }
Samoa instance from weka instance .
21,659
public Instances samoaInstances ( weka . core . Instances instances ) { Instances samoaInstances = samoaInstancesInformation ( instances ) ; this . samoaInstanceInformation = samoaInstances ; for ( int i = 0 ; i < instances . numInstances ( ) ; i ++ ) { samoaInstances . add ( samoaInstance ( instances . instance ( i ) ) ) ; } return samoaInstances ; }
Samoa instances from weka instances .
21,660
public Instances samoaInstancesInformation ( weka . core . Instances instances ) { Instances samoaInstances ; List < Attribute > attInfo = new ArrayList < Attribute > ( ) ; for ( int i = 0 ; i < instances . numAttributes ( ) ; i ++ ) { attInfo . add ( samoaAttribute ( i , instances . attribute ( i ) ) ) ; } samoaInstances = new Instances ( instances . relationName ( ) , attInfo , 0 ) ; if ( instances . classIndex ( ) >= 0 ) { samoaInstances . setClassIndex ( instances . classIndex ( ) ) ; } return samoaInstances ; }
Samoa instances information .
21,661
protected Attribute samoaAttribute ( int index , weka . core . Attribute attribute ) { Attribute samoaAttribute ; if ( attribute . isNominal ( ) ) { Enumeration enu = attribute . enumerateValues ( ) ; List < String > attributeValues = new ArrayList < String > ( ) ; while ( enu . hasMoreElements ( ) ) { attributeValues . add ( ( String ) enu . nextElement ( ) ) ; } samoaAttribute = new Attribute ( attribute . name ( ) , attributeValues ) ; } else { samoaAttribute = new Attribute ( attribute . name ( ) ) ; } return samoaAttribute ; }
Get Samoa attribute from a weka attribute .
21,662
public void doSaveAs ( ) throws IOException { JFileChooser fileChooser = new JFileChooser ( ) ; ExtensionFileFilter filterPNG = new ExtensionFileFilter ( "PNG Image Files" , ".png" ) ; fileChooser . addChoosableFileFilter ( filterPNG ) ; ExtensionFileFilter filterJPG = new ExtensionFileFilter ( "JPG Image Files" , ".jpg" ) ; fileChooser . addChoosableFileFilter ( filterJPG ) ; ExtensionFileFilter filterEPS = new ExtensionFileFilter ( "EPS Image Files" , ".eps" ) ; fileChooser . addChoosableFileFilter ( filterEPS ) ; ExtensionFileFilter filterSVG = new ExtensionFileFilter ( "SVG Image Files" , ".svg" ) ; fileChooser . addChoosableFileFilter ( filterSVG ) ; fileChooser . setCurrentDirectory ( null ) ; int option = fileChooser . showSaveDialog ( this ) ; if ( option == JFileChooser . APPROVE_OPTION ) { String fileDesc = fileChooser . getFileFilter ( ) . getDescription ( ) ; if ( fileDesc . startsWith ( "PNG" ) ) { if ( ! fileChooser . getSelectedFile ( ) . getName ( ) . toUpperCase ( ) . endsWith ( "PNG" ) ) { ChartUtilities . saveChartAsPNG ( new File ( fileChooser . getSelectedFile ( ) . getAbsolutePath ( ) + ".png" ) , this . chart , this . getWidth ( ) , this . getHeight ( ) ) ; } else { ChartUtilities . saveChartAsPNG ( fileChooser . getSelectedFile ( ) , this . chart , this . getWidth ( ) , this . getHeight ( ) ) ; } } else if ( fileDesc . startsWith ( "JPG" ) ) { if ( ! fileChooser . getSelectedFile ( ) . getName ( ) . toUpperCase ( ) . endsWith ( "JPG" ) ) { ChartUtilities . saveChartAsJPEG ( new File ( fileChooser . getSelectedFile ( ) . getAbsolutePath ( ) + ".jpg" ) , this . chart , this . getWidth ( ) , this . getHeight ( ) ) ; } else { ChartUtilities . saveChartAsJPEG ( fileChooser . getSelectedFile ( ) , this . chart , this . getWidth ( ) , this . getHeight ( ) ) ; } } } }
Method for save the images .
21,663
protected BigDecimal round ( double val ) { BigDecimal value = new BigDecimal ( val ) ; if ( val != 0.0 ) { value = value . setScale ( 3 , BigDecimal . ROUND_DOWN ) ; } return value ; }
Round an number
21,664
public void initializeRuleStatistics ( RuleClassification rl , Predicates pred , Instance inst ) { rl . predicateSet . add ( pred ) ; rl . obserClassDistrib = new DoubleVector ( ) ; rl . observers = new AutoExpandVector < AttributeClassObserver > ( ) ; rl . observersGauss = new AutoExpandVector < AttributeClassObserver > ( ) ; rl . instancesSeen = 0 ; rl . attributeStatistics = new DoubleVector ( ) ; rl . squaredAttributeStatistics = new DoubleVector ( ) ; rl . attributeStatisticsSupervised = new ArrayList < ArrayList < Double > > ( ) ; rl . squaredAttributeStatisticsSupervised = new ArrayList < ArrayList < Double > > ( ) ; rl . attributeMissingValues = new DoubleVector ( ) ; }
This function initializes the statistics of a rule
21,665
public void updateRuleAttribStatistics ( Instance inst , RuleClassification rl , int ruleIndex ) { rl . instancesSeen ++ ; if ( rl . squaredAttributeStatisticsSupervised . size ( ) == 0 && rl . attributeStatisticsSupervised . size ( ) == 0 ) { for ( int s = 0 ; s < inst . numAttributes ( ) - 1 ; s ++ ) { ArrayList < Double > temp1 = new ArrayList < Double > ( ) ; ArrayList < Double > temp2 = new ArrayList < Double > ( ) ; rl . attributeStatisticsSupervised . add ( temp1 ) ; rl . squaredAttributeStatisticsSupervised . add ( temp2 ) ; int instAttIndex = modelAttIndexToInstanceAttIndex ( s , inst ) ; if ( instance . attribute ( instAttIndex ) . isNumeric ( ) ) { for ( int i = 0 ; i < inst . numClasses ( ) ; i ++ ) { rl . attributeStatisticsSupervised . get ( s ) . add ( 0.0 ) ; rl . squaredAttributeStatisticsSupervised . get ( s ) . add ( 1.0 ) ; } } } } for ( int s = 0 ; s < inst . numAttributes ( ) - 1 ; s ++ ) { int instAttIndex = modelAttIndexToInstanceAttIndex ( s , inst ) ; if ( ! inst . isMissing ( instAttIndex ) ) { if ( instance . attribute ( instAttIndex ) . isNumeric ( ) ) { rl . attributeStatistics . addToValue ( s , inst . value ( s ) ) ; rl . squaredAttributeStatistics . addToValue ( s , inst . value ( s ) * inst . value ( s ) ) ; double sumValue = rl . attributeStatisticsSupervised . get ( s ) . get ( ( int ) inst . classValue ( ) ) + inst . value ( s ) ; rl . attributeStatisticsSupervised . get ( s ) . set ( ( int ) inst . classValue ( ) , sumValue ) ; double squaredSumvalue = rl . squaredAttributeStatisticsSupervised . get ( s ) . get ( ( int ) inst . classValue ( ) ) + ( inst . value ( s ) * inst . value ( s ) ) ; rl . squaredAttributeStatisticsSupervised . get ( s ) . set ( ( int ) inst . classValue ( ) , squaredSumvalue ) ; } } else { rl . attributeMissingValues . addToValue ( s , 1 ) ; } } }
Update rule statistics
21,666
public void createRule ( Instance inst ) { int remainder = ( int ) Double . MAX_VALUE ; int numInstanciaObservers = ( int ) this . observedClassDistribution . sumOfValues ( ) ; if ( numInstanciaObservers != 0 && this . gracePeriodOption . getValue ( ) != 0 ) { remainder = ( numInstanciaObservers ) % ( this . gracePeriodOption . getValue ( ) ) ; } if ( remainder == 0 ) { this . saveBestValGlobalEntropy = new ArrayList < ArrayList < Double > > ( ) ; this . saveBestGlobalEntropy = new DoubleVector ( ) ; this . saveTheBest = new ArrayList < Double > ( ) ; this . minEntropyTemp = Double . MAX_VALUE ; this . minEntropyNominalAttrib = Double . MAX_VALUE ; theBestAttributes ( inst , this . attributeObservers ) ; boolean HB = checkBestAttrib ( numInstanciaObservers , this . attributeObservers , this . observedClassDistribution ) ; if ( HB == true ) { double attributeValue = this . saveTheBest . get ( 3 ) ; double symbol = this . saveTheBest . get ( 2 ) ; double value = this . saveTheBest . get ( 0 ) ; this . pred = new Predicates ( attributeValue , symbol , value ) ; RuleClassification Rl = new RuleClassification ( ) ; Rl . predicateSet . add ( pred ) ; this . ruleSet . add ( Rl ) ; if ( Rl . predicateSet . get ( 0 ) . getSymbol ( ) == - 1.0 || Rl . predicateSet . get ( 0 ) . getSymbol ( ) == 1.0 ) { double posClassDouble = this . saveTheBest . get ( 4 ) ; this . ruleClassIndex . setValue ( this . ruleSet . size ( ) - 1 , posClassDouble ) ; } else { this . ruleClassIndex . setValue ( ruleSet . size ( ) - 1 , 0.0 ) ; } this . observedClassDistribution = new DoubleVector ( ) ; this . attributeObservers = new AutoExpandVector < AttributeClassObserver > ( ) ; this . attributeObserversGauss = new AutoExpandVector < AttributeClassObserver > ( ) ; } } }
This function creates a rule
21,667
public void theBestAttributes ( Instance instance , AutoExpandVector < AttributeClassObserver > observersParameter ) { for ( int z = 0 ; z < instance . numAttributes ( ) - 1 ; z ++ ) { if ( ! instance . isMissing ( z ) ) { int instAttIndex = modelAttIndexToInstanceAttIndex ( z , instance ) ; ArrayList < Double > attribBest = new ArrayList < Double > ( ) ; if ( instance . attribute ( instAttIndex ) . isNominal ( ) ) { this . minEntropyNominalAttrib = Double . MAX_VALUE ; AutoExpandVector < DoubleVector > attribNominal = ( ( NominalAttributeClassObserver ) observersParameter . get ( z ) ) . attValDistPerClass ; findBestValEntropyNominalAtt ( attribNominal , instance . attribute ( z ) . numValues ( ) ) ; attribBest . add ( this . saveBestEntropyNominalAttrib . getValue ( 0 ) ) ; attribBest . add ( this . saveBestEntropyNominalAttrib . getValue ( 1 ) ) ; attribBest . add ( this . saveBestEntropyNominalAttrib . getValue ( 2 ) ) ; this . saveBestValGlobalEntropy . add ( attribBest ) ; this . saveBestGlobalEntropy . setValue ( z , this . saveBestEntropyNominalAttrib . getValue ( 1 ) ) ; } else { this . root = ( ( BinaryTreeNumericAttributeClassObserver ) observersParameter . get ( z ) ) . root ; mainFindBestValEntropy ( this . root ) ; attribBest . add ( this . saveBestEntropy . getValue ( 0 ) ) ; attribBest . add ( this . saveBestEntropy . getValue ( 1 ) ) ; attribBest . add ( this . saveBestEntropy . getValue ( 2 ) ) ; attribBest . add ( this . saveBestEntropy . getValue ( 4 ) ) ; this . saveBestValGlobalEntropy . add ( attribBest ) ; this . saveBestGlobalEntropy . setValue ( z , this . saveBestEntropy . getValue ( 1 ) ) ; } } else { double value = Double . MAX_VALUE ; this . saveBestGlobalEntropy . setValue ( z , value ) ; } } }
This function gives the best value of entropy for each attribute
21,668
public void mainFindBestValEntropy ( Node root ) { if ( root != null ) { DoubleVector parentClassCL = new DoubleVector ( ) ; DoubleVector classCountL = root . classCountsLeft ; DoubleVector classCountR = root . classCountsRight ; double numInst = root . classCountsLeft . sumOfValues ( ) + root . classCountsRight . sumOfValues ( ) ; double classCountLSum = root . classCountsLeft . sumOfValues ( ) ; double classCountRSum = root . classCountsRight . sumOfValues ( ) ; double classCountLEntropy = entropy ( classCountL ) ; double classCountREntropy = entropy ( classCountR ) ; this . minEntropyTemp = ( classCountLSum / numInst ) * classCountLEntropy + ( classCountRSum / numInst ) * classCountREntropy ; for ( int f = 0 ; f < root . classCountsLeft . numValues ( ) ; f ++ ) { parentClassCL . setValue ( f , root . classCountsLeft . getValue ( f ) ) ; } findBestValEntropy ( root , classCountL , classCountR , true , this . minEntropyTemp , parentClassCL ) ; } }
Best value of entropy
21,669
public void findBestValEntropyNominalAtt ( AutoExpandVector < DoubleVector > attrib , int attNumValues ) { ArrayList < ArrayList < Double > > distClassValue = new ArrayList < ArrayList < Double > > ( ) ; for ( int z = 0 ; z < attrib . size ( ) ; z ++ ) { distClassValue . add ( new ArrayList < Double > ( ) ) ; } for ( int v = 0 ; v < attNumValues ; v ++ ) { DoubleVector saveVal = new DoubleVector ( ) ; for ( int z = 0 ; z < attrib . size ( ) ; z ++ ) { if ( attrib . get ( z ) != null ) { distClassValue . get ( z ) . add ( attrib . get ( z ) . getValue ( v ) ) ; } else { distClassValue . get ( z ) . add ( 0.0 ) ; } if ( distClassValue . get ( z ) . get ( v ) . isNaN ( ) ) { distClassValue . get ( z ) . add ( 0.0 ) ; } saveVal . setValue ( z , distClassValue . get ( z ) . get ( v ) ) ; } double sumValue = saveVal . sumOfValues ( ) ; if ( sumValue > 0.0 ) { double entropyVal = entropy ( saveVal ) ; if ( entropyVal <= this . minEntropyNominalAttrib ) { this . minEntropyNominalAttrib = entropyVal ; this . saveBestEntropyNominalAttrib . setValue ( 0 , v ) ; this . saveBestEntropyNominalAttrib . setValue ( 1 , entropyVal ) ; this . saveBestEntropyNominalAttrib . setValue ( 2 , 0.0 ) ; } } } }
Find best value of entropy for nominal attributes
21,670
public boolean checkBestAttrib ( double n , AutoExpandVector < AttributeClassObserver > observerss , DoubleVector observedClassDistribution ) { double h0 = entropy ( observedClassDistribution ) ; boolean isTheBest = false ; double [ ] entropyValues = getBestSecondBestEntropy ( this . saveBestGlobalEntropy ) ; double bestEntropy = entropyValues [ 0 ] ; double secondBestEntropy = entropyValues [ 1 ] ; double range = Utils . log2 ( this . numClass ) ; double hoeffdingBound = ComputeHoeffdingBound ( range , this . splitConfidenceOption . getValue ( ) , n ) ; if ( ( h0 > bestEntropy ) && ( ( secondBestEntropy - bestEntropy > hoeffdingBound ) || ( hoeffdingBound < this . tieThresholdOption . getValue ( ) ) ) ) { for ( int i = 0 ; i < this . saveBestValGlobalEntropy . size ( ) ; i ++ ) { if ( bestEntropy == ( this . saveBestValGlobalEntropy . get ( i ) . get ( 1 ) ) ) { this . saveTheBest . add ( this . saveBestValGlobalEntropy . get ( i ) . get ( 0 ) ) ; this . saveTheBest . add ( this . saveBestValGlobalEntropy . get ( i ) . get ( 1 ) ) ; this . saveTheBest . add ( this . saveBestValGlobalEntropy . get ( i ) . get ( 2 ) ) ; this . saveTheBest . add ( ( double ) i ) ; if ( this . saveTheBest . get ( 2 ) != 0.0 ) { this . saveTheBest . add ( this . saveBestValGlobalEntropy . get ( i ) . get ( 3 ) ) ; } break ; } } isTheBest = true ; } else { isTheBest = false ; } return isTheBest ; }
Check if the best attribute is really the best
21,671
protected double [ ] getBestSecondBestEntropy ( DoubleVector entropy ) { double [ ] entropyValues = new double [ 2 ] ; double best = Double . MAX_VALUE ; double secondBest = Double . MAX_VALUE ; for ( int i = 0 ; i < entropy . numValues ( ) ; i ++ ) { if ( entropy . getValue ( i ) < best ) { secondBest = best ; best = entropy . getValue ( i ) ; } else { if ( entropy . getValue ( i ) < secondBest ) { secondBest = entropy . getValue ( i ) ; } } } entropyValues [ 0 ] = best ; entropyValues [ 1 ] = secondBest ; return entropyValues ; }
Get best and second best attributes
21,672
protected double getRuleMajorityClassIndex ( RuleClassification r ) { double maxvalue = 0.0 ; int posMaxValue = 0 ; for ( int i = 0 ; i < r . obserClassDistrib . numValues ( ) ; i ++ ) { if ( r . obserClassDistrib . getValue ( i ) > maxvalue ) { maxvalue = r . obserClassDistrib . getValue ( i ) ; posMaxValue = i ; } } return ( double ) posMaxValue ; }
Get rule majority class index
21,673
protected double [ ] oberversDistribProb ( Instance inst , DoubleVector classDistrib ) { double [ ] votes = new double [ this . numClass ] ; double sum = classDistrib . sumOfValues ( ) ; for ( int z = 0 ; z < this . numClass ; z ++ ) { votes [ z ] = classDistrib . getValue ( z ) / sum ; } return votes ; }
Get observers class distribution probability
21,674
protected double [ ] weightedMax ( Instance inst ) { int countFired = 0 ; boolean fired = false ; double highest = 0.0 ; double [ ] votes = new double [ this . numClass ] ; ArrayList < Double > ruleSetVotes = new ArrayList < Double > ( ) ; ArrayList < ArrayList < Double > > majorityProb = new ArrayList < ArrayList < Double > > ( ) ; for ( int j = 0 ; j < this . ruleSet . size ( ) ; j ++ ) { ArrayList < Double > ruleProb = new ArrayList < Double > ( ) ; if ( this . ruleSet . get ( j ) . ruleEvaluate ( inst ) == true ) { countFired = countFired + 1 ; for ( int z = 0 ; z < this . numClass ; z ++ ) { ruleSetVotes . add ( this . ruleSet . get ( j ) . obserClassDistrib . getValue ( z ) / this . ruleSet . get ( j ) . obserClassDistrib . sumOfValues ( ) ) ; ruleProb . add ( this . ruleSet . get ( j ) . obserClassDistrib . getValue ( z ) / this . ruleSet . get ( j ) . obserClassDistrib . sumOfValues ( ) ) ; } majorityProb . add ( ruleProb ) ; } } if ( countFired > 0 ) { fired = true ; Collections . sort ( ruleSetVotes ) ; highest = ruleSetVotes . get ( ruleSetVotes . size ( ) - 1 ) ; for ( int t = 0 ; t < majorityProb . size ( ) ; t ++ ) { for ( int m = 0 ; m < majorityProb . get ( t ) . size ( ) ; m ++ ) { if ( majorityProb . get ( t ) . get ( m ) == highest ) { for ( int h = 0 ; h < majorityProb . get ( t ) . size ( ) ; h ++ ) { votes [ h ] = majorityProb . get ( t ) . get ( h ) ; } break ; } } } } else { fired = false ; } if ( fired == false ) { votes = oberversDistribProb ( inst , this . observedClassDistribution ) ; } return votes ; }
Get the votes using weighted Max
21,675
protected double [ ] weightedSum ( Instance inst ) { boolean fired = false ; int countFired = 0 ; double [ ] votes = new double [ this . numClass ] ; ArrayList < Double > weightSum = new ArrayList < Double > ( ) ; ArrayList < ArrayList < Double > > majorityProb = new ArrayList < ArrayList < Double > > ( ) ; for ( int j = 0 ; j < this . ruleSet . size ( ) ; j ++ ) { ArrayList < Double > ruleProb = new ArrayList < Double > ( ) ; if ( this . ruleSet . get ( j ) . ruleEvaluate ( inst ) == true ) { countFired = countFired + 1 ; for ( int z = 0 ; z < this . numClass ; z ++ ) { ruleProb . add ( this . ruleSet . get ( j ) . obserClassDistrib . getValue ( z ) / this . ruleSet . get ( j ) . obserClassDistrib . sumOfValues ( ) ) ; } majorityProb . add ( ruleProb ) ; } } if ( countFired > 0 ) { fired = true ; for ( int m = 0 ; m < majorityProb . get ( 0 ) . size ( ) ; m ++ ) { double sum = 0.0 ; for ( int t = 0 ; t < majorityProb . size ( ) ; t ++ ) { sum = sum + majorityProb . get ( t ) . get ( m ) ; } weightSum . add ( sum ) ; } for ( int h = 0 ; h < weightSum . size ( ) ; h ++ ) { votes [ h ] = weightSum . get ( h ) / majorityProb . size ( ) ; } } else { fired = false ; } if ( fired == false ) { votes = oberversDistribProb ( inst , this . observedClassDistribution ) ; } return votes ; }
Get the votes using weighted Sum
21,676
protected void closeDialog ( ) { if ( m_CustomEditor instanceof Container ) { Dialog dlg = PropertyDialog . getParentDialog ( ( Container ) m_CustomEditor ) ; if ( dlg != null ) dlg . setVisible ( false ) ; } }
Closes the dialog .
21,677
protected Component createCustomEditor ( ) { JPanel panel ; panel = new JPanel ( new BorderLayout ( ) ) ; panel . setBorder ( BorderFactory . createEmptyBorder ( 5 , 5 , 5 , 5 ) ) ; m_EditComponent = ( ClassOptionEditComponent ) getEditComponent ( ( ClassOption ) getValue ( ) ) ; m_EditComponent . addChangeListener ( new ChangeListener ( ) { public void stateChanged ( ChangeEvent e ) { m_EditComponent . applyState ( ) ; setValue ( m_EditComponent . getEditedOption ( ) ) ; } } ) ; panel . add ( m_EditComponent , BorderLayout . CENTER ) ; return panel ; }
Creates the custom editor .
21,678
public void paintValue ( Graphics gfx , Rectangle box ) { FontMetrics fm ; int vpad ; String val ; fm = gfx . getFontMetrics ( ) ; vpad = ( box . height - fm . getHeight ( ) ) / 2 ; val = ( ( ClassOption ) getValue ( ) ) . getValueAsCLIString ( ) ; gfx . drawString ( val , 2 , fm . getHeight ( ) + vpad ) ; }
Paints a representation of the current Object .
21,679
private double prediction ( Instance inst ) { if ( this . initialisePerceptron ) { return 0 ; } else { double [ ] normalizedInstance = normalizedInstance ( inst ) ; double normalizedPrediction = prediction ( normalizedInstance ) ; return denormalizedPrediction ( normalizedPrediction ) ; } }
Output the prediction made by this perceptron on the given instance
21,680
void insertPoint ( Point p ) { int cursize = this . buckets [ 0 ] . cursize ; if ( cursize >= this . maxBucketsize ) { int curbucket = 0 ; int nextbucket = 1 ; if ( this . buckets [ nextbucket ] . cursize == 0 ) { int i ; for ( i = 0 ; i < this . maxBucketsize ; i ++ ) { this . buckets [ nextbucket ] . points [ i ] = this . buckets [ curbucket ] . points [ i ] . clone ( ) ; } this . buckets [ nextbucket ] . cursize = this . maxBucketsize ; this . buckets [ curbucket ] . cursize = 0 ; cursize = 0 ; } else { int i ; for ( i = 0 ; i < this . maxBucketsize ; i ++ ) { this . buckets [ nextbucket ] . spillover [ i ] = this . buckets [ curbucket ] . points [ i ] . clone ( ) ; } this . buckets [ 0 ] . cursize = 0 ; cursize = 0 ; curbucket ++ ; nextbucket ++ ; while ( this . buckets [ nextbucket ] . cursize == this . maxBucketsize ) { this . treeCoreset . unionTreeCoreset ( this . maxBucketsize , this . maxBucketsize , this . maxBucketsize , p . dimension , this . buckets [ curbucket ] . points , this . buckets [ curbucket ] . spillover , this . buckets [ nextbucket ] . spillover , this . clustererRandom ) ; this . buckets [ curbucket ] . cursize = 0 ; curbucket ++ ; nextbucket ++ ; } this . treeCoreset . unionTreeCoreset ( this . maxBucketsize , this . maxBucketsize , this . maxBucketsize , p . dimension , this . buckets [ curbucket ] . points , this . buckets [ curbucket ] . spillover , this . buckets [ nextbucket ] . points , this . clustererRandom ) ; this . buckets [ curbucket ] . cursize = 0 ; this . buckets [ nextbucket ] . cursize = this . maxBucketsize ; } } this . buckets [ 0 ] . points [ cursize ] = p . clone ( ) ; this . buckets [ 0 ] . cursize ++ ; }
inserts a single point into the bucketmanager
21,681
protected void processChunk ( ) { Classifier addedClassifier = null ; double mse_r = this . computeMseR ( ) ; double candidateClassifierWeight = 1.0 / ( mse_r + Double . MIN_VALUE ) ; for ( int i = 0 ; i < this . learners . length ; i ++ ) { this . weights [ i ] [ 0 ] = 1.0 / ( mse_r + this . computeMse ( this . learners [ ( int ) this . weights [ i ] [ 1 ] ] , this . currentChunk ) + Double . MIN_VALUE ) ; } if ( this . learners . length < this . memberCountOption . getValue ( ) ) { addedClassifier = this . addToStored ( this . candidate , candidateClassifierWeight ) ; } else { int poorestClassifier = this . getPoorestClassifierIndex ( ) ; if ( this . weights [ poorestClassifier ] [ 0 ] < candidateClassifierWeight ) { this . weights [ poorestClassifier ] [ 0 ] = candidateClassifierWeight ; addedClassifier = this . candidate . copy ( ) ; this . learners [ ( int ) this . weights [ poorestClassifier ] [ 1 ] ] = addedClassifier ; } } for ( int i = 0 ; i < this . learners . length ; i ++ ) { this . trainOnChunk ( this . learners [ ( int ) this . weights [ i ] [ 1 ] ] ) ; } this . classDistributions = null ; this . currentChunk = null ; this . candidate = ( Classifier ) getPreparedClassOption ( this . learnerOption ) ; this . candidate . resetLearning ( ) ; this . enforceMemoryLimit ( ) ; }
Processes a chunk of instances . This method is called after collecting a chunk of examples .
21,682
protected double computeMse ( Classifier learner , Instances chunk ) { double mse_i = 0 ; double f_ci ; double voteSum ; for ( int i = 0 ; i < chunk . numInstances ( ) ; i ++ ) { try { voteSum = 0 ; for ( double element : learner . getVotesForInstance ( chunk . instance ( i ) ) ) { voteSum += element ; } if ( voteSum > 0 ) { f_ci = learner . getVotesForInstance ( chunk . instance ( i ) ) [ ( int ) chunk . instance ( i ) . classValue ( ) ] / voteSum ; mse_i += ( 1 - f_ci ) * ( 1 - f_ci ) ; } else { mse_i += 1 ; } } catch ( Exception e ) { mse_i += 1 ; } } mse_i /= this . chunkSizeOption . getValue ( ) ; return mse_i ; }
Computes the MSE of a learner for a given chunk of examples .
21,683
private void trainOnChunk ( Classifier classifierToTrain ) { for ( int num = 0 ; num < this . chunkSizeOption . getValue ( ) ; num ++ ) { classifierToTrain . trainOnInstance ( this . currentChunk . instance ( num ) ) ; } }
Trains a component classifier on the most recent chunk of data .
21,684
public Cluster get ( int index ) { if ( index < clusters . size ( ) ) { return clusters . get ( index ) ; } return null ; }
get a cluster from the clustering
21,685
public FoundNode [ ] filterInstanceToLeaves ( Instance inst , SplitNode parent , int parentBranch , boolean updateSplitterCounts ) { List < FoundNode > nodes = new LinkedList < FoundNode > ( ) ; ( ( NewNode ) this . treeRoot ) . filterInstanceToLeaves ( inst , parent , parentBranch , nodes , updateSplitterCounts ) ; return nodes . toArray ( new FoundNode [ nodes . size ( ) ] ) ; }
New for options vote
21,686
public void setRange ( String range ) { String single = range . trim ( ) ; int hyphenIndex = range . indexOf ( '-' ) ; if ( hyphenIndex > 0 ) { this . start = rangeSingle ( range . substring ( 0 , hyphenIndex ) ) ; this . end = rangeSingle ( range . substring ( hyphenIndex + 1 ) ) ; } else { int number = rangeSingle ( range ) ; if ( number >= 0 ) { this . start = 0 ; this . end = number ; } else { this . start = this . upperLimit + number > 0 ? this . upperLimit + number : 0 ; this . end = this . upperLimit - 1 ; } } }
Sets the range from a string representation .
21,687
protected int rangeSingle ( String singleSelection ) { String single = singleSelection . trim ( ) ; if ( single . toLowerCase ( ) . equals ( "first" ) ) { return 0 ; } if ( single . toLowerCase ( ) . equals ( "last" ) || single . toLowerCase ( ) . equals ( "-1" ) ) { return - 1 ; } int index = Integer . parseInt ( single ) ; if ( index >= 1 ) { index -- ; } return index ; }
Translates a single string selection into it s internal 0 - based equivalent .
21,688
public static < T extends Comparable < T > > Pair < T > minMax ( Iterable < T > items ) { Iterator < T > iterator = items . iterator ( ) ; if ( ! iterator . hasNext ( ) ) { return null ; } T min = iterator . next ( ) ; T max = min ; while ( iterator . hasNext ( ) ) { T item = iterator . next ( ) ; if ( item . compareTo ( min ) < 0 ) { min = item ; } if ( item . compareTo ( max ) > 0 ) { max = item ; } } return new Pair < T > ( min , max ) ; }
Identifies the minimum and maximum elements from an iterable according to the natural ordering of the elements .
21,689
public static < T > List < T > randomSample ( Collection < T > collection , int n ) { List < T > list = new ArrayList < T > ( collection ) ; List < T > sample = new ArrayList < T > ( n ) ; Random random = new Random ( ) ; while ( n > 0 && ! list . isEmpty ( ) ) { int index = random . nextInt ( list . size ( ) ) ; sample . add ( list . get ( index ) ) ; int indexLast = list . size ( ) - 1 ; T last = list . remove ( indexLast ) ; if ( index < indexLast ) { list . set ( index , last ) ; } n -- ; } return sample ; }
Randomly chooses elements from the collection .
21,690
private boolean updateMinMaxValues ( ) { double min_y_value_new = min_y_value ; double max_y_value_new = max_y_value ; double max_x_value_new = max_x_value ; if ( measure0 != null && measure1 != null ) { min_y_value_new = Math . min ( measure0 . getMinValue ( measureSelected ) , measure1 . getMinValue ( measureSelected ) ) ; max_y_value_new = Math . max ( measure0 . getMaxValue ( measureSelected ) , measure1 . getMaxValue ( measureSelected ) ) ; max_x_value_new = Math . max ( measure0 . getNumberOfValues ( measureSelected ) , max_x_value ) ; } else { if ( measure0 != null ) { min_y_value_new = measure0 . getMinValue ( measureSelected ) ; max_y_value_new = measure0 . getMaxValue ( measureSelected ) ; max_x_value_new = Math . max ( measure0 . getNumberOfValues ( measureSelected ) , max_x_value ) ; } } if ( max_x_value_new != max_x_value || max_y_value_new != max_y_value || min_y_value_new != min_y_value ) { min_y_value = min_y_value_new ; max_y_value = max_y_value_new ; max_x_value = max_x_value_new ; return true ; } return false ; }
returns true when values have changed
21,691
private void addEvents ( ) { if ( clusterEvents != null && clusterEvents . size ( ) > eventCounter ) { ClusterEvent ev = clusterEvents . get ( eventCounter ) ; eventCounter ++ ; JLabel eventMarker = new JLabel ( ev . getType ( ) . substring ( 0 , 1 ) ) ; eventMarker . setPreferredSize ( new Dimension ( 20 , y_offset_top ) ) ; eventMarker . setSize ( new Dimension ( 20 , y_offset_top ) ) ; eventMarker . setHorizontalAlignment ( javax . swing . SwingConstants . CENTER ) ; int x = ( int ) ( ev . getTimestamp ( ) / processFrequency / x_resolution ) ; eventMarker . setLocation ( x - 10 , 0 ) ; eventMarker . setToolTipText ( ev . getType ( ) + " at " + ev . getTimestamp ( ) + ": " + ev . getMessage ( ) ) ; eventPanel . add ( eventMarker ) ; eventLabelList . add ( eventMarker ) ; eventPanel . repaint ( ) ; } }
check if there are any new events in the event list and add them to the plot
21,692
public void addResult ( Example < Instance > example , double [ ] classVotes ) { Prediction p = new MultiLabelPrediction ( 1 ) ; p . setVotes ( classVotes ) ; addResult ( example , p ) ; }
only for one output
21,693
public void setGraph ( MeasureCollection [ ] measures , MeasureCollection [ ] measureStds , double [ ] variedParamValues , Color [ ] colors ) { this . measures = measures ; this . variedParamValues = variedParamValues ; ( ( GraphScatter ) this . plotPanel ) . setGraph ( measures , measureStds , variedParamValues , colors ) ; updateCanvas ( false ) ; }
Sets the scatter graph .
21,694
public double [ ] getVotesForInstance ( Instance instance ) { CNode host = m_cobwebTree ; CNode temp = null ; determineNumberOfClusters ( ) ; if ( this . m_numberOfClusters < 1 ) { return ( new double [ 0 ] ) ; } double [ ] ret = new double [ this . m_numberOfClusters ] ; do { if ( host . m_children == null ) { temp = null ; break ; } host . updateStats ( instance , false ) ; temp = host . findHost ( instance , true ) ; host . updateStats ( instance , true ) ; if ( temp != null ) { host = temp ; } } while ( temp != null ) ; ret [ host . m_clusterNum ] = 1.0 ; return ret ; }
Classifies a given instance .
21,695
protected void determineNumberOfClusters ( ) { if ( ! m_numberOfClustersDetermined && ( m_cobwebTree != null ) ) { int [ ] numClusts = new int [ 1 ] ; numClusts [ 0 ] = 0 ; m_cobwebTree . assignClusterNums ( numClusts ) ; m_numberOfClusters = numClusts [ 0 ] ; m_numberOfClustersDetermined = true ; } }
determines the number of clusters if necessary
21,696
public String graph ( ) { StringBuffer text = new StringBuffer ( ) ; text . append ( "digraph CobwebTree {\n" ) ; m_cobwebTree . graphTree ( text ) ; text . append ( "}\n" ) ; return text . toString ( ) ; }
Generates the graph string of the Cobweb tree
21,697
public double sqDifference ( int index , double val1 , double val2 ) { double val = difference ( index , val1 , val2 ) ; return val * val ; }
Returns the squared difference of two values of an attribute .
21,698
public int closestPoint ( Instance instance , Instances allPoints , int [ ] pointList ) throws Exception { double minDist = Integer . MAX_VALUE ; int bestPoint = 0 ; for ( int i = 0 ; i < pointList . length ; i ++ ) { double dist = distance ( instance , allPoints . instance ( pointList [ i ] ) , Double . POSITIVE_INFINITY ) ; if ( dist < minDist ) { minDist = dist ; bestPoint = i ; } } return pointList [ bestPoint ] ; }
Returns the index of the closest point to the current instance . Index is index in Instances object that is the second parameter .
21,699
public void openConfig ( String path ) { Properties properties = new Properties ( ) ; try { properties . load ( new FileInputStream ( path ) ) ; } catch ( IOException ex ) { JOptionPane . showMessageDialog ( this , "Problems reading the properties file" , "Error" , JOptionPane . ERROR_MESSAGE ) ; } this . jTextFieldProcess . setText ( properties . getProperty ( "processors" ) ) ; this . jTextFieldTask . setText ( properties . getProperty ( "task" ) ) ; try { this . currentTask = ( MainTask ) ClassOption . cliStringToObject ( this . jTextFieldTask . getText ( ) , MainTask . class , null ) ; } catch ( Exception ex ) { Logger . getLogger ( TaskManagerTabPanel . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } this . jTextFieldDir . setText ( properties . getProperty ( "ResultsDir" ) ) ; this . resultsPath = this . jTextFieldDir . getText ( ) ; String [ ] streamShortNames = properties . getProperty ( "streamShortNames" ) . split ( "," ) ; String [ ] streamCommand = properties . getProperty ( "streamCommand" ) . split ( "," ) ; String [ ] algShortNames = properties . getProperty ( "algorithmShortNames" ) . split ( "," ) ; String [ ] algorithmCommand = properties . getProperty ( "algorithmCommand" ) . split ( "," ) ; cleanTables ( ) ; for ( int i = 0 ; i < streamShortNames . length ; i ++ ) { this . streamModel . addRow ( new Object [ ] { streamCommand [ i ] , streamShortNames [ i ] } ) ; } for ( int i = 0 ; i < algShortNames . length ; i ++ ) { this . algoritmModel . addRow ( new Object [ ] { algorithmCommand [ i ] , algShortNames [ i ] } ) ; } }
Opens a previously saved configuration