Certainly! Below is a step-by-step example of how you can:
- Clean the
University column,
- Apply TF-IDF vectorization,
- Perform KMeans clustering,
- Assign cluster labels to the original DataFrame,
- And then predict cluster labels for new unseen data using the saved vectorizer and clustering model.
Step 1: Prepare your initial DataFrame
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
# Your initial data
data = {
'pid': [1, 1, 2, 2, 3, 3],
'University': [
'American Medical University ',
'Bejing Univ ',
'Berlin Unv ',
'American Medical University ',
None,
'Jakartha University'
]
}
df = pd.DataFrame(data)
print(df)
Step 2: Clean the University column and fill missing values
# Strip extra spaces and fill NaN with 'UNKNOWN'
df['University'] = df['University'].str.strip().fillna('UNKNOWN')
print(df)
Step 3: Apply TF-IDF vectorization to the University column
# Initialize TF-IDF Vectorizer
vectorizer = TfidfVectorizer()
# Fit_transform the University column and get TF-IDF features
X = vectorizer.fit_transform(df['University'])
Step 4: Perform KMeans clustering with 5 clusters
n_clusters = 5
kmeans = KMeans(n_clusters=n_clusters, random_state=42)
# Fit KMeans on TF-IDF features
kmeans.fit(X)
# Assign cluster labels to original DataFrame
df['cluster'] = kmeans.labels_
print(df)
Step 5: Predict cluster for a new data DataFrame
Suppose this is your new unseen data:
new_data = {
'pid': [4, 5],
'University': ['American Medical Univ', 'Bejing University'] # slightly different names
}
new_df = pd.DataFrame(new_data)
# Preprocess new data similar to training
new_df['University'] = new_df['University'].str.strip().fillna('UNKNOWN')
# Transform using the already-fitted TF-IDF vectorizer
X_new = vectorizer.transform(new_df['University'])
# Predict clusters using the fitted KMeans model
new_df['cluster'] = kmeans.predict(X_new)
print(new_df)
Full Script for reference:
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
# Original data
data = {
'pid': [1, 1, 2, 2, 3, 3],
'University': [
'American Medical University ',
'Bejing Univ ',
'Berlin Unv ',
'American Medical University ',
None,
'Jakartha University'
]
}
df = pd.DataFrame(data)
# Clean and preprocess
df['University'] = df['University'].str.strip().fillna('UNKNOWN')
# Vectorize using TF-IDF
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(df['University'])
# KMeans clustering
n_clusters = 5
kmeans = KMeans(n_clusters=n_clusters, random_state=42)
kmeans.fit(X)
# Assign cluster labels to df
df['cluster'] = kmeans.labels_
print("Original Data with clusters:")
print(df)
# New data
new_data = {
'pid': [4, 5],
'University': ['American Medical Univ', 'Bejing University']
}
new_df = pd.DataFrame(new_data)
new_df['University'] = new_df['University'].str.strip().fillna('UNKNOWN')
# Vectorize new data
X_new = vectorizer.transform(new_df['University'])
# Predict clusters
new_df['cluster'] = kmeans.predict(X_new)
print("\nNew Data with predicted clusters:")
print(new_df)
Notes:
- You can tune
TfidfVectorizer parameters (like ngram_range) depending on the data.
- The choice of 5 clusters is arbitrary here; you can adjust based on the problem.
- Missing values replaced by
'UNKNOWN' so vectorizer can handle missing data.
- This ensures cluster assignments remain consistent between train and new data.
Let me know if you want me to help do any additional steps or explain!