idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
10,900
private void swap ( int i , int j ) { int t = pq [ i ] ; pq [ i ] = pq [ j ] ; pq [ j ] = t ; qp [ pq [ i ] ] = i ; qp [ pq [ j ] ] = j ; }
Swap i and j items of pq and qp .
10,901
private void swim ( int k ) { while ( k > 1 && less ( k , ( k + d - 2 ) / d ) ) { swap ( k , ( k + d - 2 ) / d ) ; k = ( k + d - 2 ) / d ; } }
fix up .
10,902
private void sink ( int k , int N ) { int j ; while ( ( j = d * ( k - 1 ) + 2 ) <= N ) { for ( int i = j + 1 ; i < j + d && i <= N ; i ++ ) { if ( less ( i , j ) ) { j = i ; } } if ( ! ( less ( j , k ) ) ) { break ; } swap ( k , j ) ; k = j ; } }
fix down .
10,903
public void insert ( int v ) { pq [ ++ n ] = v ; qp [ v ] = n ; swim ( n ) ; }
Insert a new item into queue .
10,904
public static double inverfc ( double p ) { double x , err , t , pp ; if ( p >= 2.0 ) { return - 100. ; } if ( p <= 0.0 ) { return 100. ; } pp = ( p < 1.0 ) ? p : 2. - p ; t = Math . sqrt ( - 2. * Math . log ( pp / 2. ) ) ; x = - 0.70711 * ( ( 2.30753 + t * 0.27061 ) / ( 1. + t * ( 0.99229 + t * 0.04481 ) ) - t ) ; for ( int j = 0 ; j < 2 ; j ++ ) { err = erfc ( x ) - pp ; x += err / ( 1.12837916709551257 * Math . exp ( - x * x ) - x * err ) ; } return ( p < 1.0 ? x : - x ) ; }
The inverse complementary error function .
10,905
public static double digamma ( double x ) { final double C7 [ ] [ ] = { { 1.3524999667726346383e4 , 4.5285601699547289655e4 , 4.5135168469736662555e4 , 1.8529011818582610168e4 , 3.3291525149406935532e3 , 2.4068032474357201831e2 , 5.1577892000139084710 , 6.2283506918984745826e-3 } , { 6.9389111753763444376e-7 , 1.9768574263046736421e4 , 4.1255160835353832333e4 , 2.9390287119932681918e4 , 9.0819666074855170271e3 , 1.2447477785670856039e3 , 6.7429129516378593773e1 , 1.0 } } ; final double C4 [ ] [ ] = { { - 2.728175751315296783e-15 , - 6.481571237661965099e-1 , - 4.486165439180193579 , - 7.016772277667586642 , - 2.129404451310105168 } , { 7.777885485229616042 , 5.461177381032150702e1 , 8.929207004818613702e1 , 3.227034937911433614e1 , 1.0 } } ; double prodPj = 0.0 ; double prodQj = 0.0 ; double digX = 0.0 ; if ( x >= 3.0 ) { double x2 = 1.0 / ( x * x ) ; for ( int j = 4 ; j >= 0 ; j -- ) { prodPj = prodPj * x2 + C4 [ 0 ] [ j ] ; prodQj = prodQj * x2 + C4 [ 1 ] [ j ] ; } digX = Math . log ( x ) - ( 0.5 / x ) + ( prodPj / prodQj ) ; } else if ( x >= 0.5 ) { final double X0 = 1.46163214496836234126 ; for ( int j = 7 ; j >= 0 ; j -- ) { prodPj = x * prodPj + C7 [ 0 ] [ j ] ; prodQj = x * prodQj + C7 [ 1 ] [ j ] ; } digX = ( x - X0 ) * ( prodPj / prodQj ) ; } else { double f = ( 1.0 - x ) - Math . floor ( 1.0 - x ) ; digX = digamma ( 1.0 - x ) + Math . PI / Math . tan ( Math . PI * f ) ; } return digX ; }
The digamma function is defined as the logarithmic derivative of the gamma function .
10,906
public static double inverseRegularizedIncompleteGamma ( double a , double p ) { if ( a <= 0.0 ) { throw new IllegalArgumentException ( "a must be pos in invgammap" ) ; } final double EPS = 1.0E-8 ; double x , err , t , u , pp ; double lna1 = 0.0 ; double afac = 0.0 ; double a1 = a - 1 ; double gln = lgamma ( a ) ; if ( p >= 1. ) { return Math . max ( 100. , a + 100. * Math . sqrt ( a ) ) ; } if ( p <= 0.0 ) { return 0.0 ; } if ( a > 1.0 ) { lna1 = Math . log ( a1 ) ; afac = Math . exp ( a1 * ( lna1 - 1. ) - gln ) ; pp = ( p < 0.5 ) ? p : 1. - p ; t = Math . sqrt ( - 2. * Math . log ( pp ) ) ; x = ( 2.30753 + t * 0.27061 ) / ( 1. + t * ( 0.99229 + t * 0.04481 ) ) - t ; if ( p < 0.5 ) { x = - x ; } x = Math . max ( 1.e-3 , a * Math . pow ( 1. - 1. / ( 9. * a ) - x / ( 3. * Math . sqrt ( a ) ) , 3 ) ) ; } else { t = 1.0 - a * ( 0.253 + a * 0.12 ) ; if ( p < t ) { x = Math . pow ( p / t , 1. / a ) ; } else { x = 1. - Math . log ( 1. - ( p - t ) / ( 1. - t ) ) ; } } for ( int j = 0 ; j < 12 ; j ++ ) { if ( x <= 0.0 ) { return 0.0 ; } err = regularizedIncompleteGamma ( a , x ) - p ; if ( a > 1. ) { t = afac * Math . exp ( - ( x - a1 ) + a1 * ( Math . log ( x ) - lna1 ) ) ; } else { t = Math . exp ( - x + a1 * Math . log ( x ) - gln ) ; } u = err / t ; x -= ( t = u / ( 1. - 0.5 * Math . min ( 1. , u * ( ( a - 1. ) / x - 1 ) ) ) ) ; if ( x <= 0. ) { x = 0.5 * ( x + t ) ; } if ( Math . abs ( t ) < EPS * x ) { break ; } } return x ; }
The inverse of regularized incomplete gamma function .
10,907
private void findNeighbor ( int p ) { if ( npoints == 1 ) { neighbor [ p ] = p ; distance [ p ] = Float . MAX_VALUE ; return ; } int first = 0 ; if ( p == points [ first ] ) { first = 1 ; } neighbor [ p ] = points [ first ] ; distance [ p ] = linkage . d ( p , neighbor [ p ] ) ; for ( int i = first + 1 ; i < npoints ; i ++ ) { int q = points [ i ] ; if ( q != p ) { float d = linkage . d ( p , q ) ; if ( d < distance [ p ] ) { distance [ p ] = d ; neighbor [ p ] = q ; } } } }
Find nearest neighbor of a given point .
10,908
public void remove ( int p ) { npoints -- ; int q = index [ p ] ; index [ points [ q ] = points [ npoints ] ] = q ; for ( int i = 0 ; i < npoints ; i ++ ) { if ( neighbor [ points [ i ] ] == p ) { findNeighbor ( points [ i ] ) ; } } }
Remove a point and update neighbors of points for which it had been nearest
10,909
public double getNearestPair ( int [ ] pair ) { if ( npoints < 2 ) { throw new IllegalStateException ( "FastPair: not enough points to form pair" ) ; } double d = distance [ points [ 0 ] ] ; int r = 0 ; for ( int i = 1 ; i < npoints ; i ++ ) { if ( distance [ points [ i ] ] < d ) { d = distance [ points [ i ] ] ; r = i ; } } pair [ 0 ] = points [ r ] ; pair [ 1 ] = neighbor [ pair [ 0 ] ] ; if ( pair [ 0 ] > pair [ 1 ] ) { int t = pair [ 0 ] ; pair [ 0 ] = pair [ 1 ] ; pair [ 1 ] = t ; } return d ; }
Find closest pair by scanning list of nearest neighbors
10,910
public void updatePoint ( int p ) { neighbor [ p ] = p ; distance [ p ] = Float . MAX_VALUE ; for ( int i = 0 ; i < npoints ; i ++ ) { int q = points [ i ] ; if ( q != p ) { float d = linkage . d ( p , q ) ; if ( d < distance [ p ] ) { distance [ p ] = d ; neighbor [ p ] = q ; } if ( neighbor [ q ] == p ) { if ( d > distance [ q ] ) { findNeighbor ( q ) ; } else { distance [ q ] = d ; } } } } }
All distances to point have changed check if our structures are ok Note that although we completely recompute the neighbors of p we don t explicitly call findNeighbor since that would double the number of distance computations made by this routine . Also like deletion we don t change any other point s neighbor to p .
10,911
public void updateDistance ( int p , int q ) { float d = linkage . d ( p , q ) ; if ( d < distance [ p ] ) { distance [ p ] = q ; neighbor [ p ] = q ; } else if ( neighbor [ p ] == q && d > distance [ p ] ) { findNeighbor ( p ) ; } if ( d < distance [ q ] ) { distance [ q ] = p ; neighbor [ q ] = p ; } else if ( neighbor [ q ] == p && d > distance [ q ] ) { findNeighbor ( q ) ; } }
Single distance has changed check if our structures are ok .
10,912
private static void softmax ( double [ ] prob ) { double max = Double . NEGATIVE_INFINITY ; for ( int i = 0 ; i < prob . length ; i ++ ) { if ( prob [ i ] > max ) { max = prob [ i ] ; } } double Z = 0.0 ; for ( int i = 0 ; i < prob . length ; i ++ ) { double p = Math . exp ( prob [ i ] - max ) ; prob [ i ] = p ; Z += p ; } for ( int i = 0 ; i < prob . length ; i ++ ) { prob [ i ] /= Z ; } }
Calculate softmax function without overflow .
10,913
private boolean isIntersect ( double z0 , double z1 , double zc ) { if ( ( z0 - zc ) * ( z1 - zc ) < 0.0 ) { return true ; } return false ; }
Returns true if zc is between z0 and z1 .
10,914
private int segdir ( double xend , double yend , int [ ] ij ) { if ( YMATCH ( yend , y [ ij [ 1 ] ] ) ) { if ( ij [ 1 ] == 0 ) { return 0 ; } ij [ 1 ] -= 1 ; return 3 ; } if ( XMATCH ( xend , x [ ij [ 0 ] ] ) ) { if ( ij [ 0 ] == 0 ) { return 0 ; } ij [ 0 ] -= 1 ; return 4 ; } if ( YMATCH ( yend , y [ ij [ 1 ] + 1 ] ) ) { if ( ij [ 1 ] >= y . length - 1 ) { return 0 ; } ij [ 1 ] += 1 ; return 1 ; } if ( XMATCH ( xend , x [ ij [ 0 ] + 1 ] ) ) { if ( ij [ 0 ] >= x . length - 1 ) { return 0 ; } ij [ 0 ] += 1 ; return 2 ; } return 0 ; }
Determine the entry direction to the next cell and update the cell indices .
10,915
private static int [ ] freq ( int [ ] [ ] itemsets ) { int [ ] f = new int [ Math . max ( itemsets ) + 1 ] ; for ( int [ ] itemset : itemsets ) { for ( int i : itemset ) { f [ i ] ++ ; } } return f ; }
Returns the frequency of single items .
10,916
public void add ( int [ ] itemset ) { numTransactions ++ ; int m = 0 ; int t = itemset . length ; int [ ] o = new int [ t ] ; for ( int i = 0 ; i < t ; i ++ ) { int item = itemset [ i ] ; o [ i ] = order [ item ] ; if ( itemSupport [ item ] >= minSupport ) { m ++ ; } } if ( m > 0 ) { QuickSort . sort ( o , itemset , t ) ; for ( int i = 1 ; i < m ; i ++ ) { if ( itemset [ i ] == itemset [ i - 1 ] ) { m -- ; for ( int j = i ; j < m ; j ++ ) { itemset [ j ] = itemset [ j + 1 ] ; } } } root . add ( 0 , m , itemset , 1 ) ; } }
Add an item set into the FP - tree .
10,917
public void add ( int index , int end , int [ ] itemset , int support ) { root . add ( index , end , itemset , support ) ; }
Add an item set into the FP - tree . The items in the set is already in the descending order of frequency .
10,918
public double d ( T [ ] x , T [ ] y ) { if ( x . length != y . length ) throw new IllegalArgumentException ( String . format ( "Arrays have different length: x[%d], y[%d]" , x . length , y . length ) ) ; int dist = 0 ; for ( int i = 0 ; i < x . length ; i ++ ) { if ( ! x [ i ] . equals ( y [ i ] ) ) dist ++ ; } return dist ; }
Returns Hamming distance between the two arrays .
10,919
public static int d ( int x , int y ) { int dist = 0 ; int val = x ^ y ; while ( val != 0 ) { ++ dist ; val &= val - 1 ; } return dist ; }
Returns Hamming distance between the two integers .
10,920
public static int d ( BitSet x , BitSet y ) { if ( x . size ( ) != y . size ( ) ) throw new IllegalArgumentException ( String . format ( "BitSets have different length: x[%d], y[%d]" , x . size ( ) , y . size ( ) ) ) ; int dist = 0 ; for ( int i = 0 ; i < x . size ( ) ; i ++ ) { if ( x . get ( i ) != y . get ( i ) ) dist ++ ; } return dist ; }
Returns Hamming distance between the two BitSets .
10,921
void initBaseCoord ( ) { baseCoords = new double [ dimension + 1 ] [ ] ; for ( int i = 0 ; i < baseCoords . length ; i ++ ) { baseCoords [ i ] = lowerBound . clone ( ) ; if ( i > 0 ) { baseCoords [ i ] [ i - 1 ] = upperBound [ i - 1 ] ; } } }
Reset coord .
10,922
void setPrecisionUnit ( int i ) { if ( upperBound [ i ] > lowerBound [ i ] ) { double digits = Math . log10 ( Math . abs ( upperBound [ i ] - lowerBound [ i ] ) ) ; double residual = digits - Math . floor ( digits ) ; if ( residual < 0.2 ) { digits -= 1.0 ; } precisionDigits [ i ] = ( int ) Math . floor ( digits ) ; precisionUnit [ i ] = Math . pow ( 10 , precisionDigits [ i ] ) ; if ( residual >= 0.2 && residual <= 0.7 ) { precisionUnit [ i ] /= 2 ; precisionDigits [ i ] -= 1 ; } } else { precisionUnit [ i ] = 0.1 ; } }
Set the precision unit for axis i .
10,923
public void extendBound ( int i ) { if ( i < 0 || i >= dimension ) { throw new IllegalArgumentException ( "Invalid bound index: " + i ) ; } extendBound [ i ] = true ; lowerBound [ i ] = precisionUnit [ i ] * ( Math . floor ( originalLowerBound [ i ] / precisionUnit [ i ] ) ) ; upperBound [ i ] = precisionUnit [ i ] * ( Math . ceil ( originalUpperBound [ i ] / precisionUnit [ i ] ) ) ; }
Round the bounds for axis i .
10,924
public void extendLowerBound ( double [ ] bound ) { if ( bound . length != dimension ) { throw new IllegalArgumentException ( BOUND_SIZE_DON_T_MATCH_THE_DIMENSION ) ; } boolean extend = false ; for ( int i = 0 ; i < bound . length ; i ++ ) { if ( bound [ i ] < originalLowerBound [ i ] ) { originalLowerBound [ i ] = bound [ i ] ; extend = true ; } } if ( extend ) { reset ( ) ; } }
Extend lower bounds .
10,925
public void extendUpperBound ( double [ ] bound ) { if ( bound . length != dimension ) { throw new IllegalArgumentException ( BOUND_SIZE_DON_T_MATCH_THE_DIMENSION ) ; } boolean extend = false ; for ( int i = 0 ; i < bound . length ; i ++ ) { if ( bound [ i ] > originalUpperBound [ i ] ) { originalUpperBound [ i ] = bound [ i ] ; extend = true ; } } if ( extend ) { reset ( ) ; } }
Extend upper bounds .
10,926
private double getRandomNeighbor ( T [ ] data , T [ ] medoids , int [ ] y , double [ ] d ) { int n = data . length ; int index = Math . randomInt ( k ) ; T medoid = null ; boolean dup ; do { dup = false ; medoid = data [ Math . randomInt ( n ) ] ; for ( int i = 0 ; i < k ; i ++ ) { if ( medoid == medoids [ i ] ) { dup = true ; break ; } } } while ( dup ) ; medoids [ index ] = medoid ; for ( int i = 0 ; i < n ; i ++ ) { double dist = distance . d ( data [ i ] , medoid ) ; if ( d [ i ] > dist ) { y [ i ] = index ; d [ i ] = dist ; } else if ( y [ i ] == index ) { d [ i ] = dist ; y [ i ] = index ; for ( int j = 0 ; j < k ; j ++ ) { if ( j != index ) { dist = distance . d ( data [ i ] , medoids [ j ] ) ; if ( d [ i ] > dist ) { y [ i ] = j ; d [ i ] = dist ; } } } } } return Math . sum ( d ) ; }
Generate a random neighbor which differs in only one medoid with current clusters .
10,927
private void init ( ) { quantiles = new double [ data . length ] [ 8 ] ; for ( int i = 0 ; i < data . length ; i ++ ) { int n = data [ i ] . length ; Arrays . sort ( data [ i ] ) ; quantiles [ i ] [ 1 ] = data [ i ] [ n / 4 ] ; quantiles [ i ] [ 2 ] = data [ i ] [ n / 2 ] ; quantiles [ i ] [ 3 ] = data [ i ] [ 3 * n / 4 ] ; quantiles [ i ] [ 5 ] = quantiles [ i ] [ 3 ] - quantiles [ i ] [ 1 ] ; quantiles [ i ] [ 6 ] = quantiles [ i ] [ 1 ] - 1.5 * quantiles [ i ] [ 5 ] ; quantiles [ i ] [ 7 ] = quantiles [ i ] [ 3 ] + 1.5 * quantiles [ i ] [ 5 ] ; quantiles [ i ] [ 0 ] = quantiles [ i ] [ 6 ] < data [ i ] [ 0 ] ? data [ i ] [ 0 ] : quantiles [ i ] [ 6 ] ; quantiles [ i ] [ 4 ] = quantiles [ i ] [ 7 ] > data [ i ] [ data [ i ] . length - 1 ] ? data [ i ] [ data [ i ] . length - 1 ] : quantiles [ i ] [ 7 ] ; } }
Calculate quantiles .
10,928
public static PlotCanvas plot ( double [ ] data ) { double [ ] lowerBound = { 0 , Math . min ( data ) } ; double [ ] upperBound = { 1 , Math . max ( data ) } ; PlotCanvas canvas = new PlotCanvas ( lowerBound , upperBound ) ; canvas . add ( new BoxPlot ( data ) ) ; canvas . getAxis ( 0 ) . setGridVisible ( false ) ; canvas . getAxis ( 0 ) . setLabelVisible ( false ) ; return canvas ; }
Create a plot canvas with the box plot of given data .
10,929
public static PlotCanvas plot ( double [ ] [ ] data , String [ ] labels ) { if ( data . length != labels . length ) { throw new IllegalArgumentException ( "Data size and label size don't match." ) ; } double [ ] lowerBound = { 0 , Math . min ( data ) } ; double [ ] upperBound = { data . length , Math . max ( data ) } ; PlotCanvas canvas = new PlotCanvas ( lowerBound , upperBound ) ; canvas . add ( new BoxPlot ( labels , data ) ) ; double [ ] locations = new double [ labels . length ] ; for ( int i = 0 ; i < labels . length ; i ++ ) { locations [ i ] = i + 0.5 ; } canvas . getAxis ( 0 ) . addLabel ( labels , locations ) ; canvas . getAxis ( 0 ) . setGridVisible ( false ) ; if ( labels . length > 10 ) { canvas . getAxis ( 0 ) . setRotation ( - Math . PI / 2 ) ; } return canvas ; }
Create a plot canvas with multiple box plots of given data .
10,930
public double [ ] transform ( double [ ] x ) { if ( x . length != scale . length ) { throw new IllegalArgumentException ( String . format ( "Invalid vector size %d, expected %d" , x . length , scale . length ) ) ; } double [ ] y = copy ? new double [ x . length ] : x ; for ( int i = 0 ; i < x . length ; i ++ ) { y [ i ] = x [ i ] / scale [ i ] ; } return y ; }
Scales each feature by its maximum absolute value .
10,931
private double impurity ( int [ ] count , int n ) { double impurity = 0.0 ; switch ( rule ) { case GINI : impurity = 1.0 ; for ( int i = 0 ; i < count . length ; i ++ ) { if ( count [ i ] > 0 ) { double p = ( double ) count [ i ] / n ; impurity -= p * p ; } } break ; case ENTROPY : for ( int i = 0 ; i < count . length ; i ++ ) { if ( count [ i ] > 0 ) { double p = ( double ) count [ i ] / n ; impurity -= p * Math . log2 ( p ) ; } } break ; case CLASSIFICATION_ERROR : impurity = 0 ; for ( int i = 0 ; i < count . length ; i ++ ) { if ( count [ i ] > 0 ) { impurity = Math . max ( impurity , count [ i ] / ( double ) n ) ; } } impurity = Math . abs ( 1 - impurity ) ; break ; } return impurity ; }
Returns the impurity of a node .
10,932
public GeneticAlgorithm < T > setTournament ( int size , double p ) { if ( size < 1 ) { throw new IllegalArgumentException ( "Invalid tournament size: " + size ) ; } if ( p < 0.5 || p > 1.0 ) { throw new IllegalArgumentException ( "Invalid best-player-wins probability: " + p ) ; } tournamentSize = size ; tournamentProbability = p ; return this ; }
Set the tournament size and the best - player - wins probability in tournament selection .
10,933
public T evolve ( int generation , double threshold ) { if ( generation <= 0 ) { throw new IllegalArgumentException ( "Invalid number of generations to go: " + generation ) ; } try { MulticoreExecutor . run ( tasks ) ; } catch ( Exception ex ) { logger . error ( "Failed to run Genetic Algorithm on multi-core" , ex ) ; for ( Task task : tasks ) { task . call ( ) ; } } Arrays . sort ( population ) ; T best = population [ size - 1 ] ; Chromosome [ ] offsprings = new Chromosome [ size ] ; for ( int g = 1 ; g <= generation && best . fitness ( ) < threshold ; g ++ ) { for ( int i = 0 ; i < elitism ; i ++ ) { offsprings [ i ] = population [ size - i - 1 ] ; } for ( int i = elitism ; i < size ; i += 2 ) { T father = select ( population ) ; T mother = select ( population ) ; while ( mother == father ) { mother = select ( population ) ; } Chromosome [ ] children = father . crossover ( mother ) ; offsprings [ i ] = children [ 0 ] ; offsprings [ i ] . mutate ( ) ; if ( i + 1 < size ) { offsprings [ i + 1 ] = children [ 1 ] ; offsprings [ i + 1 ] . mutate ( ) ; } } System . arraycopy ( offsprings , 0 , population , 0 , size ) ; try { MulticoreExecutor . run ( tasks ) ; } catch ( Exception ex ) { logger . error ( "Failed to run Genetic Algorithm on multi-core" , ex ) ; for ( Task task : tasks ) { task . call ( ) ; } } Arrays . sort ( population ) ; best = population [ size - 1 ] ; double avg = 0.0 ; for ( Chromosome ch : population ) { avg += ch . fitness ( ) ; } avg /= size ; logger . info ( String . format ( "Genetic Algorithm: generation %d, best fitness %g, average fitness %g" , g , best . fitness ( ) , avg ) ) ; } return best ; }
Performs genetic algorithm until the given number of generations is reached or the best fitness is larger than the given threshold .
10,934
@ SuppressWarnings ( "unchecked" ) private T select ( T [ ] population ) { double worst = population [ 0 ] . fitness ( ) ; double [ ] fitness = new double [ size ] ; switch ( selection ) { case ROULETTE_WHEEL : if ( worst > 0.0 ) { worst = 0.0 ; } for ( int i = 0 ; i < size ; i ++ ) { fitness [ i ] = population [ i ] . fitness ( ) - worst ; } Math . unitize1 ( fitness ) ; return population [ Math . random ( fitness ) ] ; case SCALED_ROULETTE_WHEEL : for ( int i = 0 ; i < size ; i ++ ) { fitness [ i ] = population [ i ] . fitness ( ) - worst ; } Math . unitize1 ( fitness ) ; return population [ Math . random ( fitness ) ] ; case RANK : for ( int i = 0 ; i < size ; i ++ ) { fitness [ i ] = i + 1 ; } Math . unitize1 ( fitness ) ; return population [ Math . random ( fitness ) ] ; case TOURNAMENT : Chromosome [ ] pool = new Chromosome [ tournamentSize ] ; for ( int i = 0 ; i < tournamentSize ; i ++ ) { pool [ i ] = population [ Math . randomInt ( size ) ] ; } Arrays . sort ( pool ) ; for ( int i = 1 ; i <= tournamentSize ; i ++ ) { double p = Math . random ( ) ; if ( p < tournamentProbability ) { return ( T ) pool [ tournamentSize - i ] ; } } return ( T ) pool [ tournamentSize - 1 ] ; } return null ; }
Select a chromosome with replacement from the population based on their fitness . Note that the population should be in ascending order in terms of fitness .
10,935
public double logp ( int [ ] o , int [ ] s ) { if ( o . length != s . length ) { throw new IllegalArgumentException ( "The observation sequence and state sequence are not the same length." ) ; } int n = s . length ; double p = log ( pi [ s [ 0 ] ] ) + log ( b [ s [ 0 ] ] [ o [ 0 ] ] ) ; for ( int i = 1 ; i < n ; i ++ ) { p += log ( a [ s [ i - 1 ] ] [ s [ i ] ] ) + log ( b [ s [ i ] ] [ o [ i ] ] ) ; } return p ; }
Returns the log joint probability of an observation sequence along a state sequence given this HMM .
10,936
public double logp ( int [ ] o ) { double [ ] [ ] alpha = new double [ o . length ] [ numStates ] ; double [ ] scaling = new double [ o . length ] ; forward ( o , alpha , scaling ) ; double p = 0.0 ; for ( int t = 0 ; t < o . length ; t ++ ) { p += java . lang . Math . log ( scaling [ t ] ) ; } return p ; }
Returns the logarithm probability of an observation sequence given this HMM . A scaling procedure is used in order to avoid underflows when computing the probability of long sequences .
10,937
private void forward ( int [ ] o , double [ ] [ ] alpha , double [ ] scaling ) { for ( int k = 0 ; k < numStates ; k ++ ) { alpha [ 0 ] [ k ] = pi [ k ] * b [ k ] [ o [ 0 ] ] ; } scale ( scaling , alpha , 0 ) ; for ( int t = 1 ; t < o . length ; t ++ ) { for ( int k = 0 ; k < numStates ; k ++ ) { double sum = 0.0 ; for ( int i = 0 ; i < numStates ; i ++ ) { sum += alpha [ t - 1 ] [ i ] * a [ i ] [ k ] ; } alpha [ t ] [ k ] = sum * b [ k ] [ o [ t ] ] ; } scale ( scaling , alpha , t ) ; } }
Scaled forward procedure without underflow .
10,938
private void backward ( int [ ] o , double [ ] [ ] beta , double [ ] scaling ) { int n = o . length - 1 ; for ( int i = 0 ; i < numStates ; i ++ ) { beta [ n ] [ i ] = 1.0 / scaling [ n ] ; } for ( int t = n ; t -- > 0 ; ) { for ( int i = 0 ; i < numStates ; i ++ ) { double sum = 0. ; for ( int j = 0 ; j < numStates ( ) ; j ++ ) { sum += beta [ t + 1 ] [ j ] * a [ i ] [ j ] * b [ j ] [ o [ t + 1 ] ] ; } beta [ t ] [ i ] = sum / scaling [ t ] ; } } }
Scaled backward procedure without underflow .
10,939
public void addKeyword ( String keyword ) { if ( taxonomy . concepts . containsKey ( keyword ) ) { throw new IllegalArgumentException ( String . format ( "Concept %s already exists." , keyword ) ) ; } taxonomy . concepts . put ( keyword , this ) ; if ( synset == null ) { synset = new TreeSet < > ( ) ; } synset . add ( keyword ) ; }
Add a keyword to the concept synset .
10,940
public void addKeywords ( String [ ] keywords ) { for ( String keyword : keywords ) { if ( taxonomy . concepts . containsKey ( keyword ) ) { throw new IllegalArgumentException ( String . format ( "Concept %s already exists." , keyword ) ) ; } } for ( String keyword : keywords ) { taxonomy . concepts . put ( keyword , this ) ; } if ( synset == null ) { synset = new TreeSet < > ( ) ; } for ( String keyword : keywords ) { synset . add ( keyword ) ; } }
Add a list of synomym to the concept synset .
10,941
public void removeKeyword ( String keyword ) { if ( ! taxonomy . concepts . containsKey ( keyword ) ) { throw new IllegalArgumentException ( String . format ( "Concept %s does not exist." , keyword ) ) ; } taxonomy . concepts . remove ( keyword ) ; if ( synset != null ) { synset . remove ( keyword ) ; } }
Remove a keyword from the concept synset .
10,942
public void addChild ( Concept concept ) { if ( taxonomy != concept . taxonomy ) { throw new IllegalArgumentException ( "Concepts are not from the same taxonomy." ) ; } if ( children == null ) { children = new ArrayList < > ( ) ; } children . add ( concept ) ; concept . parent = this ; }
Add a child to this node
10,943
public boolean removeChild ( Concept concept ) { if ( concept . parent != this ) { throw new IllegalArgumentException ( "Concept to remove is not a child" ) ; } for ( int i = 0 ; i < children . size ( ) ; i ++ ) { if ( children . get ( i ) == concept ) { children . remove ( i ) ; concept . parent = null ; return true ; } } return false ; }
Remove a child to this node
10,944
public boolean isAncestorOf ( Concept concept ) { Concept p = concept . parent ; while ( p != null ) { if ( p == this ) { return true ; } else { p = p . parent ; } } return false ; }
Returns true if this concept is an ancestor of the given concept .
10,945
public List < Concept > getPathFromRoot ( ) { LinkedList < Concept > path = new LinkedList < > ( ) ; Concept node = this ; while ( node != null ) { path . addFirst ( node ) ; node = node . parent ; } return path ; }
Returns the path from root to the given node .
10,946
public List < Concept > getPathToRoot ( ) { LinkedList < Concept > path = new LinkedList < > ( ) ; Concept node = this ; while ( node != null ) { path . add ( node ) ; node = node . parent ; } return path ; }
Returns the path from the given node to the root .
10,947
public double [ ] featureset ( double [ ] features , int label ) { double [ ] fs = new double [ features . length + 1 ] ; System . arraycopy ( features , 0 , fs , 0 , features . length ) ; fs [ features . length ] = label ; return fs ; }
Returns a feature set with the class label of previous position .
10,948
private int [ ] predictForwardBackward ( int [ ] [ ] x ) { int n = x . length ; TrellisNode [ ] [ ] trellis = getTrellis ( x ) ; double [ ] scaling = new double [ n ] ; forward ( trellis , scaling ) ; backward ( trellis ) ; int [ ] label = new int [ n ] ; double [ ] p = new double [ numClasses ] ; for ( int i = 0 ; i < n ; i ++ ) { TrellisNode [ ] ti = trellis [ i ] ; for ( int j = 0 ; j < numClasses ; j ++ ) { TrellisNode tij = ti [ j ] ; p [ j ] = tij . alpha * tij . beta ; } double max = Double . NEGATIVE_INFINITY ; for ( int j = 0 ; j < numClasses ; j ++ ) { if ( max < p [ j ] ) { max = p [ j ] ; label [ i ] = j ; } } } return label ; }
Returns the most likely label sequence given the feature sequence by the forward - backward algorithm .
10,949
private int [ ] predictViterbi ( int [ ] [ ] x ) { int n = x . length ; double [ ] [ ] trellis = new double [ n ] [ numClasses ] ; int [ ] [ ] psy = new int [ n ] [ numClasses ] ; int p = x [ 0 ] . length ; double [ ] t0 = trellis [ 0 ] ; int [ ] p0 = psy [ 0 ] ; int [ ] features = featureset ( x [ 0 ] , numClasses ) ; for ( int j = 0 ; j < numClasses ; j ++ ) { t0 [ j ] = potentials [ j ] . f ( features ) ; p0 [ j ] = 0 ; } for ( int t = 1 ; t < n ; t ++ ) { System . arraycopy ( x [ t ] , 0 , features , 0 , p ) ; double [ ] tt = trellis [ t ] ; double [ ] tt1 = trellis [ t - 1 ] ; int [ ] pt = psy [ t ] ; for ( int i = 0 ; i < numClasses ; i ++ ) { double max = Double . NEGATIVE_INFINITY ; int maxPsy = 0 ; for ( int j = 0 ; j < numClasses ; j ++ ) { features [ p ] = numFeatures + j ; double delta = potentials [ i ] . f ( features ) + tt1 [ j ] ; if ( max < delta ) { max = delta ; maxPsy = j ; } } tt [ i ] = max ; pt [ i ] = maxPsy ; } } int [ ] label = new int [ n ] ; double [ ] tn1 = trellis [ n - 1 ] ; double max = Double . NEGATIVE_INFINITY ; for ( int i = 0 ; i < numClasses ; i ++ ) { if ( max < tn1 [ i ] ) { max = tn1 [ i ] ; label [ n - 1 ] = i ; } } for ( int t = n - 1 ; t -- > 0 ; ) { label [ t ] = psy [ t + 1 ] [ label [ t + 1 ] ] ; } return label ; }
Returns the most likely label sequence given the feature sequence by the Viterbi algorithm .
10,950
private void backward ( TrellisNode [ ] [ ] trellis ) { int n = trellis . length - 1 ; TrellisNode [ ] tn = trellis [ n ] ; for ( int i = 0 ; i < numClasses ; i ++ ) { tn [ i ] . beta = 1.0 ; } for ( int t = n ; t -- > 0 ; ) { TrellisNode [ ] tt = trellis [ t ] ; TrellisNode [ ] tt1 = trellis [ t + 1 ] ; for ( int i = 0 ; i < numClasses ; i ++ ) { TrellisNode tti = tt [ i ] ; tti . beta = 0.0 ; for ( int j = 0 ; j < numClasses ; j ++ ) { tti . beta += tt1 [ j ] . expScores [ i ] * tt1 [ j ] . beta ; } } double sum = 0.0 ; for ( int i = 0 ; i < numClasses ; i ++ ) { sum += tt [ i ] . beta ; } for ( int i = 0 ; i < numClasses ; i ++ ) { tt [ i ] . beta /= sum ; } } }
Performs backward procedure on the trellis .
10,951
private void setTargets ( TrellisNode [ ] [ ] trellis , double [ ] scaling , int [ ] label ) { TrellisNode [ ] t0 = trellis [ 0 ] ; double normalizer = 0.0 ; for ( int i = 0 ; i < numClasses ; i ++ ) { normalizer += t0 [ i ] . expScores [ 0 ] * t0 [ i ] . beta ; } for ( int i = 0 ; i < numClasses ; i ++ ) { if ( label [ 0 ] == i ) { t0 [ i ] . target [ 0 ] = 1 - t0 [ i ] . expScores [ 0 ] * t0 [ i ] . beta / normalizer ; } else { t0 [ i ] . target [ 0 ] = - t0 [ i ] . expScores [ 0 ] * t0 [ i ] . beta / normalizer ; } } for ( int t = 1 ; t < label . length ; t ++ ) { normalizer = 0.0 ; TrellisNode [ ] tt = trellis [ t ] ; TrellisNode [ ] tt1 = trellis [ t - 1 ] ; for ( int i = 0 ; i < numClasses ; i ++ ) { normalizer += tt [ i ] . alpha * tt [ i ] . beta ; } normalizer *= scaling [ t ] ; for ( int i = 0 ; i < numClasses ; i ++ ) { TrellisNode tti = tt [ i ] ; for ( int j = 0 ; j < numClasses ; j ++ ) { if ( label [ t ] == i && label [ t - 1 ] == j ) { tti . target [ j ] = 1 - tti . expScores [ j ] * tt1 [ j ] . alpha * tti . beta / normalizer ; } else { tti . target [ j ] = - tti . expScores [ j ] * tt1 [ j ] . alpha * tti . beta / normalizer ; } } } } }
Set training targets based on results of forward - backward
10,952
public int [ ] partition ( int k ) { int n = merge . length + 1 ; int [ ] membership = new int [ n ] ; IntHeapSelect heap = new IntHeapSelect ( k ) ; for ( int i = 2 ; i <= k ; i ++ ) { heap . add ( merge [ n - i ] [ 0 ] ) ; heap . add ( merge [ n - i ] [ 1 ] ) ; } for ( int i = 0 ; i < k ; i ++ ) { bfs ( membership , heap . get ( i ) , i ) ; } return membership ; }
Cuts a tree into several groups by specifying the desired number .
10,953
public int [ ] partition ( double h ) { for ( int i = 0 ; i < height . length - 1 ; i ++ ) { if ( height [ i ] > height [ i + 1 ] ) { throw new IllegalStateException ( "Non-monotonic cluster tree -- the linkage is probably not appropriate!" ) ; } } int n = merge . length + 1 ; int k = 2 ; for ( ; k <= n ; k ++ ) { if ( height [ n - k ] < h ) { break ; } } if ( k <= 2 ) { throw new IllegalArgumentException ( "The parameter h is too large." ) ; } return partition ( k - 1 ) ; }
Cuts a tree into several groups by specifying the cut height .
10,954
private void bfs ( int [ ] membership , int cluster , int id ) { int n = merge . length + 1 ; Queue < Integer > queue = new LinkedList < > ( ) ; queue . offer ( cluster ) ; for ( Integer i = queue . poll ( ) ; i != null ; i = queue . poll ( ) ) { if ( i < n ) { membership [ i ] = id ; continue ; } i -= n ; int m1 = merge [ i ] [ 0 ] ; if ( m1 >= n ) { queue . offer ( m1 ) ; } else { membership [ m1 ] = id ; } int m2 = merge [ i ] [ 1 ] ; if ( m2 >= n ) { queue . offer ( m2 ) ; } else { membership [ m2 ] = id ; } } }
BFS the merge tree and identify cluster membership .
10,955
private final boolean vowelinstem ( ) { int i ; for ( i = 0 ; i <= j ; i ++ ) { if ( ! isConsonant ( i ) ) { return true ; } } return false ; }
Returns true if 0 ... j contains a vowel
10,956
public String stripPluralParticiple ( String word ) { b = word . toCharArray ( ) ; k = word . length ( ) - 1 ; if ( k > 1 && ! word . equalsIgnoreCase ( "is" ) && ! word . equalsIgnoreCase ( "was" ) && ! word . equalsIgnoreCase ( "has" ) && ! word . equalsIgnoreCase ( "his" ) && ! word . equalsIgnoreCase ( "this" ) ) { step1 ( true ) ; return new String ( b , 0 , k + 1 ) ; } return word ; }
Remove plurals and participles .
10,957
private static ActivationFunction natural ( ErrorFunction error , int k ) { if ( error == ErrorFunction . CROSS_ENTROPY ) { if ( k == 1 ) { return ActivationFunction . LOGISTIC_SIGMOID ; } else { return ActivationFunction . SOFTMAX ; } } else { return ActivationFunction . LOGISTIC_SIGMOID ; } }
Returns the activation function of output layer based on natural pairing .
10,958
private void setInput ( double [ ] x ) { if ( x . length != inputLayer . units ) { throw new IllegalArgumentException ( String . format ( "Invalid input vector size: %d, expected: %d" , x . length , inputLayer . units ) ) ; } System . arraycopy ( x , 0 , inputLayer . output , 0 , inputLayer . units ) ; }
Sets the input vector into the input layer .
10,959
private void getOutput ( double [ ] y ) { if ( y . length != outputLayer . units ) { throw new IllegalArgumentException ( String . format ( "Invalid output vector size: %d, expected: %d" , y . length , outputLayer . units ) ) ; } System . arraycopy ( outputLayer . output , 0 , y , 0 , outputLayer . units ) ; }
Returns the output vector into the given array .
10,960
private void softmax ( ) { double max = Double . NEGATIVE_INFINITY ; for ( int i = 0 ; i < outputLayer . units ; i ++ ) { if ( outputLayer . output [ i ] > max ) { max = outputLayer . output [ i ] ; } } double sum = 0.0 ; for ( int i = 0 ; i < outputLayer . units ; i ++ ) { double out = Math . exp ( outputLayer . output [ i ] - max ) ; outputLayer . output [ i ] = out ; sum += out ; } for ( int i = 0 ; i < outputLayer . units ; i ++ ) { outputLayer . output [ i ] /= sum ; } }
Calculate softmax activation function in output layer without overflow .
10,961
private void propagate ( ) { for ( int l = 0 ; l < net . length - 1 ; l ++ ) { propagate ( net [ l ] , net [ l + 1 ] ) ; } }
Propagates the signals through the neural network .
10,962
private void backpropagate ( ) { for ( int l = net . length ; -- l > 0 ; ) { backpropagate ( net [ l ] , net [ l - 1 ] ) ; } }
Propagates the errors back through the network .
10,963
private void adjustWeights ( ) { for ( int l = 1 ; l < net . length ; l ++ ) { for ( int i = 0 ; i < net [ l ] . units ; i ++ ) { for ( int j = 0 ; j <= net [ l - 1 ] . units ; j ++ ) { double out = net [ l - 1 ] . output [ j ] ; double err = net [ l ] . error [ i ] ; double delta = ( 1 - alpha ) * eta * err * out + alpha * net [ l ] . delta [ i ] [ j ] ; net [ l ] . delta [ i ] [ j ] = delta ; net [ l ] . weight [ i ] [ j ] += delta ; if ( lambda != 0.0 && j < net [ l - 1 ] . units ) { net [ l ] . weight [ i ] [ j ] *= ( 1.0 - eta * lambda ) ; } } } } }
Adjust network weights by back - propagation algorithm .
10,964
public int predict ( double [ ] x , double [ ] y ) { setInput ( x ) ; propagate ( ) ; getOutput ( y ) ; if ( outputLayer . units == 1 ) { if ( outputLayer . output [ 0 ] > 0.5 ) { return 0 ; } else { return 1 ; } } double max = Double . NEGATIVE_INFINITY ; int label = - 1 ; for ( int i = 0 ; i < outputLayer . units ; i ++ ) { if ( outputLayer . output [ i ] > max ) { max = outputLayer . output [ i ] ; label = i ; } } return label ; }
Predict the target value of a given instance . Note that this method is NOT multi - thread safe .
10,965
public double learn ( double [ ] x , double [ ] y , double weight ) { setInput ( x ) ; propagate ( ) ; double err = weight * computeOutputError ( y ) ; if ( weight != 1.0 ) { for ( int i = 0 ; i < outputLayer . units ; i ++ ) { outputLayer . error [ i ] *= weight ; } } backpropagate ( ) ; adjustWeights ( ) ; return err ; }
Update the neural network with given instance and associated target value . Note that this method is NOT multi - thread safe .
10,966
public void learn ( double [ ] x , int y , double weight ) { if ( weight < 0.0 ) { throw new IllegalArgumentException ( "Invalid weight: " + weight ) ; } if ( weight == 0.0 ) { logger . info ( "Ignore the training instance with zero weight." ) ; return ; } if ( y < 0 ) { throw new IllegalArgumentException ( "Invalid class label: " + y ) ; } if ( outputLayer . units == 1 && y > 1 ) { throw new IllegalArgumentException ( "Invalid class label: " + y ) ; } if ( outputLayer . units > 1 && y >= outputLayer . units ) { throw new IllegalArgumentException ( "Invalid class label: " + y ) ; } if ( errorFunction == ErrorFunction . CROSS_ENTROPY ) { if ( activationFunction == ActivationFunction . LOGISTIC_SIGMOID ) { if ( y == 0 ) { target [ 0 ] = 1.0 ; } else { target [ 0 ] = 0.0 ; } } else { for ( int i = 0 ; i < target . length ; i ++ ) { target [ i ] = 0.0 ; } target [ y ] = 1.0 ; } } else { for ( int i = 0 ; i < target . length ; i ++ ) { target [ i ] = 0.1 ; } target [ y ] = 0.9 ; } learn ( x , target , weight ) ; }
Online update the neural network with a new training instance . Note that this method is NOT multi - thread safe .
10,967
public void learn ( double [ ] [ ] x , int [ ] y ) { int n = x . length ; int [ ] index = Math . permutate ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { learn ( x [ index [ i ] ] , y [ index [ i ] ] ) ; } }
Trains the neural network with the given dataset for one epoch by stochastic gradient descent .
10,968
public static PlotCanvas plot ( String id , double [ ] [ ] [ ] data ) { double [ ] lowerBound = { data [ 0 ] [ 0 ] [ 0 ] , data [ 0 ] [ 0 ] [ 1 ] } ; double [ ] upperBound = { data [ 0 ] [ 0 ] [ 0 ] , data [ 0 ] [ 0 ] [ 1 ] } ; for ( int i = 0 ; i < data . length ; i ++ ) { for ( int j = 0 ; j < data [ i ] . length ; j ++ ) { if ( data [ i ] [ j ] [ 0 ] < lowerBound [ 0 ] ) { lowerBound [ 0 ] = data [ i ] [ j ] [ 0 ] ; } if ( data [ i ] [ j ] [ 0 ] > upperBound [ 0 ] ) { upperBound [ 0 ] = data [ i ] [ j ] [ 0 ] ; } if ( data [ i ] [ j ] [ 1 ] < lowerBound [ 1 ] ) { lowerBound [ 1 ] = data [ i ] [ j ] [ 1 ] ; } if ( data [ i ] [ j ] [ 1 ] > upperBound [ 1 ] ) { upperBound [ 1 ] = data [ i ] [ j ] [ 1 ] ; } } } PlotCanvas canvas = new PlotCanvas ( lowerBound , upperBound ) ; Grid grid = new Grid ( data ) ; if ( id != null ) grid . setID ( id ) ; canvas . add ( grid ) ; return canvas ; }
Create a 2D grid plot canvas .
10,969
public JComponent learn ( ) { double [ ] [ ] data = dataset [ datasetIndex ] . toArray ( new double [ dataset [ datasetIndex ] . size ( ) ] [ ] ) ; String [ ] names = dataset [ datasetIndex ] . toArray ( new String [ dataset [ datasetIndex ] . size ( ) ] ) ; if ( names [ 0 ] == null ) { names = null ; } int [ ] label = dataset [ datasetIndex ] . toArray ( new int [ dataset [ datasetIndex ] . size ( ) ] ) ; int min = Math . min ( label ) ; for ( int i = 0 ; i < label . length ; i ++ ) { label [ i ] -= min ; } long clock = System . currentTimeMillis ( ) ; FLD lda = new FLD ( data , label , Math . unique ( label ) . length > 3 ? 3 : 2 ) ; System . out . format ( "Learn LDA from %d samples in %dms\n" , data . length , System . currentTimeMillis ( ) - clock ) ; double [ ] [ ] y = lda . project ( data ) ; PlotCanvas plot = new PlotCanvas ( Math . colMin ( y ) , Math . colMax ( y ) ) ; if ( names != null ) { plot . points ( y , names ) ; } else if ( dataset [ datasetIndex ] . responseAttribute ( ) != null ) { int [ ] labels = dataset [ datasetIndex ] . toArray ( new int [ dataset [ datasetIndex ] . size ( ) ] ) ; for ( int i = 0 ; i < y . length ; i ++ ) { plot . point ( pointLegend , Palette . COLORS [ labels [ i ] ] , y [ i ] ) ; } } else { plot . points ( y , pointLegend ) ; } plot . setTitle ( "Linear Discriminant Analysis" ) ; return plot ; }
Execute the projection algorithm and return a swing JComponent representing the clusters .
10,970
public DenseMatrix getD ( ) { int n = V . nrows ( ) ; DenseMatrix D = Matrix . zeros ( n , n ) ; for ( int i = 0 ; i < n ; i ++ ) { D . set ( i , i , d [ i ] ) ; if ( e != null ) { if ( e [ i ] > 0 ) { D . set ( i , i + 1 , e [ i ] ) ; } else if ( e [ i ] < 0 ) { D . set ( i , i - 1 , e [ i ] ) ; } } } return D ; }
Returns the block diagonal eigenvalue matrix whose diagonal are the real part of eigenvalues lower subdiagonal are positive imaginary parts and upper subdiagonal are negative imaginary parts .
10,971
public static Color [ ] terrain ( int n , float alpha ) { int k = n / 2 ; float [ ] H = { 4 / 12f , 2 / 12f , 0 / 12f } ; float [ ] S = { 1f , 1f , 0f } ; float [ ] V = { 0.65f , 0.9f , 0.95f } ; Color [ ] palette = new Color [ n ] ; float h = H [ 0 ] ; float hw = ( H [ 1 ] - H [ 0 ] ) / ( k - 1 ) ; float s = S [ 0 ] ; float sw = ( S [ 1 ] - S [ 0 ] ) / ( k - 1 ) ; float v = V [ 0 ] ; float vw = ( V [ 1 ] - V [ 0 ] ) / ( k - 1 ) ; for ( int i = 0 ; i < k ; i ++ ) { palette [ i ] = hsv ( h , s , v , alpha ) ; h += hw ; s += sw ; v += vw ; } h = H [ 1 ] ; hw = ( H [ 2 ] - H [ 1 ] ) / ( n - k ) ; s = S [ 1 ] ; sw = ( S [ 2 ] - S [ 1 ] ) / ( n - k ) ; v = V [ 1 ] ; vw = ( V [ 2 ] - V [ 1 ] ) / ( n - k ) ; for ( int i = k ; i < n ; i ++ ) { h += hw ; s += sw ; v += vw ; palette [ i ] = hsv ( h , s , v , alpha ) ; } return palette ; }
Generate terrain color palette .
10,972
public static Color [ ] topo ( int n , float alpha ) { int j = n / 3 ; int k = n / 3 ; int i = n - j - k ; Color [ ] palette = new Color [ n ] ; float h = 43 / 60.0f ; float hw = ( 31 / 60.0f - h ) / ( i - 1 ) ; int l = 0 ; for ( ; l < i ; l ++ ) { palette [ l ] = hsv ( h , 1.0f , 1.0f , alpha ) ; h += hw ; } h = 23 / 60.0f ; hw = ( 11 / 60.0f - h ) / ( j - 1 ) ; for ( ; l < i + j ; l ++ ) { palette [ l ] = hsv ( h , 1.0f , 1.0f , alpha ) ; h += hw ; } h = 10 / 60.0f ; hw = ( 6 / 60.0f - h ) / ( k - 1 ) ; float s = 1.0f ; float sw = ( 0.3f - s ) / ( k - 1 ) ; for ( ; l < n ; l ++ ) { palette [ l ] = hsv ( h , s , 1.0f , alpha ) ; h += hw ; s += sw ; } return palette ; }
Generate topo color palette .
10,973
public static Color [ ] jet ( int n , float alpha ) { int m = ( int ) Math . ceil ( n / 4 ) ; float [ ] u = new float [ 3 * m ] ; for ( int i = 0 ; i < u . length ; i ++ ) { if ( i == 0 ) { u [ i ] = 0.0f ; } else if ( i <= m ) { u [ i ] = i / ( float ) m ; } else if ( i <= 2 * m - 1 ) { u [ i ] = 1.0f ; } else { u [ i ] = ( 3 * m - i ) / ( float ) m ; } } int m2 = m / 2 + m % 2 ; int mod = n % 4 ; int [ ] r = new int [ n ] ; int [ ] g = new int [ n ] ; int [ ] b = new int [ n ] ; for ( int i = 0 ; i < u . length - 1 ; i ++ ) { if ( m2 - mod + i < n ) { g [ m2 - mod + i ] = i + 1 ; } if ( m2 - mod + i + m < n ) { r [ m2 - mod + i + m ] = i + 1 ; } if ( i > 0 && m2 - mod + i < u . length ) { b [ i ] = m2 - mod + i ; } } Color [ ] palette = new Color [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { palette [ i ] = new Color ( u [ r [ i ] ] , u [ g [ i ] ] , u [ b [ i ] ] , alpha ) ; } return palette ; }
Generate jet color palette .
10,974
public static Color [ ] redgreen ( int n , float alpha ) { Color [ ] palette = new Color [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { palette [ i ] = new Color ( ( float ) Math . sqrt ( ( i + 1.0f ) / n ) , ( float ) Math . sqrt ( 1 - ( i + 1.0f ) / n ) , 0.0f , alpha ) ; } return palette ; }
Generate red - green color palette .
10,975
public static Color [ ] redblue ( int n , float alpha ) { Color [ ] palette = new Color [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { palette [ i ] = new Color ( ( float ) Math . sqrt ( ( i + 1.0f ) / n ) , 0.0f , ( float ) Math . sqrt ( 1 - ( i + 1.0f ) / n ) , alpha ) ; } return palette ; }
Generate red - blue color palette .
10,976
public static Color [ ] heat ( int n , float alpha ) { int j = n / 4 ; int k = n - j ; float h = 1.0f / 6 ; Color [ ] c = rainbow ( k , 0 , h , alpha ) ; Color [ ] palette = new Color [ n ] ; System . arraycopy ( c , 0 , palette , 0 , k ) ; float s = 1 - 1.0f / ( 2 * j ) ; float end = 1.0f / ( 2 * j ) ; float w = ( end - s ) / ( j - 1 ) ; for ( int i = k ; i < n ; i ++ ) { palette [ i ] = hsv ( h , s , 1.0f , alpha ) ; s += w ; } return palette ; }
Generate heat color palette .
10,977
private static Color hsv ( float h , float s , float v , float alpha ) { float r = 0 ; float g = 0 ; float b = 0 ; if ( s == 0 ) { r = v ; g = v ; b = v ; } else { if ( h == 1.0f ) { h = 0.0f ; } h *= 6 ; int i = ( int ) Math . floor ( h ) ; float f = h - i ; float p = v * ( 1 - s ) ; float q = v * ( 1 - ( s * f ) ) ; float t = v * ( 1 - ( s * ( 1 - f ) ) ) ; switch ( i ) { case 0 : r = v ; g = t ; b = p ; break ; case 1 : r = q ; g = v ; b = p ; break ; case 2 : r = p ; g = v ; b = t ; break ; case 3 : r = p ; g = q ; b = v ; break ; case 4 : r = t ; g = p ; b = v ; break ; case 5 : r = v ; g = p ; b = q ; break ; } } return new Color ( r , g , b , alpha ) ; }
Generate a color based on HSV model .
10,978
public static HMMPOSTagger getDefault ( ) { if ( DEFAULT_TAGGER == null ) { try { ObjectInputStream ois = new ObjectInputStream ( HMMPOSTagger . class . getResourceAsStream ( "/smile/nlp/pos/hmmpostagger.model" ) ) ; DEFAULT_TAGGER = ( HMMPOSTagger ) ois . readObject ( ) ; ois . close ( ) ; } catch ( Exception ex ) { logger . error ( "Failed to load /smile/nlp/pos/hmmpostagger.model" , ex ) ; } } return DEFAULT_TAGGER ; }
Returns the default English POS tagger .
10,979
private static int [ ] translate ( PennTreebankPOS [ ] tags ) { int [ ] seq = new int [ tags . length ] ; for ( int i = 0 ; i < tags . length ; i ++ ) { seq [ i ] = tags [ i ] . ordinal ( ) ; } return seq ; }
Translate a POS tag sequence to internal representation .
10,980
public static void load ( String dir , List < String [ ] > sentences , List < PennTreebankPOS [ ] > labels ) { List < File > files = new ArrayList < > ( ) ; walkin ( new File ( dir ) , files ) ; for ( File file : files ) { try { FileInputStream stream = new FileInputStream ( file ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( stream ) ) ; String line = null ; List < String > sent = new ArrayList < > ( ) ; List < PennTreebankPOS > label = new ArrayList < > ( ) ; while ( ( line = reader . readLine ( ) ) != null ) { line = line . trim ( ) ; if ( line . isEmpty ( ) ) { if ( ! sent . isEmpty ( ) ) { sentences . add ( sent . toArray ( new String [ sent . size ( ) ] ) ) ; labels . add ( label . toArray ( new PennTreebankPOS [ label . size ( ) ] ) ) ; sent . clear ( ) ; label . clear ( ) ; } } else if ( ! line . startsWith ( "===" ) && ! line . startsWith ( "*x*" ) ) { String [ ] words = line . split ( "\\s" ) ; for ( String word : words ) { String [ ] w = word . split ( "/" ) ; if ( w . length == 2 ) { sent . add ( w [ 0 ] ) ; int pos = w [ 1 ] . indexOf ( '|' ) ; String tag = pos == - 1 ? w [ 1 ] : w [ 1 ] . substring ( 0 , pos ) ; if ( tag . equals ( "PRP$R" ) ) tag = "PRP$" ; if ( tag . equals ( "JJSS" ) ) tag = "JJS" ; label . add ( PennTreebankPOS . getValue ( tag ) ) ; } } } } if ( ! sent . isEmpty ( ) ) { sentences . add ( sent . toArray ( new String [ sent . size ( ) ] ) ) ; labels . add ( label . toArray ( new PennTreebankPOS [ label . size ( ) ] ) ) ; sent . clear ( ) ; label . clear ( ) ; } reader . close ( ) ; } catch ( Exception e ) { logger . error ( "Failed to load training data {}" , file , e ) ; } } }
Load training data from a corpora .
10,981
public static void walkin ( File dir , List < File > files ) { String pattern = ".POS" ; File [ ] listFile = dir . listFiles ( ) ; if ( listFile != null ) { for ( File file : listFile ) { if ( file . isDirectory ( ) ) { walkin ( file , files ) ; } else { if ( file . getName ( ) . endsWith ( pattern ) ) { files . add ( file ) ; } } } } }
Recursive function to descend into the directory tree and find all the files that end with . POS
10,982
public static void main ( String [ ] argvs ) { List < String [ ] > sentences = new ArrayList < > ( ) ; List < PennTreebankPOS [ ] > labels = new ArrayList < > ( ) ; load ( "D:\\sourceforge\\corpora\\PennTreebank\\PennTreebank2\\TAGGED\\POS\\WSJ" , sentences , labels ) ; load ( "D:\\sourceforge\\corpora\\PennTreebank\\PennTreebank2\\TAGGED\\POS\\BROWN" , sentences , labels ) ; String [ ] [ ] x = sentences . toArray ( new String [ sentences . size ( ) ] [ ] ) ; PennTreebankPOS [ ] [ ] y = labels . toArray ( new PennTreebankPOS [ labels . size ( ) ] [ ] ) ; HMMPOSTagger tagger = HMMPOSTagger . learn ( x , y ) ; try { FileOutputStream fos = new FileOutputStream ( "hmmpostagger.model" ) ; ObjectOutputStream oos = new ObjectOutputStream ( fos ) ; oos . writeObject ( tagger ) ; oos . flush ( ) ; oos . close ( ) ; } catch ( Exception ex ) { logger . error ( "Failed to save HMM POS model" , ex ) ; } }
Train the default model on WSJ and BROWN datasets .
10,983
public static < T extends Comparable < ? super T > > int [ ] sort ( T [ ] arr ) { int [ ] order = new int [ arr . length ] ; for ( int i = 0 ; i < order . length ; i ++ ) { order [ i ] = i ; } sort ( arr , order ) ; return order ; }
Sorts the specified array into ascending order .
10,984
public static < T extends Comparable < ? super T > > void sort ( T [ ] arr , int [ ] brr ) { sort ( arr , brr , arr . length ) ; }
Besides sorting the array arr the array brr will be also rearranged as the same order of arr .
10,985
public void set ( int i , int y ) { if ( response == null ) { throw new IllegalArgumentException ( "The dataset has no response values." ) ; } if ( response . getType ( ) != Attribute . Type . NOMINAL ) { throw new IllegalArgumentException ( "The response variable is not nominal." ) ; } if ( i < 0 ) { throw new IllegalArgumentException ( "Invalid index: i = " + i ) ; } int nrows = size ( ) ; if ( i >= nrows ) { for ( int k = nrows ; k <= i ; k ++ ) { data . add ( new Datum < > ( new SparseArray ( ) ) ) ; } } get ( i ) . y = y ; }
Set the class label of a datum . If the index exceeds the current matrix size the matrix will resize itself .
10,986
public void set ( int i , double y , double weight ) { if ( i < 0 ) { throw new IllegalArgumentException ( "Invalid index: i = " + i ) ; } int nrows = size ( ) ; if ( i >= nrows ) { for ( int k = nrows ; k <= i ; k ++ ) { data . add ( new Datum < > ( new SparseArray ( ) ) ) ; } } Datum < SparseArray > datum = get ( i ) ; datum . y = y ; datum . weight = weight ; }
Set the class label of real - valued response of a datum . If the index exceeds the current matrix size the matrix will resize itself .
10,987
public void set ( int i , int j , double x ) { if ( i < 0 || j < 0 ) { throw new IllegalArgumentException ( "Invalid index: i = " + i + " j = " + j ) ; } int nrows = size ( ) ; if ( i >= nrows ) { for ( int k = nrows ; k <= i ; k ++ ) { data . add ( new Datum < > ( new SparseArray ( ) ) ) ; } } if ( j >= ncols ( ) ) { numColumns = j + 1 ; if ( numColumns > colSize . length ) { int [ ] size = new int [ 3 * numColumns / 2 ] ; System . arraycopy ( colSize , 0 , size , 0 , colSize . length ) ; colSize = size ; } } if ( get ( i ) . x . set ( j , x ) ) { colSize [ j ] ++ ; n ++ ; } }
Set a nonzero entry into the matrix . If the index exceeds the current matrix size the matrix will resize itself .
10,988
public Datum < SparseArray > remove ( int i ) { Datum < SparseArray > datum = data . remove ( i ) ; n -= datum . x . size ( ) ; for ( SparseArray . Entry item : datum . x ) { colSize [ item . i ] -- ; } return datum ; }
Removes the element at the specified position in this dataset .
10,989
public void unitize ( ) { for ( Datum < SparseArray > row : this ) { double sum = 0.0 ; for ( SparseArray . Entry e : row . x ) { sum += Math . sqr ( e . x ) ; } sum = Math . sqrt ( sum ) ; for ( SparseArray . Entry e : row . x ) { e . x /= sum ; } } }
Unitize each row so that L2 norm of x = 1 .
10,990
public void unitize1 ( ) { for ( Datum < SparseArray > row : this ) { double sum = 0.0 ; for ( SparseArray . Entry e : row . x ) { sum += Math . abs ( e . x ) ; } for ( SparseArray . Entry e : row . x ) { e . x /= sum ; } } }
Unitize each row so that L1 norm of x is 1 .
10,991
public Iterator < Datum < SparseArray > > iterator ( ) { return new Iterator < Datum < SparseArray > > ( ) { int i = 0 ; public boolean hasNext ( ) { return i < data . size ( ) ; } public Datum < SparseArray > next ( ) { return get ( i ++ ) ; } public void remove ( ) { SparseDataset . this . remove ( i ) ; } } ; }
Returns an iterator over the elements in this dataset in proper sequence .
10,992
public double [ ] [ ] toArray ( ) { int m = data . size ( ) ; double [ ] [ ] a = new double [ m ] [ ncols ( ) ] ; for ( int i = 0 ; i < m ; i ++ ) { for ( SparseArray . Entry item : get ( i ) . x ) { a [ i ] [ item . i ] = item . x ; } } return a ; }
Returns a dense two - dimensional array containing the whole matrix in this dataset in proper sequence .
10,993
public void put ( double [ ] key , E value ) { int index = keys . size ( ) ; keys . add ( key ) ; data . add ( value ) ; for ( Hash h : hash ) { h . add ( index , key , value ) ; } }
Insert an item into the hash table .
10,994
public Neighbor < double [ ] , E > nearest ( double [ ] q , double recall , int T ) { if ( recall > 1 || recall < 0 ) { throw new IllegalArgumentException ( "Invalid recall: " + recall ) ; } double alpha = 1 - Math . pow ( 1 - recall , 1.0 / hash . size ( ) ) ; IntArrayList candidates = new IntArrayList ( ) ; for ( int i = 0 ; i < hash . size ( ) ; i ++ ) { IntArrayList buckets = model . get ( i ) . getProbeSequence ( q , alpha , T ) ; for ( int j = 0 ; j < buckets . size ( ) ; j ++ ) { int bucket = buckets . get ( j ) ; ArrayList < HashEntry > bin = hash . get ( i ) . table [ bucket % H ] ; if ( bin != null ) { for ( HashEntry e : bin ) { if ( e . bucket == bucket ) { if ( q != e . key || ! identicalExcluded ) { candidates . add ( e . index ) ; } } } } } } Neighbor < double [ ] , E > neighbor = new Neighbor < > ( null , null , - 1 , Double . MAX_VALUE ) ; int [ ] cand = candidates . toArray ( ) ; Arrays . sort ( cand ) ; int prev = - 1 ; for ( int index : cand ) { if ( index == prev ) { continue ; } else { prev = index ; } double [ ] key = keys . get ( index ) ; double distance = Math . distance ( q , key ) ; if ( distance < neighbor . distance ) { neighbor . index = index ; neighbor . distance = distance ; neighbor . key = key ; neighbor . value = data . get ( index ) ; } } return neighbor ; }
Returns the approximate nearest neighbor . A posteriori multiple probe model has to be trained already .
10,995
public void sort ( ) { if ( ! sorted ) { sort ( heap , Math . min ( k , n ) ) ; sorted = true ; } }
Sort the smallest values .
10,996
public void print ( Printable painter ) { printer . setPrintable ( painter ) ; if ( printer . printDialog ( printAttributes ) ) { try { printer . print ( printAttributes ) ; } catch ( PrinterException ex ) { logger . error ( "Failed to print" , ex ) ; JOptionPane . showMessageDialog ( null , ex . getMessage ( ) , "Error" , JOptionPane . ERROR_MESSAGE ) ; } } }
Prints a document that implements Printable interface .
10,997
public double randInverseCDF ( ) { final double a0 = 2.50662823884 ; final double a1 = - 18.61500062529 ; final double a2 = 41.39119773534 ; final double a3 = - 25.44106049637 ; final double b0 = - 8.47351093090 ; final double b1 = 23.08336743743 ; final double b2 = - 21.06224101826 ; final double b3 = 3.13082909833 ; final double c0 = 0.3374754822726147 ; final double c1 = 0.9761690190917186 ; final double c2 = 0.1607979714918209 ; final double c3 = 0.0276438810333863 ; final double c4 = 0.0038405729373609 ; final double c5 = 0.0003951896511919 ; final double c6 = 0.0000321767881768 ; final double c7 = 0.0000002888167364 ; final double c8 = 0.0000003960315187 ; double y , r , x ; double u = Math . random ( ) ; while ( u == 0.0 ) { u = Math . random ( ) ; } y = u - 0.5 ; if ( Math . abs ( y ) < 0.42 ) { r = y * y ; x = y * ( ( ( a3 * r + a2 ) * r + a1 ) * r + a0 ) / ( ( ( ( b3 * r + b2 ) * r + b1 ) * r + b0 ) * r + 1 ) ; } else { r = u ; if ( y > 0 ) { r = 1 - u ; } r = Math . log ( - Math . log ( r ) ) ; x = c0 + r * ( c1 + r * ( c2 + r * ( c3 + r * ( c4 + r * ( c5 + r * ( c6 + r * ( c7 + r * c8 ) ) ) ) ) ) ) ; if ( y < 0 ) { x = - ( x ) ; } } return mu + sigma * x ; }
Uses Inverse CDF method to generate a Gaussian deviate .
10,998
public int predict ( double [ ] x , double [ ] posteriori ) { Arrays . fill ( posteriori , 0.0 ) ; for ( int i = 0 ; i < trees . length ; i ++ ) { posteriori [ trees [ i ] . predict ( x ) ] += alpha [ i ] ; } double sum = Math . sum ( posteriori ) ; for ( int i = 0 ; i < k ; i ++ ) { posteriori [ i ] /= sum ; } return Math . whichMax ( posteriori ) ; }
Predicts the class label of an instance and also calculate a posteriori probabilities . Not supported .
10,999
public double quantile ( double p ) { if ( nd > 0 ) { update ( ) ; } int jl = 0 , jh = nq - 1 , j ; while ( jh - jl > 1 ) { j = ( jh + jl ) >> 1 ; if ( p > pval [ j ] ) { jl = j ; } else { jh = j ; } } j = jl ; double q = qile [ j ] + ( qile [ j + 1 ] - qile [ j ] ) * ( p - pval [ j ] ) / ( pval [ j + 1 ] - pval [ j ] ) ; return Math . max ( qile [ 0 ] , Math . min ( qile [ nq - 1 ] , q ) ) ; }
Returns the estimated p - quantile for the data seen so far . For example p = 0 . 5 for median .