Here's the refactored and combined script that performs both the cleaning and clustering tasks in a clear, professional, and efficient manner, suitable for production deployment. The script uses command-line arguments for flexibility and includes detailed logging for better traceability.
import os
import csv
import re
import sys
import argparse
import logging
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 AgglomerativeClustering
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from nltk.corpus import wordnet as wn
from nltk.corpus import stopwords
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize the lemmatizer and ensure NLTK data is downloaded
lemmatizer = WordNetLemmatizer()
nltk.download('wordnet', quiet=True)
nltk.download('stopwords', quiet=True)
nltk.download('averaged_perceptron_tagger', quiet=True)
# Set of stopwords to filter out
stop_words = set(stopwords.words('english'))
def parse_arguments():
parser = argparse.ArgumentParser(description='Processing and clustering script')
parser.add_argument('--input_file', type=str, required=True, help='Path to the input CSV file')
parser.add_argument('--output_file', type=str, required=True, help='Path to save the cleaned output CSV file')
parser.add_argument('--model_type', type=str, choices=['word2vec', 'glove', 'fasttext'], default='glove', help='Type of word embedding model')
parser.add_argument('--model_path', type=str, required=True, help='Path to the word embedding model file')
parser.add_argument('--lemmatized_counts_output_file', type=str, required=True, help='Path to save lemmatized keyword counts')
parser.add_argument('--category_limit', type=int, default=50, help='Limit of keywords per category')
parser.add_argument('--frequency_threshold', type=int, default=10, help='Threshold for keyword frequency')
parser.add_argument('--num_clusters', type=int, default=5, help='Number of clusters for infrequent keywords')
parser.add_argument('--distance_threshold', type=float, help='Distance threshold for hierarchical clustering')
parser.add_argument('--remove_duplicates', action='store_true', help='Remove duplicates in clustered keywords per row')
parser.add_argument('--one_hot_encoded_file', type=str, required=True, help='Path to save one-hot encoded features')
parser.add_argument('--id_column', type=str, default='Image Name', help='Name of the ID column in the CSV')
parser.add_argument('--remove_extension', type=str, default='.jpg', help='Extension to remove from ID column')
args = parser.parse_args()
return args
def clean_csv(input_file, output_file):
total_row_count = 0 # Counter for total rows
empty_row_count = 0 # Counter for empty rows
na_count = 0 # Counter for occurrences of N/A and empty spaces
no_comma_count = 0 # Counter for rows without commas
no_comma_rows = [] # Store rows without commas for inspection
# Check if the input file exists
if not os.path.exists(input_file):
logger.error(f"The input file '{input_file}' does not exist.")
sys.exit(1)
# Read the entire content of the file
with open(input_file, 'r', newline='', encoding='utf-8') as infile:
content = infile.read()
# Remove newline characters inside quoted strings
content = re.sub(r'("\[.*?")\n', r'\1 ', content)
# Create a temporary cleaned content
temp_file_path = 'temp_cleaned.csv'
with open(temp_file_path, 'w', newline='', encoding='utf-8') as temp_file:
temp_file.write(content)
with open(temp_file_path, 'r', newline='', encoding='utf-8') as infile:
reader = csv.reader(infile)
# Skip the first line (header)
header = next(reader)
# Prepare to write to the output file
with open(output_file, 'w', newline='', encoding='utf-8') as outfile:
writer = csv.writer(outfile)
# Write the desired header to the output file
writer.writerow(['Image Name', 'Keywords'])
# Process each row
for row in reader:
total_row_count += 1 # Increment the total row counter
# Adjust the row processing to account for variable row lengths
if len(row) >= 2:
jpg_file = row[0]
keywords = extract_keywords(row[1])
# Count occurrences of "N/A" and empty spaces
na_count += keywords.count("N/A")
na_count += sum(1 for k in keywords if k.strip() == "")
# Check if the row is empty or contains only "N/A" or empty spaces
if not keywords or all(k.strip().upper() == 'N/A' or k.strip() == '' for k in keywords):
empty_row_count += 1
continue # Skip this row
# Concatenate the keywords into a single string
keywords_str = ', '.join(keywords)
# Replace multiple spaces with a comma and a single space
keywords_str = re.sub(r'\s{2,}', ', ', keywords_str)
# Check if the row has no commas
if ',' not in keywords_str:
no_comma_count += 1
no_comma_rows.append(f'{jpg_file},{keywords_str}')
# Log the result in the desired format
logger.debug(f'JPG File: {jpg_file}, Keywords: {keywords_str}')
# Write only the Image Name and Keywords to the output file
writer.writerow([jpg_file, keywords_str])
else:
# Handle the case where the row doesn't have enough columns
logger.warning(f"Row {total_row_count} does not have enough columns: {row}")
continue
# Remove the temporary file
if os.path.exists(temp_file_path):
os.remove(temp_file_path)
# Reopen the output file and clean it again
clean_output_file(output_file)
# Log the counts
logger.info(f"Total rows: {total_row_count}")
logger.info(f"Number of empty or N/A rows: {empty_row_count}")
logger.info(f"Occurrences of N/A (including empty spaces): {na_count}")
logger.info(f"Number of rows without commas: {no_comma_count}")
logger.info("Rows without commas:")
for row in no_comma_rows:
logger.info(row)
def extract_keywords(line):
# First, try to extract keywords between curly braces
keywords = re.findall(r'\{([^}]+)\}', line)
if keywords:
return keywords
# If no keywords found between curly braces, use the existing extraction logic
# Remove newline characters from the keywords section
line = line.replace('\n', ' ')
# Remove the labels for various formats
labels = ['Object', 'Adjective', 'Activity', 'Place', 'Feeling']
for label in labels:
line = re.sub(rf'(\[?{label}\]?[: -]?)', '', line, flags=re.IGNORECASE)
# Remove any '- ' (dash and space)
line = line.replace('- ', '')
# Remove single quotes around keywords
line = re.sub(r"'([^']+)'", r'\1', line)
# Remove any remaining brackets
line = line.replace('[', '').replace(']', '')
# Split keywords by commas and strip whitespace
keywords = [keyword.strip() for keyword in line.split(',')]
return keywords
def clean_output_file(output_file):
cleaned_rows = []
# Reopen the output file for reading
with open(output_file, 'r', newline='', encoding='utf-8') as infile:
reader = csv.reader(infile)
# Process each row to remove unwanted labels and characters
for row in reader:
jpg_file = row[0]
keywords_str = row[1]
# Remove any occurrences of labels
keywords_str = re.sub(r'(Object|Adjective|Activity|Place|Feeling)\s*', '', keywords_str, flags=re.IGNORECASE)
# Remove any '- ' (dash and space)
keywords_str = keywords_str.replace('- ', '')
# Remove single quotes around keywords
keywords_str = re.sub(r"'([^']+)'", r'\1', keywords_str)
# Replace multiple spaces with a comma and a single space
keywords_str = re.sub(r'\s{2,}', ', ', keywords_str)
# Add cleaned row to the list
cleaned_rows.append([jpg_file, keywords_str])
# Write the cleaned rows back to the output file
with open(output_file, 'w', newline='', encoding='utf-8') as outfile:
writer = csv.writer(outfile)
writer.writerows(cleaned_rows)
def lemmatize_keyword(keyword):
return lemmatizer.lemmatize(keyword.lower())
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:
logger.error("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)
logger.info(f"Lemmatized keyword counts saved to '{lemmatized_counts_output_file}'.")
return per_row_df, keyword_counts
def load_model(model_type, model_path):
if model_type == 'word2vec':
logger.info("Loading Word2Vec model. This may take a few minutes...")
model = KeyedVectors.load_word2vec_format(model_path, binary=True)
logger.info("Word2Vec model loaded successfully.")
elif model_type == 'glove':
logger.info("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.split()
word = values[0]
vector = np.asarray(values[1:], dtype='float32')
model[word] = vector
logger.info("GloVe model loaded successfully.")
elif model_type == 'fasttext':
logger.info("Loading FastText model. This may take a few minutes...")
model = FastText.load_fasttext_format(model_path)
logger.info("FastText model loaded successfully.")
else:
logger.error(f"Unsupported model type: {model_type}")
sys.exit(1)
return model
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
def cluster_infrequent_keywords(keywords, keyword_counts, model, model_type, num_clusters=5, distance_threshold=None):
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:
logger.debug(f"Vector not found for keyword: '{keyword}'")
if not vectors:
logger.warning("No valid vectors found for clustering.")
return {}
vectors = np.array(vectors)
# Perform Hierarchical Clustering with distance threshold
if distance_threshold is not None:
logger.info(f"Performing Agglomerative Clustering with distance_threshold={distance_threshold}")
clustering_model = AgglomerativeClustering(n_clusters=None, distance_threshold=distance_threshold)
else:
logger.info(f"Performing Agglomerative Clustering with n_clusters={num_clusters}")
clustering_model = AgglomerativeClustering(n_clusters=num_clusters)
labels = clustering_model.fit_predict(vectors)
# Organize keywords by clusters
clusters = defaultdict(list)
for label, keyword in zip(labels, valid_keywords):
clusters[label].append(keyword)
# Select the most frequent keyword in each cluster as the representative
representative_keywords = {}
for label, words in clusters.items():
most_frequent = max(words, key=lambda w: keyword_counts[w])
representative_keywords[label] = most_frequent
# Create a mapping from keyword to representative
keyword_to_representative = {}
for label, words in clusters.items():
rep = representative_keywords[label]
for word in words:
keyword_to_representative[word] = rep
return keyword_to_representative
def perform_clustering_with_threshold(keyword_counts, model, model_type, threshold=5, num_clusters=5, distance_threshold=None):
# Separate frequent and infrequent keywords
frequent_keywords = [kw for kw, count in keyword_counts.items() if count > threshold]
infrequent_keywords = [kw for kw, count in keyword_counts.items() if count <= threshold]
logger.info(f"Number of frequent keywords (> {threshold}): {len(frequent_keywords)}")
logger.info(f"Number of infrequent keywords (<= {threshold}): {len(infrequent_keywords)}")
# Keep frequent keywords as-is
clustered = {kw: kw for kw in frequent_keywords}
# Cluster infrequent keywords and map them to their representatives
if infrequent_keywords:
mapping = cluster_infrequent_keywords(
infrequent_keywords, keyword_counts, model, model_type,
num_clusters=num_clusters, distance_threshold=distance_threshold
)
clustered.update(mapping)
logger.info(f"Number of cluster representatives: {len(set(mapping.values()))}")
else:
logger.info("No infrequent keywords to cluster.")
return clustered
def categorize_and_count_clustered_keywords(per_row_df, Category_Limit=50):
category_keyword_counts = {'Object': Counter(), 'Adjective': Counter(), 'Activity': Counter(),
'Place': Counter(), 'Feeling': Counter()}
for idx, row in per_row_df.iterrows():
clustered_keywords = row['Clustered Keywords'].split(', ')
if len(clustered_keywords) > 0:
category_keyword_counts['Object'][clustered_keywords[0]] +=1
if len(clustered_keywords) > 1:
category_keyword_counts['Adjective'][clustered_keywords[1]] +=1
if len(clustered_keywords) > 2:
category_keyword_counts['Activity'][clustered_keywords[2]] +=1
if len(clustered_keywords) > 3:
category_keyword_counts['Place'][clustered_keywords[3]] +=1
if len(clustered_keywords) > 4:
category_keyword_counts['Feeling'][clustered_keywords[4]] +=1
# Limit to top N keywords per category
for category in category_keyword_counts:
category_keyword_counts[category] = Counter(dict(category_keyword_counts[category].most_common(Category_Limit)))
return category_keyword_counts
def generate_clustered_keywords_and_categories(per_row_df, clustered_keyword_mapping, category_keyword_counts, remove_duplicates=False):
top_keywords_per_category = {category: set(counts.keys()) for category, counts in category_keyword_counts.items()}
# Initialize lists for categories and counters for "Other"
categories = ['Object', 'Adjective', 'Activity', 'Place', 'Feeling']
category_keywords_list = {cat: [] for cat in categories}
clustered_keywords_list = []
# Initialize a counter for the number of rows with specific "Other" counts
other_count_rows = {i: 0 for i in range(6)} # assuming "Other" count ranges from 0 to 5
for idx, row in per_row_df.iterrows():
lemmatized_keywords = row['Lemmatized Keywords'].split(', ')
clustered_keywords = [clustered_keyword_mapping.get(kw, kw) for kw in lemmatized_keywords]
if remove_duplicates:
# Remove duplicates while preserving order
clustered_keywords = list(dict.fromkeys(clustered_keywords))
clustered_keywords_list.append(', '.join(clustered_keywords))
# Initialize "Other" counter for each row
row_other_count = 0
# Assign keywords to categories based on positions
for i, category in enumerate(categories):
if i < len(clustered_keywords):
keyword = clustered_keywords[i]
# Map to 'Other' if not in top keywords
if keyword not in top_keywords_per_category[category]:
keyword = 'Other'
row_other_count += 1 # Increase the row counter for "Other"
category_keywords_list[category].append(keyword)
else:
category_keywords_list[category].append('') # or 'Other'
# Count the number of rows with the specific number of "Other" keywords
if row_other_count <= 5:
other_count_rows[row_other_count] += 1
if row_other_count > 0:
logger.debug(f"{row['Image Name']}, {clustered_keywords}, {category_keywords_list['Object'][idx]} {category_keywords_list['Adjective'][idx]} {category_keywords_list['Activity'][idx]} {category_keywords_list['Feeling'][idx]} {category_keywords_list['Place'][idx]}, keywords: {row_other_count}")
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]
# Print summary of "Other" counts per category
other_count = {cat: 0 for cat in categories} # Counter for "Other" per category
logger.info("\nSummary of 'Other' counts per category:")
for category, keywords in category_keywords_list.items():
other_count[category] = sum(1 for keyword in keywords if keyword == 'Other')
logger.info(f"{category}: {other_count[category]}")
# Print the summary of rows having specific "Other" counts
logger.info("\nSummary of 'Other' count rows:")
for count in range(6):
logger.info(f"Rows with {count} 'Other' keywords: {other_count_rows[count]}")
return per_row_df
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)
# Ensure the directory exists
output_dir = os.path.dirname(output_tsv_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 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)
def main():
args = parse_arguments()
# Step 1: Clean the CSV file
clean_csv(args.input_file, args.output_file)
# Step 2: Lemmatize keywords and save lemmatized counts
per_row_df, keyword_counts = lemmatize_keywords(args.output_file, args.lemmatized_counts_output_file)
if per_row_df is None:
logger.error("Error in lemmatization step.")
sys.exit(1)
# Step 3: Load the desired word embedding model
model = load_model(args.model_type, args.model_path)
# Step 4: Perform clustering on infrequent keywords
clustered_keyword_mapping = perform_clustering_with_threshold(
keyword_counts, model, args.model_type,
threshold=args.frequency_threshold, num_clusters=args.num_clusters,
distance_threshold=args.distance_threshold
)
# Step 5: Generate 'Clustered Keywords' column
per_row_df['Clustered Keywords'] = per_row_df['Lemmatized Keywords'].apply(
lambda kws: ', '.join([clustered_keyword_mapping.get(kw, kw) for kw in kws.split(', ')])
)
# Step 6: Categorize and count clustered keywords
category_keyword_counts = categorize_and_count_clustered_keywords(per_row_df, Category_Limit=args.category_limit)
# Step 7: Generate clustered keywords per row and categorize with top keywords only
per_row_df = generate_clustered_keywords_and_categories(
per_row_df, clustered_keyword_mapping, category_keyword_counts, remove_duplicates=args.remove_duplicates
)
# Optionally, write category counts to CSV files
output_dir = os.path.dirname(args.one_hot_encoded_file)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
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 = os.path.join(output_dir, f'{category}_keywords_counts.csv')
category_counts_df.to_csv(category_counts_output_file, index=False)
logger.info(f"{category} keyword counts saved to '{category_counts_output_file}'.")
# Step 8: Write the output CSV
output_csv_file = args.one_hot_encoded_file.replace('_onehot.tsv', '.csv')
per_row_df.to_csv(output_csv_file, index=False)
logger.info(f"Process completed. Output saved to '{output_csv_file}'.")
logger.info(f"Lemmatized counts saved to '{args.lemmatized_counts_output_file}'.")
# Step 9: One-hot encode the categorical features
encode_categorical_features(
output_csv_file,
args.one_hot_encoded_file,
id_column=args.id_column,
remove_extension=args.remove_extension,
sep='\t', header=False, index=False
)
logger.info(f"One-hot encoded features saved to '{args.one_hot_encoded_file}'.")
if __name__ == "__main__":
main()
Instructions for Running the Script:
-
Ensure all dependencies are installed:
pip install nltk pandas gensim scikit-learn numpy
-
Provide the necessary arguments when running the script:
python script_name.py \
--input_file path/to/input.csv \
--output_file path/to/cleaned_output.csv \
--model_type glove \
--model_path path/to/glove.6B.300d.txt \
--lemmatized_counts_output_file path/to/lemmatized_counts.csv \
--one_hot_encoded_file path/to/onehot_output.tsv \
--category_limit 100 \
--frequency_threshold 10 \
--num_clusters 50 \
--distance_threshold None \
--remove_duplicates
Replace path/to/... with the actual paths and adjust parameters as needed.
Key Improvements:
- Parameterization: Used
argparse to make the script flexible and configurable via command-line arguments.
- Logging: Replaced
print statements with logging for better control over log levels and to provide more detailed tracing.
- Error Handling: Added checks and error messages for missing files and invalid conditions.
- Modularization: Organized the code into well-defined functions for better readability and maintainability.
- Efficiency: Avoided redundant computations and ensured data is processed efficiently, especially when handling large datasets and models.
- Compatibility: Ensured that paths and directories are handled correctly, creating directories when necessary.
- Comments and Documentation: Added comments and instructions to help understand how to use the script and what each part does.
Note: Ensure that the word embedding model file (model_path) is compatible with the model_type you've specified. Loading large models like GloVe or Word2Vec can consume significant memory, so make sure your system has enough resources.