idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
21,400
public static double mean ( double [ ] vector ) { double sum = 0 ; if ( vector . length == 0 ) { return 0 ; } for ( int i = 0 ; i < vector . length ; i ++ ) { sum += vector [ i ] ; } return sum / ( double ) vector . length ; }
Computes the mean for an array of doubles .
21,401
public static int minIndex ( int [ ] ints ) { int minimum = 0 ; int minIndex = 0 ; for ( int i = 0 ; i < ints . length ; i ++ ) { if ( ( i == 0 ) || ( ints [ i ] < minimum ) ) { minIndex = i ; minimum = ints [ i ] ; } } return minIndex ; }
Returns index of minimum element in a given array of integers . First minimum is returned .
21,402
public static int minIndex ( double [ ] doubles ) { double minimum = 0 ; int minIndex = 0 ; for ( int i = 0 ; i < doubles . length ; i ++ ) { if ( ( i == 0 ) || ( doubles [ i ] < minimum ) ) { minIndex = i ; minimum = doubles [ i ] ; } } return minIndex ; }
Returns index of minimum element in a given array of doubles . First minimum is returned .
21,403
public static void normalize ( double [ ] doubles ) { double sum = 0 ; for ( int i = 0 ; i < doubles . length ; i ++ ) { sum += doubles [ i ] ; } normalize ( doubles , sum ) ; }
Normalizes the doubles in the array by their sum .
21,404
public static void normalize ( double [ ] doubles , double sum ) { if ( Double . isNaN ( sum ) ) { throw new IllegalArgumentException ( "Can't normalize array. Sum is NaN." ) ; } if ( sum == 0 ) { throw new IllegalArgumentException ( "Can't normalize array. Sum is zero." ) ; } for ( int i = 0 ; i < doubles . length ; i...
Normalizes the doubles in the array using the given value .
21,405
public static double [ ] logs2probs ( double [ ] a ) { double max = a [ maxIndex ( a ) ] ; double sum = 0.0 ; double [ ] result = new double [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { result [ i ] = Math . exp ( a [ i ] - max ) ; sum += result [ i ] ; } normalize ( result , sum ) ; return result ; }
Converts an array containing the natural logarithms of probabilities stored in a vector back into probabilities . The probabilities are assumed to sum to one .
21,406
public static double probToLogOdds ( double prob ) { if ( gr ( prob , 1 ) || ( sm ( prob , 0 ) ) ) { throw new IllegalArgumentException ( "probToLogOdds: probability must " + "be in [0,1] " + prob ) ; } double p = SMALL + ( 1.0 - 2 * SMALL ) * prob ; return Math . log ( p / ( 1 - p ) ) ; }
Returns the log - odds for a given probabilitiy .
21,407
public static double roundDouble ( double value , int afterDecimalPoint ) { double mask = Math . pow ( 10.0 , ( double ) afterDecimalPoint ) ; return ( double ) ( Math . round ( value * mask ) ) / mask ; }
Rounds a double to the given number of decimal places .
21,408
public static double variance ( double [ ] vector ) { double sum = 0 , sumSquared = 0 ; if ( vector . length <= 1 ) { return 0 ; } for ( int i = 0 ; i < vector . length ; i ++ ) { sum += vector [ i ] ; sumSquared += ( vector [ i ] * vector [ i ] ) ; } double result = ( sumSquared - ( sum * sum / ( double ) vector . len...
Computes the variance for an array of doubles .
21,409
public static int sum ( int [ ] ints ) { int sum = 0 ; for ( int i = 0 ; i < ints . length ; i ++ ) { sum += ints [ i ] ; } return sum ; }
Computes the sum of the elements of an array of integers .
21,410
private static void quickSort ( double [ ] array , int [ ] index , int left , int right ) { if ( left < right ) { int middle = partition ( array , index , left , right ) ; quickSort ( array , index , left , middle ) ; quickSort ( array , index , middle + 1 , right ) ; } }
assignable index ;
21,411
public static String [ ] breakUp ( String s , int columns ) { Vector < String > result ; String line ; BreakIterator boundary ; int boundaryStart ; int boundaryEnd ; String word ; String punctuation ; int i ; String [ ] lines ; result = new Vector < String > ( ) ; punctuation = " .,;:!?'\"" ; lines = s . split ( "\n" )...
Breaks up the string if wider than columns characters .
21,412
public boolean isMetBy ( Class < ? > klass ) { if ( ! CapabilitiesHandler . class . isAssignableFrom ( klass ) ) return isMetBy ( NON_HANDLER_CAPABILITIES ) ; CapabilitiesHandler instance ; try { instance = ( CapabilitiesHandler ) klass . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) {...
Tests if the requirement is met by the given class .
21,413
public static CapabilityRequirement hasAll ( Capability ... capabilities ) { return new CapabilityRequirement ( c -> { for ( Capability capability : capabilities ) { if ( ! c . hasCapability ( capability ) ) return false ; } return true ; } ) ; }
Creates a requirement that a given set of capabilities have all of the specified capabilities .
21,414
protected void setGraph ( MeasureCollection [ ] measures , MeasureCollection [ ] measureStds , int [ ] processFrequencies , Color [ ] colors ) { super . setGraph ( measures , measureStds , colors ) ; }
Updates the measure collection information and repaints the curves .
21,415
private void paintFullCurve ( Graphics g , int i ) { if ( this . measures [ i ] . getNumberOfValues ( this . measureSelected ) == 0 ) { return ; } g . setColor ( this . colors [ i ] ) ; int height = getHeight ( ) ; int n = this . measures [ i ] . getNumberOfValues ( this . measureSelected ) ; int [ ] x = new int [ n ] ...
Draws a single curve on the canvas .
21,416
public void computeValue ( DoubleVector values ) { if ( this . isType ( ) ) { setValues ( values ) ; double sumDif = 0.0 ; this . value = this . values . sumOfValues ( ) / ( double ) values . numValues ( ) ; for ( int i = 0 ; i < this . values . numValues ( ) ; i ++ ) { double dif = this . values . getValue ( i ) - thi...
Calculates the value of measure
21,417
protected void xAxis ( Graphics g ) { g . setColor ( Color . BLACK ) ; g . drawLine ( X_OFFSET_LEFT , calcY ( 0 ) , width + X_OFFSET_LEFT , calcY ( 0 ) ) ; drawXLabels ( g ) ; }
Draws the x axis containing of the axis line and the labels .
21,418
private void yAxis ( Graphics g ) { g . setColor ( Color . BLACK ) ; g . drawLine ( X_OFFSET_LEFT , calcY ( 0 ) , X_OFFSET_LEFT , Y_OFFSET_TOP ) ; g . setColor ( new Color ( 220 , 220 , 220 ) ) ; g . drawLine ( X_OFFSET_LEFT , height / 2 + Y_OFFSET_TOP , getWidth ( ) , height / 2 + Y_OFFSET_TOP ) ; g . setColor ( Color...
Draws the y axis containing og the axis line the horizontal helping line and the labels .
21,419
private void constructMeanStdPreviewsForParam ( int numEntriesPerPreview , int numParamValues , int paramValue ) { List < double [ ] > meanParamMeasurements = calculateMeanMeasurementsForParam ( numEntriesPerPreview , numParamValues , paramValue ) ; List < double [ ] > stdParamMeasurements = calculateStdMeasurementsFor...
Construct the mean and standard deviation Previews for one specific parameter value .
21,420
private List < double [ ] > calculateMeanMeasurementsForParam ( int numEntriesPerPreview , int numParamValues , int paramValue ) { List < double [ ] > paramMeasurementsSum = new ArrayList < double [ ] > ( numEntriesPerPreview ) ; List < double [ ] > meanParamMeasurements = new ArrayList < double [ ] > ( numEntriesPerPr...
Calculate the mean measurements for the given parameter value .
21,421
private List < double [ ] > calculateStdMeasurementsForParam ( int numEntriesPerPreview , int numParamValues , int paramValue , List < double [ ] > meanParamMeasurements ) { List < double [ ] > paramMeasurementsSquaredDiffSum = new ArrayList < double [ ] > ( numEntriesPerPreview ) ; List < double [ ] > paramMeasurement...
Calculate the standard deviation measurements for the given parameter value .
21,422
private void addPreviewMeasurementsToSum ( List < double [ ] > measurementsSum , Preview preview , int numEntriesPerPreview ) { List < double [ ] > previewMeasurements = preview . getData ( ) ; for ( int entryIdx = 0 ; entryIdx < numEntriesPerPreview ; entryIdx ++ ) { double [ ] previewEntry = previewMeasurements . get...
Add measurements from the given Preview to the overall sum .
21,423
private void addPreviewMeasurementSquaredDiffsToSum ( List < double [ ] > meanMeasurements , List < double [ ] > measurementsSquaredDiffSum , Preview preview , int numEntriesPerPreview ) { List < double [ ] > previewMeasurements = preview . getData ( ) ; for ( int entryIdx = 0 ; entryIdx < numEntriesPerPreview ; entryI...
Add squared deviations from the mean value from the given Preview to the overall sum .
21,424
public static double [ ] doNaiveBayesPredictionLog ( Instance inst , DoubleVector observedClassDistribution , AutoExpandVector < AttributeClassObserver > observers , AutoExpandVector < AttributeClassObserver > observers2 ) { AttributeClassObserver obs ; double [ ] votes = new double [ observedClassDistribution . numVal...
Naive Bayes Prediction using log10 for VFDR rules
21,425
private double [ ] generatePriors ( Random r , int L , double z , boolean skew ) { double P [ ] = new double [ L ] ; for ( int i = 0 ; i < L ; i ++ ) { P [ i ] = r . nextDouble ( ) ; } do { double c = Utils . sum ( P ) / z ; for ( int i = 0 ; i < L ; i ++ ) { P [ i ] = Math . min ( 1.0 , P [ i ] / c ) ; } } while ( Uti...
Generate Priors . Generate the label priors .
21,426
private HashSet generateSet ( ) { int y [ ] = new int [ m_L ] ; int k = samplePMF ( priors_norm ) ; y [ k ] = 1 ; ArrayList < Integer > indices = getShuffledListToLWithoutK ( m_L , k ) ; for ( int j : indices ) { y [ j ] = ( joint ( j , y ) > m_MetaRandom . nextDouble ( ) ) ? 1 : 0 ; } return vector2set ( y ) ; }
Generate Set .
21,427
protected double [ ] modifyPriorVector ( double P [ ] , double u , Random r , boolean skew ) { for ( int j = 0 ; j < P . length ; j ++ ) { if ( r . nextDouble ( ) < u ) { P [ j ] = r . nextDouble ( ) ; } } return P ; }
ModifyPriorVector . A certain number of values will be altered .
21,428
private HashSet [ ] getTopCombinations ( int n ) { final HashMap < HashSet , Integer > count = new HashMap < HashSet , Integer > ( ) ; HashMap < HashSet , Integer > isets = new HashMap < HashSet , Integer > ( ) ; int N = 100000 ; double lc = 0.0 ; for ( int i = 0 ; i < N ; i ++ ) { HashSet Y = generateSet ( ) ; lc += Y...
GetTopCombinations . Calculating the full joint probability distribution is too complex . - sample from the approximate joint many times - record the the n most commonly ocurring Y and their frequencies - create a map based on these frequencies
21,429
private int [ ] set2vector ( HashSet < Integer > Y , int L ) { int y [ ] = new int [ L ] ; for ( int j : Y ) { y [ j ] = 1 ; } return y ; }
convert set Y to an L - length vector y
21,430
private HashSet < Integer > vector2set ( int y [ ] ) { HashSet < Integer > Y = new HashSet < Integer > ( ) ; for ( int j = 0 ; j < y . length ; j ++ ) { if ( y [ j ] > 0 ) { Y . add ( j ) ; } } return Y ; }
convert L - length vector y to set Y
21,431
public Option [ ] discoverOptionsViaReflection ( ) { Class c = this . handler . getClass ( ) ; Field [ ] fields = c . getFields ( ) ; List < Option > optList = new LinkedList < Option > ( ) ; for ( Field field : fields ) { String fName = field . getName ( ) ; Class < ? > fType = field . getType ( ) ; if ( fType . getNa...
Gets the options of this class via reflection .
21,432
public Instances kNearestNeighbours ( Instance target , int kNN ) throws Exception { boolean print = false ; MyHeap heap = new MyHeap ( kNN ) ; double distance ; int firstkNN = 0 ; for ( int i = 0 ; i < m_Instances . numInstances ( ) ; i ++ ) { if ( target == m_Instances . instance ( i ) ) continue ; if ( firstkNN < kN...
Returns k nearest instances in the current neighbourhood to the supplied instance .
21,433
public void update ( Instance ins ) throws Exception { if ( m_Instances == null ) throw new Exception ( "No instances supplied yet. Cannot update without" + "supplying a set of instances first." ) ; m_DistanceFunction . update ( ins ) ; }
Updates the LinearNNSearch to cater for the new added instance . This implementation only updates the ranges of the DistanceFunction class since our set of instances is passed by reference and should already have the newly added instance .
21,434
public void addInstanceInfo ( Instance ins ) { if ( m_Instances != null ) try { update ( ins ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } }
Adds the given instance info . This implementation updates the range datastructures of the DistanceFunction class .
21,435
public static boolean nameIsLegal ( String optionName ) { for ( char illegalChar : illegalNameCharacters ) { if ( optionName . indexOf ( illegalChar ) >= 0 ) { return false ; } } return true ; }
Gets whether the name is valid or not .
21,436
public void setGraph ( MeasureCollection [ ] measures , MeasureCollection [ ] measureStds , int [ ] processFrequencies , int min_processFrequency , Color [ ] colors ) { this . measures = measures ; this . processFrequencies = processFrequencies ; this . min_processFrequency = min_processFrequency ; ( ( ProcessGraphAxes...
Sets the graph containing multiple curves .
21,437
public void splitNode ( KDTreeNode node , int numNodesCreated , double [ ] [ ] nodeRanges , double [ ] [ ] universe ) throws Exception { correctlyInitialized ( ) ; int splitDim = widestDim ( nodeRanges , universe ) ; double splitVal = m_EuclideanDistance . getMiddle ( nodeRanges [ splitDim ] ) ; int rightStart = rearra...
Splits a node into two based on the midpoint value of the dimension in which the points have the widest spread . After splitting two new nodes are created and correctly initialised . And node . left and node . right are set appropriately .
21,438
private double computeStabilityIndex ( ) { int m = ( int ) Math . floor ( ( this . ensemble . length - MAXPERMANENT ) / 2 ) ; int [ ] [ ] votes = new int [ m ] [ tau_size ] ; double errors = 0 ; int count = 0 ; Pair [ ] arr = getHalf ( true ) ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < tau_size ; j ++ ) ...
Returns the stability index of the adaptive ensemble of classifiers . The ensemble is considered stable here if its diversity level and error rates are low .
21,439
private Classifier getBestAdaptiveClassifier ( ) { Pair [ ] newEnsembleWeights = new Pair [ ensembleWeights . length - MAXPERMANENT ] ; for ( int i = 0 ; i < newEnsembleWeights . length ; i ++ ) newEnsembleWeights [ i ] = ensembleWeights [ i ] ; Arrays . sort ( newEnsembleWeights , Collections . reverseOrder ( ) ) ; re...
Returns the adaptive classifier with the highest weight
21,440
public void scaleYResolution ( double factor ) { this . y_resolution = Math . max ( 1.0 , this . y_resolution * factor ) ; updateYResolution ( ) ; updateUpperYValue ( ) ; updateCanvas ( true ) ; }
Scales the resolution on the y - axis by the given factor and updates the canvas . The y - resolution must not be lower than 1 .
21,441
private double getMaxSelectedValue ( ) { double max = Double . MIN_VALUE ; for ( int i = 0 ; i < this . measures . length ; i ++ ) { if ( this . measures [ i ] . getMaxValue ( this . measureSelected ) > max ) { max = this . measures [ i ] . getMaxValue ( this . measureSelected ) ; } } return max ; }
Computes the maximum value of the underlying measures at the currently selected measure .
21,442
private boolean updateMinMaxValues ( ) { double min_x_value_new ; double max_x_value_new ; double max_y_value_new ; if ( this . measures == null ) { min_x_value_new = 0 ; max_x_value_new = 1 ; max_y_value_new = 1 ; } else { min_x_value_new = getMinXValue ( ) ; max_x_value_new = getMaxXValue ( ) ; max_y_value_new = getM...
Computes the minimum and maximum values for the x and y - axis and updates the children if necessary .
21,443
private void updateLowerXValue ( ) { double lower = 0.0 ; if ( this . measures != null ) { lower = this . min_x_value * ( 1 - ( 0.1 / x_resolution ) ) ; } this . axesPanel . setLowerXValue ( lower ) ; this . plotPanel . setLowerXValue ( lower ) ; }
Updates the lower value on the x - axis .
21,444
private void updateUpperXValue ( ) { double upper = 1.0 ; if ( this . measures != null ) { upper = max_x_value * ( 1 + ( 0.1 / x_resolution ) ) ; } this . axesPanel . setUpperXValue ( upper ) ; this . plotPanel . setUpperXValue ( upper ) ; }
Updates the upper value on the x - axis .
21,445
private void updateUpperYValue ( ) { double upper = 1.0 ; if ( this . measures != null ) { upper = max_y_value * ( 1 + ( 0.1 / y_resolution ) ) ; } this . axesPanel . setUpperYValue ( upper ) ; this . plotPanel . setUpperYValue ( upper ) ; }
Updates the upper value on the y - axis .
21,446
private void updateChildren ( ) { axesPanel . setSize ( getWidth ( ) , getHeight ( ) ) ; plotPanel . setSize ( getWidth ( ) - X_OFFSET_LEFT - X_OFFSET_RIGHT , getHeight ( ) - Y_OFFSET_BOTTOM - Y_OFFSET_TOP ) ; }
Updates the size of the axes curve and event panel . Recomputes the event locations if necessary .
21,447
public void setOptions ( String [ ] labels , String [ ] descriptions , int defaultIndex ) { if ( labels . length != descriptions . length ) { throw new IllegalArgumentException ( "Labels/descriptions mismatch." ) ; } if ( labels . length > 0 ) { this . optionLabels = labels . clone ( ) ; this . optionDescriptions = des...
Set new options for this MultiChoiceOption and refresh the edit component .
21,448
public void put ( long key , T element ) { Entry < T > entry = new Entry < T > ( key , element ) ; elements . add ( entry ) ; this . numElements ++ ; fileElement ( entry , true ) ; }
Adds an element to the hash table .
21,449
private void fileElement ( Entry < T > currentElement , boolean rehash ) { int maxFailures = Math . max ( ( int ) Math . log ( this . numElements ) , this . numTables * 2 ) ; int currentTable = 0 ; for ( int i = 0 ; i < maxFailures ; i ++ ) { int hash = this . hashfunctions . get ( currentTable ) . hash ( currentElemen...
Adds an element to one of the tables for Cuckoo Hashing .
21,450
private void increaseAndReset ( ) { if ( this . hashSize < 30 ) { this . hashSize += 1 ; this . hashfunctions . clear ( ) ; for ( List < Entry < T > > table : this . tables ) { this . hashfunctions . add ( new DietzfelbingerHash ( this . hashSize , this . random ) ) ; ( ( ArrayList < Entry < T > > ) table ) . ensureCap...
Adds a new table and rebuild the hash table .
21,451
public T get ( long key ) { for ( int i = 0 ; i < this . numTables ; i ++ ) { Entry < T > entry = this . tables . get ( i ) . get ( this . hashfunctions . get ( i ) . hash ( key ) ) ; if ( entry != null && entry . getKey ( ) == key ) { return entry . getValue ( ) ; } } for ( Entry < T > entry : this . stash ) { if ( en...
Gets an element of the hash table .
21,452
private void reset ( ) { for ( DietzfelbingerHash hashfunction : this . hashfunctions ) { hashfunction . nextHashFunction ( ) ; } int sizeTables = 1 << this . hashSize ; for ( List < Entry < T > > table : this . tables ) { table . clear ( ) ; for ( int j = 0 ; j < sizeTables ; j ++ ) { table . add ( null ) ; } } this ....
Rebuilds the hash table .
21,453
public void clear ( ) { this . hashSize = this . startHashSize ; this . numTables = this . startNumTables ; this . numElements = 0 ; this . hashfunctions . clear ( ) ; this . tables . clear ( ) ; int sizeTables = 1 << this . startHashSize ; for ( int i = 0 ; i < this . startNumTables ; i ++ ) { this . hashfunctions . a...
Removes all of the elements from this hash table . The hash table will be empty after this call returns .
21,454
public void splitNode ( KDTreeNode node , int numNodesCreated , double [ ] [ ] nodeRanges , double [ ] [ ] universe ) throws Exception { correctlyInitialized ( ) ; int splitDim = widestDim ( nodeRanges , universe ) ; int medianIdxIdx = node . m_Start + ( node . m_End - node . m_Start ) / 2 ; int medianIdx = select ( sp...
Splits a node into two based on the median value of the dimension in which the points have the widest spread . After splitting two new nodes are created and correctly initialised . And node . left and node . right are set appropriately .
21,455
public int select ( int attIdx , int [ ] indices , int left , int right , int k ) { if ( left == right ) { return left ; } else { int middle = partition ( attIdx , indices , left , right ) ; if ( ( middle - left + 1 ) >= k ) { return select ( attIdx , indices , left , middle , k ) ; } else { return select ( attIdx , in...
Implements computation of the kth - smallest element according to Manber s Introduction to Algorithms .
21,456
public void deleteAttributeAt ( Integer integer ) { this . instanceInformation . deleteAttributeAt ( integer ) ; for ( int i = 0 ; i < numInstances ( ) ; i ++ ) { instance ( i ) . setDataset ( null ) ; instance ( i ) . deleteAttributeAt ( integer ) ; instance ( i ) . setDataset ( this ) ; } }
Delete attribute at .
21,457
public void insertAttributeAt ( Attribute attribute , int position ) { if ( this . instanceInformation == null ) { this . instanceInformation = new InstanceInformation ( ) ; } this . instanceInformation . insertAttributeAt ( attribute , position ) ; for ( int i = 0 ; i < numInstances ( ) ; i ++ ) { instance ( i ) . set...
Insert attribute at .
21,458
public Instances trainCV ( int numFolds , int numFold , Random random ) { Instances train = trainCV ( numFolds , numFold ) ; train . randomize ( random ) ; return train ; }
Train cv .
21,459
public boolean readInstance ( Reader fileReader ) { Instance inst = arff . readInstance ( ) ; if ( inst != null ) { inst . setDataset ( this ) ; add ( inst ) ; return true ; } else { return false ; } }
Read instance .
21,460
protected String stringWithoutHeader ( ) { StringBuffer text = new StringBuffer ( ) ; for ( int i = 0 ; i < numInstances ( ) ; i ++ ) { text . append ( instance ( i ) ) ; if ( i < numInstances ( ) - 1 ) { text . append ( '\n' ) ; } } return text . toString ( ) ; }
Returns the instances in the dataset as a string in ARFF format . Strings are quoted if they contain whitespace characters or if they are a question mark .
21,461
private void computeAttributesIndices ( ) { this . hsAttributesIndices = new HashMap < String , Integer > ( ) ; for ( int i = 0 ; i < this . numAttributes ( ) ; i ++ ) { hsAttributesIndices . put ( this . attribute ( i ) . name ( ) , i ) ; } }
Completes the hashset with attributes indices .
21,462
public void setIndicesRelevants ( int [ ] indicesRelevants ) { this . indicesRelevants = indicesRelevants ; int numIrrelevantFeatures = this . numAttributes ( ) - this . indicesRelevants . length - 1 ; this . indicesIrrelevants = new int [ numIrrelevantFeatures ] ; int index = 0 ; int indexRel = 0 ; for ( int i = 0 ; i...
Sets the indices of relevant features . This method also sets the irrelevant ones since it is the set complement .
21,463
public Instance sample ( Random random ) { double [ ] center = getCenter ( ) ; final int dimensions = center . length ; final double sin [ ] = new double [ dimensions - 1 ] ; final double cos [ ] = new double [ dimensions - 1 ] ; final double length = random . nextDouble ( ) * getRadius ( ) ; double lastValue = 1.0 ; f...
Samples this cluster by returning a point from inside it .
21,464
public static List < double [ ] > generatekMeansPlusPlusCentroids ( int k , List < double [ ] > input , Random random ) { int n = input . size ( ) ; assert ( n > 0 ) ; int d = input . get ( 0 ) . length - 1 ; assert ( k <= n ) ; List < double [ ] > centerValue = new ArrayList < double [ ] > ( k ) ; double [ ] lastCente...
Generates the initial centroids like the k - means ++ algorithm .
21,465
protected boolean isLeaf ( ) { for ( int i = 0 ; i < entries . length ; i ++ ) { Entry entry = entries [ i ] ; if ( entry . getChild ( ) != null ) { return false ; } } return true ; }
Checks if this node is a leaf . A node is a leaf when none of the entries in the node have children .
21,466
private int getNextEmptyPosition ( ) { int counter ; for ( counter = 0 ; counter < entries . length ; counter ++ ) { Entry e = entries [ counter ] ; if ( e . isEmpty ( ) ) { break ; } } if ( counter == entries . length ) { throw new RuntimeException ( "Entry added to a node which is already full." ) ; } return counter ...
Returns the position of the next free Entry .
21,467
public void setText ( Preview preview ) { Point p = this . scrollPaneTable . getViewport ( ) . getViewPosition ( ) ; previewTableModel . setPreview ( preview ) ; SwingUtilities . invokeLater ( new Runnable ( ) { boolean structureChanged = previewTableModel . structureChanged ( ) ; public void run ( ) { if ( ! scrollPan...
Updates the preview table based on the information given by preview .
21,468
public ParsedPreview readCollection ( PreviewCollection < Preview > pc ) { ParsedPreview pp = new ParsedPreview ( ) ; List < Preview > sps = pc . getPreviews ( ) ; if ( sps . size ( ) > 0 && sps . get ( 0 ) instanceof PreviewCollection ) { for ( Preview sp : sps ) { @ SuppressWarnings ( "unchecked" ) ParsedPreview tmp ...
Parses a PreviewCollection and return the resulting ParsedPreview object . If the PreviewCollection contains PreviewCollections again it recursively adds their results . If it contains simple Previews it adds their properties to the result .
21,469
private ParsedPreview read ( Preview p ) { String [ ] measureNames = p . getMeasurementNames ( ) ; int numMeasures = p . getMeasurementNameCount ( ) ; int processFrequencyColumn = - 1 ; int accuracyColumn = - 1 ; int kappaColumn = - 1 ; int kappaTempColumn = - 1 ; int ramColumn = - 1 ; int timeColumn = - 1 ; int memory...
Parses a preview with respect to the process frequency and several measurements .
21,470
public static boolean isJavaVersionOK ( ) { boolean isJavaVersionOK = true ; String versionStr = System . getProperty ( "java.version" ) ; String [ ] parts ; double version ; if ( versionStr . contains ( "." ) ) { parts = versionStr . split ( "\\." ) ; } else { parts = new String [ ] { versionStr } ; } if ( parts . len...
Checks if the Java version is recent enough to run MOA .
21,471
protected double computeCandidateWeight ( Classifier candidate , Instances chunk , int numFolds ) { double candidateWeight = 0.0 ; Random random = new Random ( 1 ) ; Instances randData = new Instances ( chunk ) ; randData . randomize ( random ) ; if ( randData . classAttribute ( ) . isNominal ( ) ) { randData . stratif...
Computes the weight of a candidate classifier .
21,472
protected double computeWeight ( Classifier learner , Instances chunk ) { double mse_i = 0 ; double mse_r = 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 += elem...
Computes the weight of a given classifie .
21,473
public double [ ] getVotesForInstance ( Instance inst ) { DoubleVector combinedVote = new DoubleVector ( ) ; if ( this . trainingWeightSeenByModel > 0.0 ) { for ( int i = 0 ; i < this . ensemble . length ; i ++ ) { if ( this . ensembleWeights [ i ] > 0.0 ) { DoubleVector vote = new DoubleVector ( this . ensemble [ i ] ...
Predicts a class for an example .
21,474
protected int removePoorestModelBytes ( ) { int poorestIndex = Utils . minIndex ( this . ensembleWeights ) ; int byteSize = this . ensemble [ poorestIndex ] . measureByteSize ( ) ; discardModel ( poorestIndex ) ; return byteSize ; }
Removes the poorest classifier from the model thus decreasing the models size .
21,475
private DataSet [ ] splitDataSetUsingEM ( DataSet dataSet , int nrOfPartitions ) throws Exception { if ( dataSet . size ( ) <= 1 ) throw new Exception ( "EMsplit needs at least 2 objects!" ) ; EMProjectedClustering myEM = new EMProjectedClustering ( ) ; int nrOfIterations = 1 ; double log10 = Math . log ( dataSet . siz...
This methods splits the given data set into partitions using the EM algorithm . The resulting number of partitions is < = nrOfPartitions . If EM returns only one partition the data set is split using mean shift . The size of each resulting partition is AT LEAST 2 i . e . partitions with size 1 are merged with the close...
21,476
private final void setSeed ( int seed ) { if ( mt == null ) mt = new int [ N ] ; mt [ 0 ] = seed ; for ( mti = 1 ; mti < N ; mti ++ ) { mt [ mti ] = ( MAGIC_FACTOR1 * ( mt [ mti - 1 ] ^ ( mt [ mti - 1 ] >>> 30 ) ) + mti ) ; } }
not be made public .
21,477
public final synchronized void setSeed ( int [ ] buf ) { int length = buf . length ; if ( length == 0 ) throw new IllegalArgumentException ( "Seed buffer may not be empty" ) ; int i = 1 , j = 0 , k = ( N > length ? N : length ) ; setSeed ( MAGIC_SEED ) ; for ( ; k > 0 ; k -- ) { mt [ i ] = ( mt [ i ] ^ ( ( mt [ i - 1 ]...
This method resets the state of this instance using the integer array of seed data provided . This is the canonical way of resetting the pseudo random number sequence .
21,478
protected static synchronized void initCache ( ) { if ( m_Cache == null ) { m_Cache = new ClassCache ( ) ; if ( m_Cache . isEmpty ( ) ) { InputStream inputStream = null ; try { inputStream = m_Cache . getClass ( ) . getResourceAsStream ( CLASS_LIST ) ; m_Cache = new ClassCache ( new FixedClassListTraversal ( inputStrea...
Initializes the class cache
21,479
public static List < String > getAllClassNames ( ) { List < String > result = new ArrayList < > ( ) ; Iterator < String > pkgs = m_Cache . packages ( ) ; while ( pkgs . hasNext ( ) ) { String pkg = pkgs . next ( ) ; if ( pkg . startsWith ( "moa" ) ) { Set < String > classnames = m_Cache . getClassnames ( pkg ) ; result...
Returns all class names stored in the cache .
21,480
public static void main ( String [ ] args ) throws Exception { initCache ( ) ; List < String > allClassnames = getAllClassNames ( ) ; PrintStream out = System . out ; if ( args . length > 0 ) out = new PrintStream ( new File ( args [ 0 ] ) ) ; Collections . sort ( allClassnames ) ; for ( String clsname : allClassnames ...
Outputs all class names below moa either to stdout or to the file provided as first argument .
21,481
public void add ( DATA data ) { if ( root == null ) { root = new RootLeafNode ( data ) ; try { root . addData ( data , 0 ) ; } catch ( SplitNodeReplacement e ) { throw new RuntimeException ( "Should never happen!" ) ; } } else { double distance = distanceFunction . calculate ( data , root . data ) ; try { root . addDat...
Adds and indexes a data object .
21,482
public boolean remove ( DATA data ) { if ( root == null ) { return false ; } double distanceToRoot = distanceFunction . calculate ( data , root . data ) ; try { root . removeData ( data , distanceToRoot ) ; } catch ( RootNodeReplacement e ) { @ SuppressWarnings ( "unchecked" ) Node newRoot = ( Node ) e . newRoot ; root...
Removes a data object from the M - Tree .
21,483
public Query getNearestByRange ( DATA queryData , double range ) { return getNearest ( queryData , range , Integer . MAX_VALUE ) ; }
Performs a nearest - neighbors query on the M - Tree constrained by distance .
21,484
public Query getNearestByLimit ( DATA queryData , int limit ) { return getNearest ( queryData , Double . POSITIVE_INFINITY , limit ) ; }
Performs a nearest - neighbors query on the M - Tree constrained by the number of neighbors .
21,485
public Query getNearest ( DATA queryData ) { return new Query ( queryData , Double . POSITIVE_INFINITY , Integer . MAX_VALUE ) ; }
Performs a nearest - neighbor query on the M - Tree without constraints .
21,486
private static double distance ( double [ ] pointA , double [ ] pointB ) { double distance = 0.0 ; for ( int i = 0 ; i < pointA . length ; i ++ ) { double d = pointA [ i ] - pointB [ i ] ; distance += d * d ; } return Math . sqrt ( distance ) ; }
Distance between two vectors .
21,487
protected static Clustering cleanUpKMeans ( Clustering kMeansResult , ArrayList < CFCluster > microclusters ) { int k = kMeansResult . size ( ) ; CFCluster [ ] converted = new CFCluster [ k ] ; for ( CFCluster mc : microclusters ) { double minDistance = Double . MAX_VALUE ; int closestCluster = 0 ; for ( int i = 0 ; i ...
Rearrange the k - means result into a set of CFClusters cleaning up the redundancies .
21,488
protected void clear ( ) { this . data . clear ( ) ; this . buffer . clear ( ) ; this . child = null ; this . timestamp = Entry . defaultTimestamp ; }
Clear the Entry . All points in the buffer and in the data cluster are lost the connection to the child is lost and the timestamp is set to the default value .
21,489
protected void makeOlder ( long currentTime , double negLambda ) { long diff = currentTime - this . timestamp ; this . buffer . makeOlder ( diff , negLambda ) ; this . data . makeOlder ( diff , negLambda ) ; this . timestamp = currentTime ; }
Ages this entrie s data AND buffer according to the given time and aging constant .
21,490
public void resetLearningImpl ( ) { this . windowSize = this . windowSizeOption . getValue ( ) ; this . numTrees = this . numTreesOption . getValue ( ) ; this . maxDepth = this . maxDepthOption . getValue ( ) ; this . sizeLimit = this . sizeLimitOption . getValue ( ) ; this . numInstances = 0 ; this . forest = new HSTr...
Reset the classifier s parameters and data structures .
21,491
public void trainOnInstanceImpl ( Instance inst ) { if ( this . numInstances == 0 ) { this . buildForest ( inst ) ; } for ( int i = 0 ; i < this . numTrees ; i ++ ) { forest [ i ] . updateMass ( inst , referenceWindow ) ; } if ( this . numInstances > 50 ) referenceWindow = false ; if ( this . numInstances % windowSize ...
Update the forest with the argument instance
21,492
private void buildForest ( Instance inst ) { this . dimensions = inst . numAttributes ( ) ; double [ ] max = new double [ dimensions ] ; double [ ] min = new double [ dimensions ] ; double sq ; for ( int i = 0 ; i < this . numTrees ; i ++ ) { for ( int j = 0 ; j < this . dimensions ; j ++ ) { sq = this . classifierRand...
Build the forest of Streaming Half - Space Trees
21,493
public double [ ] getVotesForInstance ( Instance inst ) { double [ ] votes = { 0.5 , 0.5 } ; if ( ! referenceWindow ) { votes [ 1 ] = this . getAnomalyScore ( inst ) + 0.5 - this . anomalyThreshold ; votes [ 0 ] = 1.0 - votes [ 1 ] ; } return votes ; }
Combine the anomaly scores from each HSTree in the forest and convert into a vote score .
21,494
public double getAnomalyScore ( Instance inst ) { if ( this . referenceWindow ) return 0.5 ; else { double accumulatedScore = 0.0 ; int massLimit = ( int ) ( Math . ceil ( this . sizeLimit * this . windowSize ) ) ; double maxScore = this . windowSize * Math . pow ( 2.0 , this . maxDepth ) ; for ( int i = 0 ; i < this ....
Returns the anomaly score for the argument instance .
21,495
public void initialize ( Collection < Instance > trainingPoints ) { Iterator < Instance > trgPtsIterator = trainingPoints . iterator ( ) ; if ( trgPtsIterator . hasNext ( ) && this . numInstances == 0 ) { Instance inst = trgPtsIterator . next ( ) ; this . buildForest ( inst ) ; this . trainOnInstance ( inst ) ; } while...
Initializes the Streaming HS - Trees classifier on the argument trainingPoints .
21,496
protected AttributeSplitSuggestion searchForBestSplitOption ( Node currentNode , AttributeSplitSuggestion currentBestOption , SplitCriterion criterion , int attIndex ) { if ( currentNode == null || countRightTotal == 0.0 ) { return currentBestOption ; } if ( currentNode . left != null ) { currentBestOption = searchForB...
Implementation of the FindBestSplit algorithm from E . Ikonomovska et al .
21,497
public void removeBadSplits ( SplitCriterion criterion , double lastCheckRatio , double lastCheckSDR , double lastCheckE ) { removeBadSplitNodes ( criterion , this . root , lastCheckRatio , lastCheckSDR , lastCheckE ) ; }
A method to remove all nodes in the E - BST in which it and all it s children represent bad split points
21,498
private boolean removeBadSplitNodes ( SplitCriterion criterion , Node currentNode , double lastCheckRatio , double lastCheckSDR , double lastCheckE ) { boolean isBad = false ; if ( currentNode == null ) { return true ; } if ( currentNode . left != null ) { isBad = removeBadSplitNodes ( criterion , currentNode . left , ...
Recursive method that first checks all of a node s children before deciding if it is bad and may be removed
21,499
public void resetLearningImpl ( ) { this . nbhdSize = this . neighbourhoodSizeOption . getValue ( ) ; this . tau = this . thresholdOption . getValue ( ) ; this . neighbourhood = new FixedLengthList < Instance > ( nbhdSize ) ; }
Resets the implementation s parameters and data structures .