idx
int64
0
241k
question
stringlengths
64
6.21k
target
stringlengths
5
803
13,400
public static function isRfc ( $ url ) { if ( isset ( $ url ) && 1 < strlen ( $ url ) ) { $ host = self :: parseHost ( $ url ) ; $ scheme = strtolower ( parse_url ( $ url , PHP_URL_SCHEME ) ) ; if ( false !== $ host && ( $ scheme == 'http' || $ scheme == 'https' ) ) { $ pattern = '([A-Za-z][A-Za-z0-9+.-]{1,120}:[A-Za-z...
Validates the initialized object URL syntax .
13,401
function utf162utf8 ( $ utf16 ) { if ( function_exists ( 'mb_convert_encoding' ) ) { return mb_convert_encoding ( $ utf16 , 'UTF-8' , 'UTF-16' ) ; } $ bytes = ( ord ( $ utf16 { 0 } ) << 8 ) | ord ( $ utf16 { 1 } ) ; switch ( true ) { case ( ( 0x7F & $ bytes ) == $ bytes ) : return chr ( 0x7F & $ bytes ) ; case ( 0x07FF...
convert a string from one UTF - 16 char to one UTF - 8 char
13,402
public static function decode ( $ str , $ assoc = false ) { if ( ! function_exists ( 'json_decode' ) ) { $ j = self :: getJsonService ( ) ; return $ j -> decode ( $ str ) ; } else { return $ assoc ? json_decode ( $ str , true ) : json_decode ( $ str ) ; } }
Decodes a JSON string into appropriate variable .
13,403
public static function getPageRank ( $ url = false ) { if ( ! class_exists ( '\GTB_PageRank' ) ) { require_once realpath ( __DIR__ . '/3rdparty/GTB_PageRank.php' ) ; } $ gtb = new \ GTB_PageRank ( parent :: getUrl ( $ url ) ) ; $ result = $ gtb -> getPageRank ( ) ; return $ result != "" ? $ result : static :: noDataDef...
Gets the Google Pagerank
13,404
public static function getSearchResultsTotal ( $ url = false ) { $ url = parent :: getUrl ( $ url ) ; $ url = sprintf ( Config \ Services :: GOOGLE_APISEARCH_URL , 1 , $ url ) ; $ ret = static :: _getPage ( $ url ) ; $ obj = Helper \ Json :: decode ( $ ret ) ; return ! isset ( $ obj -> responseData -> cursor -> estimat...
Returns total amount of results for any Google search requesting the deprecated Websearch API .
13,405
public static function getVisibilityIndex ( $ url = false ) { $ url = parent :: getUrl ( $ url ) ; $ domain = Helper \ Url :: parseHost ( $ url ) ; $ dataUrl = sprintf ( Config \ Services :: SISTRIX_VI_URL , urlencode ( $ domain ) ) ; $ html = static :: _getPage ( $ dataUrl ) ; @ preg_match_all ( '#<h3>(.*?)<\/h3>#si' ...
Returns the Sistrix visibility index
13,406
public static function getVisibilityIndexByApi ( $ url = false , $ db = false ) { self :: guardApiKey ( ) ; self :: guardApiCredits ( ) ; $ url = parent :: getUrl ( $ url ) ; $ domain = static :: getDomainFromUrl ( $ url ) ; $ database = static :: getValidDatabase ( $ db ) ; $ dataUrl = sprintf ( Config \ Services :: S...
Returns the Sistrix visibility index by using the SISTRIX API
13,407
public static function getHttpCode ( $ url ) { $ ua = self :: getUserAgent ( ) ; $ curlopt_proxy = self :: getProxy ( ) ; $ curlopt_proxyuserpwd = self :: getProxyUserPwd ( ) ; $ ch = curl_init ( $ url ) ; curl_setopt_array ( $ ch , array ( CURLOPT_USERAGENT => $ ua , CURLOPT_RETURNTRANSFER => 1 , CURLOPT_CONNECTTIMEOU...
HTTP HEAD request with curl .
13,408
public static function getDailyRank ( $ url = false ) { self :: setRankingKeys ( $ url ) ; if ( 0 == self :: $ _rankKeys [ '1d' ] ) { return parent :: noDataDefaultValue ( ) ; } $ xpath = self :: _getXPath ( $ url ) ; $ nodes = @ $ xpath -> query ( "//*[@id='rank']/table/tr[" . self :: $ _rankKeys [ '1d' ] . "]/td[1]" ...
Get yesterday s rank
13,409
public static function getGlobalRank ( $ url = false ) { $ xpath = self :: _getXPath ( $ url ) ; $ xpathQueryList = array ( "//*[@id='traffic-rank-content']/div/span[2]/div[1]/span/span/div/strong" , "//*[@id='traffic-rank-content']/div/span[2]/div[1]/span/span/div/strong/a" ) ; return static :: parseDomByXpathsToInteg...
Get the average rank over the last 3 months
13,410
public static function setRankingKeys ( $ url = false ) { $ xpath = self :: _getXPath ( $ url ) ; $ nodes = @ $ xpath -> query ( "//*[@id='rank']/table/tr" ) ; if ( 5 == $ nodes -> length ) { self :: $ _rankKeys = array ( '1d' => 2 , '7d' => 3 , '1m' => 4 , '3m' => 5 , ) ; } else if ( 4 == $ nodes -> length ) { self ::...
Get the average rank over the week
13,411
public function priors ( ) : array { $ priors = [ ] ; if ( is_array ( $ this -> priors ) ) { $ total = logsumexp ( $ this -> priors ) ; foreach ( $ this -> priors as $ class => $ probability ) { $ priors [ $ class ] = exp ( $ probability - $ total ) ; } } return $ priors ; }
Return the cluster prior probabilities .
13,412
protected function initialize ( Dataset $ dataset ) : array { $ centroids = $ this -> seeder -> seed ( $ dataset , $ this -> k ) ; $ kernel = new Euclidean ( ) ; $ clusters = array_fill ( 0 , $ this -> k , [ ] ) ; foreach ( $ dataset as $ sample ) { $ bestDistance = INF ; $ bestCluster = - 1 ; foreach ( $ centroids as ...
Initialize the gaussian components by calculating the means and variances of k initial cluster centroids generated by the seeder .
13,413
protected function compute ( Matrix $ z ) : Matrix { if ( ! $ this -> alpha ) { throw new RuntimeException ( 'Layer is not initialized.' ) ; } $ alphas = $ this -> alpha -> w ( ) ; $ computed = [ ] ; foreach ( $ z as $ i => $ row ) { $ alpha = $ alphas [ $ i ] ; $ activations = [ ] ; foreach ( $ row as $ value ) { $ ac...
Compute the leaky ReLU activation function and return a matrix .
13,414
protected function differentiate ( Matrix $ z ) : Matrix { if ( ! $ this -> alpha ) { throw new RuntimeException ( 'Layer has not been initlaized.' ) ; } $ alphas = $ this -> alpha -> w ( ) ; $ gradient = [ ] ; foreach ( $ z as $ i => $ row ) { $ alpha = $ alphas [ $ i ] ; $ temp = [ ] ; foreach ( $ row as $ value ) { ...
Calculate the partial derivatives of the activation function .
13,415
public static function comb ( int $ n , int $ k = 2 ) : int { return $ k === 0 ? 1 : ( int ) ( ( $ n * self :: comb ( $ n - 1 , $ k - 1 ) ) / $ k ) ; }
Compute n choose k .
13,416
public static function ints ( int $ min , int $ max , int $ n = 10 ) : array { if ( ( $ max - $ min ) < 0 ) { throw new InvalidArgumentException ( 'Maximum cannot be' . ' less than minimum.' ) ; } if ( $ n < 1 ) { throw new InvalidArgumentException ( 'Cannot generate less' . ' than 1 parameter.' ) ; } if ( $ n > ( $ ma...
Generate a random unique integer distribution .
13,417
public static function floats ( float $ min , float $ max , int $ n = 10 ) : array { if ( ( $ max - $ min ) < 0. ) { throw new InvalidArgumentException ( 'Maximum cannot be' . ' less than minimum.' ) ; } if ( $ n < 1 ) { throw new InvalidArgumentException ( 'Cannot generate less' . ' than 1 parameter.' ) ; } $ min = ( ...
Generate a random distribution of floating point parameters .
13,418
public static function grid ( float $ min , float $ max , int $ n = 10 ) : array { if ( $ min > $ max ) { throw new InvalidArgumentException ( 'Max cannot be less' . ' then min.' ) ; } if ( $ n < 2 ) { throw new InvalidArgumentException ( 'Cannot generate less' . ' than 2 parameters.' ) ; } $ interval = ( $ max - $ min...
Generate a grid of evenly distributed parameters .
13,419
public static function args ( $ object ) : array { if ( ! is_object ( $ object ) ) { throw new InvalidArgumentException ( 'Argument must be' . ' an object ' . gettype ( $ object ) . ' found.' ) ; } $ reflector = new ReflectionClass ( $ object ) ; $ constructor = $ reflector -> getConstructor ( ) ; if ( $ constructor in...
Extract the arguments from the model constructor for display .
13,420
public static function stringify ( array $ constructor , string $ equator = '=' , string $ separator = ' ' ) : string { $ strings = [ ] ; foreach ( $ constructor as $ arg => $ param ) { if ( is_object ( $ param ) ) { $ param = self :: shortName ( $ param ) ; } if ( is_array ( $ param ) ) { $ temp = array_combine ( arra...
Return a string representation of the constructor arguments from an associative constructor array .
13,421
public function train ( Dataset $ dataset ) : void { if ( $ this -> type === self :: CLASSIFIER or $ this -> type === self :: REGRESSOR ) { if ( ! $ dataset instanceof Labeled ) { throw new InvalidArgumentException ( 'This estimator requires a' . ' labeled training set.' ) ; } } DatasetIsCompatibleWithEstimator :: chec...
Train all the experts with the dataset .
13,422
public function decideClass ( array $ votes ) { $ scores = array_fill_keys ( $ this -> classes , 0. ) ; foreach ( $ votes as $ i => $ vote ) { $ scores [ $ vote ] += $ this -> influences [ $ i ] ; } return argmax ( $ scores ) ; }
Decide on a class outcome .
13,423
public function decideAnomaly ( array $ votes ) : int { $ scores = array_fill ( 0 , 2 , 0. ) ; foreach ( $ votes as $ i => $ vote ) { $ scores [ $ vote ] += $ this -> influences [ $ i ] ; } return argmax ( $ scores ) ; }
Decide on an anomaly outcome .
13,424
public function _train ( Learner $ estimator , Dataset $ dataset ) : Learner { $ estimator -> train ( $ dataset ) ; return $ estimator ; }
Train an learner using a dataset and return it .
13,425
public function result ( ) : Matrix { if ( ! $ this -> result ) { $ this -> result = call_user_func ( $ this -> computation ) ; } return $ this -> result ; }
Return the result of the computation .
13,426
public function train ( Dataset $ dataset ) : void { if ( ! $ dataset instanceof Labeled ) { throw new InvalidArgumentException ( 'This Estimator requires a' . ' Labeled training set.' ) ; } DatasetIsCompatibleWithEstimator :: check ( $ dataset , $ this ) ; $ classes = $ dataset -> possibleOutcomes ( ) ; $ this -> clas...
Compute the necessary statistics to estimate a probability density for each feature column .
13,427
public function partial ( Dataset $ dataset ) : void { if ( empty ( $ this -> weights ) or empty ( $ this -> means ) or empty ( $ this -> variances ) ) { $ this -> train ( $ dataset ) ; return ; } if ( ! $ dataset instanceof Labeled ) { throw new InvalidArgumentException ( 'This Estimator requires a' . ' Labeled traini...
Uupdate the rolling means and variances of each feature column using an online updating algorithm .
13,428
public function back ( Deferred $ prevGradient , Optimizer $ optimizer ) : Deferred { if ( ! $ this -> beta or ! $ this -> gamma ) { throw new RuntimeException ( 'Layer has not been initilaized.' ) ; } if ( ! $ this -> stdInv or ! $ this -> xHat ) { throw new RuntimeException ( 'Must perform forward pass before' . ' ba...
Calculate the errors and gradients of the layer and update the parameters .
13,429
protected function terminate ( Labeled $ dataset ) : BinaryNode { $ n = $ dataset -> numRows ( ) ; $ labels = $ dataset -> labels ( ) ; $ counts = array_count_values ( $ labels ) ; $ outcome = argmax ( $ counts ) ; $ probabilities = [ ] ; foreach ( $ counts as $ class => $ count ) { $ probabilities [ $ class ] = $ coun...
Terminate the branch by selecting the class outcome with the highest probability .
13,430
protected function splitImpurity ( array $ groups ) : float { $ n = array_sum ( array_map ( 'count' , $ groups ) ) ; $ impurity = 0. ; foreach ( $ groups as $ dataset ) { $ k = $ dataset -> numRows ( ) ; if ( $ k < 2 ) { continue 1 ; } $ counts = array_count_values ( $ dataset -> labels ( ) ) ; $ p = 0. ; foreach ( $ c...
Calculate the Gini impurity for a given split .
13,431
public function columnType ( int $ index ) : int { if ( empty ( $ this -> samples ) ) { throw new RuntimeException ( 'Cannot determine data type' . ' of an empty data frame.' ) ; } $ sample = reset ( $ this -> samples ) ; if ( ! isset ( $ sample [ $ index ] ) ) { throw new InvalidArgumentException ( "Column $index does...
Get the datatype for a feature column given a column index .
13,432
public function columns ( ) : array { if ( $ this -> numRows ( ) > 1 ) { return array_map ( null , ... $ this -> samples ) ; } $ n = $ this -> numColumns ( ) ; $ columns = [ ] ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ columns [ ] = array_column ( $ this -> samples , $ i ) ; } return $ columns ; }
Rotate the dataframe and return it in an array . i . e . rows become columns and columns become rows .
13,433
public function columnsByType ( int $ type ) : array { $ n = $ this -> numColumns ( ) ; $ columns = [ ] ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ this -> columnType ( $ i ) === $ type ) { $ columns [ $ i ] = $ this -> column ( $ i ) ; } } return $ columns ; }
Return the columns that match a given data type .
13,434
public function partial ( Dataset $ dataset ) : void { if ( ! $ this -> network ) { $ this -> train ( $ dataset ) ; return ; } if ( ! $ dataset instanceof Labeled ) { throw new InvalidArgumentException ( 'This estimator requires a' . ' labeled training set.' ) ; } DatasetIsCompatibleWithEstimator :: check ( $ dataset ,...
Perform mini - batch gradient descent with given optimizer over the training set and update the input weights accordingly .
13,435
public function compatibility ( ) : array { $ compatibility = array_intersect ( $ this -> base -> compatibility ( ) , $ this -> booster -> compatibility ( ) ) ; return array_values ( $ compatibility ) ; }
Return the data types that this estimator is compatible with .
13,436
public function predict ( Dataset $ dataset ) : array { if ( empty ( $ this -> ensemble ) ) { throw new RuntimeException ( 'Estimator has not been trained.' ) ; } DatasetIsCompatibleWithEstimator :: check ( $ dataset , $ this ) ; $ predictions = $ this -> base -> predict ( $ dataset ) ; foreach ( $ this -> ensemble as ...
Make a prediction from a dataset .
13,437
protected function pairwiseDistances ( Matrix $ samples ) : Matrix { $ distances = [ ] ; foreach ( $ samples as $ a ) { $ temp = [ ] ; foreach ( $ samples as $ b ) { $ temp [ ] = $ this -> kernel -> compute ( $ a , $ b ) ; } $ distances [ ] = $ temp ; } return Matrix :: quick ( $ distances ) ; }
Calculate the pairwise distances for each sample .
13,438
protected function highAffinities ( Matrix $ distances ) : Matrix { $ zeros = array_fill ( 0 , count ( $ distances ) , 0 ) ; $ p = [ ] ; foreach ( $ distances as $ i => $ row ) { $ affinities = $ zeros ; $ minBeta = - INF ; $ maxBeta = INF ; $ beta = 1. ; for ( $ l = 0 ; $ l < self :: BINARY_PRECISION ; $ l ++ ) { $ af...
Calculate the joint likelihood of each sample in the high dimensional space as being nearest neighbor to each other sample .
13,439
protected function gradient ( Matrix $ p , Matrix $ y , Matrix $ distances ) : Matrix { $ q = $ distances -> square ( ) -> divide ( $ this -> degrees ) -> add ( 1. ) -> pow ( ( 1. + $ this -> degrees ) / - 2. ) ; $ qSigma = $ q -> sum ( ) -> multiply ( 2. ) ; $ q = $ q -> divide ( $ qSigma ) -> clipLower ( EPSILON ) ; ...
Compute the gradient of the KL Divergence cost function with respect to the embedding .
13,440
public function train ( Dataset $ dataset ) : void { if ( $ this -> type ( ) === self :: CLASSIFIER or $ this -> type ( ) === self :: REGRESSOR ) { if ( ! $ dataset instanceof Labeled ) { throw new InvalidArgumentException ( 'This estimator requires a' . ' labeled training set.' ) ; } } DatasetIsCompatibleWithEstimator...
Instantiate and train each base estimator in the ensemble on a bootstrap training set .
13,441
public static function split ( Dataset $ dataset ) : self { $ column = rand ( 0 , $ dataset -> numColumns ( ) - 1 ) ; $ sample = $ dataset [ rand ( 0 , count ( $ dataset ) - 1 ) ] ; $ value = $ sample [ $ column ] ; $ groups = $ dataset -> partition ( $ column , $ value ) ; return new self ( $ column , $ value , $ grou...
Factory method to build a isolator node from a dataset using a random split of the dataset .
13,442
public static function estimateRadius ( Dataset $ dataset , float $ percentile = 30. , ? Distance $ kernel = null ) : float { if ( $ percentile < 0. or $ percentile > 100. ) { throw new InvalidArgumentException ( 'Percentile must be between' . " 0 and 100, $percentile given." ) ; } $ kernel = $ kernel ?? new Euclidean ...
Estimate the radius of a cluster that encompasses a certain percentage of the total training samples .
13,443
protected function assign ( array $ sample ) : int { $ bestDistance = INF ; $ bestCluster = - 1 ; foreach ( $ this -> centroids as $ cluster => $ centroid ) { $ distance = $ this -> kernel -> compute ( $ sample , $ centroid ) ; if ( $ distance < $ bestDistance ) { $ bestDistance = $ distance ; $ bestCluster = $ cluster...
Label a given sample based on its distance from a particular centroid .
13,444
protected function membership ( array $ sample ) : array { $ membership = $ distances = [ ] ; foreach ( $ this -> centroids as $ centroid ) { $ distances [ ] = $ this -> kernel -> compute ( $ sample , $ centroid ) ; } $ total = array_sum ( $ distances ) ? : EPSILON ; foreach ( $ distances as $ distance ) { $ membership...
Return the membership of a sample to each of the centroids .
13,445
protected function logLikelihood ( Matrix $ z ) : array { $ likelihoods = array_fill ( 0 , $ z -> n ( ) , 0. ) ; foreach ( $ z as $ i => $ values ) { [ $ edges , $ counts , $ densities ] = $ this -> histograms [ $ i ] ; foreach ( $ values as $ j => $ value ) { foreach ( $ edges as $ k => $ edge ) { if ( $ value < $ edg...
Return the negative log likelihoods of each projection .
13,446
public static function minDimensions ( int $ n , float $ maxDistortion = 0.1 ) : int { return ( int ) round ( 4. * log ( $ n ) / ( $ maxDistortion ** 2 / 2. - $ maxDistortion ** 3 / 3. ) ) ; }
Calculate the minimum number of dimensions for n total samples with a given maximum distortion using the Johnson - Lindenstrauss lemma .
13,447
public function tail ( int $ n = 10 ) : self { return self :: quick ( array_slice ( $ this -> samples , - $ n ) ) ; }
Return a dataset containing only the last n samples .
13,448
public function append ( Dataset $ dataset ) : Dataset { return self :: quick ( array_merge ( $ this -> samples , $ dataset -> samples ( ) ) ) ; }
Append this dataset with another dataset .
13,449
public function batch ( int $ n = 50 ) : array { $ batches = [ ] ; $ samples = $ this -> samples ; foreach ( array_chunk ( $ this -> samples , $ n ) as $ batch ) { $ batches [ ] = self :: quick ( $ batch ) ; } return $ batches ; }
Generate a collection of batches of size n from the dataset . If there are not enough samples to fill an entire batch then the dataset will contain as many samples as possible .
13,450
protected function split ( Labeled $ dataset ) : Decision { $ bestImpurity = INF ; $ bestColumn = $ bestValue = null ; $ bestGroups = [ ] ; $ max = $ dataset -> numRows ( ) - 1 ; shuffle ( $ this -> columns ) ; foreach ( array_slice ( $ this -> columns , 0 , $ this -> maxFeatures ) as $ column ) { $ sample = $ dataset ...
Randomized algorithm that chooses the split point with the lowest variance among a random assortment of features .
13,451
public static function combineGrid ( array $ grid ) : array { $ combinations = [ [ ] ] ; foreach ( $ grid as $ i => $ params ) { $ append = [ ] ; foreach ( $ combinations as $ product ) { foreach ( $ params as $ param ) { $ product [ $ i ] = $ param ; $ append [ ] = $ product ; } } $ combinations = $ append ; } return ...
Return an array of all possible combinations of parameters . i . e the Cartesian product of the supplied parameter grid .
13,452
public function train ( Dataset $ dataset ) : void { if ( ! $ dataset instanceof Labeled ) { throw new InvalidArgumentException ( 'This Estimator requires a' . ' Labeled training set.' ) ; } DatasetIsCompatibleWithEstimator :: check ( $ dataset , $ this ) ; if ( $ this -> logger ) { $ this -> logger -> info ( 'Learner ...
Train one estimator per combination of parameters given by the grid and assign the best one as the base estimator of this instance .
13,453
public function score ( Learner $ estimator , Labeled $ dataset ) : float { return $ this -> validator -> test ( $ estimator , $ dataset , $ this -> metric ) ; }
Cross validate a learner with a given dataset and return the score .
13,454
public static function stack ( array $ datasets ) : self { $ samples = $ labels = [ ] ; foreach ( $ datasets as $ dataset ) { if ( ! $ dataset instanceof self ) { throw new InvalidArgumentException ( 'Dataset must be' . ' an instance of Labeled, ' . get_class ( $ dataset ) . ' given.' ) ; } $ samples = array_merge ( $ ...
Stack a number of datasets on top of each other to form a single dataset .
13,455
public function zip ( ) : array { $ rows = $ this -> samples ; foreach ( $ rows as $ i => & $ row ) { $ row [ ] = $ this -> labels [ $ i ] ; } return $ rows ; }
Return the samples and labels in a single array .
13,456
public function label ( int $ index ) { if ( ! isset ( $ this -> labels [ $ index ] ) ) { throw new InvalidArgumentException ( "Row at offset $index" . ' does not exist.' ) ; } return $ this -> labels [ $ index ] ; }
Return a label given by row index .
13,457
public function labelType ( ) : ? int { if ( ! isset ( $ this -> labels [ 0 ] ) ) { return null ; } return DataType :: determine ( $ this -> labels [ 0 ] ) ; }
Return the integer encoded data type of the label or null if empty .
13,458
public function transformLabels ( callable $ fn ) : void { $ labels = array_map ( $ fn , $ this -> labels ) ; foreach ( $ labels as $ label ) { if ( ! is_string ( $ label ) and ! is_numeric ( $ label ) ) { throw new RuntimeException ( 'Label must be a string or' . ' numeric type, ' . gettype ( $ label ) . ' found.' ) ;...
Map labels to their new values .
13,459
public function leave ( int $ n = 1 ) : self { if ( $ n < 0 ) { throw new InvalidArgumentException ( 'Cannot leave less than 0 samples.' ) ; } return $ this -> splice ( $ n , $ this -> numRows ( ) ) ; }
Leave n samples and labels on this dataset and return the rest in a new dataset .
13,460
public function randomize ( ) : self { $ order = range ( 0 , $ this -> numRows ( ) - 1 ) ; shuffle ( $ order ) ; array_multisort ( $ order , $ this -> samples , $ this -> labels ) ; return $ this ; }
Randomize the dataset in place and return self for chaining .
13,461
public function filterByColumn ( int $ index , callable $ fn ) : self { $ samples = $ labels = [ ] ; foreach ( $ this -> samples as $ i => $ sample ) { if ( $ fn ( $ sample [ $ index ] ) ) { $ samples [ ] = $ sample ; $ labels [ ] = $ this -> labels [ $ i ] ; } } return self :: quick ( $ samples , $ labels ) ; }
Run a filter over the dataset using the values of a given column .
13,462
public function filterByLabel ( callable $ fn ) : self { $ samples = $ labels = [ ] ; foreach ( $ this -> labels as $ i => $ label ) { if ( $ fn ( $ label ) ) { $ samples [ ] = $ this -> samples [ $ i ] ; $ labels [ ] = $ label ; } } return self :: quick ( $ samples , $ labels ) ; }
Run a filter over the dataset using the labels for Decision .
13,463
public function sortByColumn ( int $ index , bool $ descending = false ) { $ order = $ this -> column ( $ index ) ; array_multisort ( $ order , $ this -> samples , $ this -> labels , $ descending ? SORT_DESC : SORT_ASC ) ; return $ this ; }
Sort the dataset in place by a column in the sample matrix .
13,464
public function sortByLabel ( bool $ descending = false ) : Dataset { array_multisort ( $ this -> labels , $ this -> samples , $ descending ? SORT_DESC : SORT_ASC ) ; return $ this ; }
Sort the dataset in place by its labels .
13,465
public function stratify ( ) : array { $ strata = [ ] ; foreach ( $ this -> _stratify ( ) as $ label => $ stratum ) { $ labels = array_fill ( 0 , count ( $ stratum ) , $ label ) ; $ strata [ $ label ] = self :: quick ( $ stratum , $ labels ) ; } return $ strata ; }
Group samples by label and return an array of stratified datasets . i . e . n datasets consisting of samples with the same label where n is equal to the number of unique labels .
13,466
public function split ( float $ ratio = 0.5 ) : array { if ( $ ratio <= 0 or $ ratio >= 1 ) { throw new InvalidArgumentException ( 'Split ratio must be strictly' . " between 0 and 1, $ratio given." ) ; } $ n = ( int ) ( $ ratio * $ this -> numRows ( ) ) ; $ leftSamples = array_slice ( $ this -> samples , 0 , $ n ) ; $ ...
Split the dataset into two subsets with a given ratio of samples .
13,467
public function stratifiedFold ( int $ k = 10 ) : array { if ( $ k < 2 ) { throw new InvalidArgumentException ( 'Cannot create less than' . " 2 folds, $k given." ) ; } $ folds = [ ] ; for ( $ i = 0 ; $ i < $ k ; $ i ++ ) { $ samples = $ labels = [ ] ; foreach ( $ this -> _stratify ( ) as $ label => $ stratum ) { $ n = ...
Fold the dataset into k equal sized stratified datasets .
13,468
protected function _stratify ( ) : array { $ strata = [ ] ; foreach ( $ this -> labels as $ index => $ label ) { $ strata [ $ label ] [ ] = $ this -> samples [ $ index ] ; } return $ strata ; }
Stratifying subroutine groups samples by label .
13,469
public function batch ( int $ n = 50 ) : array { $ sChunks = array_chunk ( $ this -> samples , $ n ) ; $ lChunks = array_chunk ( $ this -> labels , $ n ) ; $ batches = [ ] ; foreach ( $ sChunks as $ i => $ samples ) { $ batches [ ] = self :: quick ( $ samples , $ lChunks [ $ i ] ) ; } return $ batches ; }
Generate a collection of batches of size n from the dataset . If there are not enough samples to fill an entire batch then the dataset will contain as many samples and labels as possible .
13,470
public function randomWeightedSubsetWithReplacement ( int $ n , array $ weights ) : self { if ( $ n < 1 ) { throw new InvalidArgumentException ( 'Cannot generate a' . " subset of less than 1 sample, $n given." ) ; } if ( count ( $ weights ) !== count ( $ this -> samples ) ) { throw new InvalidArgumentException ( 'The n...
Generate a random weighted subset with replacement .
13,471
protected function membership ( array $ sample ) : array { $ membership = $ deltas = [ ] ; foreach ( $ this -> centroids as $ centroid ) { $ deltas [ ] = $ this -> kernel -> compute ( $ sample , $ centroid ) ; } foreach ( $ this -> centroids as $ cluster => $ centroid ) { $ alpha = $ this -> kernel -> compute ( $ sampl...
Return the membership of a sample to each of the c centroids .
13,472
public static function split ( Dataset $ dataset , Distance $ kernel ) : self { $ samples = $ dataset -> samples ( ) ; $ center = Matrix :: quick ( $ samples ) -> transpose ( ) -> mean ( ) -> asArray ( ) ; $ distances = [ ] ; foreach ( $ samples as $ sample ) { $ distances [ ] = $ kernel -> compute ( $ sample , $ cente...
Factory method to build a centroid node from a labeled dataset using the column with the highest variance as the column for the split .
13,473
public function train ( Dataset $ dataset ) : void { if ( ! $ dataset instanceof Labeled ) { throw new InvalidArgumentException ( 'This estimator requires a' . ' labeled training set.' ) ; } $ this -> strategy -> fit ( $ dataset -> labels ( ) ) ; $ this -> trained = true ; }
Fit the training set to the given guessing strategy .
13,474
public function predict ( Dataset $ dataset ) : array { if ( ! $ this -> trained ) { throw new RuntimeException ( 'The learner has not' . ' been trained.' ) ; } $ n = $ dataset -> numRows ( ) ; $ predictions = [ ] ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ predictions [ ] = $ this -> strategy -> guess ( ) ; } return $ ...
Make a prediction of a given sample dataset .
13,475
public function trained ( ) : bool { return ( $ this -> estimator instanceof Learner and $ this -> estimator -> trained ( ) and $ this -> fitted ) or $ this -> fitted ; }
Has the learner been trained?
13,476
public function train ( Dataset $ dataset ) : void { $ this -> fit ( $ dataset ) ; if ( $ this -> estimator instanceof Learner ) { $ this -> estimator -> train ( $ dataset ) ; } $ this -> fitted = true ; }
Run the training dataset through all transformers in order and use the transformed dataset to train the estimator .
13,477
public function partial ( Dataset $ dataset ) : void { if ( $ this -> elastic ) { $ this -> update ( $ dataset ) ; } if ( $ this -> estimator instanceof Online ) { $ this -> estimator -> partial ( $ dataset ) ; } }
Perform a partial train .
13,478
public function predict ( Dataset $ dataset ) : array { $ this -> preprocess ( $ dataset ) ; return $ this -> estimator -> predict ( $ dataset ) ; }
Preprocess the dataset and return predictions from the estimator .
13,479
protected function fit ( Dataset $ dataset ) : void { foreach ( $ this -> transformers as $ transformer ) { if ( $ transformer instanceof Stateful ) { $ transformer -> fit ( $ dataset ) ; if ( $ this -> logger ) { $ this -> logger -> info ( 'Fitted ' . Params :: shortName ( $ transformer ) ) ; } } $ dataset -> apply ( ...
Fit the transformer middelware to a dataset .
13,480
protected function update ( Dataset $ dataset ) : void { foreach ( $ this -> transformers as $ transformer ) { if ( $ transformer instanceof Elastic ) { $ transformer -> update ( $ dataset ) ; if ( $ this -> logger ) { $ this -> logger -> info ( 'Updated ' . Params :: shortName ( $ transformer ) ) ; } } $ dataset -> ap...
Update the fitting of the transformer middleware .
13,481
protected function preprocess ( Dataset $ dataset ) : void { foreach ( $ this -> transformers as $ transformer ) { $ dataset -> apply ( $ transformer ) ; } }
Apply the transformer middleware over a dataset .
13,482
public function children ( ) : Generator { if ( $ this -> left ) { yield $ this -> left ; } if ( $ this -> right ) { yield $ this -> right ; } }
Return the children of this node in an array .
13,483
public function height ( ) : int { return 1 + max ( $ this -> left ? $ this -> left -> height ( ) : 0 , $ this -> right ? $ this -> right -> height ( ) : 0 ) ; }
Recursive function to determine the height of the node .
13,484
public function balance ( ) : int { return ( $ this -> right ? $ this -> right -> height ( ) : 0 ) - ( $ this -> left ? $ this -> left -> height ( ) : 0 ) ; }
The balance factor of the node . Negative numbers indicate a lean to the left positive to the right and 0 is perfectly balanced .
13,485
public function attachLeft ( BinaryNode $ node ) : void { $ node -> setParent ( $ this ) ; $ this -> left = $ node ; }
Set the left child node .
13,486
public function attachRight ( BinaryNode $ node ) : void { $ node -> setParent ( $ this ) ; $ this -> right = $ node ; }
Set the right child node .
13,487
public function detachLeft ( ) : void { if ( $ this -> left ) { $ this -> left -> setParent ( null ) ; $ this -> left = null ; } }
Detach the left child node .
13,488
public function detachRight ( ) : void { if ( $ this -> right ) { $ this -> right -> setParent ( null ) ; $ this -> right = null ; } }
Detach the right child node .
13,489
public function predict ( Dataset $ dataset ) : array { if ( ! $ this -> centroids ) { throw new RuntimeException ( 'Estimator has not been trained.' ) ; } DatasetIsCompatibleWithEstimator :: check ( $ dataset , $ this ) ; return array_map ( [ self :: class , 'assign' ] , $ dataset -> samples ( ) ) ; }
Cluster the dataset by assigning a label to each sample .
13,490
public static function load ( Persister $ persister ) : self { $ learner = $ persister -> load ( ) ; if ( ! $ learner instanceof Learner ) { throw new InvalidArgumentException ( 'Peristable must be a' . ' learner.' ) ; } return new self ( $ learner , $ persister ) ; }
Factory method to restore the model from persistence .
13,491
public function save ( ) : void { if ( $ this -> base instanceof Persistable ) { $ this -> persister -> save ( $ this -> base ) ; if ( $ this -> logger ) { $ this -> logger -> info ( 'Model saved successully' ) ; } } }
Save the model using the user - provided persister .
13,492
public function save ( Persistable $ persistable ) : void { $ data = $ this -> serializer -> serialize ( $ persistable ) ; $ success = $ this -> connector -> set ( $ this -> key , $ data ) ; if ( ! $ success ) { throw new RuntimeException ( 'Failed to save persistable' . ' to the database.' ) ; } }
Save the persitable object .
13,493
public function guess ( ) : float { if ( $ this -> min === null or $ this -> max === null ) { throw new RuntimeException ( 'Strategy has not been fitted.' ) ; } $ min = ( int ) round ( $ this -> min * $ this -> precision ) ; $ max = ( int ) round ( $ this -> max * $ this -> precision ) ; return rand ( $ min , $ max ) /...
Make a continuous guess .
13,494
public static function mcc ( int $ tp , int $ tn , int $ fp , int $ fn ) : float { return ( $ tp * $ tn - $ fp * $ fn ) / ( sqrt ( ( $ tp + $ fp ) * ( $ tp + $ fn ) * ( $ tn + $ fp ) * ( $ tn + $ fn ) ) ? : EPSILON ) ; }
Compute the class mcc score .
13,495
public function predict ( Dataset $ dataset ) : array { if ( ! $ this -> weights or $ this -> bias === null ) { throw new RuntimeException ( 'Estimator has not been trained.' ) ; } DatasetIsCompatibleWithEstimator :: check ( $ dataset , $ this ) ; return Matrix :: build ( $ dataset -> samples ( ) ) -> dot ( $ this -> w...
Make a prediction based on the line calculated from the training data .
13,496
public function predict ( Dataset $ dataset ) : array { if ( ! $ this -> network ) { throw new RuntimeException ( 'The learner has not' . ' been trained.' ) ; } DatasetIsCompatibleWithEstimator :: check ( $ dataset , $ this ) ; $ xT = Matrix :: quick ( $ dataset -> samples ( ) ) -> transpose ( ) ; return $ this -> netw...
Feed a sample through the network and make a prediction based on the activation of the output neuron .
13,497
public function back ( Deferred $ prevGradient , Optimizer $ optimizer ) : Deferred { if ( ! $ this -> mask ) { throw new RuntimeException ( 'Must perform forward pass before' . ' backpropagating.' ) ; } $ mask = $ this -> mask ; unset ( $ this -> mask ) ; return new Deferred ( function ( ) use ( $ prevGradient , $ mas...
Calculate the gradients of the layer and update the parameters .
13,498
public function compute ( array $ a , array $ b ) : float { $ distance = 0. ; foreach ( $ a as $ i => $ value ) { $ distance += abs ( $ value - $ b [ $ i ] ) ** $ this -> lambda ; } return $ distance ** $ this -> inverse ; }
Compute the distance given two vectors .
13,499
public static function mean ( array $ values , ? int $ n = null ) : float { $ n = $ n ?? count ( $ values ) ; if ( $ n < 1 ) { throw new InvalidArgumentException ( 'Mean is undefined for empty' . ' set.' ) ; } return array_sum ( $ values ) / $ n ; }
Compute the population mean of a set of values .