To save the clustering model and then load it later for applying to new data, typically you can use Python's pickle or joblib, but there's one caveat:
AgglomerativeClustering in scikit-learn does not implement predict method, because hierarchical clustering is a fit-only algorithm. So you cannot directly "predict" clusters for new data points with the fitted model.
Hence, if you want to apply the same clustering model to new data, the standard approach is:
- Save the vectorizer fitted on the original data.
- For new data:
- Clean the new data by the same rules.
- Transform the new university names with the saved vectorizer.
- Append the new data vectors to the original dataset vectors.
- Fit the agglomerative clustering again on the combined data (old + new), or use another clustering algorithm that supports prediction, e.g., KMeans.
Solution to save vectorizer and demonstrate clustering on new data:
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import AgglomerativeClustering
import numpy as np
import joblib
# Original data
data = {
'pid': [1, 1, 2, 2, 3, 3],
'University': ['American Medical University ', 'Bejing Univ ', 'Berlin Unv ',
'American Medical University ', np.nan, 'Jakartha University']
}
df = pd.DataFrame(data)
# 1. Preprocessing
df['University_clean'] = df['University'].str.strip().fillna('missing')
# 2. Fit TF-IDF vectorizer
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(df['University_clean'])
# Save vectorizer
joblib.dump(vectorizer, 'tfidf_vectorizer.joblib')
# 3. Fit AgglomerativeClustering
agg_clust = AgglomerativeClustering(n_clusters=3)
clusters = agg_clust.fit_predict(X.toarray())
df['cluster'] = clusters
print("Original data clustering:")
print(df[['pid', 'University', 'cluster']])
# Save cluster labels - (model can't predict new clusters, so model itself can't be re-used for predictions)
# -------------------------------------------------
# Now, suppose you get new data, and want to assign clusters:
new_data = {
'pid': [4, 4, 5],
'University': ['American Medical Univ', 'Jakartha University', 'New University']
}
df_new = pd.DataFrame(new_data)
# 1. Clean the new data same as before
df_new['University_clean'] = df_new['University'].str.strip().fillna('missing')
# 2. Load saved vectorizer and transform the new data
loaded_vectorizer = joblib.load('tfidf_vectorizer.joblib')
X_new = loaded_vectorizer.transform(df_new['University_clean'])
# 3. Since AgglomerativeClustering cannot predict clusters for new data,
# the best practice is to combine old + new data and fit clustering again:
combined_X = np.vstack([X.toarray(), X_new.toarray()])
# Fit clustering on combined data
agg_clust_new = AgglomerativeClustering(n_clusters=3)
combined_clusters = agg_clust_new.fit_predict(combined_X)
# Separate old and new clusters
old_clusters = combined_clusters[:len(df)]
new_clusters = combined_clusters[len(df):]
print("\nNew data clustering after refit:")
df_new['cluster'] = new_clusters
print(df_new[['pid', 'University', 'cluster']])
Summary:
- Save the TF-IDF vectorizer so new text can be vectorized consistently.
- You cannot load the AgglomerativeClustering and predict new clusters directly.
- The typical approach is to vectorize new data with the saved vectorizer, combine with old data, and cluster again.
- Alternatively, use algorithms like KMeans which support
.predict() for new data.
If you want a workflow where you can easily assign clusters to new data, consider using KMeans, for example:
from sklearn.cluster import KMeans
# Fit KMeans on X, save model and vectorizer
kmeans = KMeans(n_clusters=3)
clusters = kmeans.fit_predict(X)
joblib.dump(kmeans, 'kmeans_model.joblib')
# Later, load models
loaded_vect = joblib.load('tfidf_vectorizer.joblib')
loaded_kmeans = joblib.load('kmeans_model.joblib')
X_new = loaded_vect.transform(df_new['University_clean'])
new_clusters = loaded_kmeans.predict(X_new)
Let me know if you want a full example using KMeans!