idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
21,500
public double [ ] getVotesForInstance ( Instance inst ) { double [ ] votes = { 0.5 , 0.5 } ; if ( this . neighbourhood . size ( ) > 2 ) { votes [ 1 ] = Math . pow ( 2.0 , - 1.0 * this . getAnomalyScore ( inst ) / this . tau ) ; votes [ 0 ] = 1.0 - votes [ 1 ] ; } return votes ; }
Calculates the distance between the argument instance and its nearest neighbour as well as the distance between that nearest neighbour and its own nearest neighbour . The ratio of these distances is compared to the threshold value tau and converted into a vote score .
21,501
public double getAnomalyScore ( Instance inst ) { if ( this . neighbourhood . size ( ) < 2 ) return 1.0 ; Instance nearestNeighbour = getNearestNeighbour ( inst , this . neighbourhood , false ) ; Instance nnNearestNeighbour = getNearestNeighbour ( nearestNeighbour , this . neighbourhood , true ) ; double indicatorArgument = distance ( inst , nearestNeighbour ) / distance ( nearestNeighbour , nnNearestNeighbour ) ; return indicatorArgument ; }
Returns the anomaly score for an argument instance based on the distance from it to its nearest neighbour compared to the distance from its nearest neighbour to the neighbour s nearest neighbour .
21,502
private Instance getNearestNeighbour ( Instance inst , List < Instance > neighbourhood2 , boolean inNbhd ) { double dist = Double . MAX_VALUE ; Instance nearestNeighbour = null ; for ( Instance candidateNN : neighbourhood2 ) { if ( inNbhd && ( distance ( inst , candidateNN ) == 0 ) ) { inNbhd = false ; } else { if ( distance ( inst , candidateNN ) < dist ) { nearestNeighbour = candidateNN . copy ( ) ; dist = distance ( inst , candidateNN ) ; } } } return nearestNeighbour ; }
Searches the neighbourhood in order to find the argument instance s nearest neighbour .
21,503
private double distance ( Instance inst1 , Instance inst2 ) { double dist = 0.0 ; for ( int i = 0 ; i < inst1 . numAttributes ( ) ; i ++ ) { dist += Math . pow ( ( inst1 . value ( i ) - inst2 . value ( i ) ) , 2.0 ) ; } return Math . sqrt ( dist ) ; }
Calculates the Euclidean distance between two instances .
21,504
public double costOfPointToCenter ( Point centre ) { if ( this . weight == 0.0 ) { return 0.0 ; } double distance = 0.0 ; for ( int l = 0 ; l < this . dimension ; l ++ ) { double centroidCoordinatePoint ; if ( this . weight != 0.0 ) { centroidCoordinatePoint = this . coordinates [ l ] / this . weight ; } else { centroidCoordinatePoint = this . coordinates [ l ] ; } double centroidCoordinateCentre ; if ( centre . weight != 0.0 ) { centroidCoordinateCentre = centre . coordinates [ l ] / centre . weight ; } else { centroidCoordinateCentre = centre . coordinates [ l ] ; } distance += ( centroidCoordinatePoint - centroidCoordinateCentre ) * ( centroidCoordinatePoint - centroidCoordinateCentre ) ; } return distance * this . weight ; }
Computes the cost of this point with centre centre
21,505
public static MOAObject fromOption ( ClassOption option ) { return MOAUtils . fromCommandLine ( option . getRequiredType ( ) , option . getValueAsCLIString ( ) ) ; }
Creates a MOA object from the specified class option .
21,506
public static String toCommandLine ( MOAObject obj ) { String result = obj . getClass ( ) . getName ( ) ; if ( obj instanceof AbstractOptionHandler ) result += " " + ( ( AbstractOptionHandler ) obj ) . getOptions ( ) . getAsCLIString ( ) ; return result . trim ( ) ; }
Returs the commandline for the given object . If the object is not derived from AbstractOptionHandler then only the classname . Otherwise the classname and the options are returned .
21,507
private Instance readDenseInstanceSparse ( ) { Instance instance = newDenseInstance ( this . instanceInformation . numAttributes ( ) ) ; int numAttribute ; try { streamTokenizer . nextToken ( ) ; while ( streamTokenizer . ttype != StreamTokenizer . TT_EOL && streamTokenizer . ttype != StreamTokenizer . TT_EOF ) { while ( streamTokenizer . ttype != '}' ) { numAttribute = ( int ) streamTokenizer . nval ; streamTokenizer . nextToken ( ) ; if ( streamTokenizer . ttype == StreamTokenizer . TT_NUMBER ) { this . setValue ( instance , numAttribute , streamTokenizer . nval , true ) ; } else if ( streamTokenizer . sval != null && ( streamTokenizer . ttype == StreamTokenizer . TT_WORD || streamTokenizer . ttype == 34 ) ) { if ( this . auxAttributes . get ( numAttribute ) . isNumeric ( ) ) { this . setValue ( instance , numAttribute , Double . valueOf ( streamTokenizer . sval ) . doubleValue ( ) , true ) ; } else { this . setValue ( instance , numAttribute , this . instanceInformation . attribute ( numAttribute ) . indexOfValue ( streamTokenizer . sval ) , false ) ; } } streamTokenizer . nextToken ( ) ; } streamTokenizer . nextToken ( ) ; } streamTokenizer . nextToken ( ) ; } catch ( IOException ex ) { Logger . getLogger ( ArffLoader . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } return instance ; }
Reads an instance sparse and returns a dense one .
21,508
public static void main ( String [ ] args ) { try { System . err . println ( ) ; System . err . println ( Globals . getWorkbenchInfoString ( ) ) ; System . err . println ( ) ; if ( args . length < 2 ) { System . err . println ( "usage: java " + MakeObject . class . getName ( ) + " outputfile.moa \"<object name> <options>\"" ) ; System . err . println ( ) ; } else { String filename = args [ 0 ] ; StringBuilder cliString = new StringBuilder ( ) ; for ( int i = 1 ; i < args . length ; i ++ ) { cliString . append ( " " + args [ i ] ) ; } System . err . println ( "Making object..." ) ; Object result = ClassOption . cliStringToObject ( cliString . toString ( ) , Object . class , null ) ; System . err . println ( "Writing object to file: " + filename ) ; SerializeUtils . writeToFile ( new File ( filename ) , ( Serializable ) result ) ; System . err . println ( "Done." ) ; } } catch ( Exception ex ) { ex . printStackTrace ( ) ; } }
Main method for writing an object to a file from the command line .
21,509
public static void addVectors ( double [ ] a1 , double [ ] a2 ) { assert ( a1 != null ) ; assert ( a2 != null ) ; assert ( a1 . length == a2 . length ) : "Adding two arrays of different " + "length" ; for ( int i = 0 ; i < a1 . length ; i ++ ) { a1 [ i ] += a2 [ i ] ; } }
Adds the second array to the first array element by element . The arrays must have the same length .
21,510
private void refresh ( ) { if ( this . previewedThread != null ) { if ( this . previewedThread . isComplete ( ) ) { setLatestPreview ( ) ; disableRefresh ( ) ; } else { this . previewedThread . getPreview ( ALPreviewPanel . this ) ; } } }
Refreshes the preview .
21,511
public void setTaskThreadToPreview ( ALTaskThread thread ) { this . previewedThread = thread ; setLatestPreview ( ) ; if ( thread == null ) { disableRefresh ( ) ; } else if ( ! thread . isComplete ( ) ) { enableRefresh ( ) ; } }
Sets the TaskThread that will be previewed .
21,512
private Color [ ] getColorCodings ( ALTaskThread thread ) { if ( thread == null ) { return null ; } ALMainTask task = ( ALMainTask ) thread . getTask ( ) ; List < ALTaskThread > subtaskThreads = task . getSubtaskThreads ( ) ; if ( subtaskThreads . size ( ) == 0 ) { return new Color [ ] { task . getColorCoding ( ) } ; } if ( task . getClass ( ) == ALPartitionEvaluationTask . class ) { return getColorCodings ( subtaskThreads . get ( 0 ) ) ; } Color [ ] colors = new Color [ subtaskThreads . size ( ) ] ; for ( int i = 0 ; i < subtaskThreads . size ( ) ; i ++ ) { ALMainTask subtask = ( ALMainTask ) subtaskThreads . get ( i ) . getTask ( ) ; colors [ i ] = subtask . getColorCoding ( ) ; } return colors ; }
Reads the color codings of the subtasks .
21,513
private void disableRefresh ( ) { this . refreshButton . setEnabled ( false ) ; this . autoRefreshLabel . setEnabled ( false ) ; this . autoRefreshComboBox . setEnabled ( false ) ; this . autoRefreshTimer . stop ( ) ; }
Disables refreshing .
21,514
private void enableRefresh ( ) { this . refreshButton . setEnabled ( true ) ; this . autoRefreshLabel . setEnabled ( true ) ; this . autoRefreshComboBox . setEnabled ( true ) ; updateAutoRefreshTimer ( ) ; }
Enables refreshing .
21,515
public Instance filterInstance ( Instance x ) { if ( dataset == null ) { initialize ( x ) ; } double z_ [ ] = new double [ H + 1 ] ; int d = x . numAttributes ( ) - 1 ; for ( int k = 0 ; k < H ; k ++ ) { double a_k = 0. ; for ( int j = 0 ; j < d ; j ++ ) { a_k += ( x . value ( j ) * W [ k ] [ j ] ) ; } z_ [ k ] = ( a_k > 0. ? a_k : 0. ) ; } z_ [ H ] = x . classValue ( ) ; Instance z = new InstanceImpl ( x . weight ( ) , z_ ) ; z . setDataset ( dataset ) ; return z ; }
Filter an instance . Assume that the instance has a single class label as the final attribute . Note that this may not always be the case!
21,516
double treeNodeSplitCost ( treeNode node , Point centreA , Point centreB ) { int i ; double sum = 0.0 ; for ( i = 0 ; i < node . n ; i ++ ) { int l ; double distanceA = 0.0 ; for ( l = 0 ; l < node . points [ i ] . dimension ; l ++ ) { double centroidCoordinatePoint ; if ( node . points [ i ] . weight != 0.0 ) { centroidCoordinatePoint = node . points [ i ] . coordinates [ l ] / node . points [ i ] . weight ; } else { centroidCoordinatePoint = node . points [ i ] . coordinates [ l ] ; } double centroidCoordinateCentre ; if ( centreA . weight != 0.0 ) { centroidCoordinateCentre = centreA . coordinates [ l ] / centreA . weight ; } else { centroidCoordinateCentre = centreA . coordinates [ l ] ; } distanceA += ( centroidCoordinatePoint - centroidCoordinateCentre ) * ( centroidCoordinatePoint - centroidCoordinateCentre ) ; } double distanceB = 0.0 ; for ( l = 0 ; l < node . points [ i ] . dimension ; l ++ ) { double centroidCoordinatePoint ; if ( node . points [ i ] . weight != 0.0 ) { centroidCoordinatePoint = node . points [ i ] . coordinates [ l ] / node . points [ i ] . weight ; } else { centroidCoordinatePoint = node . points [ i ] . coordinates [ l ] ; } double centroidCoordinateCentre ; if ( centreB . weight != 0.0 ) { centroidCoordinateCentre = centreB . coordinates [ l ] / centreB . weight ; } else { centroidCoordinateCentre = centreB . coordinates [ l ] ; } distanceB += ( centroidCoordinatePoint - centroidCoordinateCentre ) * ( centroidCoordinatePoint - centroidCoordinateCentre ) ; } if ( distanceA < distanceB ) { sum += distanceA * node . points [ i ] . weight ; } else { sum += distanceB * node . points [ i ] . weight ; } } return sum ; }
computes the hypothetical cost if the node would be split with new centers centreA centreB
21,517
double treeNodeCostOfPoint ( treeNode node , Point p ) { if ( p . weight == 0.0 ) { return 0.0 ; } double distance = 0.0 ; int l ; for ( l = 0 ; l < p . dimension ; l ++ ) { double centroidCoordinatePoint ; if ( p . weight != 0.0 ) { centroidCoordinatePoint = p . coordinates [ l ] / p . weight ; } else { centroidCoordinatePoint = p . coordinates [ l ] ; } double centroidCoordinateCentre ; if ( node . centre . weight != 0.0 ) { centroidCoordinateCentre = node . centre . coordinates [ l ] / node . centre . weight ; } else { centroidCoordinateCentre = node . centre . coordinates [ l ] ; } distance += ( centroidCoordinatePoint - centroidCoordinateCentre ) * ( centroidCoordinatePoint - centroidCoordinateCentre ) ; } return distance * p . weight ; }
computes the cost of point p with the centre of treenode node
21,518
boolean isLeaf ( treeNode node ) { if ( node . lc == null && node . rc == null ) { return true ; } else { return false ; } }
tests if a node is a leaf
21,519
Point determineClosestCentre ( Point p , Point centreA , Point centreB ) { int l ; double distanceA = 0.0 ; for ( l = 0 ; l < p . dimension ; l ++ ) { double centroidCoordinatePoint ; if ( p . weight != 0.0 ) { centroidCoordinatePoint = p . coordinates [ l ] / p . weight ; } else { centroidCoordinatePoint = p . coordinates [ l ] ; } double centroidCoordinateCentre ; if ( centreA . weight != 0.0 ) { centroidCoordinateCentre = centreA . coordinates [ l ] / centreA . weight ; } else { centroidCoordinateCentre = centreA . coordinates [ l ] ; } distanceA += ( centroidCoordinatePoint - centroidCoordinateCentre ) * ( centroidCoordinatePoint - centroidCoordinateCentre ) ; } double distanceB = 0.0 ; for ( l = 0 ; l < p . dimension ; l ++ ) { double centroidCoordinatePoint ; if ( p . weight != 0.0 ) { centroidCoordinatePoint = p . coordinates [ l ] / p . weight ; } else { centroidCoordinatePoint = p . coordinates [ l ] ; } double centroidCoordinateCentre ; if ( centreB . weight != 0.0 ) { centroidCoordinateCentre = centreB . coordinates [ l ] / centreB . weight ; } else { centroidCoordinateCentre = centreB . coordinates [ l ] ; } distanceB += ( centroidCoordinatePoint - centroidCoordinateCentre ) * ( centroidCoordinatePoint - centroidCoordinateCentre ) ; } if ( distanceA < distanceB ) { return centreA ; } else { return centreB ; } }
returns the next centre
21,520
boolean treeFinished ( treeNode root ) { return ( root . parent == null && root . lc == null && root . rc == null ) ; }
Checks if the storage is completly freed
21,521
void freeTree ( treeNode root ) { while ( ! treeFinished ( root ) ) { if ( root . lc == null && root . rc == null ) { root = root . parent ; } else if ( root . lc == null && root . rc != null ) { if ( isLeaf ( root . rc ) ) { root . rc . free ( ) ; root . rc = null ; } else { root = root . rc ; } } else if ( root . lc != null ) { if ( isLeaf ( root . lc ) ) { root . lc . free ( ) ; root . lc = null ; } else { root = root . lc ; } } } root . free ( ) ; }
frees a tree of its storage
21,522
private void initializeNetwork ( ) { this . hiddenLayerSize = this . hiddenLayerOption . getValue ( ) ; this . learningRate = this . learningRateOption . getValue ( ) ; this . threshold = this . thresholdOption . getValue ( ) ; double [ ] [ ] randomWeightsOne = new double [ this . hiddenLayerSize ] [ this . numAttributes ] ; double [ ] [ ] randomWeightsTwo = new double [ this . numAttributes ] [ this . hiddenLayerSize ] ; for ( int i = 0 ; i < this . numAttributes ; i ++ ) { for ( int j = 0 ; j < this . hiddenLayerSize ; j ++ ) { randomWeightsOne [ j ] [ i ] = this . classifierRandom . nextDouble ( ) ; randomWeightsTwo [ i ] [ j ] = this . classifierRandom . nextDouble ( ) ; } } this . weightsOne = new Array2DRowRealMatrix ( randomWeightsOne ) ; this . weightsTwo = new Array2DRowRealMatrix ( randomWeightsTwo ) ; this . biasOne = this . classifierRandom . nextDouble ( ) ; this . biasTwo = this . classifierRandom . nextDouble ( ) ; this . reset = false ; }
Initializes the autoencoder network .
21,523
public void trainOnInstanceImpl ( Instance inst ) { if ( this . reset ) { this . numAttributes = inst . numAttributes ( ) - 1 ; this . initializeNetwork ( ) ; } this . backpropagation ( inst ) ; }
Uses backpropagation to update the weights in the autoencoder .
21,524
private RealMatrix firstLayer ( RealMatrix input ) { RealMatrix hidden = ( this . weightsOne . multiply ( input ) ) . scalarAdd ( this . biasOne ) ; double [ ] tempValues = new double [ this . hiddenLayerSize ] ; for ( int i = 0 ; i < this . hiddenLayerSize ; i ++ ) { tempValues [ i ] = 1.0 / ( 1.0 + Math . pow ( Math . E , - 1.0 * hidden . getEntry ( i , 0 ) ) ) ; } return new Array2DRowRealMatrix ( tempValues ) ; }
Performs the requisite calculations between the input layer and the hidden layer .
21,525
private RealMatrix secondLayer ( RealMatrix hidden ) { RealMatrix output = ( this . weightsTwo . multiply ( hidden ) ) . scalarAdd ( this . biasTwo ) ; double [ ] tempValues = new double [ this . numAttributes ] ; for ( int i = 0 ; i < this . numAttributes ; i ++ ) { tempValues [ i ] = 1.0 / ( 1.0 + Math . pow ( Math . E , - 1.0 * output . getEntry ( i , 0 ) ) ) ; } return new Array2DRowRealMatrix ( tempValues ) ; }
Performs the requisite calculations between the hidden layer and the output layer .
21,526
private void backpropagation ( Instance inst ) { double [ ] attributeValues = new double [ this . numAttributes ] ; for ( int i = 0 ; i < this . numAttributes ; i ++ ) { attributeValues [ i ] = inst . value ( i ) ; } RealMatrix input = new Array2DRowRealMatrix ( attributeValues ) ; RealMatrix hidden = firstLayer ( input ) ; RealMatrix output = secondLayer ( hidden ) ; RealMatrix delta = new Array2DRowRealMatrix ( this . numAttributes , 1 ) ; double adjustBiasTwo = 0.0 ; for ( int i = 0 ; i < this . numAttributes ; i ++ ) { double inputVal = input . getEntry ( i , 0 ) ; double outputVal = output . getEntry ( i , 0 ) ; delta . setEntry ( i , 0 , ( outputVal - inputVal ) * outputVal * ( 1.0 - outputVal ) ) ; adjustBiasTwo -= this . learningRate * delta . getEntry ( i , 0 ) * this . biasTwo ; } RealMatrix adjustmentTwo = ( delta . multiply ( hidden . transpose ( ) ) ) . scalarMultiply ( - 1.0 * this . learningRate ) ; RealMatrix hidden2 = hidden . scalarMultiply ( - 1.0 ) . scalarAdd ( 1.0 ) ; RealMatrix delta2 = delta . transpose ( ) . multiply ( this . weightsTwo ) ; double adjustBiasOne = 0.0 ; for ( int i = 0 ; i < this . hiddenLayerSize ; i ++ ) { delta2 . setEntry ( 0 , i , delta2 . getEntry ( 0 , i ) * hidden2 . getEntry ( i , 0 ) * hidden . getEntry ( i , 0 ) ) ; adjustBiasOne -= this . learningRate * delta2 . getEntry ( 0 , i ) * this . biasOne ; } RealMatrix adjustmentOne = delta2 . transpose ( ) . multiply ( input . transpose ( ) ) . scalarMultiply ( - 1.0 * this . learningRate ) ; this . weightsOne = this . weightsOne . add ( adjustmentOne ) ; this . biasOne += adjustBiasOne ; this . weightsTwo = this . weightsTwo . add ( adjustmentTwo ) ; this . biasTwo += adjustBiasTwo ; }
Performs backpropagation based on a training instance .
21,527
public double [ ] getVotesForInstance ( Instance inst ) { double [ ] votes = new double [ 2 ] ; if ( this . reset == false ) { double error = this . getAnomalyScore ( inst ) ; votes [ 0 ] = Math . pow ( 2.0 , - 1.0 * ( error / this . threshold ) ) ; votes [ 1 ] = 1.0 - votes [ 0 ] ; } return votes ; }
Calculates the error between the autoencoder s reconstruction of the input and the argument instances . This error is converted to vote scores .
21,528
public double getAnomalyScore ( Instance inst ) { double error = 0.0 ; if ( ! this . reset ) { double [ ] attributeValues = new double [ inst . numAttributes ( ) - 1 ] ; for ( int i = 0 ; i < attributeValues . length ; i ++ ) { attributeValues [ i ] = inst . value ( i ) ; } RealMatrix input = new Array2DRowRealMatrix ( attributeValues ) ; RealMatrix output = secondLayer ( firstLayer ( input ) ) ; for ( int i = 0 ; i < this . numAttributes ; i ++ ) { error += 0.5 * Math . pow ( output . getEntry ( i , 0 ) - input . getEntry ( i , 0 ) , 2.0 ) ; } } return error ; }
Returns the squared error between the input value and the reconstructed value as the anomaly score for the argument instance .
21,529
public void initialize ( Collection < Instance > trainingPoints ) { Iterator < Instance > trgPtsIterator = trainingPoints . iterator ( ) ; if ( trgPtsIterator . hasNext ( ) && this . reset ) { Instance inst = ( Instance ) trgPtsIterator . next ( ) ; this . numAttributes = inst . numAttributes ( ) - 1 ; this . initializeNetwork ( ) ; } while ( trgPtsIterator . hasNext ( ) ) { this . trainOnInstance ( ( Instance ) trgPtsIterator . next ( ) ) ; } }
Initializes the Autoencoder classifier on the argument trainingPoints .
21,530
public void setAttributes ( Attribute [ ] v ) { this . attributes = v ; this . numberAttributes = v . length ; this . indexValues = new int [ numberAttributes ] ; for ( int i = 0 ; i < numberAttributes ; i ++ ) { this . indexValues [ i ] = i ; } }
Sets the attribute information .
21,531
public int locateIndex ( int index ) { int min = 0 ; int max = this . indexValues . length - 1 ; if ( max == - 1 ) { return - 1 ; } while ( ( this . indexValues [ min ] <= index ) && ( this . indexValues [ max ] >= index ) ) { int current = ( max + min ) / 2 ; if ( this . indexValues [ current ] > index ) { max = current - 1 ; } else if ( this . indexValues [ current ] < index ) { min = current + 1 ; } else { return current ; } } if ( this . indexValues [ max ] < index ) { return max ; } else { return min - 1 ; } }
Locates the greatest index that is not greater than the given index .
21,532
public void setIsLastSubtaskOnLevel ( boolean [ ] parentIsLastSubtaskList , boolean isLastSubtask ) { this . isLastSubtaskOnLevel = new boolean [ parentIsLastSubtaskList . length + 1 ] ; for ( int i = 0 ; i < parentIsLastSubtaskList . length ; i ++ ) { this . isLastSubtaskOnLevel [ i ] = parentIsLastSubtaskList [ i ] ; } this . isLastSubtaskOnLevel [ parentIsLastSubtaskList . length ] = isLastSubtask ; }
Set the list of booleans indicating if the current branch in the subtask tree is the last one on its respective level .
21,533
public void fontSelection ( ) { FontChooserPanel panel = new FontChooserPanel ( textFont ) ; int result = JOptionPane . showConfirmDialog ( this , panel , "Font Selection" , JOptionPane . OK_CANCEL_OPTION , JOptionPane . PLAIN_MESSAGE ) ; if ( result == JOptionPane . OK_OPTION ) { textFont = panel . getSelectedFont ( ) ; } }
Allow to select the text font .
21,534
protected static String [ ] splitParameterFromRemainingOptions ( String cliString ) { String [ ] paramSplit = new String [ 2 ] ; cliString = cliString . trim ( ) ; if ( cliString . startsWith ( "\"" ) || cliString . startsWith ( "'" ) ) { int endQuoteIndex = cliString . indexOf ( cliString . charAt ( 0 ) , 1 ) ; if ( endQuoteIndex < 0 ) { throw new IllegalArgumentException ( "Quotes not terminated correctly." ) ; } paramSplit [ 0 ] = cliString . substring ( 1 , endQuoteIndex ) ; paramSplit [ 1 ] = cliString . substring ( endQuoteIndex + 1 , cliString . length ( ) ) ; } else if ( cliString . startsWith ( "(" ) ) { int bracketsOpen = 1 ; int currPos = 1 ; int nextCloseIndex = cliString . indexOf ( ")" , currPos ) ; int nextOpenIndex = cliString . indexOf ( "(" , currPos ) ; while ( bracketsOpen != 0 ) { if ( nextCloseIndex < 0 ) { throw new IllegalArgumentException ( "Brackets do not match." ) ; } else if ( ( nextOpenIndex < 0 ) || ( nextCloseIndex < nextOpenIndex ) ) { bracketsOpen -- ; currPos = nextCloseIndex + 1 ; nextCloseIndex = cliString . indexOf ( ")" , currPos ) ; } else { bracketsOpen ++ ; currPos = nextOpenIndex + 1 ; nextOpenIndex = cliString . indexOf ( "(" , currPos ) ; } } paramSplit [ 0 ] = cliString . substring ( 1 , currPos - 1 ) ; paramSplit [ 1 ] = cliString . substring ( currPos , cliString . length ( ) ) ; } else { int firstSpaceIndex = cliString . indexOf ( " " , 0 ) ; if ( firstSpaceIndex >= 0 ) { paramSplit [ 0 ] = cliString . substring ( 0 , firstSpaceIndex ) ; paramSplit [ 1 ] = cliString . substring ( firstSpaceIndex + 1 , cliString . length ( ) ) ; } else { paramSplit [ 0 ] = cliString ; paramSplit [ 1 ] = "" ; } } return paramSplit ; }
Internal method that splits a string into two parts - the parameter for the current option and the remaining options .
21,535
private void updateToTop ( Node toUpdate ) { while ( toUpdate != null ) { for ( Entry e : toUpdate . getEntries ( ) ) e . recalculateData ( ) ; if ( toUpdate . getEntries ( ) [ 0 ] . getParentEntry ( ) == null ) break ; toUpdate = toUpdate . getEntries ( ) [ 0 ] . getParentEntry ( ) . getNode ( ) ; } }
recalculates data for all entries that lie on the path from the root to the Entry toUpdate .
21,536
private Entry insertHereWithSplit ( Entry toInsert , Node insertNode , long timestamp ) { if ( insertNode . getEntries ( ) [ 0 ] . getParentEntry ( ) == null ) { root . makeOlder ( timestamp , negLambda ) ; Entry irrelevantEntry = insertNode . getIrrelevantEntry ( this . weightThreshold ) ; int numFreeEntries = insertNode . numFreeEntries ( ) ; if ( irrelevantEntry != null ) { irrelevantEntry . overwriteOldEntry ( toInsert ) ; } else if ( numFreeEntries > 0 ) { insertNode . addEntry ( toInsert , timestamp ) ; } else { this . numRootSplits ++ ; this . height += this . height < this . maxHeight ? 1 : 0 ; Entry oldRootEntry = new Entry ( this . numberDimensions , root , timestamp , null , null ) ; Node newRoot = new Node ( this . numberDimensions , this . height ) ; Entry newRootEntry = split ( toInsert , root , oldRootEntry , timestamp ) ; newRoot . addEntry ( oldRootEntry , timestamp ) ; newRoot . addEntry ( newRootEntry , timestamp ) ; this . root = newRoot ; for ( Entry c : oldRootEntry . getChild ( ) . getEntries ( ) ) c . setParentEntry ( root . getEntries ( ) [ 0 ] ) ; for ( Entry c : newRootEntry . getChild ( ) . getEntries ( ) ) c . setParentEntry ( root . getEntries ( ) [ 1 ] ) ; } return null ; } insertNode . makeOlder ( timestamp , negLambda ) ; Entry irrelevantEntry = insertNode . getIrrelevantEntry ( this . weightThreshold ) ; int numFreeEntries = insertNode . numFreeEntries ( ) ; if ( irrelevantEntry != null ) { irrelevantEntry . overwriteOldEntry ( toInsert ) ; } else if ( numFreeEntries > 0 ) { insertNode . addEntry ( toInsert , timestamp ) ; } else { Entry parentEntry = insertNode . getEntries ( ) [ 0 ] . getParentEntry ( ) ; Entry residualEntry = split ( toInsert , insertNode , parentEntry , timestamp ) ; if ( alsoUpdate != null ) { alsoUpdate = residualEntry ; } Node nodeForResidualEntry = insertNode . getEntries ( ) [ 0 ] . getParentEntry ( ) . getNode ( ) ; return insertHereWithSplit ( residualEntry , nodeForResidualEntry , timestamp ) ; } return null ; }
Method called by insertBreadthFirst .
21,537
private Node findBestLeafNode ( ClusKernel newPoint ) { double minDist = Double . MAX_VALUE ; Node bestFit = null ; for ( Node e : collectLeafNodes ( root ) ) { if ( newPoint . calcDistance ( e . nearestEntry ( newPoint ) . getData ( ) ) < minDist ) { bestFit = e ; minDist = newPoint . calcDistance ( e . nearestEntry ( newPoint ) . getData ( ) ) ; } } if ( bestFit != null ) return bestFit ; else return root ; }
This method calculates the distances between the new point and each Entry in a leaf node . It returns the node that contains the entry with the smallest distance to the new point .
21,538
private BestMergeInNode calculateBestMergeInNode ( Node node ) { assert ( node . numFreeEntries ( ) == 0 ) ; Entry [ ] entries = node . getEntries ( ) ; int toMerge1 = - 1 ; int toMerge2 = - 1 ; double distanceBetweenMergeEntries = Double . NaN ; double minDistance = Double . MAX_VALUE ; for ( int i = 0 ; i < entries . length ; i ++ ) { Entry e1 = entries [ i ] ; for ( int j = i + 1 ; j < entries . length ; j ++ ) { Entry e2 = entries [ j ] ; double distance = e1 . calcDistance ( e2 ) ; if ( distance < minDistance ) { toMerge1 = i ; toMerge2 = j ; distanceBetweenMergeEntries = distance ; } } } assert ( toMerge1 != - 1 && toMerge2 != - 1 ) ; if ( Double . isNaN ( distanceBetweenMergeEntries ) ) { throw new RuntimeException ( "The minimal distance between two " + "Entrys in a Node was Double.MAX_VAUE. That can hardly " + "be right." ) ; } return new BestMergeInNode ( toMerge1 , toMerge2 , distanceBetweenMergeEntries ) ; }
Calculates the best merge possible between two nodes in a node . This means that the pair with the smallest distance is found .
21,539
protected void setMeasures ( boolean [ ] measures ) { this . generalEvalOption . setValue ( measures [ 0 ] ) ; this . f1Option . setValue ( measures [ 1 ] ) ; this . entropyOption . setValue ( measures [ 2 ] ) ; this . cmmOption . setValue ( measures [ 3 ] ) ; this . ssqOption . setValue ( measures [ 4 ] ) ; this . separationOption . setValue ( measures [ 5 ] ) ; this . silhouetteOption . setValue ( measures [ 6 ] ) ; this . statisticalOption . setValue ( measures [ 7 ] ) ; }
Given an array summarizing selected measures set the appropriate flag options
21,540
public boolean isConnected ( ) { this . visited = new HashMap < DensityGrid , Boolean > ( ) ; Iterator < DensityGrid > initIter = this . grids . keySet ( ) . iterator ( ) ; DensityGrid dg ; if ( initIter . hasNext ( ) ) { dg = initIter . next ( ) ; visited . put ( dg , this . grids . get ( dg ) ) ; boolean changesMade ; do { changesMade = false ; Iterator < Map . Entry < DensityGrid , Boolean > > visIter = this . visited . entrySet ( ) . iterator ( ) ; HashMap < DensityGrid , Boolean > toAdd = new HashMap < DensityGrid , Boolean > ( ) ; while ( visIter . hasNext ( ) && toAdd . isEmpty ( ) ) { Map . Entry < DensityGrid , Boolean > toVisit = visIter . next ( ) ; DensityGrid dg2V = toVisit . getKey ( ) ; Iterator < DensityGrid > dg2VNeighbourhood = dg2V . getNeighbours ( ) . iterator ( ) ; while ( dg2VNeighbourhood . hasNext ( ) ) { DensityGrid dg2VN = dg2VNeighbourhood . next ( ) ; if ( this . grids . containsKey ( dg2VN ) && ! this . visited . containsKey ( dg2VN ) ) toAdd . put ( dg2VN , this . grids . get ( dg2VN ) ) ; } } if ( ! toAdd . isEmpty ( ) ) { this . visited . putAll ( toAdd ) ; changesMade = true ; } } while ( changesMade ) ; } if ( this . visited . size ( ) == this . grids . size ( ) ) { return true ; } else { return false ; } }
Tests a grid cluster for connectedness according to Definition 3 . 4 Grid Group from Chen and Tu 2007 .
21,541
public double getInclusionProbability ( Instance instance ) { Iterator < Map . Entry < DensityGrid , Boolean > > gridIter = grids . entrySet ( ) . iterator ( ) ; while ( gridIter . hasNext ( ) ) { Map . Entry < DensityGrid , Boolean > grid = gridIter . next ( ) ; DensityGrid dg = grid . getKey ( ) ; if ( dg . getInclusionProbability ( instance ) == 1.0 ) return 1.0 ; } return 0.0 ; }
Iterates through the DensityGrids in the cluster and calculates the inclusion probability for each .
21,542
public void add ( int numPoints , double [ ] sumPoints , double sumSquaredPoints ) { assert ( this . sumPoints . length == sumPoints . length ) ; this . numPoints += numPoints ; super . setWeight ( this . numPoints ) ; for ( int i = 0 ; i < this . sumPoints . length ; i ++ ) { this . sumPoints [ i ] += sumPoints [ i ] ; } this . sumSquaredLength += sumSquaredPoints ; }
Adds a point to the ClusteringFeature .
21,543
public void merge ( ClusteringFeature x ) { assert ( this . sumPoints . length == x . sumPoints . length ) ; this . numPoints += x . numPoints ; super . setWeight ( this . numPoints ) ; for ( int i = 0 ; i < this . sumPoints . length ; i ++ ) { this . sumPoints [ i ] += x . sumPoints [ i ] ; } this . sumSquaredLength += x . sumSquaredLength ; }
Merges the ClusteringFeature with an other ClusteringFeature .
21,544
public Cluster toCluster ( ) { double [ ] output = new double [ this . sumPoints . length ] ; System . arraycopy ( this . sumPoints , 0 , output , 0 , this . sumPoints . length ) ; for ( int i = 0 ; i < output . length ; i ++ ) { output [ i ] /= this . numPoints ; } return new SphereCluster ( output , getThreshold ( ) , this . numPoints ) ; }
Creates a Cluster of the ClusteringFeature .
21,545
public double [ ] toClusterCenter ( ) { double [ ] output = new double [ this . sumPoints . length + 1 ] ; System . arraycopy ( this . sumPoints , 0 , output , 1 , this . sumPoints . length ) ; output [ 0 ] = this . numPoints ; for ( int i = 1 ; i < output . length ; i ++ ) { output [ i ] /= this . numPoints ; } return output ; }
Creates the cluster center of the ClusteringFeature .
21,546
public void printClusterCenter ( Writer stream ) throws IOException { stream . write ( String . valueOf ( this . numPoints ) ) ; for ( int j = 0 ; j < this . sumPoints . length ; j ++ ) { stream . write ( ' ' ) ; stream . write ( String . valueOf ( this . sumPoints [ j ] / this . numPoints ) ) ; } stream . write ( System . getProperty ( "line.separator" ) ) ; }
Writes the cluster center to a given stream .
21,547
public double calcKMeansCosts ( double [ ] center ) { assert ( this . sumPoints . length == center . length ) ; return this . sumSquaredLength - 2 * Metric . dotProduct ( this . sumPoints , center ) + this . numPoints * Metric . dotProduct ( center ) ; }
Calculates the k - means costs of the ClusteringFeature too a center .
21,548
public double calcKMeansCosts ( double [ ] center , double [ ] point ) { assert ( this . sumPoints . length == center . length && this . sumPoints . length == point . length ) ; return ( this . sumSquaredLength + Metric . distanceSquared ( point ) ) - 2 * Metric . dotProductWithAddition ( this . sumPoints , point , center ) + ( this . numPoints + 1 ) * Metric . dotProduct ( center ) ; }
Calculates the k - means costs of the ClusteringFeature and a point too a center .
21,549
public double calcKMeansCosts ( double [ ] center , ClusteringFeature points ) { assert ( this . sumPoints . length == center . length && this . sumPoints . length == points . sumPoints . length ) ; return ( this . sumSquaredLength + points . sumSquaredLength ) - 2 * Metric . dotProductWithAddition ( this . sumPoints , points . sumPoints , center ) + ( this . numPoints + points . numPoints ) * Metric . dotProduct ( center ) ; }
Calculates the k - means costs of the ClusteringFeature and another ClusteringFeature too a center .
21,550
protected double computeWeight ( int i , Instance example ) { int d = this . windowSize ; int t = this . processedInstances - this . ensemble [ i ] . birthday ; double e_it = 0 ; double mse_it = 0 ; double voteSum = 0 ; try { double [ ] votes = this . ensemble [ i ] . classifier . getVotesForInstance ( example ) ; for ( double element : votes ) { voteSum += element ; } if ( voteSum > 0 ) { double f_it = 1 - ( votes [ ( int ) example . classValue ( ) ] / voteSum ) ; e_it = f_it * f_it ; } else { e_it = 1 ; } } catch ( Exception e ) { e_it = 1 ; } if ( t > d ) { mse_it = this . ensemble [ i ] . mse_it + e_it / ( double ) d - this . ensemble [ i ] . squareErrors [ t % d ] / ( double ) d ; } else { mse_it = this . ensemble [ i ] . mse_it * ( t - 1 ) / t + e_it / ( double ) t ; } this . ensemble [ i ] . squareErrors [ t % d ] = e_it ; this . ensemble [ i ] . mse_it = mse_it ; if ( linearOption . isSet ( ) ) { return java . lang . Math . max ( mse_r - mse_it , Double . MIN_VALUE ) ; } else { return 1.0 / ( this . mse_r + mse_it + Double . MIN_VALUE ) ; } }
Computes the weight of a learner before training a given example .
21,551
private int getPoorestClassifierIndex ( ) { int minIndex = 0 ; for ( int i = 1 ; i < this . weights . length ; i ++ ) { if ( this . weights [ i ] [ 0 ] < this . weights [ minIndex ] [ 0 ] ) { minIndex = i ; } } return minIndex ; }
Finds the index of the classifier with the smallest weight .
21,552
public int classIndex ( ) { int classIndex = instanceHeader . classIndex ( ) ; if ( classIndex == Integer . MAX_VALUE ) if ( this . instanceHeader . instanceInformation . range != null ) classIndex = instanceHeader . instanceInformation . range . getStart ( ) ; else classIndex = 0 ; return classIndex ; }
Class index .
21,553
public void setDataset ( Instances dataset ) { if ( dataset instanceof InstancesHeader ) { this . instanceHeader = ( InstancesHeader ) dataset ; } else { this . instanceHeader = new InstancesHeader ( dataset ) ; } }
Sets the dataset .
21,554
public void addSparseValues ( int [ ] indexValues , double [ ] attributeValues , int numberAttributes ) { this . instanceData = new SparseInstanceData ( attributeValues , indexValues , numberAttributes ) ; }
Adds the sparse values .
21,555
protected void initVariables ( ) { int ensembleSize = ( int ) this . memberCountOption . getValue ( ) ; this . ensemble = new Classifier [ ensembleSize ] ; this . ensembleAges = new double [ ensembleSize ] ; this . ensembleWindows = new int [ ensembleSize ] [ ( int ) this . evaluationSizeOption . getValue ( ) ] ; }
Initializes the method variables
21,556
protected void trainAndClassify ( Instance inst ) { nbInstances ++ ; boolean mature = true ; boolean unmature = true ; for ( int i = 0 ; i < getNbActiveClassifiers ( ) ; i ++ ) { if ( this . ensembleAges [ i ] < this . maturityOption . getValue ( ) && i < getNbAdaptiveClassifiers ( ) ) mature = false ; if ( this . ensembleAges [ i ] >= this . maturityOption . getValue ( ) && i < getNbAdaptiveClassifiers ( ) ) unmature = false ; if ( this . nbInstances >= this . ensembleWeights [ i ] . index + 1 ) { if ( i < getNbAdaptiveClassifiers ( ) ) this . ensemble [ i ] . trainOnInstance ( inst ) ; int val = this . ensemble [ i ] . correctlyClassifies ( inst ) ? 1 : 0 ; double sum = updateEvaluationWindow ( i , val ) ; this . ensembleWeights [ i ] . val = sum ; this . ensembleAges [ i ] = this . ensembleAges [ i ] + 1 ; } } if ( unmature ) for ( int i = 0 ; i < getNbAdaptiveClassifiers ( ) ; i ++ ) this . ensembleWeights [ i ] . val = 1 ; if ( mature ) { Pair [ ] learners = getHalf ( false ) ; if ( learners . length > 0 ) { double rand = classifierRandom . nextInt ( learners . length ) ; discardModel ( learners [ ( int ) rand ] . index ) ; } } }
Receives a training instance from the stream and updates the adaptive classifiers accordingly
21,557
public void discardModel ( int index ) { this . ensemble [ index ] . resetLearning ( ) ; this . ensembleWeights [ index ] . val = 0 ; this . ensembleAges [ index ] = 0 ; this . ensembleWindows [ index ] = new int [ ( int ) this . evaluationSizeOption . getValue ( ) ] ; }
Resets a classifier in the ensemble
21,558
protected double updateEvaluationWindow ( int index , int val ) { int [ ] newEnsembleWindows = new int [ this . ensembleWindows [ index ] . length ] ; int wsize = ( int ) Math . min ( this . evaluationSizeOption . getValue ( ) , this . ensembleAges [ index ] + 1 ) ; int sum = 0 ; for ( int i = 0 ; i < wsize - 1 ; i ++ ) { newEnsembleWindows [ i + 1 ] = this . ensembleWindows [ index ] [ i ] ; sum = sum + this . ensembleWindows [ index ] [ i ] ; } newEnsembleWindows [ 0 ] = val ; this . ensembleWindows [ index ] = newEnsembleWindows ; if ( this . ensembleAges [ index ] >= this . maturityOption . getValue ( ) ) return ( sum + val ) * 1.0 / wsize ; else return 0 ; }
Updates the evaluation window of a classifier and returns the updated weight value .
21,559
protected ArrayList < Integer > getMAXIndexes ( ) { ArrayList < Integer > maxWIndex = new ArrayList < Integer > ( ) ; Pair [ ] newEnsembleWeights = new Pair [ getNbActiveClassifiers ( ) ] ; System . arraycopy ( ensembleWeights , 0 , newEnsembleWeights , 0 , newEnsembleWeights . length ) ; Arrays . sort ( newEnsembleWeights ) ; double maxWVal = newEnsembleWeights [ newEnsembleWeights . length - 1 ] . val ; for ( int i = newEnsembleWeights . length - 1 ; i >= 0 ; i -- ) { if ( newEnsembleWeights [ i ] . val != maxWVal ) break ; else maxWIndex . add ( newEnsembleWeights [ i ] . index ) ; } return maxWIndex ; }
Returns the classifiers that vote for the final prediction when the MAX combination function is selected
21,560
public void exportIMG ( String path , String type ) throws IOException { switch ( type ) { case "JPG" : try { ChartUtilities . saveChartAsJPEG ( new File ( path + File . separator + name + ".jpg" ) , chart , width , height ) ; } catch ( IOException e ) { } break ; case "PNG" : try { ChartUtilities . saveChartAsPNG ( new File ( path + File . separator + name + ".png" ) , chart , width , height ) ; } catch ( IOException e ) { } break ; case "SVG" : String svg = generateSVG ( width , height ) ; BufferedWriter writer = null ; try { writer = new BufferedWriter ( new FileWriter ( new File ( path + File . separator + name + ".svg" ) ) ) ; writer . write ( "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n" ) ; writer . write ( svg + "\n" ) ; writer . flush ( ) ; } finally { try { if ( writer != null ) { writer . close ( ) ; } } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } } break ; } }
Export the image to formats JPG PNG SVG and EPS .
21,561
public void setActionListener ( ActionListener listener ) { for ( int i = 0 ; i < this . radioButtons . length ; i ++ ) { this . radioButtons [ i ] . addActionListener ( listener ) ; } }
Sets the ActionListener for the radio buttons .
21,562
public void update ( MeasureCollection [ ] measures , String variedParamName , double [ ] variedParamValues ) { this . measures = measures ; this . variedParamName = variedParamName ; this . variedParamValues = variedParamValues ; update ( ) ; updateParamBox ( ) ; }
Updates the measure overview by assigning new measure collections and varied parameter properties . If no measures are currently to display reset the display to hyphens . Otherwise display the last measured and mean values . Updates the parameter combo box if needed .
21,563
public void update ( ) { if ( this . measures == null || this . measures . length == 0 ) { for ( int i = 0 ; i < this . currentValues . length ; i ++ ) { this . currentValues [ i ] . setText ( "-" ) ; this . meanValues [ i ] . setText ( "-" ) ; } return ; } DecimalFormat d = new DecimalFormat ( "0.00" ) ; MeasureCollection mc ; if ( this . measures . length > this . measureCollectionSelected ) { mc = this . measures [ this . measureCollectionSelected ] ; } else { mc = this . measures [ 0 ] ; } for ( int i = 0 ; i < this . currentValues . length ; i ++ ) { if ( Double . isNaN ( mc . getLastValue ( i ) ) ) { this . currentValues [ i ] . setText ( "-" ) ; } else { this . currentValues [ i ] . setText ( d . format ( mc . getLastValue ( i ) ) ) ; } if ( Double . isNaN ( mc . getMean ( i ) ) ) { this . meanValues [ i ] . setText ( "-" ) ; } else { this . meanValues [ i ] . setText ( d . format ( mc . getMean ( i ) ) ) ; } } }
Updates the measure overview . If no measures are currently to display reset the display to hyphens . Otherwise display the last measured and mean values .
21,564
private void updateParamBox ( ) { if ( this . variedParamValues == null || this . variedParamValues . length == 0 ) { this . paramBox . removeAllItems ( ) ; this . paramBox . setEnabled ( false ) ; } else if ( this . paramBox . getItemCount ( ) != this . variedParamValues . length ) { this . paramBox . removeAllItems ( ) ; for ( int i = 0 ; i < variedParamValues . length ; i ++ ) { this . paramBox . addItem ( String . format ( "%s: %s" , this . variedParamName , this . variedParamValues [ i ] ) ) ; } this . paramBox . setEnabled ( true ) ; } }
Updates the parameter combo box . If there is no varied parameter empty and disable the box . Otherwise display the available parameters .
21,565
protected Measurement [ ] getModelMeasurementsImpl ( ) { return new Measurement [ ] { new Measurement ( "anomaly detections" , this . numAnomaliesDetected ) , new Measurement ( "change detections" , this . numChangesDetected ) , new Measurement ( "rules (number)" , this . ruleSet . size ( ) + 1 ) } ; }
print GUI evaluate model
21,566
public void getModelDescription ( StringBuilder out , int indent ) { indent = 0 ; if ( ! this . unorderedRulesOption . isSet ( ) ) { StringUtils . appendIndented ( out , indent , "Method Ordered" ) ; StringUtils . appendNewline ( out ) ; } else { StringUtils . appendIndented ( out , indent , "Method Unordered" ) ; StringUtils . appendNewline ( out ) ; } if ( this . DriftDetectionOption . isSet ( ) ) { StringUtils . appendIndented ( out , indent , "Change Detection OFF" ) ; StringUtils . appendNewline ( out ) ; } else { StringUtils . appendIndented ( out , indent , "Change Detection ON" ) ; StringUtils . appendNewline ( out ) ; } if ( this . noAnomalyDetectionOption . isSet ( ) ) { StringUtils . appendIndented ( out , indent , "Anomaly Detection OFF" ) ; StringUtils . appendNewline ( out ) ; } else { StringUtils . appendIndented ( out , indent , "Anomaly Detection ON" ) ; StringUtils . appendNewline ( out ) ; } StringUtils . appendIndented ( out , indent , "Number of Rules: " + ( this . ruleSet . size ( ) + 1 ) ) ; StringUtils . appendNewline ( out ) ; }
print GUI learn model
21,567
protected void debug ( String string , int level ) { if ( VerbosityOption . getValue ( ) >= level ) { System . out . println ( string ) ; } }
Print to console
21,568
public Vote getVotes ( Instance instance ) { ErrorWeightedVote errorWeightedVote = newErrorWeightedVote ( ) ; debug ( "Test" , 3 ) ; int numberOfRulesCovering = 0 ; VerboseToConsole ( instance ) ; for ( Rule rule : ruleSet ) { if ( rule . isCovering ( instance ) == true ) { numberOfRulesCovering ++ ; double [ ] vote = rule . getPrediction ( instance ) ; double error = rule . getCurrentError ( ) ; debug ( "Rule No" + rule . getRuleNumberID ( ) + " Vote: " + Arrays . toString ( vote ) + " Error: " + error + " Y: " + instance . classValue ( ) , 3 ) ; errorWeightedVote . addVote ( vote , error ) ; if ( ! this . unorderedRulesOption . isSet ( ) ) { break ; } } } if ( numberOfRulesCovering == 0 ) { double [ ] vote = defaultRule . getPrediction ( instance ) ; double error = defaultRule . getCurrentError ( ) ; errorWeightedVote . addVote ( vote , error ) ; debug ( "Default Rule Vote " + Arrays . toString ( vote ) + " Error " + error + " Y: " + instance . classValue ( ) , 3 ) ; } double [ ] weightedVote = errorWeightedVote . computeWeightedVote ( ) ; double weightedError = errorWeightedVote . getWeightedError ( ) ; debug ( "Weighted Rule - Vote: " + Arrays . toString ( weightedVote ) + " Weighted Error: " + weightedError + " Y:" + instance . classValue ( ) , 3 ) ; return new Vote ( weightedVote , weightedError ) ; }
getVotes extension of the instance method getVotesForInstance in moa . classifier . java returns the prediction of the instance . Called in WeightedRandomRules
21,569
protected static synchronized boolean isPresent ( ) { if ( m_Present == null ) { try { SizeOfAgent . fullSizeOf ( new Integer ( 1 ) ) ; m_Present = true ; } catch ( Throwable t ) { m_Present = false ; } } return m_Present ; }
Checks whteher the agent is present .
21,570
private String createScript ( File resultFile ) { String newLine = System . getProperty ( "line.separator" ) ; int sourceFileIdx = 0 ; String script = "set term " + terminalOptions ( Terminal . valueOf ( outputTypeOption . getChosenLabel ( ) ) ) + newLine ; script += "set output '" + resultFile . getAbsolutePath ( ) + "'" + newLine ; script += "set datafile separator ','" + newLine ; script += "set grid" + newLine ; script += "set style line 1 pt 8" + newLine ; script += "set style line 2 lt rgb '#00C000'" + newLine ; script += "set style line 5 lt rgb '#FFD800'" + newLine ; script += "set style line 6 lt rgb '#4E0000'" + newLine ; script += "set format x '%.0s %c" + getAxisUnit ( xUnitOption . getValue ( ) ) + "'" + newLine ; script += "set format y '%.0s %c" + getAxisUnit ( yUnitOption . getValue ( ) ) + "'" + newLine ; script += "set ylabel '" + yTitleOption . getValue ( ) + "'" + newLine ; script += "set xlabel '" + xTitleOption . getValue ( ) + "'" + newLine ; if ( ! legendTypeOption . getChosenLabel ( ) . equals ( LegendType . NONE ) ) { script += "set key " + legendTypeOption . getChosenLabel ( ) . toLowerCase ( ) . replace ( '_' , ' ' ) + " " + legendLocationOption . getChosenLabel ( ) . toLowerCase ( ) . replace ( '_' , ' ' ) + newLine ; } script += additionalSetOption . getValue ( ) ; script += "plot " + additionalPlotOption . getValue ( ) + " " ; for ( int i = 0 ; i < inputFilesOption . getList ( ) . length ; i ++ ) { if ( sourceFileIdx > 0 ) { script += ", " ; } sourceFileIdx ++ ; script += "'" + ( ( StringOption ) inputFilesOption . getList ( ) [ i ] ) . getValue ( ) + "' using " + xColumnOption . getValue ( ) + ":" + yColumnOption . getValue ( ) ; if ( smoothOption . isSet ( ) ) { script += ":(1.0) smooth bezier" ; } script += " with " + plotStyleOption . getChosenLabel ( ) . toLowerCase ( ) + " ls " + sourceFileIdx + " lw " + lineWidthOption . getValue ( ) ; if ( plotStyleOption . getChosenLabel ( ) . equals ( PlotStyle . LINESPOINTS . toString ( ) ) && pointIntervalOption . getValue ( ) > 0 ) { script += " pointinterval " + pointIntervalOption . getValue ( ) ; } script += " title '" + ( ( StringOption ) fileAliasesOption . getList ( ) [ i ] ) . getValue ( ) + "'" ; } script += newLine ; return script ; }
Creates the content of the gnuplot script .
21,571
private void calculateGTPointQualities ( ) { for ( int p = 0 ; p < numPoints ; p ++ ) { CMMPoint cmdp = cmmpoints . get ( p ) ; if ( ! cmdp . isNoise ( ) ) { cmdp . connectivity = getConnectionValue ( cmdp , cmdp . workclass ( ) ) ; cmdp . p . setMeasureValue ( "Connectivity" , cmdp . connectivity ) ; } } }
calculate initial connectivities
21,572
private void calculateGTClusterConnections ( ) { for ( int c0 = 0 ; c0 < gt0Clusters . size ( ) ; c0 ++ ) { for ( int c1 = 0 ; c1 < gt0Clusters . size ( ) ; c1 ++ ) { gt0Clusters . get ( c0 ) . calculateClusterConnection ( c1 , true ) ; } } boolean changedConnection = true ; while ( changedConnection ) { if ( debug ) { System . out . println ( "Cluster Connection" ) ; for ( int c = 0 ; c < gt0Clusters . size ( ) ; c ++ ) { System . out . print ( "C" + gt0Clusters . get ( c ) . label + " ) ; for ( int c1 = 0 ; c1 < gt0Clusters . get ( c ) . connections . size ( ) ; c1 ++ ) { System . out . print ( " C" + gt0Clusters . get ( c1 ) . label + ": " + gt0Clusters . get ( c ) . connections . get ( c1 ) ) ; } System . out . println ( "" ) ; } System . out . println ( "" ) ; } double max = 0 ; int maxIndexI = - 1 ; int maxIndexJ = - 1 ; changedConnection = false ; for ( int c0 = 0 ; c0 < gt0Clusters . size ( ) ; c0 ++ ) { for ( int c1 = c0 + 1 ; c1 < gt0Clusters . size ( ) ; c1 ++ ) { if ( c0 == c1 ) continue ; double min = Math . min ( gt0Clusters . get ( c0 ) . connections . get ( c1 ) , gt0Clusters . get ( c1 ) . connections . get ( c0 ) ) ; if ( min > max ) { max = min ; maxIndexI = c0 ; maxIndexJ = c1 ; } } } if ( maxIndexI != - 1 && max > tauConnection ) { gt0Clusters . get ( maxIndexI ) . mergeCluster ( maxIndexJ ) ; if ( debug ) System . out . println ( "Merging " + maxIndexI + " and " + maxIndexJ + " because of connection " + max ) ; changedConnection = true ; } } numGT0Classes = gt0Clusters . size ( ) ; }
Calculate connections between clusters and merge clusters accordingly as long as connections exceed threshold
21,573
public double getNoiseSeparability ( ) { if ( noise . isEmpty ( ) ) return 1 ; double connectivity = 0 ; for ( int p : noise ) { CMMPoint npoint = cmmpoints . get ( p ) ; double maxConnection = 0 ; for ( int c = 0 ; c < gt0Clusters . size ( ) ; c ++ ) { double connection = getConnectionValue ( npoint , c ) ; if ( connection > maxConnection ) maxConnection = connection ; } connectivity += maxConnection ; npoint . p . setMeasureValue ( "MaxConnection" , maxConnection ) ; } return 1 - ( connectivity / noise . size ( ) ) ; }
Calculates how well noise is separable from the given clusters Small values indicate bad separability values close to 1 indicate good separability
21,574
public double getModelQuality ( ) { for ( int p = 0 ; p < numPoints ; p ++ ) { CMMPoint cmdp = cmmpoints . get ( p ) ; for ( int hc = 0 ; hc < numGTClusters ; hc ++ ) { if ( gtClustering . get ( hc ) . getGroundTruth ( ) != cmdp . trueClass ) { if ( gtClustering . get ( hc ) . getInclusionProbability ( cmdp ) >= 1 ) { if ( ! cmdp . isNoise ( ) ) pointErrorByModel ++ ; else noiseErrorByModel ++ ; break ; } } } } if ( debug ) System . out . println ( "Error by model: noise " + noiseErrorByModel + " point " + pointErrorByModel ) ; return 1 - ( ( pointErrorByModel + noiseErrorByModel ) / ( double ) numPoints ) ; }
Calculates the relative number of errors being caused by the underlying cluster model
21,575
private double distance ( Instance inst1 , double [ ] inst2 ) { double distance = 0.0 ; for ( int i = 0 ; i < numDims ; i ++ ) { double d = inst1 . value ( i ) - inst2 [ i ] ; distance += d * d ; } return Math . sqrt ( distance ) ; }
Calculates Euclidian distance
21,576
public String getParameterString ( ) { String para = "" ; para += "k=" + knnNeighbourhood + ";" ; if ( useExpConnectivity ) { para += "lambdaConnX=" + lambdaConnX + ";" ; para += "lambdaConn=" + lamdaConn + ";" ; para += "lambdaConnRef=" + lambdaConnRefXValue + ";" ; } para += "m=" + clusterConnectionMaxPoints + ";" ; para += "tauConn=" + tauConnection + ";" ; return para ; }
String with main CMM parameters
21,577
public Color [ ] generateColors ( int numColors ) { Color [ ] colors = new Color [ numColors ] ; Random rand = new Random ( 0 ) ; for ( int i = 0 ; i < numColors ; ++ i ) { float hueRatio = i / ( float ) numColors ; float saturationRatio = rand . nextFloat ( ) ; float brightnessRatio = rand . nextFloat ( ) ; float hue = lerp ( hueMin , hueMax , hueRatio ) ; float saturation = lerp ( saturationMin , saturationMax , saturationRatio ) ; float brightness = lerp ( brightnessMin , brightnessMax , brightnessRatio ) ; colors [ i ] = Color . getHSBColor ( hue , saturation , brightness ) ; } return colors ; }
Generate numColors unique colors which should be easily distinguishable .
21,578
public void updateMass ( Instance inst , boolean referenceWindow ) { if ( referenceWindow ) r ++ ; else l ++ ; if ( internalNode ) { if ( inst . value ( this . splitAttribute ) > this . splitValue ) right . updateMass ( inst , referenceWindow ) ; else left . updateMass ( inst , referenceWindow ) ; } }
Update the mass profile of this node .
21,579
public double score ( Instance inst , int sizeLimit ) { double anomalyScore = 0.0 ; if ( this . internalNode && this . r > sizeLimit ) { if ( inst . value ( this . splitAttribute ) > this . splitValue ) anomalyScore = right . score ( inst , sizeLimit ) ; else anomalyScore = left . score ( inst , sizeLimit ) ; } else { anomalyScore = this . r * Math . pow ( 2.0 , this . depth ) ; } return anomalyScore ; }
If this node is a leaf node or it has a mass profile of less than sizeLimit this returns the anomaly score for the argument instance . Otherwise this node determines which of its subordinate nodes the argument instance belongs to and asks it provide the anomaly score .
21,580
protected void printNode ( ) { System . out . println ( this . depth + ", " + this . splitAttribute + ", " + this . splitValue + ", " + this . r ) ; if ( this . internalNode ) { this . right . printNode ( ) ; this . left . printNode ( ) ; } }
Prints this node to string and if it is an internal node prints its children nodes as well . Useful for debugging the entire tree structure .
21,581
private void initialClustering ( ) { updateGridListDensity ( ) ; Iterator < Map . Entry < DensityGrid , CharacteristicVector > > glIter = this . grid_list . entrySet ( ) . iterator ( ) ; HashMap < DensityGrid , CharacteristicVector > newGL = new HashMap < DensityGrid , CharacteristicVector > ( ) ; while ( glIter . hasNext ( ) ) { Map . Entry < DensityGrid , CharacteristicVector > grid = glIter . next ( ) ; DensityGrid dg = grid . getKey ( ) ; CharacteristicVector cvOfG = grid . getValue ( ) ; if ( cvOfG . getAttribute ( ) == DENSE ) { int gridClass = this . cluster_list . size ( ) ; cvOfG . setLabel ( gridClass ) ; GridCluster gc = new GridCluster ( ( CFCluster ) dg , new ArrayList < CFCluster > ( ) , gridClass ) ; gc . addGrid ( dg ) ; this . cluster_list . add ( gc ) ; } else cvOfG . setLabel ( NO_CLASS ) ; newGL . put ( dg , cvOfG ) ; } this . grid_list = newGL ; boolean changesMade ; do { changesMade = adjustLabels ( ) ; } while ( changesMade ) ; }
Implements the procedure given in Figure 3 of Chen and Tu 2007
21,582
private HashMap < DensityGrid , CharacteristicVector > adjustForSparseGrid ( DensityGrid dg , CharacteristicVector cv , int dgClass ) { HashMap < DensityGrid , CharacteristicVector > glNew = new HashMap < DensityGrid , CharacteristicVector > ( ) ; if ( dgClass != NO_CLASS ) { GridCluster gc = this . cluster_list . get ( dgClass ) ; gc . removeGrid ( dg ) ; cv . setLabel ( NO_CLASS ) ; glNew . put ( dg , cv ) ; this . cluster_list . set ( dgClass , gc ) ; if ( gc . getWeight ( ) > 0.0 && ! gc . isConnected ( ) ) glNew . putAll ( recluster ( gc ) ) ; } return glNew ; }
Adjusts the clustering of a sparse density grid . Implements lines 5 and 6 from Figure 4 of Chen and Tu 2007 .
21,583
private HashMap < DensityGrid , CharacteristicVector > adjustForTransitionalGrid ( DensityGrid dg , CharacteristicVector cv , int dgClass ) { GridCluster ch ; double hChosenSize = 0.0 ; DensityGrid dgH ; int hClass = NO_CLASS ; int hChosenClass = NO_CLASS ; Iterator < DensityGrid > dgNeighbourhood = dg . getNeighbours ( ) . iterator ( ) ; HashMap < DensityGrid , CharacteristicVector > glNew = new HashMap < DensityGrid , CharacteristicVector > ( ) ; while ( dgNeighbourhood . hasNext ( ) ) { dgH = dgNeighbourhood . next ( ) ; if ( this . grid_list . containsKey ( dgH ) ) { hClass = this . grid_list . get ( dgH ) . getLabel ( ) ; if ( hClass != NO_CLASS ) { ch = this . cluster_list . get ( hClass ) ; if ( ( ch . getWeight ( ) > hChosenSize ) && ! ch . isInside ( dg , dg ) ) { hChosenSize = ch . getWeight ( ) ; hChosenClass = hClass ; } } } } if ( hChosenClass != NO_CLASS && hChosenClass != dgClass ) { ch = this . cluster_list . get ( hChosenClass ) ; ch . addGrid ( dg ) ; this . cluster_list . set ( hChosenClass , ch ) ; if ( dgClass != NO_CLASS ) { GridCluster c = this . cluster_list . get ( dgClass ) ; c . removeGrid ( dg ) ; this . cluster_list . set ( dgClass , c ) ; } cv . setLabel ( hChosenClass ) ; glNew . put ( dg , cv ) ; } return glNew ; }
Adjusts the clustering of a transitional density grid . Implements lines 20 and 21 from Figure 4 of Chen and Tu 2007 .
21,584
private void cleanClusters ( ) { Iterator < GridCluster > clusIter = this . cluster_list . iterator ( ) ; ArrayList < GridCluster > toRem = new ArrayList < GridCluster > ( ) ; while ( clusIter . hasNext ( ) ) { GridCluster c = clusIter . next ( ) ; if ( c . getWeight ( ) == 0 ) toRem . add ( c ) ; } if ( ! toRem . isEmpty ( ) ) { clusIter = toRem . iterator ( ) ; while ( clusIter . hasNext ( ) ) { this . cluster_list . remove ( clusIter . next ( ) ) ; } } clusIter = this . cluster_list . iterator ( ) ; while ( clusIter . hasNext ( ) ) { GridCluster c = clusIter . next ( ) ; int index = this . cluster_list . indexOf ( c ) ; c . setClusterLabel ( index ) ; this . cluster_list . set ( index , c ) ; Iterator < Map . Entry < DensityGrid , Boolean > > gridsOfClus = c . getGrids ( ) . entrySet ( ) . iterator ( ) ; while ( gridsOfClus . hasNext ( ) ) { DensityGrid dg = gridsOfClus . next ( ) . getKey ( ) ; CharacteristicVector cv = this . grid_list . get ( dg ) ; if ( cv == null ) { System . out . println ( "Warning, cv is null for " + dg . toString ( ) + " from cluster " + index + "." ) ; printGridList ( ) ; printGridClusters ( ) ; } cv . setLabel ( index ) ; this . grid_list . put ( dg , cv ) ; } } }
Iterates through cluster_list to ensure that all empty clusters have been removed and that all cluster IDs match the cluster s index in cluster_list .
21,585
private void removeSporadic ( ) { Iterator < Map . Entry < DensityGrid , CharacteristicVector > > glIter = this . grid_list . entrySet ( ) . iterator ( ) ; HashMap < DensityGrid , CharacteristicVector > newGL = new HashMap < DensityGrid , CharacteristicVector > ( ) ; ArrayList < DensityGrid > remGL = new ArrayList < DensityGrid > ( ) ; while ( glIter . hasNext ( ) ) { Map . Entry < DensityGrid , CharacteristicVector > grid = glIter . next ( ) ; DensityGrid dg = grid . getKey ( ) ; CharacteristicVector cv = grid . getValue ( ) ; if ( cv . isSporadic ( ) ) { if ( ( this . getCurrTime ( ) - cv . getUpdateTime ( ) ) >= gap ) { int dgClass = cv . getLabel ( ) ; if ( dgClass != - 1 ) this . cluster_list . get ( dgClass ) . removeGrid ( dg ) ; remGL . add ( dg ) ; } else { cv . setSporadic ( checkIfSporadic ( cv ) ) ; newGL . put ( dg , cv ) ; } } else { cv . setSporadic ( checkIfSporadic ( cv ) ) ; newGL . put ( dg , cv ) ; } } this . grid_list . putAll ( newGL ) ; Iterator < DensityGrid > remIter = remGL . iterator ( ) ; while ( remIter . hasNext ( ) ) { DensityGrid sporadicDG = remIter . next ( ) ; this . deleted_grids . put ( sporadicDG , new Integer ( this . getCurrTime ( ) ) ) ; this . grid_list . remove ( sporadicDG ) ; } }
Implements the procedure described in section 4 . 2 of Chen and Tu 2007
21,586
private boolean checkIfSporadic ( CharacteristicVector cv ) { if ( cv . getCurrGridDensity ( this . getCurrTime ( ) , this . getDecayFactor ( ) ) < densityThresholdFunction ( cv . getDensityTimeStamp ( ) , this . cl , this . getDecayFactor ( ) , this . N ) ) { if ( cv . getRemoveTime ( ) == - 1 || this . getCurrTime ( ) >= ( ( 1 + this . beta ) * cv . getRemoveTime ( ) ) ) return true ; } return false ; }
Determines whether a sparse density grid is sporadic using rules S1 and S2 of Chen and Tu 2007
21,587
private double densityThresholdFunction ( int tg , double cl , double decayFactor , int N ) { return ( cl * ( 1.0 - Math . pow ( decayFactor , ( this . getCurrTime ( ) - tg + 1.0 ) ) ) ) / ( N * ( 1.0 - decayFactor ) ) ; }
Implements the function pi given in Definition 4 . 1 of Chen and Tu 2007
21,588
private void mergeClusters ( int smallClus , int bigClus ) { for ( Map . Entry < DensityGrid , CharacteristicVector > grid : grid_list . entrySet ( ) ) { DensityGrid dg = grid . getKey ( ) ; CharacteristicVector cv = grid . getValue ( ) ; if ( cv . getLabel ( ) == smallClus ) { cv . setLabel ( bigClus ) ; this . grid_list . put ( dg , cv ) ; } } GridCluster bGC = this . cluster_list . get ( bigClus ) ; bGC . absorbCluster ( this . cluster_list . get ( smallClus ) ) ; this . cluster_list . set ( bigClus , bGC ) ; this . cluster_list . remove ( smallClus ) ; cleanClusters ( ) ; }
Reassign all grids belonging in the small cluster to the big cluster Merge the GridCluster objects representing each cluster
21,589
private void updateGridListDensity ( ) { for ( Map . Entry < DensityGrid , CharacteristicVector > grid : grid_list . entrySet ( ) ) { DensityGrid dg = grid . getKey ( ) ; CharacteristicVector cvOfG = grid . getValue ( ) ; dg . setVisited ( false ) ; cvOfG . updateGridDensity ( this . getCurrTime ( ) , this . getDecayFactor ( ) , this . getDL ( ) , this . getDM ( ) ) ; this . grid_list . put ( dg , cvOfG ) ; } }
Iterates through grid_list and updates the density for each density grid therein . Also marks each density grid as unvisited for this call to adjustClustering .
21,590
public void printGridList ( ) { System . out . println ( "Grid List. Size " + this . grid_list . size ( ) + "." ) ; for ( Map . Entry < DensityGrid , CharacteristicVector > grid : grid_list . entrySet ( ) ) { DensityGrid dg = grid . getKey ( ) ; CharacteristicVector cv = grid . getValue ( ) ; if ( cv . getAttribute ( ) != SPARSE ) { double dtf = densityThresholdFunction ( cv . getUpdateTime ( ) , this . cl , this . getDecayFactor ( ) , this . N ) ; System . out . println ( dg . toString ( ) + " " + cv . toString ( ) + " // Density Threshold Function = " + dtf ) ; } } }
Iterates through grid_list and prints out each density grid therein as a string .
21,591
public void printGridClusters ( ) { System . out . println ( "List of Clusters. Total " + this . cluster_list . size ( ) + "." ) ; for ( GridCluster gc : this . cluster_list ) { System . out . println ( gc . getClusterLabel ( ) + ": " + gc . getWeight ( ) + " {" + gc . toString ( ) + "}" ) ; } }
Iterates through cluster_list and prints out each grid cluster therein as a string .
21,592
public void addObject ( DataSet dataSet ) throws Exception { DataObject [ ] dataObjects = dataSet . getDataObjectArray ( ) ; for ( int i = 0 ; i < dataObjects . length ; i ++ ) { this . addObject ( dataObjects [ i ] ) ; } }
Adds all objects in the given data set
21,593
public int getNrOfClasses ( ) { HashMap < Integer , Integer > classes = new HashMap < Integer , Integer > ( ) ; for ( DataObject currentObject : dataList ) { if ( ! classes . containsKey ( currentObject . getClassLabel ( ) ) ) classes . put ( currentObject . getClassLabel ( ) , 1 ) ; } return classes . size ( ) ; }
Counts the number of classes that are present in the data set . !!! It does not check whether all classes are contained !!!
21,594
public DataSet [ ] getDataSetsPerClass ( ) throws Exception { DataSet [ ] dataSetsPerClass = new DataSet [ this . getNrOfClasses ( ) ] ; for ( int i = 0 ; i < dataSetsPerClass . length ; i ++ ) { dataSetsPerClass [ i ] = new DataSet ( this . nrOfDimensions ) ; } for ( DataObject currentObject : dataList ) { dataSetsPerClass [ currentObject . getClassLabel ( ) ] . addObject ( currentObject ) ; } return dataSetsPerClass ; }
Separates the objects in this data set according to their class label
21,595
public double [ ] getVariances ( ) { double N = this . size ( ) ; double [ ] LS = new double [ this . getNrOfDimensions ( ) ] ; double [ ] SS = new double [ this . getNrOfDimensions ( ) ] ; double [ ] tmpFeatures ; double [ ] variances = new double [ this . getNrOfDimensions ( ) ] ; for ( DataObject dataObject : dataList ) { tmpFeatures = dataObject . getFeatures ( ) ; for ( int j = 0 ; j < tmpFeatures . length ; j ++ ) { LS [ j ] += tmpFeatures [ j ] ; SS [ j ] += tmpFeatures [ j ] * tmpFeatures [ j ] ; } } for ( int i = 0 ; i < LS . length ; i ++ ) { variances [ i ] = ( SS [ i ] / N - ( ( LS [ i ] / N ) * ( LS [ i ] / N ) ) ) ; } return variances ; }
Calculates the variance of this data set for each dimension
21,596
public double [ ] toDoubleArray ( ) { double [ ] array = new double [ numAttributes ( ) ] ; for ( int i = 0 ; i < numValues ( ) ; i ++ ) { array [ index ( i ) ] = valueSparse ( i ) ; } return array ; }
To double array .
21,597
private double calcC1 ( int objectId ) { int nrOfPreviousResults = previousOScoreResultList . get ( objectId ) . size ( ) ; if ( nrOfPreviousResults == 0 ) { return 0.0 ; } int count = 1 ; double difSum_k = Math . abs ( lastOScoreResult . get ( objectId ) - previousOScoreResultList . get ( objectId ) . get ( nrOfPreviousResults - 1 ) ) ; for ( int i = Math . max ( 0 , nrOfPreviousResults - ( confK - 1 ) ) + 1 ; i < nrOfPreviousResults ; i ++ ) { difSum_k += Math . abs ( previousOScoreResultList . get ( objectId ) . get ( i ) - previousOScoreResultList . get ( objectId ) . get ( i - 1 ) ) ; count ++ ; } difSum_k /= count ; return Math . pow ( Math . E , ( - 1.0 * difSum_k ) ) ; }
Calculates the Confidence on the basis of the standard deviation of previous OScore results
21,598
public void invertedSumariesPerMeasure ( String path ) { int cont = 0 ; int algorithmSize = this . streams . get ( 0 ) . algorithm . size ( ) ; int streamSize = this . streams . size ( ) ; int measureSize = this . streams . get ( 0 ) . algorithm . get ( 0 ) . measures . size ( ) ; while ( cont != measureSize ) { String output = "" ; output += "\\documentclass{article}\n" ; output += "\\usepackage{multirow}\n\\usepackage{booktabs}\n\\begin{document}\n\\begin{table}[htbp]\n\\caption{Add caption}" ; output += "\\begin{tabular}" ; output += "{" ; for ( int i = 0 ; i < algorithmSize + 1 ; i ++ ) { output += "r" ; } output += "}\n\\toprule\nAlgorithm" ; for ( int i = 0 ; i < algorithmSize ; i ++ ) { output += "& " + this . streams . get ( 0 ) . algorithm . get ( i ) . name ; } output += "\\\\" ; output += "\n\\midrule\n" ; for ( int i = 0 ; i < streamSize ; i ++ ) { List < Algorithm > alg = this . streams . get ( i ) . algorithm ; output += this . streams . get ( i ) . name ; for ( int j = 0 ; j < algorithmSize ; j ++ ) { if ( alg . get ( j ) . measures . get ( cont ) . isType ( ) ) { output += "&" + Algorithm . format ( alg . get ( j ) . measures . get ( cont ) . getValue ( ) ) + "$\\,\\pm$" + Algorithm . format ( alg . get ( j ) . measures . get ( cont ) . getStd ( ) ) ; } else { output += "&" + Algorithm . format1 ( alg . get ( j ) . measures . get ( cont ) . getValue ( ) ) ; } } output += "\\\\\n" ; } output += "\\bottomrule\n\\end{tabular}%\n\\label{tab:addlabel}%\n\\end{table}%\n\\end{document}" ; String name = this . streams . get ( 0 ) . algorithm . get ( 0 ) . measures . get ( cont ) . getName ( ) ; try { BufferedWriter out = new BufferedWriter ( new FileWriter ( path + name + ".tex" ) ) ; out . write ( output ) ; out . close ( ) ; } catch ( IOException e ) { System . out . println ( "Error saving " + name + ".tex" ) ; } cont ++ ; } }
Generates a latex summary in which the rows are the datasets and the columns the algorithms .
21,599
public void generateCSV ( ) { int cont = 0 ; int algorithmSize = this . streams . get ( 0 ) . algorithm . size ( ) ; int streamSize = this . streams . size ( ) ; int measureSize = this . streams . get ( 0 ) . algorithm . get ( 0 ) . measures . size ( ) ; while ( cont != measureSize ) { String output = "" ; output += "Algorithm," ; output += this . streams . get ( 0 ) . algorithm . get ( 0 ) . name ; for ( int i = 1 ; i < algorithmSize ; i ++ ) { output += "," + this . streams . get ( 0 ) . algorithm . get ( i ) . name ; } output += "\n" ; for ( int i = 0 ; i < streamSize ; i ++ ) { List < Algorithm > alg = this . streams . get ( i ) . algorithm ; output += this . streams . get ( i ) . name ; for ( int j = 0 ; j < algorithmSize ; j ++ ) { output += "," + alg . get ( j ) . measures . get ( cont ) . getValue ( ) ; } output += "\n" ; } String name = this . streams . get ( 0 ) . algorithm . get ( 0 ) . measures . get ( cont ) . getName ( ) ; try { BufferedWriter out = new BufferedWriter ( new FileWriter ( path + name + ".csv" ) ) ; out . write ( output ) ; out . close ( ) ; } catch ( IOException e ) { System . out . println ( name + ".csv" ) ; } cont ++ ; } }
Generate a csv file for the statistical analysis .