Skip to content

Instantly share code, notes, and snippets.

@novoselrok
Created October 18, 2018 20:22
Show Gist options
  • Select an option

  • Save novoselrok/658b636eeef54215c35a1b7e97021dfc to your computer and use it in GitHub Desktop.

Select an option

Save novoselrok/658b636eeef54215c35a1b7e97021dfc to your computer and use it in GitHub Desktop.
config const filename = "../data/input.txt";
config const out_filename = "out.txt";
config const iterations = 1;
config const k = 2;
var f = open(filename, iomode.r);
var reader = f.reader();
const rows = reader.read(int);
const cols = reader.read(int);
type point = [0..#cols] real;
const pDomain = 0..#rows;
const clustersDomain = 0..#k;
var data: [pDomain] point;
reader.read(data);
f.close();
reader.close();
record Cluster {
var n_items: int;
var centroid: point;
var centroidMean: point;
proc init() {
n_items = 0;
centroid = 0.0;
}
proc init(row: point) {
n_items = 1;
centroid = row;
}
proc addRow(row: point) {
n_items += 1;
centroid += row;
}
proc addCluster(otherCluster: Cluster) {
n_items += otherCluster.n_items;
centroid += otherCluster.centroid;
}
proc dist(row: point) {
return sqrt(+ reduce ((centroidMean - row) ** 2));
}
proc reset() {
n_items = 0;
centroid = 0.0;
}
proc mean() {
centroidMean = centroid / n_items;
return centroidMean;
}
}
var clusters: [clustersDomain] Cluster;
var labels: [pDomain] int;
for i in pDomain {
labels[i] = i % k;
clusters[labels[i]].addRow(data[i]);
}
[cluster in clusters] cluster.mean();
[cluster in clusters] writeln(cluster);
[cluster in clusters] cluster.reset();
forall i in pDomain {
var row = data[i];
var dists = [cluster in clusters] cluster.dist(row);
var (_, min_index) = minloc reduce zip(dists, dists.domain);
clusters[min_index].addRow(row);
}
[cluster in clusters] cluster.mean();
[cluster in clusters] writeln(cluster);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment