Convert thich funtion to one the uses a helper function "getembedding" which returns the…
- User
Convert thich funtion to one the uses a helper function "get_embedding" which returns the td-idf and svd dimention reduction of a given text.
implement the helper.
""" def calc_cos(contribution_1: str, contribution_2: str) -> float: """ Calculate the cosine similarity between two contributions.
Args: contribution_1: The first contribution text contribution_2: The second contribution text Returns: float: Cosine similarity score between the two contributions """ vectorizer = TfidfVectorizer() # todo can add Hebrew stopwords or other preprocessing if needed tfidf_matrix = vectorizer.fit_transform([contribution_1, contribution_2]) # Optional: reduce dimensionality with SVD (LSA) if tfidf_matrix.shape[1] > 100: # only if high-dimensional svd = TruncatedSVD(n_components=100, random_state=SEED) reduced = svd.fit_transform(tfidf_matrix) sim = cosine_similarity(reduced)[0, 1] else: sim = cosine_similarity(tfidf_matrix)[0, 1] return float(sim)"""
- Assistant
Sure! I can refactor your code to use a helper function get_embedding which will return the TF-IDF vector (optionally reduced via SVD). Here's a clean implementation: pythonCopyEditfrom sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import TruncatedSVD from sklearn.metrics.pairwise import cosine_similarity import numpy as np
SEED = 42 # for reproducibility
def get_embedding(text: str, svd_components: int = 100) -> np.ndarray: """ Returns the TF-IDF vector of a text, optionally reduced using SVD.
- User
yes
- Assistant
Perfect! We can refactor get_embedding to take a list of texts and return embeddings for all of them at once. This way the TF-IDF vectorizer is fit once, and SVD is applied once if needed. Here's the updated version: pythonCopyEditfrom sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import TruncatedSVD from sklearn.metrics.pairwise import cosine_similarity import numpy as np
- User
Does this align with the paper's definitions?
def calculate_newness(discussion_data: pd.DataFrame, participant: str) -> float: """ Calculate newness score for a specific participant in a discussion - First calculate the participant's contribution probabilities, then calculate the newness of each contribution, and finally average the newness scores weighted by the probabilities.
Average over all the given-new scores of this participant's contributions: newness(a) = (p_a(1)*new(c_1) + p_a(2)*new(c_2) + ... + p_a(n)*new(c_n)) / norm_p_a Args: discussion_data: DataFrame containing the discussion data participant: The participant ID/name Returns: float: Newness score """ # Get the participation sequence for this participant participation_data = calculate_participation(discussion_data, participant) participation_seq = participation_data['participation_seq'] norm_p_a = sum(participation_seq) if norm_p_a == 0: return 0.0 newness_scores = [] for time, p_a_t in enumerate(participation_seq, start=1): if p_a_t > 0: newness_score = new_semantic_content(discussion_data, time) newness_scores.append(p_a_t * newness_score) else: newness_scores.append(0.0) # Calculate the weighted average of newness scores newness_score = sum(newness_scores) / norm_p_a if norm_p_a > 0 else 0.0 return newness_score - Assistant
- User
ok
- Assistant
Here’s a cleaner, fully vectorized version of your calculate_newness function using pandas. It avoids the explicit loop, handles zero contributions naturally, and aligns with your formula: pythonCopyEditdef calculate_newness(discussion_data: pd.DataFrame, participant: str) -> float: """ Calculate newness score for a specific participant in a discussion.
Weighted average of contribution newness, using participant probabilities. Args: discussion_data: DataFrame containing the discussion data participant: The participant ID/name Returns: float: Newness score """ # Get participation probabilities participation_data = calculate_participation(discussion_data, participant) participation_seq = participation_data['participation_seq'] norm_p_a = participation_seq.sum() if norm_p_a == 0: return 0.0 # Calculate newness for each contribution # Vectorized version using apply or list comprehension newness_scores = participation_seq.index.to_series().apply( lambda t: new_semantic_content(discussion_data, t) ) # Weighted average weighted_newness = (participation_seq * newness_scores).sum() / norm_p_a return float(weighted_newness)