|
| 1 | +import tempfile |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +import pandas as pd |
| 6 | +import pytest |
| 7 | +from sentence_transformers import SentenceTransformer |
| 8 | +from sklearn.datasets import fetch_20newsgroups |
| 9 | + |
| 10 | +from turftopic import ( |
| 11 | + GMM, |
| 12 | + AutoEncodingTopicModel, |
| 13 | + ClusteringTopicModel, |
| 14 | + KeyNMF, |
| 15 | + SemanticSignalSeparation, |
| 16 | +) |
| 17 | + |
| 18 | +newsgroups = fetch_20newsgroups( |
| 19 | + subset="all", |
| 20 | + categories=[ |
| 21 | + "misc.forsale", |
| 22 | + ], |
| 23 | + remove=("headers", "footers", "quotes"), |
| 24 | +) |
| 25 | +texts = newsgroups.data |
| 26 | +trf = SentenceTransformer("all-MiniLM-L6-v2") |
| 27 | +embeddings = np.asarray(trf.encode(texts)) |
| 28 | + |
| 29 | +models = [ |
| 30 | + GMM(5, encoder=trf), |
| 31 | + SemanticSignalSeparation(5, encoder=trf), |
| 32 | + KeyNMF(5, encoder=trf), |
| 33 | + ClusteringTopicModel( |
| 34 | + n_reduce_to=5, |
| 35 | + feature_importance="c-tf-idf", |
| 36 | + encoder=trf, |
| 37 | + reduction_method="agglomerative", |
| 38 | + ), |
| 39 | + ClusteringTopicModel( |
| 40 | + n_reduce_to=5, |
| 41 | + feature_importance="centroid", |
| 42 | + encoder=trf, |
| 43 | + reduction_method="smallest", |
| 44 | + ), |
| 45 | + AutoEncodingTopicModel(5, combined=True), |
| 46 | +] |
| 47 | + |
| 48 | + |
| 49 | +@pytest.mark.parametrize("model", models) |
| 50 | +def test_fit_export_table(model): |
| 51 | + doc_topic_matrix = model.fit_transform(texts, embeddings=embeddings) |
| 52 | + table = model.export_topics(format="csv") |
| 53 | + with tempfile.TemporaryDirectory() as tmpdirname: |
| 54 | + out_path = Path(tmpdirname).joinpath("topics.csv") |
| 55 | + with out_path.open("w") as out_file: |
| 56 | + out_file.write(table) |
| 57 | + df = pd.read_csv(out_path) |
0 commit comments