Skip to content

Convert kmeans from numpy to numphp #1

@bluescreen

Description

@bluescreen

Hi, i tried to port a kmeans algorithm from python to php using your numpy like library.
Somehow I do not fully understand how to operate matrices correctly using your lib.
Are the Parameters axis, keepdims of sum compatible to numpy?
Can you help me get this code running with your lib? I put the Python version into comments.

function kmeans(NdArray $X, $K, $maxIter = 20, $beta = 1.0){
    list($N, $D) = $X->shape;

    $R          = np::zeros($N, $K); // Responsibility Matrix
    $exponents  = np::nulls($N, $K); // Exponents

    // initialize M with random values of X
    $M = randomize($X, $K, $N);


    for($i=0; $i< $maxIter; $i++){
        // step 1: determine assignments / resposibilities
        for($k=0; $k < $K; $k++){
            for($n=0; $n < $N; $n++){

                // Python:  exponents[n,k] = np.exp(-beta*d(M[k], X[n]))
                $exponents[$n][$k] = np::exp(-$beta * distance($M[$k], $X[$n]));

                // Python: R = exponents / exponents.sum(axis=1, keepdims=True)
                $R = $exponents->divide($exponents->sum());
            }
        }

        // step 2: recalculate means
        for($k=0; $k < $K; $k++){

            // Python: M = R.T.dot(X) / R.sum(axis=0, keepdims=True).T
            $M[$k] = np::transpose($R)->dot($X)->divide(np::transpose($R->sum()));
        }
    }

    echo $M; die;
}

function randomize(NdArray $X, $K, $N)
{
    $randomMeans = [];
    for($k=0;$k < $K; $k++){
        $randomMeans[$k] = $X[rand(0, $N-1)]->data;
    }
    return np::ar($randomMeans);
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions