this is an example of outputfile csv Image Name,Keywords,Lemmatized Keywords,Clustered…
- User
this is an example of output_file csv Image Name,Keywords,Lemmatized Keywords,Clustered Keywords B002RAYVKG.jpg,"pot, green, potty training, bathroom, practical","pot, green, potty training, bathroom, practical","pot, green, potty training, bathroom, practical" B000JOOG9I.jpg,"stuffed animals, colorful, playing, indoor, happy","stuffed animals, colorful, playing, indoor, happy","battery, colorful, playing, indoor, happy" B002GP76K4.jpg,"baby bouncer, orange, swinging, home, relaxed","baby bouncer, orange, swinging, home, relaxed","baby bouncer, orange, swinging, home, relaxed" B006Y7OYPA.jpg,"toy, cute, organizing, home, organized","toy, cute, organizing, home, organized","toy, cute, organizing, home, organized" B0068AGA96.jpg,"chain, yellow, hanging, indoor, neutral","chain, yellow, hanging, indoor, neutral","battery, yellow, hanging, indoor, neutral"
i want to cluster the keywords in order to have AT MAX a certain threshold of keywords for each Keywords category.
you should pick the clustered keywords column, then extract the 5 sub columns (separated by commas). from the 5 sub columns: the first is the Object column, the second the Adjective, then 'Activity', 'Place', 'Feeling'.
what i want to obtain is an output file, where the Object Column, only contains for example, 50 UNIQUE keywords, then and Adjective column with 50 Unique Keywords and so on
ok this is my code:
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
------------------------------#
Setup
------------------------------#
Download NLTK data files (only need to run once)
nltk.download('wordnet')
nltk.download('omw-1.4')
Initialize the lemmatizer
lemmatizer = WordNetLemmatizer()
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.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
- Assistant