Yes, I can help modify your code to cluster each category into exactly 50 unique keywords, ensuring that each category has exactly 50 labels. This will be done by clustering the keywords per category, rather than applying a frequency threshold and then limiting the top keywords.
Here's how we'll approach this:
-
Remove the initial frequency thresholding and clustering. We'll skip the step where you apply a frequency threshold and cluster infrequent keywords.
-
Collect keywords per category. We'll collect all the keywords that appear in each category (based on their positions in the lemmatized keywords list).
-
Cluster the keywords per category into exactly 50 clusters. For each category, we'll cluster its keywords into 50 clusters using KMeans clustering.
-
Map the keywords to their cluster representatives. We'll select a representative keyword for each cluster (e.g., the closest keyword to the cluster centroid) and map all keywords in the cluster to this representative.
-
Update the DataFrame with the new category labels. We'll replace the original keywords in each category with their cluster representatives.
Below is the modified code to achieve this:
import csv
import re
import os
import nltk
import pandas as pd
from collections import defaultdict, Counter
from nltk.stem import WordNetLemmatizer
from gensim.models import KeyedVectors, FastText
from sklearn.cluster import KMeans, AgglomerativeClustering
import numpy as np
from sklearn.preprocessing import OneHotEncoder
# ------------------------------#
# Setup #
# ------------------------------#
# Initialize the lemmatizer
lemmatizer = WordNetLemmatizer()
# Import for POS tagging
from nltk import pos_tag, word_tokenize
from nltk.corpus import wordnet as wn
from nltk.corpus import stopwords
# Set of stopwords to filter out
stop_words = set(stopwords.words('english'))
# Function to get WordNet POS tag from treebank tag
def get_wordnet_pos(treebank_tag):
if treebank_tag.startswith('J'):
return wn.ADJ # Adjective
elif treebank_tag.startswith('V'):
return wn.VERB # Verb
elif treebank_tag.startswith('N'):
return wn.NOUN # Noun
elif treebank_tag.startswith('R'):
return wn.ADV # Adverb
else:
return None
# Function to load the appropriate word embedding model
def load_model(model_type, model_path):
if model_type == 'word2vec':
print("Loading Word2Vec model. This may take a few minutes...")
model = KeyedVectors.load_word2vec_format(model_path, binary=True)
print("Word2Vec model loaded successfully.")
elif model_type == 'glove':
print("Loading GloVe model. This may take a few minutes...")
model = {}
with open(model_path, 'r', encoding='utf-8') as f:
for line in f:
values = line.strip().split()
word = values[0]
vector = np.asarray(values[1:], dtype='float32')
model[word] = vector
print("GloVe model loaded successfully.")
elif model_type == 'fasttext':
print("Loading FastText model. This may take a few minutes...")
model = FastText.load_fasttext_format(model_path)
print("FastText model loaded successfully.")
else:
raise ValueError(f"Unsupported model type: {model_type}")
return model
# Function to get the vector for a word/phrase
def get_word_vector(word, model, model_type):
if model_type in ['word2vec', 'fasttext']:
if word in model:
return model[word]
elif model_type == 'glove':
if word in model:
return model[word]
# Handle multi-word phrases by averaging their word vectors
words = word.split()
vectors = []
for w in words:
if model_type in ['word2vec', 'fasttext'] and w in model:
vectors.append(model[w])
elif model_type == 'glove' and w in model:
vectors.append(model[w])
if vectors:
return np.mean(vectors, axis=0)
else:
return None
# Function to lemmatize a keyword
def lemmatize_keyword(keyword):
return lemmatizer.lemmatize(keyword.lower())
# Function to process the CSV file and lemmatize keywords per row, and output lemmatized counts
def lemmatize_keywords(input_file, lemmatized_counts_output_file):
# Read the CSV file using pandas
df = pd.read_csv(input_file)
# Ensure 'Image Name' and 'Keywords' columns exist
if 'Image Name' not in df.columns or 'Keywords' not in df.columns:
print("Error: 'Image Name' and 'Keywords' columns not found in input CSV.")
return None, None
per_row_data = []
keyword_counts = Counter()
# Iterate through each row to extract and lemmatize keywords
for index, row in df.iterrows():
image_name = row.get('Image Name', '')
keywords_str = row.get('Keywords', '')
if pd.isna(keywords_str):
keywords_str = ''
# Split keywords by comma and strip whitespace
extracted_keywords = [kw.strip() for kw in keywords_str.split(',')]
# Lemmatize keywords
lemmatized_keywords = [lemmatize_keyword(kw) for kw in extracted_keywords if kw]
# Update global counts
keyword_counts.update(lemmatized_keywords)
# Store per-row data
per_row_data.append({
'Image Name': image_name,
'Keywords': ', '.join(extracted_keywords),
'Lemmatized Keywords': ', '.join(lemmatized_keywords)
})
# Create a DataFrame from per_row_data
per_row_df = pd.DataFrame(per_row_data)
# Write the lemmatized keyword counts to CSV
lemmatized_counts = [{'Lemmatized Keyword': kw, 'Count': count}
for kw, count in keyword_counts.items()]
lemmatized_counts_df = pd.DataFrame(lemmatized_counts)
# Sort by Count in descending order
lemmatized_counts_df = lemmatized_counts_df.sort_values(by='Count', ascending=False)
# Write to CSV
lemmatized_counts_df.to_csv(lemmatized_counts_output_file, index=False)
print(f"Lemmatized keyword counts saved to '{lemmatized_counts_output_file}'.")
return per_row_df, keyword_counts
# Function to collect keywords per category
def collect_category_keywords(per_row_df):
categories = ['Object', 'Adjective', 'Activity', 'Place', 'Feeling']
category_keywords = {cat: [] for cat in categories}
for idx, row in per_row_df.iterrows():
lemmatized_keywords = row['Lemmatized Keywords'].split(', ')
for i, keyword in enumerate(lemmatized_keywords):
if i < len(categories):
category_keywords[categories[i]].append(keyword)
# Convert to sets to get unique keywords per category
category_unique_keywords = {cat: set(kw_list) for cat, kw_list in category_keywords.items()}
return category_unique_keywords
# Function to cluster keywords per category into 50 clusters
def cluster_keywords_per_category(category_keywords, model, model_type, n_clusters=50):
category_cluster_mappings = {}
for category, keywords in category_keywords.items():
# Get embeddings for the keywords
vectors = []
valid_keywords = []
for keyword in keywords:
vector = get_word_vector(keyword, model, model_type)
if vector is not None:
vectors.append(vector)
valid_keywords.append(keyword)
else:
print(f"Vector not found for keyword: '{keyword}' in category '{category}'")
if not vectors:
print(f"No valid vectors found for clustering in category '{category}'.")
continue
vectors = np.array(vectors)
# Remove duplicates
unique_keywords, unique_indices = np.unique(valid_keywords, return_index=True)
unique_vectors = vectors[unique_indices]
# Perform clustering
if len(unique_keywords) <= n_clusters:
# Not enough keywords to cluster, assign each keyword to its own cluster
labels = np.arange(len(unique_keywords))
else:
clustering_model = KMeans(n_clusters=n_clusters, random_state=42)
labels = clustering_model.fit_predict(unique_vectors)
# Map keywords to cluster labels
clusters = defaultdict(list)
for label, keyword in zip(labels, unique_keywords):
clusters[label].append(keyword)
# Select representative keyword for each cluster
representative_keywords = {}
for label, words in clusters.items():
# Choose the word closest to the cluster centroid
cluster_vectors = np.array([get_word_vector(w, model, model_type) for w in words])
centroid = cluster_vectors.mean(axis=0)
distances = np.linalg.norm(cluster_vectors - centroid, axis=1)
min_idx = np.argmin(distances)
representative_word = words[min_idx]
representative_keywords[label] = representative_word
# Map each keyword to its representative
keyword_to_representative = {}
for label, words in clusters.items():
rep = representative_keywords[label]
for word in words:
keyword_to_representative[word] = rep
category_cluster_mappings[category] = keyword_to_representative
return category_cluster_mappings
# Function to generate clustered keywords and categories based on per-category cluster mappings
def generate_clustered_keywords_and_categories(per_row_df, category_cluster_mappings):
categories = ['Object', 'Adjective', 'Activity', 'Place', 'Feeling']
category_keywords_list = {cat: [] for cat in categories}
clustered_keywords_list = []
for idx, row in per_row_df.iterrows():
lemmatized_keywords = row['Lemmatized Keywords'].split(', ')
clustered_keywords = []
for i, category in enumerate(categories):
if i < len(lemmatized_keywords):
keyword = lemmatized_keywords[i]
# Map the keyword to its cluster representative
keyword_mappings = category_cluster_mappings.get(category, {})
represented_keyword = keyword_mappings.get(keyword, keyword)
clustered_keywords.append(represented_keyword)
category_keywords_list[category].append(represented_keyword)
else:
clustered_keywords.append('')
category_keywords_list[category].append('')
clustered_keywords_list.append(', '.join(clustered_keywords))
per_row_df['Clustered Keywords'] = clustered_keywords_list
# Add the category columns to per_row_df
for category in categories:
per_row_df[category] = category_keywords_list[category]
return per_row_df
# Function to one-hot encode the categorical features
def encode_categorical_features(input_csv_path, output_tsv_path, id_column='Image Name', remove_extension='.jpg', sep='\t', header=False, index=False):
# Read only the necessary columns to improve efficiency
columns_to_encode = ['Object', 'Adjective', 'Activity', 'Place', 'Feeling']
columns_to_read = [id_column] + columns_to_encode
df = pd.read_csv(input_csv_path, usecols=columns_to_read)
# Initialize OneHotEncoder with dtype set to integer to output int values
enc = OneHotEncoder(handle_unknown='ignore', dtype=np.int8)
# Fit and transform the categorical columns
emb = enc.fit_transform(df[columns_to_encode])
# Retrieve the names of the one-hot encoded features
feature_names = enc.get_feature_names_out(columns_to_encode)
# Create a DataFrame with the encoded features and ensure they are integers
emb_df = pd.DataFrame(emb.toarray(), columns=feature_names, dtype=np.int8)
# Concatenate the id_column with the one-hot encoded features
result_df = pd.concat([df[[id_column]], emb_df], axis=1)
# Remove specified extension from id_column
if remove_extension:
result_df[id_column] = result_df[id_column].str.replace(remove_extension, '', regex=False)
# Save the final DataFrame to a TSV file without headers and index
result_df.to_csv(output_tsv_path, index=index, header=header, sep=sep)
# ------------------------------#
# Main #
# ------------------------------#
def main():
# File paths (replace these with your actual file paths)
original_input_file = '/home/danilo/Projects/IR_MD/cleaned_/home/danilo/Projects/IR_MD/cleaned_/home/danilo/Projects/IR_MD/TESTING/cleaned_graffe_better_prompt_KeyExt_Qwen2VL7B_20240912-131955_.csv'
lemmatized_counts_output_file = '/home/danilo/Projects/IR_MD/TESTING/keywords_lemmatized_counts.csv'
# Clustering parameters
model_type = 'glove' # Choose from 'word2vec', 'glove', 'fasttext'
model_path = '/home/danilo/Projects/IR_MD/models/glove.6B.300d.txt' # Path to the model file
n_clusters_per_category = 50 # Number of clusters per category
# Step 1: Lemmatization and saving lemmatized counts
per_row_df, keyword_counts = lemmatize_keywords(original_input_file, lemmatized_counts_output_file)
if per_row_df is None:
return # Exit if there was an error
# Step 2: Load the appropriate model
model = load_model(model_type, model_path)
# Step 3: Collect keywords per category
category_keywords = collect_category_keywords(per_row_df)
# Step 4: Cluster keywords per category into exactly 50 clusters
category_cluster_mappings = cluster_keywords_per_category(
category_keywords, model, model_type, n_clusters=n_clusters_per_category
)
# Step 5: Generate clustered keywords and categories
per_row_df = generate_clustered_keywords_and_categories(per_row_df, category_cluster_mappings)
# Step 6: Collect counts per category (optional)
category_keyword_counts = {}
for category in category_keywords:
counts = Counter(per_row_df[category])
category_keyword_counts[category] = counts
# Print counts for each category
for category, counts in category_keyword_counts.items():
print(f"\nCategory: {category}")
for keyword, count in counts.items():
print(f"{keyword}: {count}")
# Optionally, write category counts to CSV files
for category, counts in category_keyword_counts.items():
category_counts_df = pd.DataFrame({'Keyword': list(counts.keys()), 'Count': list(counts.values())})
category_counts_df = category_counts_df.sort_values(by='Count', ascending=False)
category_counts_output_file = f'/home/danilo/Projects/IR_MD/TESTING/{category}_keywords_counts.csv'
category_counts_df.to_csv(category_counts_output_file, index=False)
print(f"\n{category} keyword counts saved to '{category_counts_output_file}'.")
# Step 7: Construct the output file name dynamically
output_file = f'/home/danilo/Projects/IR_MD/TESTING/{n_clusters_per_category}ClustersPerCategory_keywords_clustered.csv'
# Step 8: Write the output CSV
per_row_df.to_csv(output_file, index=False)
print(f"\nProcess completed. Output saved to '{output_file}'.")
print(f"Lemmatized counts saved to '{lemmatized_counts_output_file}'.")
# Step 9: One-hot encode the categorical features
one_hot_encoded_file = f'/home/danilo/Projects/IR_MD/TESTING/{n_clusters_per_category}ClustersPerCategory_keywords_clustered_onehot.csv'
encode_categorical_features(output_file, one_hot_encoded_file, id_column='Image Name', remove_extension='.jpg', sep=',', header=False, index=False)
print(f"\nOne-hot encoded features saved to '{one_hot_encoded_file}'.")
if __name__ == "__main__":
main()
Explanation of Modifications:
-
Removed Frequency Thresholding and Initial Clustering:
- The functions
perform_clustering_with_threshold and cluster_infrequent_keywords are no longer needed and have been removed.
- We no longer apply a frequency threshold or cluster the infrequent keywords.
-
Added Function collect_category_keywords:
- This function collects all the keywords per category based on their positions in the lemmatized keywords list.
-
Modified Function cluster_keywords_per_category:
- This function clusters the keywords per category into exactly 50 clusters.
- It uses KMeans clustering to cluster the embeddings of the keywords.
- For each cluster, it selects a representative keyword (closest to the cluster centroid).
- It maps each keyword to its cluster representative.
-
Modified Function generate_clustered_keywords_and_categories:
- This function uses the category-specific cluster mappings to generate the clustered keywords and category labels for each row.
- Each keyword in a category is replaced with its cluster representative.
-
Updated the Main Function:
- Reflects the changes in the workflow to perform category-specific clustering into exactly 50 clusters.
- Adjusted steps to align with the new functions and logic.
Note:
Result:
- Each category now has exactly 50 unique keywords (cluster representatives).
- The clustering is performed only once per category.
- Keywords in each category are replaced with their cluster representatives.
Output Files:
-
Clustered Keywords CSV:
- The output CSV contains the
Clustered Keywords column and category columns with the cluster representatives.
- Saved as
.../50ClustersPerCategory_keywords_clustered.csv.
-
Category Counts CSV:
- Counts of keywords per category are saved in separate CSV files for analysis.
-
One-Hot Encoded CSV:
- The categorical features are one-hot encoded and saved as
.../50ClustersPerCategory_keywords_clustered_onehot.csv.
Example Usage:
- Run the script as is, ensuring all file paths and parameters are correctly set.
- The script will process your input CSV, perform category-specific clustering, and generate the outputs.
Let me know if you need further assistance or adjustments to the code.