computationalanalysissocial_roles.pdfPDFI'm creating a replicant of this paper on my own…
- User
computational_analysis_social_roles.pdfPDFI'm creating a replicant of this paper on my own data. Which Python library can I use to calculate the cosine similarity of two contributions? Is this simple tf-idf?
- Assistant
Yes — for replicating the method in that paper, you can use cosine similarity on tf-idf vectors of contributions. Here’s how it fits together:
The paper uses Latent Semantic Analysis (LSA), which is built on tf-idf.
Each contribution is represented as a vector (from tf-idf, or after dimensionality reduction with SVD in LSA).
Cosine similarity is then calculated between these vectors to measure the semantic similarity of contributions .
In Python, you have a couple of standard library choices:
scikit-learn
TfidfVectorizer to get tf-idf vectors.
cosine_similarity from sklearn.metrics.pairwise to compute similarity.
TruncatedSVD if you want to replicate the LSA step used in the paper.
pythonCopyEditfrom sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from sklearn.decomposition import TruncatedSVD
- User
Yes
- Assistant
Perfect 👍 — let’s build a step-by-step Python workflow that follows the approach in the paper:
🔹 Workflow: Replicating Contribution Similarity (like in the paper) We’ll go through:
Preprocessing text
TF-IDF vectorization
LSA (dimensionality reduction with SVD)
- User
- Assistant
- User
No. Im ready to implement this:
def calc_cross_cohesion_matrix(discussion_data: pd.DataFrame) -> tuple[list[list[float]], list[str]]: """ 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 """ - Assistant
- User
I'm struggeling with equation 17, what are the dimentions of R(w)?
Here is what I started:
def calc_responsivity(discussion_data: pd.DataFrame, window: int) -> dict[str, float]: """ Responsivity across a time window is defined: R(w) = (cross_cohesion_m(1) + cross_cohesion_m(2) + ... + cross_cohesion_m(w))/w :return: """
- Assistant
Got it — in the paper, equation (17) defines responsivity as the average cross-cohesion over a time window www. Let’s break this down carefully:
- Dimensions of R(w)R(w)R(w)
- User
Is this correct?
""" def calculate_overall_responsivity(discussion_data: pd.DataFrame, 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: discussion_data: DataFrame containing the discussion data participant: The participant ID/name discussion_id: The discussion ID Returns: float: Overall responsivity score :param discussion_data: :param participant: :param window: """ authors = discussion_data['author'].unique().tolist() res_matrix = calc_responsivity(discussion_data, window) total_res = 0 participant_idx = authors.index(participant) for i in range(1, len(authors) + 1): if not authors[i] == participant: total_res += res_matrix[participant_idx][authors[i]] return total_res / (len(authors) - 1) if len(authors) > 1 else 0.0"""
- Assistant
You’re really close, but there are two small issues in your code:
calc_responsivity returns a tuple: (matrix, authors), so you need to unpack it correctly.
Inside the loop, authors[i] is a string, but res_matrix is indexed numerically, so you should iterate by index, not author name.
Here’s the fixed version: pythonCopyEditdef calculate_overall_responsivity( discussion_data: pd.DataFrame, participant: str, window: int ) -> float: """ Calculate overall responsivity score for a specific participant in a discussion. Overall responsivity = mean of row values (excluding self) from R(w) matrix. """ res_matrix, authors = calc_responsivity(discussion_data, window) participant_idx = authors.index(participant) k = len(authors)
total_res = 0.0 count = 0 for j in range(k): if j != participant_idx: # exclude self total_res += res_matrix[participant_idx][j] count += 1 return total_res / count if count > 0 else 0.0✅ Why this works
res_matrix[participant_idx][j] = responsivity of participant → author j
Looping over all authors except self
Mean over row values = overall responsivity score
- User
And now?
def calculate_overall_responsivity(discussion_data: pd.DataFrame, 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: discussion_data: DataFrame containing the discussion data participant: The participant ID/name discussion_id: The discussion ID Returns: float: Overall responsivity score :param discussion_data: :param participant: :param window: """ res_matrix, authors = calc_responsivity(discussion_data, window) total_res = 0 participant_idx = authors.index(participant) for i in range(len(authors)): if not i == participant_idx: # exclude self total_res += res_matrix[participant_idx][authors[i]] return total_res / (len(authors) - 1) if len(authors) > 1 else 0.0 - Assistant
You're really close again, but the issue is in this line: pythonCopyEdittotal_res += res_matrix[participant_idx][authors[i]]
Here, authors[i] is a string, but res_matrix expects a numeric column index, not a name. You should use i directly instead of authors[i]. Here’s the corrected version: pythonCopyEditdef calculate_overall_responsivity( discussion_data: pd.DataFrame, participant: str, window: int ) -> float: """ Calculate overall responsivity score for a specific participant in a discussion. Overall responsivity = mean of row values (excluding self) from R(w) matrix. """ res_matrix, authors = calc_responsivity(discussion_data, window) participant_idx = authors.index(participant) k = len(authors)
total_res = 0.0 for i in range(k): if i != participant_idx: # exclude self total_res += res_matrix[participant_idx][i] return total_res / (k - 1) if k > 1 else 0.0This now correctly:
Gets the row for the participant
Averages over all other participants
Excludes the diagonal entry (self-responsivity)
Do you want me to give you social impact and internal cohesion in the same style so the three measures work together?
- User
Is this correct?
def calculate_internal_cohesion(discussion_data: pd.DataFrame, participant: str, discussion_id: str, window: int) -> float: """ Calculate internal cohesion score for a specific participant in a discussion. First, calculate the cross-cohesion matrix for the discussion. Return Responsivity for the participant.
Args: discussion_data: DataFrame containing the discussion data participant: The participant ID/name discussion_id: The discussion ID Returns: float: Internal cohesion score """ # Get the cross-cohesion matrix and authors cross_cohesion_matrix, authors = calc_cross_cohesion_matrix(discussion_data, lag=window) author_idx = authors.index(participant) return cross_cohesion_matrix[author_idx][author_idx] - Assistant
This almost works, but there’s a key difference between what you wrote and how internal cohesion is defined in the paper.
Internal cohesion = average self-responsivity over all lags up to www:
Raa(w)=1w∑τ=1wXaa(τ)R_{aa}(w) = \frac{1}{w} \sum_{\tau=1}^{w} X_{aa}(\tau)Raa(w)=w1τ=1∑wXaa(τ)
What you wrote only uses one lag = window rather than averaging across all lags.
So to match the paper, you should use calc_responsivity, not calc_cross_cohesion_matrix.
Here’s the correct version: pythonCopyEditdef calculate_internal_cohesion(discussion_data: pd.DataFrame, participant: str, window: int) -> float: """ Internal cohesion = diagonal value R_aa(w) from responsivity matrix R(w), averaged across all lags up to w. """ res_matrix, authors = calc_responsivity(discussion_data, window) author_idx = authors.index(participant)
# Diagonal value = self-responsivity return res_matrix[author_idx][author_idx]✅ Why this is correct
calc_responsivity already averages cross-cohesion matrices across lags.
The diagonal entry [author_idx][author_idx] = self-cohesion (internal cohesion).
If you want, I can also show you how to calculate social impact the same way — that’s just the column mean from R(w) instead of the row mean. Do you want me to add that?
- User
Does the following implementation match the paper?
""" def calculate_social_impact(discussion_data: pd.DataFrame, 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: discussion_data: DataFrame containing the discussion data participant: The participant ID/name discussion_id: The discussion ID Returns: float: Social impact score :param participant: :param discussion_data: :param window: """ # Get the cross-cohesion matrix and authors cross_cohesion_matrix, authors = calc_responsivity(discussion_data, window) # window=1 for social impact author_idx = authors.index(participant) # Calculate social impact as average of column corresponding to this participant total_impact = 0.0 num_participants = len(authors) for i in range(len(authors)): if i != author_idx: # exclude self total_impact += cross_cohesion_matrix[i][author_idx] return total_impact / (num_participants - 1) if num_participants > 0 else 0.0"""
- Assistant
Yes — your implementation now matches the paper’s equation for social impact. Here’s why:
The responsivity matrix R(w)R(w)R(w) is k×kk \times kk×k.
Ria(w)R_{ia}(w)Ria(w) = how much participant iii responds to participant aaa.
So the column average (excluding diagonal) gives:
impacta(w)=1k−1∑i≠aRia(w)\text{impact}a(w) = \frac{1}{k-1} \sum{i \neq a} R_{ia}(w)impacta(w)=k−11i=a∑Ria(w) Which is exactly what you implemented: pythonCopyEdittotal_impact += cross_cohesion_matrix[i][author_idx]
and pythonCopyEditreturn total_impact / (num_participants - 1)
Minor improvement To be consistent with the paper, check for num_participants > 1, because if k=1 there are no "others": pythonCopyEditreturn total_impact / (num_participants - 1) if num_participants > 1 else 0.0
If you want, I can give you a summary table showing: MetricFormula from paperYour implementation usesOverall responsivityRow mean excluding self✅ matchesInternal cohesionDiagonal entry Raa(w)R_{aa}(w)Raa(w)✅ matches (after fix)Social impactColumn mean excluding self✅ matches Do you want me to make this summary for all metrics?
- User
How is this?
""" def span_given(discussion_data: pd.DataFrame, time: int) -> set[list[float]]: """ Given a time t, return the set of embeddings of all contributions made until that time.
Args: time: The time index to filter contributions Returns: set: :param time: :param discussion_data: """ # Filter contributions up to the given time contributions = discussion_data[discussion_data['contribution_id'] < time] # compute the tf-idf embeddings for the contributions vectorizer = TfidfVectorizer() tfidf_matrix = vectorizer.fit_transform(contributions['text'].tolist()) if tfidf_matrix.shape[1] > 100: # only if high-dimensional svd = TruncatedSVD(n_components=100, random_state=SEED) tfidf_matrix = svd.fit_transform(tfidf_matrix) # Convert to DataFrame and add embeddings as a column contributions['embedding'] = tfidf_matrix.toarray().tolist() # Extract embeddings (assuming 'embedding' column exists) embeddings = contributions['embedding'].tolist() return set(embeddings) # Return unique embeddings as a set"""
- Assistant
This function will run, but it doesn’t really match the paper’s definition of the “given” space for newness. Here’s why:
In the paper, the given space GtG_tGt at time ttt is the subspace spanned by all previous contributions’ embeddings: Gt=span{d1,d2,...,dt−1}G_t = \text{span}{d_1, d_2, ..., d_{t-1}}Gt=span{d1,d2,...,dt−1} This is not a set of embeddings — it’s the vector space they span.
Using set(embeddings) doesn’t make sense here because:
- User
Is this better?
""" def span_given(discussion_data: pd.DataFrame, time: int) -> np.ndarray: """ Given a time t, return the set of embeddings of all contributions made until that time. This represents the 'given' space G_t in the paper. Args: time: The time index to filter contributions
Returns: list[list[float]]: Matrix of embeddings for contributions made until time t :param time: :param discussion_data: """ # Filter contributions up to the given time contributions = discussion_data[discussion_data['contribution_id'] < time]['text'].tolist() # compute the tf-idf embeddings for the contributions vectorizer = TfidfVectorizer() tfidf_matrix = vectorizer.fit_transform(contributions) if tfidf_matrix.shape[1] > 100: # only if high-dimensional svd = TruncatedSVD(n_components=100, random_state=SEED) tfidf_matrix = svd.fit_transform(tfidf_matrix) else: tfidf_matrix = tfidf_matrix.toarray() return tfidf_matrix # matrix of size (#prev_contribs × dim)"""
- Assistant
Yes — this is much better and now actually matches the paper’s definition of the given space GtG_tGt. Here’s why it works:
GtG_tGt = span of all contributions before time ttt
You correctly return the matrix of embeddings for those contributions, so you can later compute:
The projection of the current contribution onto GtG_tGt (given part)
- User
def span_given(discussion_data: pd.DataFrame, time: int, vectorizer=None) -> np.ndarray: """ Given a time t, return the set of embeddings of all contributions made until that time. This represents the 'given' space G_t in the paper. Args: time: The time index to filter contributions
Returns: list[list[float]]: Matrix of embeddings for contributions made until time t :param vectorizer: :param time: :param discussion_data: """ # Filter contributions up to the given time contributions = discussion_data[discussion_data['contribution_id'] < time]['text'].tolist() # compute the tf-idf embeddings for the contributions if vectorizer is None: vectorizer = TfidfVectorizer() tfidf_matrix = vectorizer.fit_transform(contributions) if tfidf_matrix.shape[1] > 100: # only if high-dimensional svd = TruncatedSVD(n_components=100, random_state=SEED) tfidf_matrix = svd.fit_transform(tfidf_matrix) else: tfidf_matrix = tfidf_matrix.toarray() return tfidf_matrix # matrix of size (#prev_contribs × dim) - Assistant
This version works in the sense that it will produce a matrix of embeddings before time ttt, but there are a few technical details to fix so it really aligns with the paper and avoids subtle issues:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.