Modify this code so that I can define the aspects that I want to run on: """ import…
- User
Modify this code so that I can define the aspects that I want to run on:
""" import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from sentence_transformers import SentenceTransformer
""" This script provides a framework for analyzing group discussions. Uses sentence-transformer embeddings instead of TF-IDF + LSA. Calculates the aspects from: https://link.springer.com/article/10.3758/s13428-018-1102-z """
TODO decide if to implement a class for variable storage
SEED = 100 WINDOW = 10
OTHER_STOPWORDS = ["אך", "האם", "בה", "ויש", "דן", "חושבת", "באופן", "מלא", "לדעתי", "ניתן", "לכן" ]
class DiscussionAnalyzer: def init(self, data: pd.DataFrame, vectorizer: TfidfVectorizer, model_name: str = 'MPA/sambert', aspect: str = 'all', seed=100): """ Initialize the analyzer with the discussion data. Precompute TF-IDF, SVD, and caches for later use. """ self.data = data self.vectorizer = vectorizer self.authors = self.data['author'].unique().tolist() self.aspect = aspect self.seed = seed
# Initialize sentence transformer model self.model = SentenceTransformer(model_name) # Precompute sentence embeddings print(f"Computing sentence embeddings for {len(data)} contributions...") texts = data['text'].tolist() self.embeddings = self.model.encode(texts, show_progress_bar=True) self.n_components = self.embeddings.shape[1] # Embedding dimension print(f"Embeddings computed. Dimension: {self.n_components}") # Caches self.participation_cache = {} self.responsivity_cache = {} self.newness_cache = [0.0] * data.shape[0] # preallocate list self.compute_newness_cache() def get_embedding_vector(self, contribution_id: int) -> np.ndarray: """Return sentence embedding vector for a given contribution.""" return self.embeddings[contribution_id - 1] def calc_cosine_similarity(self, id1: int, id2: int) -> float: """Cosine similarity between two contributions.""" v1 = self.get_embedding_vector(id1).reshape(1, -1) v2 = self.get_embedding_vector(id2).reshape(1, -1) return float(cosine_similarity(v1, v2)[0, 0]) def get_participation(self, participant: str) -> dict: """ Cache and return participation sequence & score for a participant. Calculate participation score for a specific participant in a discussion. The logic: the discussion is split into contributions: c1, c2, ..., cn t is referred to as time: 1 <= t <= n k is the number of participants in the discussion. The participation function: p_a(t) = 1 if participant contributes at time t else 0 The participation function for a participant is the the sequence of contributions: p_a = (p_a(1), p_a(2), ..., p_a(n)) The number of contributions a participant makes is denoted as |p_a|, which is the sum of the sequence: |p_a| = p_a(1) + p_a(2) + ... + p_a(n) The sample mean participation of a participant is defined as: p_a_mean = |p_a| / n Eventually, the participation score is calculated as: participation_score = p_a_mean - 1/k """ if participant in self.participation_cache: return self.participation_cache[participant] authors = self.data['author'].tolist() n_contributions = len(authors) k = self.data['author'].nunique() # Create the participation sequence p_a for this participant # p_a(t) = 1 if participant contributes at time t, else 0 p_a = [1 if contributor == participant else 0 for contributor in authors] # Calculate |p_a| - total number of contributions by this participant p_total = sum(p_a) p_mean = p_total / n_contributions score = p_mean - (1 / k) result = {'participation_score': score, 'participation_seq': p_a} self.participation_cache[participant] = result return result def semantic_similarity(self, id1: int, id2: int) -> float: """ Semantic similarity with participation weighting. calculate the semantic similarity between two contributions: if contribution c_t was made by a and c_u was made by b: s_a,b(t, u) = p_a(t)*p_b(u)*cos(d_t, d_u) else: s_a,b(t, u) = 0 """ row1 = self.data.loc[self.data.contribution_id == id1].iloc[0] row2 = self.data.loc[self.data.contribution_id == id2].iloc[0] # Get participation sequence values p1 = self.get_participation(row1.author)['participation_seq'][id1 - 1] p2 = self.get_participation(row2.author)['participation_seq'][id2 - 1] return p1 * p2 * self.calc_cosine_similarity(id1, id2) def communication_density(self, cont_idx: int) -> float: """ Communication density for a single contribution. Calculate the communication density for a single contribution at a given time point. Use tf-idf vectorizer to get the vector for the contribution. Defined as: d(c_t) = || lsa_vector(c_t) || / || c_t || """ text = self.data.iloc[cont_idx]['text'] # Get the current contribution vector and text cur_tfidf = self.vectorizer.transform([text]) # the th-idf vector norm is a proxy for semantic richness vector_norm = np.linalg.norm(cur_tfidf.toarray()) word_count = len(text.split()) # TODO decide if to use norm or sum # Use sum instead of norm - this gives larger values tfidf_sum = cur_tfidf.sum() return float(vector_norm / word_count) if word_count > 0 else 0.0 def calc_cross_cohesion_matrix(self, lag: int) -> list[list[float]]: """ computes the cross-cohesion matrix for a given lag of the discussion. The element in row i and column j is the cross-cohesion value for authors i and j. For two authors a and b, the cross-cohesion value a lag Tao is defined as: c_cohesion_a,b(Tao) = (sim_a_b(1,Tao+1) + sim_a_b(2,Tao+2) + ... + sim_a_b(n-Tao, n))/norm(p_ab(Tao)) and norm(p_ab(Tao)) is defined as the sum: p_a(1)p_b(Tao+1) + p_a(2)p_b(Tao+2) + ... + p_a(n-Tao)p_b(n) :return: the cross-cohesion matrix and the list of contributors (authors) in the discussion """ # TODO test this function with real data num_contributions = len(self.data) num_authors = len(self.authors) res = np.zeros((num_authors, num_authors)) # Iterate over all pairs of authors and fill the matrix for i, a in enumerate(self.authors): for j, b in enumerate(self.authors): numerator = 0.0 norm_p_ab = 0.0 for t in range(lag, num_contributions): # contributions indexed by position c_prev = self.data.iloc[t - lag] c_curr = self.data.iloc[t] # only consider contributions by a (at t-lag) and b (at t) if c_prev.author == a and c_curr.author == b: # p_a(t-lag) * p_b(t) is guaranteed to be 1 here sim = self.calc_cosine_similarity(c_prev.contribution_id, c_curr.contribution_id) numerator += sim norm_p_ab += 1 # since p_a* p_b = 1 in this case # Assign cross-cohesion value res[i, j] = numerator / norm_p_ab if norm_p_ab > 0 else 0.0 return res def calc_responsivity(self, window: int) -> list[list[float]]: """ Responsivity across a time window is defined (eq. 17 in the paper) as: R(w) = (cross_cohesion_m(1) + cross_cohesion_m(2) + ... + cross_cohesion_m(w))/w :return: """ # if already computed for this window, return cached value if window in self.responsivity_cache: return self.responsivity_cache[window] return self._compute_responsivity(window) def calculate_internal_cohesion(self, participant: str, window: int) -> float: """ Internal cohesion = diagonal value R_aa(w) from responsivity matrix R(w), averaged across all lags up to w. Args: discussion_data: DataFrame containing the discussion data participant: The participant ID/name Returns: float: Internal cohesion score :param participant: :param window: """ # Get the cross-cohesion matrix responsivity_matrix = self.calc_responsivity(window) author_idx = self.authors.index(participant) return responsivity_matrix[author_idx][author_idx] def calculate_overall_responsivity(self, participant: str, window: int) -> float: """ Calculate overall responsivity score for a specific participant in a discussion. First, we need the responsivity matrix for the discussion. Then we take the mean of the row corresponding to the participant. Args: participant: The participant ID/name discussion_id: The discussion ID Returns: float: Overall responsivity score :param participant: :param window: """ res_matrix = self.calc_responsivity(window) total_res = 0 participant_idx = self.authors.index(participant) for i in range(len(self.authors)): if i != participant_idx: # exclude self total_res += res_matrix[participant_idx][i] return total_res / (len(self.authors) - 1) if len(self.authors) > 1 else 0.0 def calculate_social_impact(self, participant: str, window: int) -> float: """ Calculate social impact score for a specific participant in a discussion. By averaging over the colum vector of the responsivity matrix R(w) corresponding to the all other participants. impact_a(w) = (R_1a(w) + R_2a(w) + ... + R_ka(w)) / (k-1) Args: participant: The participant ID/name discussion_id: The discussion ID Returns: float: Social impact score :param participant: :param window: """ # Get the cross-cohesion matrix and authors responsivity_matrix = self.calc_responsivity(window) author_idx = self.authors.index(participant) # Calculate social impact as average of column corresponding to this participant total_impact = 0.0 num_participants = len(self.authors) for i in range(len(self.authors)): if i != author_idx: # exclude self total_impact += responsivity_matrix[i][author_idx] return total_impact / (num_participants - 1) if num_participants > 1 else 0.0 def analyze_participants(self) -> list[dict[str, float]]: results = [] # Iterate over each participant in the discussion for participant in self.authors: print(f" - Analyzing participant: {participant}") # Calculate all metrics for this participant in this discussion if self.aspect == 'all': participation_score = self.get_participation(participant)['participation_score'] responsivity_score = self.calculate_overall_responsivity(participant, window=WINDOW) # TODO window size? cohesion_score = self.calculate_internal_cohesion(participant, window=WINDOW) social_impact_score = self.calculate_social_impact(participant, window=WINDOW) newness_score = self.calculate_newness(participant) density_score = self.calc_overall_communication_density(participant) else: ** HERE ** # Store results results.append({ 'discussion_id': self.data['discussion'].iloc[0], 'participant': participant, 'participation_score': participation_score, 'overall_responsivity_score': responsivity_score, 'internal_cohesion_score': cohesion_score, 'social_impact_score': social_impact_score, 'newness_score': newness_score, 'communication_density_score': density_score }) return results def _compute_responsivity(self, window): num_authors = len(self.authors) res_matrix = [[0.0 for _ in range(num_authors)] for _ in range(num_authors)] # Calculate cross-cohesion for each lag from 1 to window # Sum over lags for tau in range(1, window + 1): cross_cohesion_m = self.calc_cross_cohesion_matrix(lag=tau) for i in range(num_authors): for j in range(num_authors): res_matrix[i][j] += cross_cohesion_m[i][j] # Average over w for i in range(num_authors): for j in range(num_authors): res_matrix[i][j] /= window self.responsivity_cache[window] = res_matrix return res_matrix def calculate_newness(self, participant): """ The newness score for a participant is the average newness of their contributions. :param participant: :return: """ participation_seq = self.get_participation(participant)['participation_seq'] total_newness = 0.0 for i, p in enumerate(participation_seq): total_newness += p * self.newness_cache[i] return total_newness / sum(participation_seq) if sum(participation_seq) > 0 else 0.0 def compute_newness_cache(self): """ For each contribution in the discussion, compute and cache its newness score. This is done once during initialization to avoid redundant calculations later. The newness of a contribution at time t is defined by computing the semantic similarity of the current contribution with each previous contribution, and then taking the maximum similarity. The similarity is then normalized to [0, 1] using: S_norm = (sim_max + 1)/2 The newness score is then: n(c_t) = (1-S_norm)^2 :return: """ contributions = self.data['text'].tolist() for i, cont in enumerate(contributions): if i == 0: # First contribution has no previous contributions, assign max newness newness = 1.0 else: max_sim = -1.0 for j in range(i): sim = self.calc_cosine_similarity(i + 1, j + 1) if sim > max_sim: max_sim = sim # Normalize similarity to [0, 1] sim_norm = (max_sim + 1) / 2 newness = (1 - sim_norm) ** 1 # square to emphasize high newness self.newness_cache[i] = newness def calc_overall_communication_density(self, participant): """ Calculate the overall communication density for a participant. This is the average communication density of all contributions made by the participant. :param participant: :return: """ participation_seq = self.get_participation(participant)['participation_seq'] total_density = 0.0 for i, p in enumerate(participation_seq): if p == 1: density = self.communication_density(i) total_density += density return total_density / sum(participation_seq) if sum(participation_seq) > 0 else 0.0 - Assistant