Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning K-means written in Octave into Tensorflow.js

During a project, I have prototyped an adaptation of the K-means algorithm in octave. If it is not possible to run Octave within a HTML file, how would I turn this K-means algorithm which is written in octave into Tensorflow.js so that I would be able to run it in a browser.:

x = [1,2,3,4,5,6;7,8,9,10,11,12;13,14,15,16,17,18]
time = [1,2,3,4,5,6]

k = size(x)
foo = 0
mu = zeros(k(1),1)

for i = 1:k(2),
  mu = [x(:,i)/pinv(time(i)), mu]
  foo = foo+1
endfor
mu(:,[foo+1]) = [];
usr = sum(mu') / numel(x)
usr = usr'


x = [x,usr]



centroids = [x(:,randi([1,size(x)(2)])), x(:,randi([1,size(x)(2)]))]


if centroids(:,1) == centroids(:,2),
  for i = 1:500,
    centroids = [x(:,randi([1,size(x)(2)])), x(:,randi([1,size(x)(2)]))]
  endfor
endif


K = size(centroids, 2);

idx = zeros(size(x,1), 1);


for c = 1:500,

for i = 1:size(x,2),
    min = Inf;
    for j = 1:K,
        diff = sum((x(:,i) - centroids(:,j)).^2);
        if min > diff
            min = diff;
            idx(i) = j;
        end
    end
end

for i = 1:size(centroids,2),
  xi = x(:,idx==i)
  ck = size(xi,2);
  centroids(:,i) = [sum(xi,2) * (1/size(x(:,idx==i),2))]
endfor
endfor
like image 730
jr123456jr987654321 Avatar asked Oct 26 '22 19:10

jr123456jr987654321


1 Answers

You could use some server side solution as written in this answer or if you actually need to run in a browser I'm afraid you need to translate it in JavaScript. You can do it by your hands or using a tool like matscript.

like image 145
Daniele Ricci Avatar answered Nov 09 '22 23:11

Daniele Ricci