write a python code fopr topic modelling using LSA where the results also gives the…
- User
write a python code fopr topic modelling using LSA where the results also gives the individual wights in particular documents take multiple documents in the data set(atleast 5) and the code shall be able to give the percentages of the discovered topics in each documents as a result.
- Assistant
Here's a Python code that demonstrates topic modeling using LSA (Latent Semantic Analysis) on a set of 5 documents. The code extracts topics and calculates the percentage of topics in each document:
import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import TruncatedSVD # Prepare the dataset documents = [ "The apple is a sweet red fruit.", "Oranges are a citrus fruit with a sour taste.", "Bananas are tropical fruits with a sweet taste.", "I love going to the fruit market to buy fresh fruits.", "Fruit salads are a delicious way to enjoy different types of fruits." ] # Create the Document-Term Matrix vectorizer = CountVectorizer(stop_words='english') doc_term_matrix = vectorizer.fit_transform(documents) # Perform LSA num_topics = 2 lsa = TruncatedSVD(n_components=num_topics) lsa.fit(doc_term_matrix) # Calculate the percentage of topics in each document topic_percentages = lsa.transform(doc_term_matrix) topic_percentages_normalized = topic_percentages / np.sum(topic_percentages, axis=1, keepdims=True) topic_percentages_normalized *= 100 # Display the topics terms = vectorizer.get_feature_names_out() for i, comp in enumerate(lsa.components_): terms_comp = zip(terms, comp) sorted_terms = sorted(terms_comp, key=lambda x: x[1], reverse=True)[:7] print(f"Topic {i}:") for t in sorted_terms: print(f"{t[0]}: {t[1]:.4f}") print("\nPercentages of topics in each document:") for i, percentages in enumerate(topic_percentages_normalized): print(f"Document {i}:") for j, percentage in enumerate(percentages): print(f"Topic {j}: {percentage:.2f}%") print()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.