This repository was archived by the owner on Mar 25, 2024. It is now read-only.
forked from cvqluu/simple_diarizer
-
Notifications
You must be signed in to change notification settings - Fork 2
add NME_SC method for clustering #1
Open
wghezaiel
wants to merge
12
commits into
max_speaker
Choose a base branch
from
NME_SC
base: max_speaker
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
f301ea8
add NME_SC method for clustering
wghezaiel d637251
fix version NME-SC
wghezaiel 2699270
correct main.py
wghezaiel cafb95f
channel index as an option
Jeronymous 73926b8
improve main
Jeronymous 5e9670c
merge manually modifications from branch max_speaker
Jeronymous 10db72d
correct cluster by NME
wghezaiel eeac8f3
modify NME
wghezaiel 04bbffb
fix max_num_clusters at the root
Jeronymous c643287
remove hack
Jeronymous 02fbb85
safety check
Jeronymous f190afe
speechbrain version 1.0.0
wghezaiel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| import soundfile as sf | ||
| import matplotlib.pyplot as plt | ||
| import os,sys,time | ||
|
|
||
|
|
||
| from simple_diarizer.diarizer import Diarizer | ||
| from simple_diarizer.utils import combined_waveplot | ||
|
|
||
| t0 = time.time() | ||
|
|
||
|
|
||
| diar = Diarizer( | ||
| embed_model='ecapa', # 'xvec' and 'ecapa' supported | ||
| cluster_method='NME-sc' # 'ahc' 'sc' and 'NME-sc' supported | ||
| ) | ||
|
|
||
| WAV_FILE,NUM_SPEAKERS,max_spk= sys.argv[1:] | ||
|
|
||
|
|
||
| if NUM_SPEAKERS == 'None': | ||
| print('None') | ||
| segments = diar.diarize(WAV_FILE, num_speakers=None,max_speakers=int(max_spk)) | ||
| else: | ||
| segments = diar.diarize(WAV_FILE, num_speakers=int(NUM_SPEAKERS)) | ||
|
|
||
|
|
||
| t1 = time.time() | ||
| feature_t = t1 - t0 | ||
| print("Time used for extracting features:", feature_t) | ||
|
|
||
|
|
||
|
|
||
| json = {} | ||
| _segments = [] | ||
| _speakers = {} | ||
| seg_id = 1 | ||
| spk_i = 1 | ||
| spk_i_dict = {} | ||
|
|
||
| for seg in segments: | ||
|
|
||
| segment = {} | ||
| segment["seg_id"] = seg_id | ||
|
|
||
| # Ensure speaker id continuity and numbers speaker by order of appearance. | ||
| if seg['label'] not in spk_i_dict.keys(): | ||
| spk_i_dict[seg['label']] = spk_i | ||
| spk_i += 1 | ||
|
|
||
| spk_id = "spk" + str(spk_i_dict[seg['label']]) | ||
| segment["spk_id"] = spk_id | ||
| segment["seg_begin"] = round(seg['start']) | ||
| segment["seg_end"] = round(seg['end']) | ||
|
|
||
| if spk_id not in _speakers: | ||
| _speakers[spk_id] = {} | ||
| _speakers[spk_id]["spk_id"] = spk_id | ||
| _speakers[spk_id]["duration"] = seg['end']-seg['start'] | ||
| _speakers[spk_id]["nbr_seg"] = 1 | ||
| else: | ||
| _speakers[spk_id]["duration"] += seg['end']-seg['start'] | ||
| _speakers[spk_id]["nbr_seg"] += 1 | ||
|
|
||
| _segments.append(segment) | ||
| seg_id += 1 | ||
|
|
||
| for spkstat in _speakers.values(): | ||
| spkstat["duration"] = round(spkstat["duration"]) | ||
|
|
||
| json["speakers"] = list(_speakers.values()) | ||
| json["segments"] = _segments | ||
|
|
||
|
|
||
| print(json["speakers"] ) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| import numpy as np | ||
| import scipy | ||
| from sklearn.cluster import SpectralClustering | ||
|
|
||
| # NME low-level operations | ||
| # These functions are taken from the Kaldi scripts. | ||
|
|
||
| # Prepares binarized(0/1) affinity matrix with p_neighbors non-zero elements in each row | ||
| def get_kneighbors_conn(X_dist, p_neighbors): | ||
| X_dist_out = np.zeros_like(X_dist) | ||
| for i, line in enumerate(X_dist): | ||
| sorted_idx = np.argsort(line) | ||
| sorted_idx = sorted_idx[::-1] | ||
| indices = sorted_idx[:p_neighbors] | ||
| X_dist_out[indices, i] = 1 | ||
| return X_dist_out | ||
|
|
||
|
|
||
| # Thresolds affinity matrix to leave p maximum non-zero elements in each row | ||
| def Threshold(A, p): | ||
| N = A.shape[0] | ||
| Ap = np.zeros((N, N)) | ||
| for i in range(N): | ||
| thr = sorted(A[i, :], reverse=True)[p] | ||
| Ap[i, A[i, :] > thr] = A[i, A[i, :] > thr] | ||
| return Ap | ||
|
|
||
|
|
||
| # Computes Laplacian of a matrix | ||
| def Laplacian(A): | ||
| d = np.sum(A, axis=1) - np.diag(A) | ||
| D = np.diag(d) | ||
| return D - A | ||
|
|
||
|
|
||
| # Calculates eigengaps (differences between adjacent eigenvalues sorted in descending order) | ||
| def Eigengap(S): | ||
| S = sorted(S) | ||
| return np.diff(S) | ||
|
|
||
|
|
||
| # Computes parameters of normalized eigenmaps for automatic thresholding selection | ||
| def ComputeNMEParameters(A, p, max_num_clusters): | ||
| # p-Neighbour binarization | ||
| Ap = get_kneighbors_conn(A, p) | ||
| # Symmetrization | ||
| Ap = (Ap + np.transpose(Ap)) / 2 | ||
| # Laplacian matrix computation | ||
| Lp = Laplacian(Ap) | ||
| # Get max_num_clusters+1 smallest eigenvalues | ||
| S = scipy.sparse.linalg.eigsh( | ||
| Lp, | ||
| k=max_num_clusters + 1, | ||
| which="SA", | ||
| tol=1e-6, | ||
| return_eigenvectors=False, | ||
| mode="buckling", | ||
| ) | ||
| # Get largest eigenvalue | ||
| Smax = scipy.sparse.linalg.eigsh( | ||
| Lp, k=1, which="LA", tol=1e-6, return_eigenvectors=False, mode="buckling" | ||
| ) | ||
| # Eigengap computation | ||
| e = Eigengap(S) | ||
| g = np.max(e[:max_num_clusters]) / (Smax + 1e-10) | ||
| r = p / g | ||
| k = np.argmax(e[:max_num_clusters]) | ||
| return (e, g, k, r) | ||
|
|
||
|
|
||
| """ | ||
| Performs spectral clustering with Normalized Maximum Eigengap (NME) | ||
| Parameters: | ||
| A: affinity matrix (matrix of pairwise cosine similarities or PLDA scores between speaker embeddings) | ||
| num_clusters: number of clusters to generate (if None, determined automatically) | ||
| max_num_clusters: maximum allowed number of clusters to generate | ||
| pmax: maximum count for matrix binarization (should be at least 2) | ||
| pbest: best count for matrix binarization (if 0, determined automatically) | ||
| Returns: cluster assignments for every speaker embedding | ||
| """ | ||
|
|
||
|
|
||
| def NME_SpectralClustering( | ||
| A, num_clusters=None, max_num_clusters=10, pbest=0, pmin=3, pmax=20 | ||
| ): | ||
| print(num_clusters,max_num_clusters) | ||
|
||
| if pbest == 0: | ||
| print("Selecting best number of neighbors for affinity matrix thresolding:") | ||
| rbest = None | ||
| kbest = None | ||
| for p in range(pmin, pmax + 1): | ||
| e, g, k, r = ComputeNMEParameters(A, p, max_num_clusters) | ||
| print("p={}, g={}, k={}, r={}, e={}".format(p, g, k, r, e)) | ||
| if rbest is None or rbest > r: | ||
| rbest = r | ||
| pbest = p | ||
| kbest = k | ||
| print("Best number of neighbors is {}".format(pbest)) | ||
| num_clusters = num_clusters if num_clusters is not None else (kbest + 1) | ||
| # Handle some edge cases in AMI SDM | ||
| num_clusters = 4 if num_clusters == 1 else num_clusters | ||
| return NME_SpectralClustering_sklearn( | ||
| A, num_clusters, pbest | ||
| ) | ||
| if num_clusters is None: | ||
| print("Compute number of clusters to generate:") | ||
| e, g, k, r = ComputeNMEParameters(A, pbest, max_num_clusters) | ||
| print("Number of clusters to generate is {}".format(k + 1)) | ||
| return NME_SpectralClustering_sklearn(A, k + 1, pbest) | ||
| return NME_SpectralClustering_sklearn(A, num_clusters, pbest) | ||
|
|
||
|
|
||
| """ | ||
| Performs spectral clustering with Normalized Maximum Eigengap (NME) with fixed threshold and number of clusters | ||
| Parameters: | ||
| A: affinity matrix (matrix of pairwise cosine similarities or PLDA scores between speaker embeddings) | ||
| OLVec: 0/1 vector denoting which segments are overlap segments | ||
| num_clusters: number of clusters to generate | ||
| pbest: best count for matrix binarization | ||
| Returns: cluster assignments for every speaker embedding | ||
| """ | ||
|
|
||
|
|
||
| def NME_SpectralClustering_sklearn(A, num_clusters, pbest): | ||
| print("Number of speakers is {}".format(num_clusters)) | ||
| # Ap = Threshold(A, pbest) | ||
| Ap = get_kneighbors_conn(A, pbest) # thresholded and binarized | ||
| Ap = (Ap + np.transpose(Ap)) / 2 | ||
|
|
||
|
|
||
| model = SpectralClustering( | ||
| n_clusters=num_clusters, affinity="precomputed", random_state=0 | ||
| ) | ||
| labels = model.fit_predict(Ap) | ||
| return labels | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.