idx int64 0 60.3k | question stringlengths 101 6.21k | target stringlengths 7 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-z0-9/](([A-Za-z0-9$_.+!*,;/?:@&~=-])' ; $ pattern .= '|%[A-Fa-f0-9]{2}){1,333}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*,;/?:@&~=%-]{0,1000}))?)' ; return ( bool ) preg_match ( $ pattern , $ url ) ; } } return false ; } | 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 & $ bytes ) == $ bytes : return chr ( 0xC0 | ( ( $ bytes >> 6 ) & 0x1F ) ) . chr ( 0x80 | ( $ bytes & 0x3F ) ) ; case ( 0xFFFF & $ bytes ) == $ bytes : return chr ( 0xE0 | ( ( $ bytes >> 12 ) & 0x0F ) ) . chr ( 0x80 | ( ( $ bytes >> 6 ) & 0x3F ) ) . chr ( 0x80 | ( $ bytes & 0x3F ) ) ; } return '' ; } | 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 :: noDataDefaultValue ( ) ; } | 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 -> estimatedResultCount ) ? parent :: noDataDefaultValue ( ) : intval ( $ obj -> responseData -> cursor -> estimatedResultCount ) ; } | 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' , $ html , $ matches ) ; return isset ( $ matches [ 1 ] [ 0 ] ) ? $ matches [ 1 ] [ 0 ] : parent :: noDataDefaultValue ( ) ; } | 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 :: SISTRIX_API_VI_URL , Config \ ApiKeys :: getSistrixApiAccessKey ( ) , urlencode ( $ domain ) , $ database ) ; $ json = static :: _getPage ( $ dataUrl ) ; if ( empty ( $ json ) ) { return parent :: noDataDefaultValue ( ) ; } $ json_decoded = ( Helper \ Json :: decode ( $ json , true ) ) ; if ( ! isset ( $ json_decoded [ 'answer' ] [ 0 ] [ 'sichtbarkeitsindex' ] [ 0 ] [ 'value' ] ) ) { return parent :: noDataDefaultValue ( ) ; } return $ json_decoded [ 'answer' ] [ 0 ] [ 'sichtbarkeitsindex' ] [ 0 ] [ 'value' ] ; } | 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_CONNECTTIMEOUT => 10 , CURLOPT_FOLLOWLOCATION => 1 , CURLOPT_MAXREDIRS => 2 , CURLOPT_SSL_VERIFYPEER => 0 , CURLOPT_NOBODY => 1 , ) ) ; if ( $ curlopt_proxy ) { curl_setopt ( $ ch , CURLOPT_PROXY , $ curlopt_proxy ) ; } if ( $ curlopt_proxyuserpwd ) { curl_setopt ( $ ch , CURLOPT_PROXYUSERPWD , $ curlopt_proxyuserpwd ) ; } curl_exec ( $ ch ) ; $ httpCode = curl_getinfo ( $ ch , CURLINFO_HTTP_CODE ) ; curl_close ( $ ch ) ; return ( int ) $ httpCode ; } | 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]" ) ; return ! $ nodes -> item ( 0 ) ? parent :: noDataDefaultValue ( ) : self :: retInt ( strip_tags ( $ nodes -> item ( 0 ) -> nodeValue ) ) ; } | 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 :: parseDomByXpathsToIntegerWithoutTags ( $ xpath , $ xpathQueryList ) ; } | 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 :: $ _rankKeys = array ( '1d' => 0 , '7d' => 2 , '1m' => 3 , '3m' => 4 , ) ; } else if ( 3 == $ nodes -> length ) { self :: $ _rankKeys = array ( '1d' => 0 , '7d' => 0 , '1m' => 2 , '3m' => 3 , ) ; } else if ( 2 == $ nodes -> length ) { self :: $ _rankKeys = array ( '1d' => 0 , '7d' => 0 , '1m' => 0 , '3m' => 2 , ) ; } } | 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 $ cluster => $ centroid ) { $ distance = $ kernel -> compute ( $ sample , $ centroid ) ; if ( $ distance < $ bestDistance ) { $ bestDistance = $ distance ; $ bestCluster = $ cluster ; } } $ clusters [ $ bestCluster ] [ ] = $ sample ; } $ means = $ variances = [ ] ; foreach ( $ clusters as $ cluster => $ samples ) { $ mHat = $ vHat = [ ] ; $ columns = array_map ( null , ... $ samples ) ; foreach ( $ columns as $ values ) { [ $ mean , $ variance ] = Stats :: meanVar ( $ values ) ; $ mHat [ ] = $ mean ; $ vHat [ ] = $ variance ; } $ means [ $ cluster ] = $ mHat ; $ variances [ $ cluster ] = $ vHat ; } return [ $ means , $ variances ] ; } | 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 ) { $ activations [ ] = $ value > 0. ? $ value : $ alpha * $ value ; } $ computed [ ] = $ activations ; } return Matrix :: quick ( $ computed ) ; } | 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 ) { $ temp [ ] = $ value > 0. ? 1. : $ alpha ; } $ gradient [ ] = $ temp ; } return Matrix :: quick ( $ gradient ) ; } | 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 > ( $ max - $ min + 1 ) ) { throw new InvalidArgumentException ( 'Cannot generate more' . ' unique integers than in range.' ) ; } $ distribution = [ ] ; while ( count ( $ distribution ) < $ n ) { $ r = rand ( $ min , $ max ) ; if ( ! in_array ( $ r , $ distribution ) ) { $ distribution [ ] = $ r ; } } return $ distribution ; } | 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 = ( int ) round ( $ min * self :: PHI ) ; $ max = ( int ) round ( $ max * self :: PHI ) ; $ distribution = [ ] ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ distribution [ ] = rand ( $ min , $ max ) / self :: PHI ; } return $ distribution ; } | 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 ) / ( $ n - 1 ) ; return range ( $ min , $ max , $ interval ) ; } | 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 instanceof ReflectionMethod ) { $ args = array_column ( $ constructor -> getParameters ( ) , 'name' ) ; } else { $ args = [ ] ; } return $ args ; } | 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 ( array_keys ( $ param ) , $ param ) ? : [ ] ; $ param = '[' . self :: stringify ( $ temp ) . ']' ; } $ strings [ ] = ( string ) $ arg . $ equator . ( string ) $ param ; } return implode ( $ separator , $ strings ) ; } | 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 :: check ( $ dataset , $ this ) ; if ( $ this -> logger ) { $ this -> logger -> info ( 'Learner init ' . Params :: stringify ( [ 'experts' => $ this -> experts , 'influences' => $ this -> influences , 'workers' => $ this -> workers , ] ) ) ; } Loop :: run ( function ( ) use ( $ dataset ) { $ pool = new DefaultPool ( $ this -> workers ) ; $ coroutines = [ ] ; foreach ( $ this -> experts as $ index => $ estimator ) { $ task = new CallableTask ( [ $ this , '_train' ] , [ $ estimator , $ dataset ] ) ; $ coroutines [ ] = call ( function ( ) use ( $ pool , $ task , $ index ) { $ estimator = yield $ pool -> enqueue ( $ task ) ; if ( $ this -> logger ) { $ this -> logger -> info ( Params :: stringify ( [ $ index => $ estimator , ] ) . ' finished training' ) ; } return $ estimator ; } ) ; } $ this -> experts = yield all ( $ coroutines ) ; return yield $ pool -> shutdown ( ) ; } ) ; if ( $ this -> type === self :: CLASSIFIER and $ dataset instanceof Labeled ) { $ this -> classes = $ dataset -> possibleOutcomes ( ) ; } if ( $ this -> logger ) { $ this -> logger -> info ( 'Training complete' ) ; } } | 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 -> classes = $ classes ; $ this -> weights = array_fill_keys ( $ classes , 0 ) ; $ this -> means = $ this -> variances = array_fill_keys ( $ classes , [ ] ) ; foreach ( $ dataset -> stratify ( ) as $ class => $ stratum ) { $ means = $ variances = [ ] ; foreach ( $ stratum -> columns ( ) as $ values ) { [ $ mean , $ variance ] = Stats :: meanVar ( $ values ) ; $ means [ ] = $ mean ; $ variances [ ] = $ variance ? : EPSILON ; } $ this -> means [ $ class ] = $ means ; $ this -> variances [ $ class ] = $ variances ; $ this -> weights [ $ class ] += $ stratum -> numRows ( ) ; } if ( $ this -> fitPriors ) { $ this -> priors = [ ] ; $ total = array_sum ( $ this -> weights ) ? : EPSILON ; foreach ( $ this -> weights as $ class => $ weight ) { $ this -> priors [ $ class ] = log ( $ weight / $ total ) ; } } } | 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 training set.' ) ; } DatasetIsCompatibleWithEstimator :: check ( $ dataset , $ this ) ; foreach ( $ dataset -> stratify ( ) as $ class => $ stratum ) { $ means = $ this -> means [ $ class ] ; $ variances = $ this -> variances [ $ class ] ; $ oldWeight = $ this -> weights [ $ class ] ; $ oldMeans = $ this -> means [ $ class ] ; $ oldVariances = $ this -> variances [ $ class ] ; $ n = $ stratum -> numRows ( ) ; foreach ( $ stratum -> columns ( ) as $ column => $ values ) { [ $ mean , $ variance ] = Stats :: meanVar ( $ values ) ; $ means [ $ column ] = ( ( $ n * $ mean ) + ( $ oldWeight * $ oldMeans [ $ column ] ) ) / ( $ oldWeight + $ n ) ; $ vHat = ( $ oldWeight * $ oldVariances [ $ column ] + ( $ n * $ variance ) + ( $ oldWeight / ( $ n * ( $ oldWeight + $ n ) ) ) * ( $ n * $ oldMeans [ $ column ] - $ n * $ mean ) ** 2 ) / ( $ oldWeight + $ n ) ; $ variances [ $ column ] = $ vHat ? : EPSILON ; } $ this -> means [ $ class ] = $ means ; $ this -> variances [ $ class ] = $ variances ; $ this -> weights [ $ class ] += $ n ; } if ( $ this -> fitPriors ) { $ total = array_sum ( $ this -> weights ) ? : EPSILON ; foreach ( $ this -> weights as $ class => $ weight ) { $ this -> priors [ $ class ] = log ( $ weight / $ total ) ; } } } | 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' . ' backpropagating.' ) ; } $ dOut = $ prevGradient -> result ( ) ; $ dBeta = $ dOut -> sum ( ) ; $ dGamma = $ dOut -> multiply ( $ this -> xHat ) -> sum ( ) ; $ gamma = $ this -> gamma -> w ( ) ; $ optimizer -> step ( $ this -> beta , $ dBeta ) ; $ optimizer -> step ( $ this -> gamma , $ dGamma ) ; $ stdInv = $ this -> stdInv ; $ xHat = $ this -> xHat ; unset ( $ this -> stdInv , $ this -> xHat ) ; return new Deferred ( function ( ) use ( $ dOut , $ gamma , $ stdInv , $ xHat ) { $ dXHat = $ dOut -> multiply ( $ gamma ) ; $ xHatSigma = $ dXHat -> multiply ( $ xHat ) -> sum ( ) ; $ dXHatSigma = $ dXHat -> sum ( ) ; return $ dXHat -> multiply ( $ dOut -> m ( ) ) -> subtract ( $ dXHatSigma ) -> subtract ( $ xHat -> multiply ( $ xHatSigma ) ) -> multiply ( $ stdInv -> divide ( $ dOut -> m ( ) ) ) ; } ) ; } | 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 ] = $ count / $ n ; } $ impurity = 1. - ( max ( $ counts ) / $ n ) ** 2 ; return new Outcome ( $ outcome , $ probabilities , $ impurity , $ n ) ; } | 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 ( $ counts as $ count ) { $ p += 1. - ( $ count / $ n ) ** 2 ; } $ impurity += ( $ k / $ n ) * $ p ; } return $ impurity ; } | 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" . ' not exist.' ) ; } return DataType :: determine ( $ sample [ $ index ] ) ; } | 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 , $ this ) ; if ( $ this -> logger ) { $ this -> logger -> info ( 'Learner init ' . Params :: stringify ( [ 'batch_size' => $ this -> batchSize , 'optimizer' => $ this -> optimizer , 'alpha' => $ this -> alpha , 'epochs' => $ this -> epochs , 'min_change' => $ this -> minChange , 'cost_fn' => $ this -> costFn , ] ) ) ; } $ n = $ dataset -> numRows ( ) ; $ randomize = $ n > $ this -> batchSize ? true : false ; $ previous = INF ; for ( $ epoch = 1 ; $ epoch <= $ this -> epochs ; $ epoch ++ ) { if ( $ randomize ) { $ dataset -> randomize ( ) ; } $ batches = $ dataset -> batch ( $ this -> batchSize ) ; $ loss = 0. ; foreach ( $ batches as $ batch ) { $ loss += $ this -> network -> roundtrip ( $ batch ) ; } $ loss /= $ n ; $ this -> steps [ ] = $ loss ; if ( $ this -> logger ) { $ this -> logger -> info ( "Epoch $epoch complete, loss=$loss" ) ; } if ( is_nan ( $ loss ) ) { break 1 ; } if ( abs ( $ previous - $ loss ) < $ this -> minChange ) { break 1 ; } $ previous = $ loss ; } if ( $ this -> logger ) { $ this -> logger -> info ( 'Training complete' ) ; } } | 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 $ estimator ) { foreach ( $ estimator -> predict ( $ dataset ) as $ j => $ prediction ) { $ predictions [ $ j ] += $ this -> rate * $ prediction ; } } return $ predictions ; } | 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 ++ ) { $ affinities = [ ] ; $ pSigma = 0. ; foreach ( $ row as $ j => $ distance ) { if ( $ i !== $ j ) { $ affinity = exp ( - $ distance * $ beta ) ; } else { $ affinity = 0. ; } $ affinities [ ] = $ affinity ; $ pSigma += $ affinity ; } if ( $ pSigma === 0. ) { $ pSigma = EPSILON ; } $ distSigma = 0. ; foreach ( $ affinities as $ j => & $ prob ) { $ prob /= $ pSigma ; $ distSigma += $ row [ $ j ] * $ prob ; } $ entropy = log ( $ pSigma ) + $ beta * $ distSigma ; $ diff = $ entropy - $ this -> entropy ; if ( abs ( $ diff ) < self :: SEARCH_TOLERANCE ) { break 1 ; } if ( $ diff > 0. ) { $ minBeta = $ beta ; if ( $ maxBeta === INF ) { $ beta *= 2. ; } else { $ beta = ( $ beta + $ maxBeta ) / 2. ; } } else { $ maxBeta = $ beta ; if ( $ minBeta === - INF ) { $ beta /= 2. ; } else { $ beta = ( $ beta + $ minBeta ) / 2. ; } } } $ p [ ] = $ affinities ; } $ p = Matrix :: quick ( $ p ) ; $ pHat = $ p -> add ( $ p -> transpose ( ) ) ; $ sigma = $ pHat -> sum ( ) -> clipLower ( EPSILON ) ; return $ pHat -> divide ( $ sigma ) ; } | 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 ) ; $ pqd = $ p -> subtract ( $ q ) -> multiply ( $ distances ) ; $ c = 2. * ( 1. + $ this -> degrees ) / $ this -> degrees ; $ gradient = [ ] ; foreach ( $ pqd -> asVectors ( ) as $ i => $ row ) { $ yHat = $ y -> rowAsVector ( $ i ) -> subtract ( $ y ) ; $ gradient [ ] = $ row -> matmul ( $ yHat ) -> multiply ( $ c ) -> row ( 0 ) ; } return Matrix :: quick ( $ gradient ) ; } | 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 :: check ( $ dataset , $ this ) ; $ p = ( int ) round ( $ this -> ratio * $ dataset -> numRows ( ) ) ; $ this -> ensemble = [ ] ; Loop :: run ( function ( ) use ( $ dataset , $ p ) { $ pool = new DefaultPool ( $ this -> workers ) ; $ coroutines = [ ] ; for ( $ i = 0 ; $ i < $ this -> estimators ; $ i ++ ) { $ estimator = clone $ this -> base ; $ subset = $ dataset -> randomSubsetWithReplacement ( $ p ) ; $ task = new CallableTask ( [ $ this , '_train' ] , [ $ estimator , $ subset ] ) ; $ coroutines [ ] = call ( function ( ) use ( $ pool , $ task ) { return yield $ pool -> enqueue ( $ task ) ; } ) ; } $ this -> ensemble = yield all ( $ coroutines ) ; return yield $ pool -> shutdown ( ) ; } ) ; } | 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 , $ groups ) ; } | 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 ( ) ; $ distances = [ ] ; foreach ( $ dataset as $ sampleA ) { foreach ( $ dataset as $ sampleB ) { $ distances [ ] = $ kernel -> compute ( $ sampleA , $ sampleB ) ; } } return Stats :: percentile ( $ distances , $ percentile ) ; } | 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 ; } } return ( int ) $ bestCluster ; } | 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 [ ] = $ distance / $ total ; } return $ 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 < $ edge ) { $ likelihoods [ $ j ] += $ densities [ $ k ] ; break 1 ; } } } } foreach ( $ likelihoods as & $ likelihood ) { $ likelihood /= $ this -> estimators ; } return $ likelihoods ; } | 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 -> row ( rand ( 0 , $ max ) ) ; $ value = $ sample [ $ column ] ; $ groups = $ dataset -> partition ( $ column , $ value ) ; $ impurity = $ this -> splitImpurity ( $ groups ) ; if ( $ impurity < $ bestImpurity ) { $ bestColumn = $ column ; $ bestValue = $ value ; $ bestGroups = $ groups ; $ bestImpurity = $ impurity ; } if ( $ impurity < $ this -> tolerance ) { break 1 ; } } return new Decision ( $ bestColumn , $ bestValue , $ bestGroups , $ bestImpurity ) ; } | 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 $ combinations ; } | 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 init ' . Params :: stringify ( [ 'base' => $ this -> base , 'metric' => $ this -> metric , 'validator' => $ this -> validator , 'workers' => $ this -> workers , ] ) ) ; } $ results = [ ] ; Loop :: run ( function ( ) use ( & $ results , $ dataset ) { $ pool = new DefaultPool ( $ this -> workers ) ; $ coroutines = [ ] ; foreach ( $ this -> combinations as $ params ) { $ estimator = new $ this -> base ( ... $ params ) ; $ task = new CallableTask ( [ $ this , 'score' ] , [ $ estimator , $ dataset ] ) ; $ coroutines [ ] = call ( function ( ) use ( $ pool , $ task , $ params ) { $ score = yield $ pool -> enqueue ( $ task ) ; if ( $ this -> logger ) { $ constructor = array_combine ( $ this -> args , $ params ) ? : [ ] ; $ this -> logger -> info ( 'Test complete: ' . Params :: stringify ( [ Params :: shortName ( $ this -> metric ) => $ score , ] ) . ' Params: ' . Params :: stringify ( $ constructor ) ) ; } return [ $ score , $ params ] ; } ) ; } $ results = yield all ( $ coroutines ) ; return yield $ pool -> shutdown ( ) ; } ) ; $ bestScore = - INF ; $ bestParams = [ ] ; foreach ( $ results as [ $ score , $ params ] ) { if ( $ score > $ bestScore ) { $ bestScore = $ score ; $ bestParams = $ params ; } } $ this -> best = [ 'score' => $ bestScore , 'params' => $ bestParams , ] ; if ( $ this -> logger ) { $ constructor = array_combine ( $ this -> args , $ bestParams ) ? : [ ] ; $ this -> logger -> info ( 'Best params: ' . Params :: stringify ( $ constructor ) ) ; } $ estimator = new $ this -> base ( ... $ bestParams ) ; $ estimator -> train ( $ dataset ) ; $ this -> estimator = $ estimator ; if ( $ this -> logger ) { $ this -> logger -> info ( 'Training complete' ) ; } } | 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 ( $ samples , $ dataset -> samples ( ) ) ; $ labels = array_merge ( $ labels , $ dataset -> labels ( ) ) ; } return self :: quick ( $ samples , $ labels ) ; } | 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.' ) ; } } $ this -> labels = $ labels ; } | 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 ) ; $ leftLabels = array_slice ( $ this -> labels , 0 , $ n ) ; $ rightSamples = array_slice ( $ this -> samples , $ n ) ; $ rightLabels = array_slice ( $ this -> labels , $ n ) ; return [ self :: quick ( $ leftSamples , $ leftLabels ) , self :: quick ( $ rightSamples , $ rightLabels ) , ] ; } | 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 = ( int ) floor ( count ( $ stratum ) / $ k ) ; $ samples = array_merge ( $ samples , array_slice ( $ stratum , $ i * $ n , $ n ) ) ; $ labels = array_merge ( $ labels , array_fill ( 0 , $ n , $ label ) ) ; } $ folds [ ] = self :: quick ( $ samples , $ labels ) ; } return $ folds ; } | 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 number of weights' . ' must be equal to the number of samples in the' . ' dataset, ' . count ( $ this -> samples ) . ' needed' . ' but ' . count ( $ weights ) . ' given.' ) ; } $ total = array_sum ( $ weights ) ; $ max = ( int ) round ( $ total * self :: PHI ) ; $ samples = $ labels = [ ] ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ delta = rand ( 0 , $ max ) / self :: PHI ; foreach ( $ weights as $ index => $ weight ) { $ delta -= $ weight ; if ( $ delta <= 0. ) { $ samples [ ] = $ this -> samples [ $ index ] ; $ labels [ ] = $ this -> labels [ $ index ] ; break 1 ; } } } return self :: quick ( $ samples , $ labels ) ; } | 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 ( $ sample , $ centroid ) ; $ sigma = 0. ; foreach ( $ deltas as $ delta ) { $ sigma += ( $ alpha / ( $ delta ? : EPSILON ) ) ** $ this -> lambda ; } $ membership [ $ cluster ] = 1. / ( $ sigma ? : EPSILON ) ; } return $ membership ; } | 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 , $ center ) ; } $ radius = max ( $ distances ) ; $ leftCentroid = $ dataset -> row ( argmax ( $ distances ) ) ; $ distances = [ ] ; foreach ( $ samples as $ sample ) { $ distances [ ] = $ kernel -> compute ( $ sample , $ leftCentroid ) ; } $ rightCentroid = $ dataset -> row ( argmax ( $ distances ) ) ; $ subsets = $ dataset -> spatialPartition ( $ leftCentroid , $ rightCentroid , $ kernel ) ; return new self ( $ center , $ radius , $ subsets ) ; } | 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 $ predictions ; } | 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 ( $ transformer ) ; if ( $ this -> logger ) { $ this -> logger -> info ( 'Applied ' . Params :: shortName ( $ transformer ) ) ; } } } | 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 -> apply ( $ transformer ) ; if ( $ this -> logger ) { $ this -> logger -> info ( 'Applied ' . Params :: shortName ( $ transformer ) ) ; } } } | 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 ) / $ this -> precision ; } | 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 -> weights ) -> add ( $ this -> bias ) -> asArray ( ) ; } | 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 -> network -> infer ( $ xT ) -> row ( 0 ) ; } | 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 , $ mask ) { return $ prevGradient -> result ( ) -> multiply ( $ mask ) ; } ) ; } | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.