% Solve a Clustering Problem with a Self-Organizing Map
% Script generated by Neural Clustering app
% Created 05-Dec-2021 18:55:58
%
% This script assumes these variables are defined:
%
%   simpleclusterInputs - input data.

load simplecluster_dataset
x = simplecluster_dataset;

% Create a Self-Organizing Map
dimension1 = 5;
dimension2 = 5;
net = selforgmap([dimension1 dimension2]);

% Train the Network
[net,tr] = train(net,x);

% Test the Network
y = net(x);

% View the Network
view(net)

%E= evalclusters(x, 'kmeans', 'DaviesBouldin', 'klist', [1:6]);
E= evalclusters(x','kmeans','DaviesBouldin','klist',[2:6]);
plot(E)

% Plots
% Uncomment these lines to enable various plots.
figure, plotsomtop(net)
figure, plotsomnc(net)
figure, plotsomnd(net)
%figure, plotsomplanes(net)
figure, plotsomhits(net,x)
figure, plotsompos(net,x)

SeedC=net.IW(1);
w=SeedC{1};
clusters=4;
[idx,C]=kmeans(x',clusters);
meandist=0;
for i=1:clusters
    for k=1:25
        dist(k)=(C(i,1) -w(k,1))^2+(C(i,2)-w(k,2))^2;
    end
    kmin=1;
    mindist=dist(1);
    for k=2:25
        if dist(k)<mindist
            kmin=k;
            mindist=dist(k);
        end
    end
    disp([i,kmin,mindist])
    meandist=meandist+mindist;
end
meandist=meandist/clusters;
disp(meandist)




