1# Copyright (C) 2026 Advanced Micro Devices, Inc. All rights reserved.
2#
3# Redistribution and use in source and binary forms, with or without modification,
4# are permitted provided that the following conditions are met:
5# 1. Redistributions of source code must retain the above copyright notice,
6# this list of conditions and the following disclaimer.
7# 2. Redistributions in binary form must reproduce the above copyright notice,
8# this list of conditions and the following disclaimer in the documentation
9# and/or other materials provided with the distribution.
10# 3. Neither the name of the copyright holder nor the names of its contributors
11# may be used to endorse or promote products derived from this software without
12# specific prior written permission.
13#
14# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
15# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
20# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
21# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
23# POSSIBILITY OF SUCH DAMAGE.
24#
25
26"""
27K-Means model persistence example
28"""
29
30import sys
31import os
32import pickle
33import numpy as np
34from aoclda.clustering import kmeans
35
36
37def model_persistence_kmeans_ex():
38 """
39 K-Means model persistence using pickle
40 """
41
42 # Generate sample data and train a k-means model
43 rng = np.random.default_rng(42)
44 X = rng.standard_normal((1000, 5))
45
46 print("Training k-means model...")
47 # Fit the model
48 km = kmeans(n_clusters=3, seed=42)
49 km.fit(X)
50
51 # Get predictions and centers before saving
52 labels_before = km.predict(X[:10])
53 centers_before = km.cluster_centres.copy()
54 print(f"Cluster centers shape: {centers_before.shape}")
55 print(f"First 10 predictions: {labels_before}")
56
57 # Save the trained model to a file
58 print("\nSaving model to 'kmeans_model.pkl'...")
59 with open('kmeans_model.pkl', 'wb') as f:
60 pickle.dump(km, f)
61
62 # Delete the original model
63 del km
64
65 # Later, load the model from disk
66 print("Loading model from 'kmeans_model.pkl'...")
67 with open('kmeans_model.pkl', 'rb') as f:
68 km_loaded = pickle.load(f)
69
70 # Use the loaded model for predictions
71 labels_after = km_loaded.predict(X[:10])
72 centers_after = km_loaded.cluster_centres
73 print(f"First 10 predictions after load: {labels_after}")
74
75 # Verify results match
76 labels_match = np.array_equal(labels_before, labels_after)
77 centers_match = np.array_equal(centers_before, centers_after)
78
79 if labels_match and centers_match:
80 print("\nModel persistence verified - predictions and centers match!")
81 else:
82 print("\nError: Results do not match")
83 if not labels_match:
84 print(" - Labels differ")
85 if not centers_match:
86 print(" - Cluster centers differ")
87 os.remove('kmeans_model.pkl')
88 sys.exit(1)
89
90 # Clean up created files
91 os.remove('kmeans_model.pkl')
92
93
94if __name__ == "__main__":
95 try:
96 model_persistence_kmeans_ex()
97 except Exception as e:
98 print(f"Error: {e}")
99 sys.exit(1)