<jupyter_start><jupyter_text>Use NAG Library for Python to cluster some random data using K-means<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from naginterfaces.library import mv
# Select the display backend for Jupyter:
%matplotlib inline
number_of_points = 100

# Generate a random array to try to cluster, have two variables so can plot it
np.random.seed(42) # For reproducibility

# Explicity construct two nicely separated clusters for ease of demonstration
mean1 = [-2, -2]
cov1 = [[1, 0], [0, 1]]  
X1 = np.random.multivariate_normal(mean1, cov1, number_of_points)

mean2 = [2, 2]
cov2 = [[1, 0], [0, 1]]  
X2 = np.random.multivariate_normal(mean2, cov2, number_of_points)

# Join the two together to make a single set of points
X = np.concatenate((X1, X2))

# Plot the combined dataset
_ = plt.plot(X[:,0], X[:,1], 'x')
nvar = 2 # Number of clusters
cmeans = np.random.rand(2, nvar) # Initial starting guesses for the centres
isx = np.full(2, 1.0, dtype=int) # We want to include both x and y features in the clustering
kmeans = mv.cluster_kmeans(X, isx, cmeans) # Find the cluster centres
colours = ['orange', 'blue']
plt.scatter(X[:,0], X[:,1], marker='x', c=kmeans.inc, cmap=matplotlib.colors.ListedColormap(colours))
_ = plt.scatter(kmeans.cmeans[:,0], kmeans.cmeans[:,1], color='red', s=200)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1260932944606414, 'fraction_numerical': 0.03134110787172012, 'mean_word_length': 5.269406392694064, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '365534', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 515, 'n_tokens_neox': 486, 'n_words': 158, 'path': 'multivariate_methods/k-means.ipynb', 'repo_name': 'Brunochris13/NAGPythonExamples', 'size': '1372'}