nimare 0.4.2rc4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- benchmarks/__init__.py +0 -0
- benchmarks/bench_cbma.py +57 -0
- nimare/__init__.py +45 -0
- nimare/_version.py +21 -0
- nimare/annotate/__init__.py +21 -0
- nimare/annotate/cogat.py +213 -0
- nimare/annotate/gclda.py +924 -0
- nimare/annotate/lda.py +147 -0
- nimare/annotate/text.py +75 -0
- nimare/annotate/utils.py +87 -0
- nimare/base.py +217 -0
- nimare/cli.py +124 -0
- nimare/correct.py +462 -0
- nimare/dataset.py +685 -0
- nimare/decode/__init__.py +33 -0
- nimare/decode/base.py +115 -0
- nimare/decode/continuous.py +462 -0
- nimare/decode/discrete.py +753 -0
- nimare/decode/encode.py +110 -0
- nimare/decode/utils.py +44 -0
- nimare/diagnostics.py +510 -0
- nimare/estimator.py +139 -0
- nimare/extract/__init__.py +19 -0
- nimare/extract/extract.py +466 -0
- nimare/extract/utils.py +295 -0
- nimare/generate.py +331 -0
- nimare/io.py +635 -0
- nimare/meta/__init__.py +39 -0
- nimare/meta/cbma/__init__.py +6 -0
- nimare/meta/cbma/ale.py +951 -0
- nimare/meta/cbma/base.py +947 -0
- nimare/meta/cbma/mkda.py +1361 -0
- nimare/meta/cbmr.py +970 -0
- nimare/meta/ibma.py +1683 -0
- nimare/meta/kernel.py +501 -0
- nimare/meta/models.py +1199 -0
- nimare/meta/utils.py +494 -0
- nimare/nimads.py +492 -0
- nimare/reports/__init__.py +24 -0
- nimare/reports/base.py +664 -0
- nimare/reports/default.yml +123 -0
- nimare/reports/figures.py +651 -0
- nimare/reports/report.tpl +160 -0
- nimare/resources/__init__.py +1 -0
- nimare/resources/atlases/Harvard-Oxford-LICENSE +93 -0
- nimare/resources/atlases/HarvardOxford-cort-maxprob-thr25-2mm.nii.gz +0 -0
- nimare/resources/database_file_manifest.json +142 -0
- nimare/resources/english_spellings.csv +1738 -0
- nimare/resources/filenames.json +32 -0
- nimare/resources/neurosynth_laird_studies.json +58773 -0
- nimare/resources/neurosynth_stoplist.txt +396 -0
- nimare/resources/nidm_pain_dset.json +1349 -0
- nimare/resources/references.bib +541 -0
- nimare/resources/semantic_knowledge_children.txt +325 -0
- nimare/resources/semantic_relatedness_children.txt +249 -0
- nimare/resources/templates/MNI152_2x2x2_brainmask.nii.gz +0 -0
- nimare/resources/templates/tpl-MNI152NLin6Asym_res-01_T1w.nii.gz +0 -0
- nimare/resources/templates/tpl-MNI152NLin6Asym_res-01_desc-brain_mask.nii.gz +0 -0
- nimare/resources/templates/tpl-MNI152NLin6Asym_res-02_T1w.nii.gz +0 -0
- nimare/resources/templates/tpl-MNI152NLin6Asym_res-02_desc-brain_mask.nii.gz +0 -0
- nimare/results.py +225 -0
- nimare/stats.py +276 -0
- nimare/tests/__init__.py +1 -0
- nimare/tests/conftest.py +229 -0
- nimare/tests/data/amygdala_roi.nii.gz +0 -0
- nimare/tests/data/data-neurosynth_version-7_coordinates.tsv.gz +0 -0
- nimare/tests/data/data-neurosynth_version-7_metadata.tsv.gz +0 -0
- nimare/tests/data/data-neurosynth_version-7_vocab-terms_source-abstract_type-tfidf_features.npz +0 -0
- nimare/tests/data/data-neurosynth_version-7_vocab-terms_vocabulary.txt +100 -0
- nimare/tests/data/neurosynth_dset.json +2868 -0
- nimare/tests/data/neurosynth_laird_studies.json +58773 -0
- nimare/tests/data/nidm_pain_dset.json +1349 -0
- nimare/tests/data/nimads_annotation.json +1 -0
- nimare/tests/data/nimads_studyset.json +1 -0
- nimare/tests/data/test_baseline.txt +2 -0
- nimare/tests/data/test_pain_dataset.json +1278 -0
- nimare/tests/data/test_pain_dataset_multiple_contrasts.json +1242 -0
- nimare/tests/data/test_sleuth_file.txt +18 -0
- nimare/tests/data/test_sleuth_file2.txt +10 -0
- nimare/tests/data/test_sleuth_file3.txt +5 -0
- nimare/tests/data/test_sleuth_file4.txt +5 -0
- nimare/tests/data/test_sleuth_file5.txt +5 -0
- nimare/tests/test_annotate_cogat.py +32 -0
- nimare/tests/test_annotate_gclda.py +86 -0
- nimare/tests/test_annotate_lda.py +27 -0
- nimare/tests/test_dataset.py +99 -0
- nimare/tests/test_decode_continuous.py +132 -0
- nimare/tests/test_decode_discrete.py +92 -0
- nimare/tests/test_diagnostics.py +168 -0
- nimare/tests/test_estimator_performance.py +385 -0
- nimare/tests/test_extract.py +46 -0
- nimare/tests/test_generate.py +247 -0
- nimare/tests/test_io.py +240 -0
- nimare/tests/test_meta_ale.py +298 -0
- nimare/tests/test_meta_cbmr.py +295 -0
- nimare/tests/test_meta_ibma.py +240 -0
- nimare/tests/test_meta_kernel.py +209 -0
- nimare/tests/test_meta_mkda.py +234 -0
- nimare/tests/test_nimads.py +21 -0
- nimare/tests/test_reports.py +110 -0
- nimare/tests/test_stats.py +101 -0
- nimare/tests/test_transforms.py +272 -0
- nimare/tests/test_utils.py +200 -0
- nimare/tests/test_workflows.py +221 -0
- nimare/tests/utils.py +126 -0
- nimare/transforms.py +907 -0
- nimare/utils.py +1367 -0
- nimare/workflows/__init__.py +14 -0
- nimare/workflows/base.py +189 -0
- nimare/workflows/cbma.py +165 -0
- nimare/workflows/ibma.py +108 -0
- nimare/workflows/macm.py +77 -0
- nimare/workflows/misc.py +65 -0
- nimare-0.4.2rc4.dist-info/LICENSE +21 -0
- nimare-0.4.2rc4.dist-info/METADATA +124 -0
- nimare-0.4.2rc4.dist-info/RECORD +119 -0
- nimare-0.4.2rc4.dist-info/WHEEL +5 -0
- nimare-0.4.2rc4.dist-info/entry_points.txt +2 -0
- nimare-0.4.2rc4.dist-info/top_level.txt +2 -0
nimare/annotate/gclda.py
ADDED
@@ -0,0 +1,924 @@
|
|
1
|
+
"""Topic modeling with generalized correspondence latent Dirichlet allocation."""
|
2
|
+
|
3
|
+
import logging
|
4
|
+
import os.path as op
|
5
|
+
|
6
|
+
import nibabel as nib
|
7
|
+
import numpy as np
|
8
|
+
import pandas as pd
|
9
|
+
from nilearn._utils import load_niimg
|
10
|
+
from scipy.stats import multivariate_normal
|
11
|
+
|
12
|
+
from nimare.base import NiMAREBase
|
13
|
+
from nimare.utils import get_template
|
14
|
+
|
15
|
+
LGR = logging.getLogger(__name__)
|
16
|
+
|
17
|
+
|
18
|
+
class GCLDAModel(NiMAREBase):
|
19
|
+
"""Generate a generalized correspondence latent Dirichlet allocation (GCLDA) topic model.
|
20
|
+
|
21
|
+
This model was originally described in :footcite:t:`rubin2017decoding`.
|
22
|
+
|
23
|
+
.. versionchanged:: 0.0.8
|
24
|
+
|
25
|
+
* [ENH] Support symmetric GC-LDA topics with more than two subregions.
|
26
|
+
|
27
|
+
Parameters
|
28
|
+
----------
|
29
|
+
count_df : :obj:`pandas.DataFrame`
|
30
|
+
A DataFrame with feature counts for the model. The index is 'id',
|
31
|
+
used for identifying studies. Other columns are features (e.g.,
|
32
|
+
unigrams and bigrams from Neurosynth), where each value is the number
|
33
|
+
of times the feature is found in a given article.
|
34
|
+
coordinates_df : :obj:`pandas.DataFrame`
|
35
|
+
A DataFrame with a list of foci in the dataset. The index is 'id',
|
36
|
+
used for identifying studies. Additional columns include 'x', 'y' and
|
37
|
+
'z' (foci in standard space).
|
38
|
+
n_topics : :obj:`int`, optional
|
39
|
+
Number of topics to generate in model. As a good rule of thumb, the
|
40
|
+
number of topics should be less than the number of studies in the
|
41
|
+
dataset. Otherwise, there can be errors during model training.
|
42
|
+
The default is 100.
|
43
|
+
n_regions : :obj:`int`, optional
|
44
|
+
Number of subregions per topic (>=1). The default is 2.
|
45
|
+
alpha : :obj:`float`, optional
|
46
|
+
Prior count on topics for each document. The default is 0.1.
|
47
|
+
beta : :obj:`float`, optional
|
48
|
+
Prior count on word-types for each topic. The default is 0.01.
|
49
|
+
gamma : :obj:`float`, optional
|
50
|
+
Prior count added to y-counts when sampling z assignments. The
|
51
|
+
default is 0.01.
|
52
|
+
delta : :obj:`float`, optional
|
53
|
+
Prior count on subregions for each topic. The default is 1.0.
|
54
|
+
dobs : :obj:`int`, optional
|
55
|
+
Spatial region 'default observations' (# observations weighting
|
56
|
+
Sigma estimates in direction of default 'roi_size' value). The
|
57
|
+
default is 25.
|
58
|
+
roi_size : :obj:`float`, optional
|
59
|
+
Default spatial 'region of interest' size (default value of
|
60
|
+
diagonals in covariance matrix for spatial distribution, which the
|
61
|
+
distributions are biased towards). The default is 50.0.
|
62
|
+
symmetric : :obj:`bool`, optional
|
63
|
+
Whether or not to use symmetry constraint on subregions. Symmetry
|
64
|
+
requires n_regions = 2. The default is False.
|
65
|
+
seed_init : :obj:`int`, optional
|
66
|
+
Initial value of random seed. The default is 1.
|
67
|
+
|
68
|
+
Attributes
|
69
|
+
----------
|
70
|
+
p_topic_g_voxel_ : (V x T) :obj:`numpy.ndarray`
|
71
|
+
Probability of each topic (T) give a voxel (V)
|
72
|
+
p_voxel_g_topic_ : (V x T) :obj:`numpy.ndarray`
|
73
|
+
Probability of each voxel (V) given a topic (T)
|
74
|
+
p_topic_g_word_ : (W x T) :obj:`numpy.ndarray`
|
75
|
+
Probability of each topic (T) given a word (W)
|
76
|
+
p_word_g_topic_ : (W x T) :obj:`numpy.ndarray`
|
77
|
+
Probability of each word (W) given a topic (T)
|
78
|
+
|
79
|
+
References
|
80
|
+
----------
|
81
|
+
.. footbibliography::
|
82
|
+
|
83
|
+
See Also
|
84
|
+
--------
|
85
|
+
nimare.decode.continuous.gclda_decode_map : GCLDA map decoding
|
86
|
+
nimare.decode.discrete.gclda_decode_roi : GCLDA ROI decoding
|
87
|
+
nimare.decode.encode.encode_gclda : GCLDA text-to-map encoding
|
88
|
+
"""
|
89
|
+
|
90
|
+
def __init__(
|
91
|
+
self,
|
92
|
+
count_df,
|
93
|
+
coordinates_df,
|
94
|
+
mask="mni152_2mm",
|
95
|
+
n_topics=100,
|
96
|
+
n_regions=2,
|
97
|
+
symmetric=True,
|
98
|
+
alpha=0.1,
|
99
|
+
beta=0.01,
|
100
|
+
gamma=0.01,
|
101
|
+
delta=1.0,
|
102
|
+
dobs=25,
|
103
|
+
roi_size=50.0,
|
104
|
+
seed_init=1,
|
105
|
+
):
|
106
|
+
LGR.info("Constructing/Initializing GCLDA Model")
|
107
|
+
count_df = count_df.copy()
|
108
|
+
coordinates_df = coordinates_df.copy()
|
109
|
+
|
110
|
+
# Check IDs from DataFrames
|
111
|
+
count_df.index = count_df.index.astype(str)
|
112
|
+
count_df["id"] = count_df.index
|
113
|
+
count_ids = count_df.index.tolist()
|
114
|
+
if "id" not in coordinates_df.columns:
|
115
|
+
coordinates_df["id"] = coordinates_df.index
|
116
|
+
coordinates_df["id"] = coordinates_df["id"].astype(str)
|
117
|
+
coord_ids = sorted(list(set(coordinates_df["id"].tolist())))
|
118
|
+
ids = sorted(list(set(count_ids).intersection(coord_ids)))
|
119
|
+
if len(count_ids) != len(coord_ids) != len(ids):
|
120
|
+
union_ids = sorted(list(set(count_ids + coord_ids)))
|
121
|
+
LGR.warning(
|
122
|
+
f"IDs mismatch detected: retaining {len(ids)} of {len(union_ids)} unique IDs"
|
123
|
+
)
|
124
|
+
self.ids = ids
|
125
|
+
|
126
|
+
# Reduce inputs based on shared IDs
|
127
|
+
count_df = count_df.loc[count_df["id"].isin(ids)]
|
128
|
+
coordinates_df = coordinates_df.loc[coordinates_df["id"].isin(ids)]
|
129
|
+
|
130
|
+
# --- Checking to make sure parameters are valid
|
131
|
+
if (symmetric is True) and (n_regions % 2 != 0):
|
132
|
+
# symmetric model only valid if R = 2
|
133
|
+
raise ValueError("Cannot run a symmetric model unless n_regions is even.")
|
134
|
+
|
135
|
+
# Initialize sampling parameters
|
136
|
+
# The global sampling iteration of the model
|
137
|
+
self.iter = 0
|
138
|
+
# Current random seed (is incremented after initialization and each sampling update)
|
139
|
+
self.seed = 0
|
140
|
+
|
141
|
+
# Set up model hyperparameters
|
142
|
+
# Pseudo-count hyperparams need to be floats so that when sampling
|
143
|
+
# distributions are computed the count matrices/vectors are converted
|
144
|
+
# to floats
|
145
|
+
self.params = {
|
146
|
+
"n_topics": n_topics, # Number of topics (T)
|
147
|
+
"n_regions": n_regions, # Number of subregions (R)
|
148
|
+
"alpha": alpha, # Prior count on topics for each doc
|
149
|
+
"beta": beta, # Prior count on word-types for each topic
|
150
|
+
"gamma": gamma, # Prior count added to y-counts when sampling z assignments
|
151
|
+
"delta": delta, # Prior count on subregions for each topic
|
152
|
+
# Default ROI (default covariance spatial region we regularize towards) (not in paper)
|
153
|
+
"roi_size": roi_size,
|
154
|
+
# Sample constant (# observations weighting sigma in direction of default covariance)
|
155
|
+
# (not in paper)
|
156
|
+
"dobs": dobs,
|
157
|
+
# Use constrained symmetry on subregions? (only for n_regions = 2)
|
158
|
+
"symmetric": symmetric,
|
159
|
+
"seed_init": seed_init, # Random seed for initializing model
|
160
|
+
}
|
161
|
+
|
162
|
+
# Add dictionaries for other model info
|
163
|
+
self.data = {}
|
164
|
+
self.topics = {}
|
165
|
+
|
166
|
+
# Prepare data
|
167
|
+
if isinstance(mask, str) and not op.isfile(mask):
|
168
|
+
self.mask = get_template(mask, mask="brain")
|
169
|
+
else:
|
170
|
+
self.mask = load_niimg(mask)
|
171
|
+
|
172
|
+
# Extract document and word indices from count_df
|
173
|
+
docidx_mapper = {id_: i for (i, id_) in enumerate(ids)}
|
174
|
+
|
175
|
+
# Create docidx column
|
176
|
+
count_df["docidx"] = count_df["id"].map(docidx_mapper)
|
177
|
+
count_df = count_df.drop(columns=["id"])
|
178
|
+
|
179
|
+
# Remove words not found anywhere in the corpus
|
180
|
+
n_terms = len(count_df.columns) - 1 # number of columns minus one for docidx
|
181
|
+
count_df = count_df.loc[:, (count_df != 0).any(axis=0)]
|
182
|
+
n_terms_in_corpus = len(count_df.columns) - 1
|
183
|
+
if n_terms_in_corpus != n_terms:
|
184
|
+
LGR.warning(
|
185
|
+
"Some terms in count_df do not appear in corpus. "
|
186
|
+
f"Retaining {n_terms_in_corpus/n_terms} terms."
|
187
|
+
)
|
188
|
+
|
189
|
+
# Get updated vocabulary
|
190
|
+
# List of word-strings (wtoken_word_idx values are indices into this list)
|
191
|
+
vocabulary = count_df.columns.tolist()
|
192
|
+
vocabulary.remove("docidx")
|
193
|
+
self.vocabulary = vocabulary
|
194
|
+
widx_mapper = {word: i for (i, word) in enumerate(self.vocabulary)}
|
195
|
+
|
196
|
+
# Melt dataframe and create widx column
|
197
|
+
widx_df = pd.melt(count_df, id_vars=["docidx"], var_name="word", value_name="count")
|
198
|
+
widx_df["widx"] = widx_df["word"].map(widx_mapper)
|
199
|
+
|
200
|
+
# Replicate rows based on count
|
201
|
+
widx_df = widx_df.loc[np.repeat(widx_df.index.values, widx_df["count"])]
|
202
|
+
widx_df = widx_df[["docidx", "widx"]].astype(int)
|
203
|
+
widx_df.sort_values(by=["docidx", "widx"], inplace=True)
|
204
|
+
|
205
|
+
# List of document-indices for word-tokens
|
206
|
+
self.data["wtoken_doc_idx"] = widx_df["docidx"].tolist()
|
207
|
+
# List of word-indices for word-tokens
|
208
|
+
self.data["wtoken_word_idx"] = widx_df["widx"].tolist()
|
209
|
+
|
210
|
+
# Import all peak-indices into lists
|
211
|
+
coordinates_df["docidx"] = coordinates_df["id"].astype(str).map(docidx_mapper)
|
212
|
+
coordinates_df = coordinates_df[["docidx", "x", "y", "z"]]
|
213
|
+
coordinates_df["docidx"] = coordinates_df["docidx"].astype(int)
|
214
|
+
|
215
|
+
# List of document-indices for peak-tokens x
|
216
|
+
self.data["ptoken_doc_idx"] = coordinates_df["docidx"].tolist()
|
217
|
+
self.data["ptoken_coords"] = coordinates_df[["x", "y", "z"]].values
|
218
|
+
|
219
|
+
# Seed random number generator
|
220
|
+
np.random.seed(self.params["seed_init"])
|
221
|
+
|
222
|
+
# Preallocate vectors of assignment indices
|
223
|
+
# word->topic assignments
|
224
|
+
self.topics["wtoken_topic_idx"] = np.zeros(len(self.data["wtoken_word_idx"]), dtype=int)
|
225
|
+
|
226
|
+
# Randomly initialize peak->topic assignments (y) ~ unif(1...n_topics)
|
227
|
+
self.topics["peak_topic_idx"] = np.random.randint(
|
228
|
+
self.params["n_topics"],
|
229
|
+
size=(len(self.data["ptoken_doc_idx"])),
|
230
|
+
)
|
231
|
+
|
232
|
+
# peak->region assignments
|
233
|
+
self.topics["peak_region_idx"] = np.zeros(len(self.data["ptoken_doc_idx"]), dtype=int)
|
234
|
+
|
235
|
+
# Preallocate count matrices
|
236
|
+
# Peaks: D x T: Number of peak-tokens assigned to each topic per document
|
237
|
+
self.topics["n_peak_tokens_doc_by_topic"] = np.zeros(
|
238
|
+
(len(self.ids), self.params["n_topics"]),
|
239
|
+
dtype=int,
|
240
|
+
)
|
241
|
+
|
242
|
+
# Peaks: R x T: Number of peak-tokens assigned to each subregion per topic
|
243
|
+
self.topics["n_peak_tokens_region_by_topic"] = np.zeros(
|
244
|
+
(self.params["n_regions"], self.params["n_topics"]),
|
245
|
+
dtype=int,
|
246
|
+
)
|
247
|
+
|
248
|
+
# Words: W x T: Number of word-tokens assigned to each topic per word-type
|
249
|
+
self.topics["n_word_tokens_word_by_topic"] = np.zeros(
|
250
|
+
(len(self.vocabulary), self.params["n_topics"]),
|
251
|
+
dtype=int,
|
252
|
+
)
|
253
|
+
|
254
|
+
# Words: D x T: Number of word-tokens assigned to each topic per document
|
255
|
+
self.topics["n_word_tokens_doc_by_topic"] = np.zeros(
|
256
|
+
(len(self.ids), self.params["n_topics"]),
|
257
|
+
dtype=int,
|
258
|
+
)
|
259
|
+
|
260
|
+
# Words: 1 x T: Total number of word-tokens assigned to each topic (across all docs)
|
261
|
+
self.topics["total_n_word_tokens_by_topic"] = np.zeros(
|
262
|
+
(1, self.params["n_topics"]),
|
263
|
+
dtype=int,
|
264
|
+
)
|
265
|
+
|
266
|
+
# Preallocate Gaussians for all subregions
|
267
|
+
# Regions_Mu & Regions_Sigma: Gaussian mean and covariance for all
|
268
|
+
# subregions of all topics
|
269
|
+
# Formed using lists (over topics) of lists (over subregions) of numpy
|
270
|
+
# arrays
|
271
|
+
# regions_mu = (n_topics, n_regions, 1, n_peak_dims)
|
272
|
+
# regions_sigma = (n_topics, n_regions, n_peak_dims, n_peak_dims)
|
273
|
+
# (\mu^{(t)}_r)
|
274
|
+
self.topics["regions_mu"] = np.zeros(
|
275
|
+
(
|
276
|
+
self.params["n_topics"],
|
277
|
+
self.params["n_regions"],
|
278
|
+
1,
|
279
|
+
self.data["ptoken_coords"].shape[1], # generally 3
|
280
|
+
),
|
281
|
+
)
|
282
|
+
# (\sigma^{(t)}_r)
|
283
|
+
self.topics["regions_sigma"] = np.zeros(
|
284
|
+
(
|
285
|
+
self.params["n_topics"],
|
286
|
+
self.params["n_regions"],
|
287
|
+
self.data["ptoken_coords"].shape[1], # generally 3
|
288
|
+
self.data["ptoken_coords"].shape[1], # generally 3
|
289
|
+
)
|
290
|
+
)
|
291
|
+
|
292
|
+
# Initialize lists for tracking log-likelihood of data over sampling iterations
|
293
|
+
self.loglikelihood = {
|
294
|
+
"iter": [], # Tracks iteration associated with the log-likelihood values
|
295
|
+
"x": [], # Tracks log-likelihood of peak tokens
|
296
|
+
"w": [], # Tracks log-likelihood of word tokens
|
297
|
+
"total": [], # Tracks log-likelihood of peak + word tokens
|
298
|
+
}
|
299
|
+
|
300
|
+
# Initialize peak->subregion assignments (r)
|
301
|
+
if self.params["symmetric"]:
|
302
|
+
# if symmetric model use deterministic assignment :
|
303
|
+
# if peak_val[0] > 0, r = 1, else r = 0
|
304
|
+
# Namely, check whether x-coordinate is greater than zero.
|
305
|
+
n_pairs = int(self.params["n_regions"] / 2)
|
306
|
+
initial_assignments = np.random.randint(
|
307
|
+
n_pairs,
|
308
|
+
size=(len(self.data["ptoken_doc_idx"])),
|
309
|
+
)
|
310
|
+
signs = (self.data["ptoken_coords"][:, 0] > 0).astype(int)
|
311
|
+
self.topics["peak_region_idx"][:] = (initial_assignments * 2) + signs
|
312
|
+
else:
|
313
|
+
# if asymmetric model, randomly sample r ~ unif(1...n_regions)
|
314
|
+
self.topics["peak_region_idx"][:] = np.random.randint(
|
315
|
+
self.params["n_regions"],
|
316
|
+
size=(len(self.data["ptoken_doc_idx"])),
|
317
|
+
)
|
318
|
+
|
319
|
+
# Update model vectors and count matrices to reflect y and r assignments
|
320
|
+
for i_ptoken, peak_doc in enumerate(self.data["ptoken_doc_idx"]):
|
321
|
+
# peak-token -> topic assignment (y_i)
|
322
|
+
peak_topic = self.topics["peak_topic_idx"][i_ptoken]
|
323
|
+
# peak-token -> subregion assignment (c_i)
|
324
|
+
peak_region = self.topics["peak_region_idx"][i_ptoken]
|
325
|
+
# Increment document-by-topic counts
|
326
|
+
self.topics["n_peak_tokens_doc_by_topic"][peak_doc, peak_topic] += 1
|
327
|
+
# Increment region-by-topic
|
328
|
+
self.topics["n_peak_tokens_region_by_topic"][peak_region, peak_topic] += 1
|
329
|
+
|
330
|
+
# Randomly Initialize Word->Topic Assignments (z) for each word
|
331
|
+
# token w_i: sample z_i proportional to p(topic|doc_i)
|
332
|
+
for i_wtoken, word in enumerate(self.data["wtoken_word_idx"]):
|
333
|
+
# w_i doc-index
|
334
|
+
doc = self.data["wtoken_doc_idx"][i_wtoken]
|
335
|
+
|
336
|
+
# Estimate p(t|d) for current doc
|
337
|
+
p_topic_g_doc = (
|
338
|
+
self.topics["n_peak_tokens_doc_by_topic"][doc, :] + self.params["gamma"]
|
339
|
+
)
|
340
|
+
|
341
|
+
# Sample a topic from p(t|d) for the z-assignment
|
342
|
+
# Compute a cdf of the sampling distribution for z
|
343
|
+
probs = np.cumsum(p_topic_g_doc)
|
344
|
+
|
345
|
+
# How many elements of cdf are less than sample
|
346
|
+
random_threshold = np.random.rand() * probs[-1]
|
347
|
+
# z = # elements of cdf less than rand-sample
|
348
|
+
topic = np.sum(probs < random_threshold)
|
349
|
+
|
350
|
+
# Update model assignment vectors and count-matrices to reflect z
|
351
|
+
# Word-token -> topic assignment (z_i)
|
352
|
+
self.topics["wtoken_topic_idx"][i_wtoken] = topic
|
353
|
+
self.topics["n_word_tokens_word_by_topic"][word, topic] += 1
|
354
|
+
self.topics["total_n_word_tokens_by_topic"][0, topic] += 1
|
355
|
+
self.topics["n_word_tokens_doc_by_topic"][doc, topic] += 1
|
356
|
+
|
357
|
+
def fit(self, n_iters=5000, loglikely_freq=10):
|
358
|
+
"""Run multiple iterations.
|
359
|
+
|
360
|
+
.. versionchanged:: 0.0.8
|
361
|
+
|
362
|
+
[ENH] Remove ``verbose`` parameter.
|
363
|
+
|
364
|
+
Parameters
|
365
|
+
----------
|
366
|
+
n_iters : :obj:`int`, default=5000
|
367
|
+
Number of iterations to run. Default is 5000.
|
368
|
+
loglikely_freq : :obj:`int`, optional
|
369
|
+
The frequency with which log-likelihood is updated. Default value
|
370
|
+
is 1 (log-likelihood is updated every iteration).
|
371
|
+
"""
|
372
|
+
if self.iter == 0:
|
373
|
+
# Get Initial Spatial Parameter Estimates
|
374
|
+
self._update_regions()
|
375
|
+
|
376
|
+
# Get Log-Likelihood of data for Initialized model and save to
|
377
|
+
# variables tracking loglikely
|
378
|
+
self.compute_log_likelihood()
|
379
|
+
|
380
|
+
for i in range(self.iter, n_iters):
|
381
|
+
self._update(loglikely_freq=loglikely_freq)
|
382
|
+
|
383
|
+
# TODO: Handle this more elegantly
|
384
|
+
(
|
385
|
+
p_topic_g_voxel,
|
386
|
+
p_voxel_g_topic,
|
387
|
+
p_topic_g_word,
|
388
|
+
p_word_g_topic,
|
389
|
+
) = self.get_probability_distributions()
|
390
|
+
self.p_topic_g_voxel_ = p_topic_g_voxel
|
391
|
+
self.p_voxel_g_topic_ = p_voxel_g_topic
|
392
|
+
self.p_topic_g_word_ = p_topic_g_word
|
393
|
+
self.p_word_g_topic_ = p_word_g_topic
|
394
|
+
|
395
|
+
def _update(self, loglikely_freq=1):
|
396
|
+
"""Run a complete update cycle (sample z, sample y&r, update regions).
|
397
|
+
|
398
|
+
.. versionchanged:: 0.0.8
|
399
|
+
|
400
|
+
[ENH] Remove ``verbose`` parameter.
|
401
|
+
|
402
|
+
Parameters
|
403
|
+
----------
|
404
|
+
loglikely_freq : :obj:`int`, optional
|
405
|
+
The frequency with which log-likelihood is updated. Default value
|
406
|
+
is 1 (log-likelihood is updated every iteration).
|
407
|
+
"""
|
408
|
+
self.iter += 1 # Update total iteration count
|
409
|
+
|
410
|
+
LGR.debug(f"Iter {self.iter:04d}: Sampling z")
|
411
|
+
self.seed += 1
|
412
|
+
self._update_word_topic_assignments(self.seed) # Update z-assignments
|
413
|
+
|
414
|
+
LGR.debug(f"Iter {self.iter:04d}: Sampling y|r")
|
415
|
+
self.seed += 1
|
416
|
+
self._update_peak_assignments(self.seed) # Update y-assignments
|
417
|
+
|
418
|
+
LGR.debug(f"Iter {self.iter:04d}: Updating spatial params")
|
419
|
+
self._update_regions() # Update gaussian estimates for all subregions
|
420
|
+
|
421
|
+
# Only update log-likelihood every 'loglikely_freq' iterations
|
422
|
+
# (Computing log-likelihood isn't necessary and slows things down a bit)
|
423
|
+
if self.iter % loglikely_freq == 0:
|
424
|
+
LGR.debug(f"Iter {self.iter:04d}: Computing log-likelihood")
|
425
|
+
|
426
|
+
# Compute log-likelihood of model in current state
|
427
|
+
self.compute_log_likelihood()
|
428
|
+
LGR.info(
|
429
|
+
f"Iter {self.iter:04d} Log-likely: x = {self.loglikelihood['x'][-1]:10.1f}, "
|
430
|
+
f"w = {self.loglikelihood['w'][-1]:10.1f}, "
|
431
|
+
f"tot = {self.loglikelihood['total'][-1]:10.1f}"
|
432
|
+
)
|
433
|
+
|
434
|
+
def _update_word_topic_assignments(self, randseed):
|
435
|
+
"""Update wtoken_topic_idx (z) indicator variables assigning words->topics.
|
436
|
+
|
437
|
+
Parameters
|
438
|
+
----------
|
439
|
+
randseed : :obj:`int`
|
440
|
+
Random seed for this iteration.
|
441
|
+
"""
|
442
|
+
# --- Seed random number generator
|
443
|
+
np.random.seed(randseed)
|
444
|
+
|
445
|
+
# Loop over all word tokens
|
446
|
+
for i_wtoken, word in enumerate(self.data["wtoken_word_idx"]):
|
447
|
+
# Find document in which word token (not just word) appears
|
448
|
+
doc = self.data["wtoken_doc_idx"][i_wtoken]
|
449
|
+
# current topic assignment for word token w_i
|
450
|
+
topic = self.topics["wtoken_topic_idx"][i_wtoken]
|
451
|
+
|
452
|
+
# Decrement count-matrices to remove current wtoken_topic_idx
|
453
|
+
# because wtoken will be reassigned to a new topic
|
454
|
+
self.topics["n_word_tokens_word_by_topic"][word, topic] -= 1
|
455
|
+
self.topics["total_n_word_tokens_by_topic"][0, topic] -= 1
|
456
|
+
self.topics["n_word_tokens_doc_by_topic"][doc, topic] -= 1
|
457
|
+
|
458
|
+
# Get sampling distribution:
|
459
|
+
# p(z_i|z,d,w) ~ p(w|t) * p(t|d)
|
460
|
+
# ~ p_w_t * p_topic_g_doc
|
461
|
+
p_word_g_topic = (
|
462
|
+
self.topics["n_word_tokens_word_by_topic"][word, :] + self.params["beta"]
|
463
|
+
) / (
|
464
|
+
self.topics["total_n_word_tokens_by_topic"]
|
465
|
+
+ (self.params["beta"] * len(self.vocabulary))
|
466
|
+
)
|
467
|
+
p_topic_g_doc = (
|
468
|
+
self.topics["n_peak_tokens_doc_by_topic"][doc, :] + self.params["gamma"]
|
469
|
+
)
|
470
|
+
probs = p_word_g_topic * p_topic_g_doc # The unnormalized sampling distribution
|
471
|
+
|
472
|
+
# Sample a z_i assignment for the current word-token from the sampling distribution
|
473
|
+
probs = np.squeeze(probs) / np.sum(probs) # Normalize the sampling distribution
|
474
|
+
# Numpy returns a binary [1 x T] vector with a '1' in the index of sampled topic
|
475
|
+
# and zeros everywhere else
|
476
|
+
assigned_topic_vec = np.random.multinomial(1, probs)
|
477
|
+
# Extract selected topic from vector
|
478
|
+
topic = np.where(assigned_topic_vec)[0][0]
|
479
|
+
|
480
|
+
# Update the indices and the count matrices using the sampled z assignment
|
481
|
+
self.topics["wtoken_topic_idx"][i_wtoken] = topic # Update w_i topic-assignment
|
482
|
+
self.topics["n_word_tokens_word_by_topic"][word, topic] += 1
|
483
|
+
self.topics["total_n_word_tokens_by_topic"][0, topic] += 1
|
484
|
+
self.topics["n_word_tokens_doc_by_topic"][doc, topic] += 1
|
485
|
+
|
486
|
+
def _update_peak_assignments(self, randseed):
|
487
|
+
"""Update y / r indicator variables assigning peaks->topics/subregions.
|
488
|
+
|
489
|
+
Parameters
|
490
|
+
----------
|
491
|
+
randseed : :obj:`int`
|
492
|
+
Random seed for this iteration.
|
493
|
+
"""
|
494
|
+
# Seed random number generator
|
495
|
+
np.random.seed(randseed)
|
496
|
+
|
497
|
+
# Retrieve p(x|r,y) for all subregions
|
498
|
+
peak_probs = self._get_peak_probs(self)
|
499
|
+
|
500
|
+
# Iterate over all peaks x, and sample a new y and r assignment for each
|
501
|
+
for i_ptoken, doc in enumerate(self.data["ptoken_doc_idx"]):
|
502
|
+
topic = self.topics["peak_topic_idx"][i_ptoken]
|
503
|
+
region = self.topics["peak_region_idx"][i_ptoken]
|
504
|
+
|
505
|
+
# Decrement count-matrices to remove current ptoken_topic_idx
|
506
|
+
# because ptoken will be reassigned to a new topic
|
507
|
+
self.topics["n_peak_tokens_region_by_topic"][region, topic] -= 1
|
508
|
+
self.topics["n_peak_tokens_doc_by_topic"][doc, topic] -= 1
|
509
|
+
|
510
|
+
# Retrieve the probability of generating current x from all
|
511
|
+
# subregions: [R x T] array of probs
|
512
|
+
p_x_subregions = (peak_probs[i_ptoken, :, :]).transpose()
|
513
|
+
|
514
|
+
# Compute the probabilities of all subregions given doc
|
515
|
+
# p(r|d) ~ p(r|t) * p(t|d)
|
516
|
+
# Counts of subregions per topic + prior: p(r|t)
|
517
|
+
p_region_g_topic = self.topics["n_peak_tokens_region_by_topic"] + self.params["delta"]
|
518
|
+
|
519
|
+
# Normalize the columns such that each topic's distribution over subregions sums to 1
|
520
|
+
p_region_g_topic = p_region_g_topic / np.sum(p_region_g_topic, axis=0, keepdims=True)
|
521
|
+
|
522
|
+
# Counts of topics per document + prior: p(t|d)
|
523
|
+
p_topic_g_doc = (
|
524
|
+
self.topics["n_peak_tokens_doc_by_topic"][doc, :] + self.params["alpha"]
|
525
|
+
)
|
526
|
+
|
527
|
+
# Reshape from (ntopics,) to (nregions, ntopics) with duplicated rows
|
528
|
+
# Makes it the same shape as p_region_g_topic
|
529
|
+
p_topic_g_doc = np.array([p_topic_g_doc] * self.params["n_regions"])
|
530
|
+
|
531
|
+
# Compute p(subregion | document): p(r|d) ~ p(r|t) * p(t|d)
|
532
|
+
# [R x T] array of probs
|
533
|
+
p_region_g_doc = p_topic_g_doc * p_region_g_topic
|
534
|
+
|
535
|
+
# Compute the multinomial probability: p(z|y)
|
536
|
+
# Need the current vector of all z and y assignments for current doc
|
537
|
+
# The multinomial from which z is sampled is proportional to number
|
538
|
+
# of y assigned to each topic, plus constant gamma
|
539
|
+
# Compute the proportional probabilities in log-space
|
540
|
+
logp = self.topics["n_word_tokens_doc_by_topic"][doc, :] * np.log(
|
541
|
+
(self.topics["n_peak_tokens_doc_by_topic"][doc, :] + self.params["gamma"] + 1)
|
542
|
+
/ (self.topics["n_peak_tokens_doc_by_topic"][doc, :] + self.params["gamma"])
|
543
|
+
)
|
544
|
+
# Add a constant before exponentiating to avoid any underflow issues
|
545
|
+
p_peak_g_topic = np.exp(logp - np.max(logp))
|
546
|
+
|
547
|
+
# Reshape from (ntopics,) to (nregions, ntopics) with duplicated rows
|
548
|
+
p_peak_g_topic = np.array([p_peak_g_topic] * self.params["n_regions"])
|
549
|
+
|
550
|
+
# Get the full sampling distribution:
|
551
|
+
# [R x T] array containing the proportional probability of all y/r combinations
|
552
|
+
probs_pdf = p_x_subregions * p_region_g_doc * p_peak_g_topic
|
553
|
+
|
554
|
+
# Convert from a [R x T] matrix into a [R*T x 1] array we can sample from
|
555
|
+
probs_pdf = np.reshape(probs_pdf, (self.params["n_regions"] * self.params["n_topics"]))
|
556
|
+
|
557
|
+
# Normalize the sampling distribution
|
558
|
+
probs_pdf = probs_pdf / np.sum(probs_pdf)
|
559
|
+
|
560
|
+
# Sample a single element (corresponding to a y_i and c_i assignment for the ptoken)
|
561
|
+
# from the sampling distribution
|
562
|
+
# Returns a binary [1 x R*T] vector with a '1' in location that was sampled
|
563
|
+
# and zeros everywhere else
|
564
|
+
assignment_vec = np.random.multinomial(1, probs_pdf)
|
565
|
+
|
566
|
+
# Reshape 1D back to [R x T] 2D
|
567
|
+
assignment_arr = np.reshape(
|
568
|
+
assignment_vec,
|
569
|
+
(self.params["n_regions"], self.params["n_topics"]),
|
570
|
+
)
|
571
|
+
# Transform the linear index of the sampled element into the
|
572
|
+
# subregion/topic (r/y) assignment indices
|
573
|
+
assignment_idx = np.where(assignment_arr)
|
574
|
+
# Subregion sampled (r)
|
575
|
+
region = assignment_idx[0][0]
|
576
|
+
# Topic sampled (y)
|
577
|
+
topic = assignment_idx[1][0]
|
578
|
+
|
579
|
+
# Update the indices and the count matrices using the sampled y/r assignments
|
580
|
+
# Increment count in Subregion x Topic count matrix
|
581
|
+
self.topics["n_peak_tokens_region_by_topic"][region, topic] += 1
|
582
|
+
# Increment count in Document x Topic count matrix
|
583
|
+
self.topics["n_peak_tokens_doc_by_topic"][doc, topic] += 1
|
584
|
+
# Update y->topic assignment
|
585
|
+
self.topics["peak_topic_idx"][i_ptoken] = topic
|
586
|
+
# Update y->subregion assignment
|
587
|
+
self.topics["peak_region_idx"][i_ptoken] = region
|
588
|
+
|
589
|
+
def _update_regions(self):
|
590
|
+
"""Update spatial distribution parameters (Gaussians params for all subregions).
|
591
|
+
|
592
|
+
Updates regions_mu and regions_sigma, indicating location and
|
593
|
+
distribution of each subregion.
|
594
|
+
"""
|
595
|
+
# Generate default ROI based on default_width
|
596
|
+
default_roi = self.params["roi_size"] * np.eye(self.data["ptoken_coords"].shape[1])
|
597
|
+
|
598
|
+
if self.params["symmetric"]:
|
599
|
+
n_pairs = int(self.params["n_regions"] / 2)
|
600
|
+
|
601
|
+
# With symmetric subregions, we jointly compute all estimates for subregions 1 & 2,
|
602
|
+
# constraining the means to be symmetric w.r.t. the origin along x-dimension
|
603
|
+
for i_topic in range(self.params["n_topics"]):
|
604
|
+
for j_pair in range(n_pairs):
|
605
|
+
region1, region2 = j_pair * 2, (j_pair * 2) + 1
|
606
|
+
|
607
|
+
# Get all peaks assigned to current topic & subregion 1
|
608
|
+
idx1 = (self.topics["peak_topic_idx"] == i_topic) & (
|
609
|
+
self.topics["peak_region_idx"] == region1
|
610
|
+
)
|
611
|
+
idx1_xyz = self.data["ptoken_coords"][idx1, :]
|
612
|
+
n_obs1 = self.topics["n_peak_tokens_region_by_topic"][region1, i_topic]
|
613
|
+
|
614
|
+
# Get all peaks assigned to current topic & subregion 2
|
615
|
+
idx2 = (self.topics["peak_topic_idx"] == i_topic) & (
|
616
|
+
self.topics["peak_region_idx"] == region2
|
617
|
+
)
|
618
|
+
idx2_xyz = self.data["ptoken_coords"][idx2, :]
|
619
|
+
n_obs2 = self.topics["n_peak_tokens_region_by_topic"][region2, i_topic]
|
620
|
+
|
621
|
+
# Get all peaks assigned to current topic & either subregion
|
622
|
+
all_topic_peaks = idx1 | idx2
|
623
|
+
all_xyz = self.data["ptoken_coords"][all_topic_peaks, :]
|
624
|
+
|
625
|
+
# Estimate means
|
626
|
+
# If there are no observations, we set mean equal to zeros, otherwise take MLE
|
627
|
+
|
628
|
+
# Estimate independent mean (centroid of peaks) for subregion 1
|
629
|
+
if n_obs1 == 0:
|
630
|
+
reg1_center_xyz = np.zeros([self.data["ptoken_coords"].shape[1]])
|
631
|
+
else:
|
632
|
+
reg1_center_xyz = np.mean(idx1_xyz, axis=0)
|
633
|
+
|
634
|
+
# Estimate independent mean (centroid of peaks) for subregion 2
|
635
|
+
if n_obs2 == 0:
|
636
|
+
reg2_center_xyz = np.zeros([self.data["ptoken_coords"].shape[1]])
|
637
|
+
else:
|
638
|
+
reg2_center_xyz = np.mean(idx2_xyz, axis=0)
|
639
|
+
|
640
|
+
# Estimate the weighted means of all dims, where for dim1 we
|
641
|
+
# compute the mean w.r.t. absolute distance from the origin
|
642
|
+
weighted_mean_dim1 = (
|
643
|
+
(-reg1_center_xyz[0] * n_obs1) + (reg2_center_xyz[0] * n_obs2)
|
644
|
+
) / (n_obs1 + n_obs2)
|
645
|
+
weighted_mean_otherdims = np.mean(all_xyz[:, 1:], axis=0)
|
646
|
+
|
647
|
+
# Store weighted mean estimates
|
648
|
+
mu1 = np.zeros([1, self.data["ptoken_coords"].shape[1]])
|
649
|
+
mu2 = np.zeros([1, self.data["ptoken_coords"].shape[1]])
|
650
|
+
mu1[0, 0] = -weighted_mean_dim1
|
651
|
+
mu1[0, 1:] = weighted_mean_otherdims
|
652
|
+
mu2[0, 0] = weighted_mean_dim1
|
653
|
+
mu2[0, 1:] = weighted_mean_otherdims
|
654
|
+
|
655
|
+
# Store estimates in model object
|
656
|
+
self.topics["regions_mu"][i_topic, region1, ...] = mu1
|
657
|
+
self.topics["regions_mu"][i_topic, region2, ...] = mu2
|
658
|
+
|
659
|
+
# Estimate Covariances
|
660
|
+
# Covariances are estimated independently
|
661
|
+
# Covariance for subregion 1
|
662
|
+
if n_obs1 <= 1:
|
663
|
+
c_hat1 = default_roi
|
664
|
+
else:
|
665
|
+
c_hat1 = np.cov(idx1_xyz, rowvar=False)
|
666
|
+
|
667
|
+
# Covariance for subregion 2
|
668
|
+
if n_obs2 <= 1:
|
669
|
+
c_hat2 = default_roi
|
670
|
+
else:
|
671
|
+
c_hat2 = np.cov(idx2_xyz, rowvar=False)
|
672
|
+
|
673
|
+
# Regularize the covariances, using the ratio of observations to
|
674
|
+
# sample_constant
|
675
|
+
d_c_1 = (n_obs1) / (n_obs1 + self.params["dobs"])
|
676
|
+
d_c_2 = (n_obs2) / (n_obs2 + self.params["dobs"])
|
677
|
+
sigma1 = (d_c_1 * c_hat1) + ((1 - d_c_1) * default_roi)
|
678
|
+
sigma2 = (d_c_2 * c_hat2) + ((1 - d_c_2) * default_roi)
|
679
|
+
|
680
|
+
# Store estimates in model object
|
681
|
+
self.topics["regions_sigma"][i_topic, region1, ...] = sigma1
|
682
|
+
self.topics["regions_sigma"][i_topic, region2, ...] = sigma2
|
683
|
+
else:
|
684
|
+
# For each region, compute a mean and a regularized covariance matrix
|
685
|
+
for i_topic in range(self.params["n_topics"]):
|
686
|
+
for j_region in range(self.params["n_regions"]):
|
687
|
+
# Get all peaks assigned to current topic & subregion
|
688
|
+
topic_region_peaks_idx = (self.topics["peak_topic_idx"] == i_topic) & (
|
689
|
+
self.topics["peak_region_idx"] == j_region
|
690
|
+
)
|
691
|
+
topic_region_peaks_xyz = self.data["ptoken_coords"][topic_region_peaks_idx, :]
|
692
|
+
n_obs = self.topics["n_peak_tokens_region_by_topic"][j_region, i_topic]
|
693
|
+
|
694
|
+
# Estimate mean
|
695
|
+
# If there are no observations, we set mean equal to zeros, otherwise take MLE
|
696
|
+
if n_obs == 0:
|
697
|
+
mu = np.zeros([self.data["ptoken_coords"].shape[1]])
|
698
|
+
else:
|
699
|
+
mu = np.mean(topic_region_peaks_xyz, axis=0)
|
700
|
+
|
701
|
+
# Estimate covariance
|
702
|
+
# if there are 1 or fewer observations, we set sigma_hat equal to default ROI,
|
703
|
+
# otherwise take MLE
|
704
|
+
if n_obs <= 1:
|
705
|
+
c_hat = default_roi
|
706
|
+
else:
|
707
|
+
c_hat = np.cov(topic_region_peaks_xyz, rowvar=False)
|
708
|
+
|
709
|
+
# Regularize the covariance, using the ratio of observations
|
710
|
+
# to dobs (default constant # observations)
|
711
|
+
d_c = n_obs / (n_obs + self.params["dobs"])
|
712
|
+
sigma = (d_c * c_hat) + ((1 - d_c) * default_roi)
|
713
|
+
|
714
|
+
# Store estimates in model object
|
715
|
+
self.topics["regions_mu"][i_topic, j_region, ...] = mu
|
716
|
+
self.topics["regions_sigma"][i_topic, j_region, ...] = sigma
|
717
|
+
|
718
|
+
def compute_log_likelihood(self, model=None, update_vectors=True):
|
719
|
+
"""Compute log-likelihood of a model object given current model.
|
720
|
+
|
721
|
+
Computes the log-likelihood of data in any model object (either train or test) given the
|
722
|
+
posterior predictive distributions over peaks and word-types for the model,
|
723
|
+
using the method described in :footcite:t:`newman2009distributed`.
|
724
|
+
Note that this is not computing the joint log-likelihood of model parameters and data.
|
725
|
+
|
726
|
+
Parameters
|
727
|
+
----------
|
728
|
+
model : :obj:`~nimare.annotate.gclda.GCLDAModel`, optional
|
729
|
+
The model for which log-likelihoods will be calculated.
|
730
|
+
If not provided, log-likelihood will be calculated for the current model (self).
|
731
|
+
Default is None.
|
732
|
+
update_vectors : :obj:`bool`, optional
|
733
|
+
Whether to update model's log-likelihood vectors or not.
|
734
|
+
Default is True.
|
735
|
+
|
736
|
+
Returns
|
737
|
+
-------
|
738
|
+
x_loglikely : :obj:`float`
|
739
|
+
Total log-likelihood of all peak tokens.
|
740
|
+
w_loglikely : :obj:`float`
|
741
|
+
Total log-likelihood of all word tokens.
|
742
|
+
tot_loglikely : :obj:`float`
|
743
|
+
Total log-likelihood of peak + word tokens.
|
744
|
+
|
745
|
+
References
|
746
|
+
----------
|
747
|
+
.. footbibliography::
|
748
|
+
"""
|
749
|
+
if model is None:
|
750
|
+
model = self
|
751
|
+
elif update_vectors:
|
752
|
+
LGR.info("External model detected: Disabling update_vectors")
|
753
|
+
update_vectors = False
|
754
|
+
|
755
|
+
# Pre-compute all probabilities from count matrices that are needed
|
756
|
+
# for loglikelihood computations
|
757
|
+
# Compute docprobs for y = ND x NT: p( y_i=t | d )
|
758
|
+
doccounts = self.topics["n_peak_tokens_doc_by_topic"] + self.params["alpha"]
|
759
|
+
doccounts_sum = np.sum(doccounts, axis=1)
|
760
|
+
docprobs_y = np.transpose(np.transpose(doccounts) / doccounts_sum)
|
761
|
+
|
762
|
+
# Compute docprobs for z = ND x NT: p( z_i=t | y^(d) )
|
763
|
+
doccounts = self.topics["n_peak_tokens_doc_by_topic"] + self.params["gamma"]
|
764
|
+
doccounts_sum = np.sum(doccounts, axis=1)
|
765
|
+
docprobs_z = np.transpose(np.transpose(doccounts) / doccounts_sum)
|
766
|
+
|
767
|
+
# Compute regionprobs = NR x NT: p( r | t )
|
768
|
+
regioncounts = (self.topics["n_peak_tokens_region_by_topic"]) + self.params["delta"]
|
769
|
+
regioncounts_sum = np.sum(regioncounts, axis=0)
|
770
|
+
regionprobs = regioncounts / regioncounts_sum
|
771
|
+
|
772
|
+
# Compute wordprobs = NW x NT: p( w | t )
|
773
|
+
wordcounts = self.topics["n_word_tokens_word_by_topic"] + self.params["beta"]
|
774
|
+
wordcounts_sum = np.sum(wordcounts, axis=0)
|
775
|
+
wordprobs = wordcounts / wordcounts_sum
|
776
|
+
|
777
|
+
# Get the matrix giving p(x_i|r,t) for all x:
|
778
|
+
# NY x NT x NR matrix of probabilities of all peaks given all
|
779
|
+
# topic/subregion spatial distributions
|
780
|
+
peak_probs = self._get_peak_probs(model)
|
781
|
+
|
782
|
+
# Compute observed peaks (x) Loglikelihood:
|
783
|
+
# p(x|model, doc) = p(topic|doc) * p(subregion|topic) * p(x|subregion)
|
784
|
+
# = p_topic_g_doc * p_region_g_topic * p_x_r
|
785
|
+
# Initialize variable tracking total loglikelihood of all x tokens
|
786
|
+
x_loglikely = 0
|
787
|
+
|
788
|
+
# Go over all observed peaks and add p(x|model) to running total
|
789
|
+
for i_ptoken in range(len(self.data["ptoken_doc_idx"])):
|
790
|
+
doc = self.data["ptoken_doc_idx"][i_ptoken] - 1 # convert didx from 1-idx to 0-idx
|
791
|
+
p_x = 0 # Running total for p(x|d) across subregions:
|
792
|
+
# Compute p(x_i|d) for each subregion separately and then
|
793
|
+
# sum across the subregions
|
794
|
+
for j_region in range(self.params["n_regions"]):
|
795
|
+
# p(t|d) - p(topic|doc)
|
796
|
+
p_topic_g_doc = docprobs_y[doc]
|
797
|
+
|
798
|
+
# p(r|t) - p(subregion|topic)
|
799
|
+
p_region_g_topic = regionprobs[j_region]
|
800
|
+
|
801
|
+
# p(r|d) - p(subregion|document) = p(topic|doc)*p(subregion|topic)
|
802
|
+
p_region_g_doc = p_topic_g_doc * p_region_g_topic
|
803
|
+
|
804
|
+
# p(x|r) - p(x|subregion)
|
805
|
+
p_x_r = peak_probs[i_ptoken, :, j_region]
|
806
|
+
|
807
|
+
# p(x|subregion,doc) = sum_topics ( p(subregion|doc) * p(x|subregion) )
|
808
|
+
p_x_rd = np.dot(p_region_g_doc, p_x_r)
|
809
|
+
p_x += p_x_rd # Add probability for current subregion to total
|
810
|
+
# probability for token across subregions
|
811
|
+
# Add probability for current token to running total for all x tokens
|
812
|
+
x_loglikely += np.log(p_x)
|
813
|
+
|
814
|
+
# Compute observed words (w) Loglikelihoods:
|
815
|
+
# p(w|model, doc) = p(topic|doc) * p(word|topic)
|
816
|
+
# = p_topic_g_doc * p_w_t
|
817
|
+
w_loglikely = 0 # Initialize variable tracking total loglikelihood of all w tokens
|
818
|
+
|
819
|
+
# Compute a matrix of posterior predictives over words:
|
820
|
+
# = ND x NW p(w|d) = sum_t ( p(t|d) * p(w|t) )
|
821
|
+
p_wtoken_g_doc = np.dot(docprobs_z, np.transpose(wordprobs))
|
822
|
+
|
823
|
+
# Go over all observed word tokens and add p(w|model) to running total
|
824
|
+
for i_wtoken in range(len(self.data["wtoken_word_idx"])):
|
825
|
+
# convert wtoken_word_idx from 1-idx to 0-idx
|
826
|
+
word_token = self.data["wtoken_word_idx"][i_wtoken] - 1
|
827
|
+
# convert wtoken_doc_idx from 1-idx to 0-idx
|
828
|
+
doc = self.data["wtoken_doc_idx"][i_wtoken] - 1
|
829
|
+
# Probability of sampling current w token from d
|
830
|
+
p_wtoken = p_wtoken_g_doc[doc, word_token]
|
831
|
+
# Add log-probability of current token to running total for all w tokens
|
832
|
+
w_loglikely += np.log(p_wtoken)
|
833
|
+
tot_loglikely = x_loglikely + w_loglikely
|
834
|
+
|
835
|
+
# Update model log-likelihood history vector (if update_vectors == True)
|
836
|
+
if update_vectors:
|
837
|
+
self.loglikelihood["iter"].append(self.iter)
|
838
|
+
self.loglikelihood["x"].append(x_loglikely)
|
839
|
+
self.loglikelihood["w"].append(w_loglikely)
|
840
|
+
self.loglikelihood["total"].append(tot_loglikely)
|
841
|
+
|
842
|
+
# Return loglikely values (used when computing log-likelihood for a
|
843
|
+
# model-object containing hold-out data)
|
844
|
+
return (x_loglikely, w_loglikely, tot_loglikely)
|
845
|
+
|
846
|
+
def _get_peak_probs(self, model):
|
847
|
+
"""Compute a matrix giving p(x|r,t).
|
848
|
+
|
849
|
+
This uses all x values in a model object, and each topic's spatial parameters.
|
850
|
+
|
851
|
+
Returns
|
852
|
+
-------
|
853
|
+
peak_probs : :obj:`numpy.ndarray` of :obj:`numpy.float64`
|
854
|
+
nPeaks x nTopics x nRegions matrix of probabilities, giving
|
855
|
+
probability of sampling each peak (x) from all subregions.
|
856
|
+
"""
|
857
|
+
peak_probs = np.zeros(
|
858
|
+
(len(model.data["ptoken_doc_idx"]), self.params["n_topics"], self.params["n_regions"]),
|
859
|
+
dtype=float,
|
860
|
+
)
|
861
|
+
for i_topic in range(self.params["n_topics"]):
|
862
|
+
for j_region in range(self.params["n_regions"]):
|
863
|
+
pdf = multivariate_normal.pdf(
|
864
|
+
model.data["ptoken_coords"],
|
865
|
+
mean=self.topics["regions_mu"][i_topic, j_region, 0, :],
|
866
|
+
cov=self.topics["regions_sigma"][i_topic, j_region, ...],
|
867
|
+
)
|
868
|
+
peak_probs[:, i_topic, j_region] = pdf
|
869
|
+
return peak_probs
|
870
|
+
|
871
|
+
def get_probability_distributions(self):
|
872
|
+
"""Get conditional probability of selecting each voxel in the brain mask given each topic.
|
873
|
+
|
874
|
+
Returns
|
875
|
+
-------
|
876
|
+
p_topic_g_voxel : :obj:`numpy.ndarray` of :obj:`numpy.float64`
|
877
|
+
A voxel-by-topic array of conditional probabilities: p(topic|voxel).
|
878
|
+
For cell ij, the value is the probability of topic j being selected
|
879
|
+
given voxel i is active.
|
880
|
+
p_voxel_g_topic : :obj:`numpy.ndarray` of :obj:`numpy.float64`
|
881
|
+
A voxel-by-topic array of conditional probabilities: p(voxel|topic).
|
882
|
+
For cell ij, the value is the probability of voxel i being selected
|
883
|
+
given topic j has already been selected.
|
884
|
+
p_topic_g_word : :obj:`numpy.ndarray` of :obj:`numpy.float64`
|
885
|
+
A word-by-topic array of conditional probabilities: p(topic|word).
|
886
|
+
For cell ij, the value is the probability of topic i being selected
|
887
|
+
given word j is present.
|
888
|
+
p_word_g_topic : :obj:`numpy.ndarray` of :obj:`numpy.float64`
|
889
|
+
A word-by-topic array of conditional probabilities: p(word|topic).
|
890
|
+
For cell ij, the value is the probability of word j being selected
|
891
|
+
given topic i has already been selected.
|
892
|
+
"""
|
893
|
+
affine = self.mask.affine
|
894
|
+
mask_ijk = np.vstack(np.where(self.mask.get_fdata())).T
|
895
|
+
mask_xyz = nib.affines.apply_affine(affine, mask_ijk)
|
896
|
+
|
897
|
+
spatial_dists = np.zeros((mask_xyz.shape[0], self.params["n_topics"]), float)
|
898
|
+
for i_topic in range(self.params["n_topics"]):
|
899
|
+
for j_region in range(self.params["n_regions"]):
|
900
|
+
pdf = multivariate_normal.pdf(
|
901
|
+
mask_xyz,
|
902
|
+
mean=self.topics["regions_mu"][i_topic, j_region, 0, :],
|
903
|
+
cov=self.topics["regions_sigma"][i_topic, j_region, ...],
|
904
|
+
)
|
905
|
+
spatial_dists[:, i_topic] += pdf
|
906
|
+
p_topic_g_voxel = spatial_dists / np.sum(spatial_dists, axis=1)[:, None]
|
907
|
+
p_topic_g_voxel = np.nan_to_num(p_topic_g_voxel, 0) # might be unnecessary
|
908
|
+
|
909
|
+
p_voxel_g_topic = spatial_dists / np.sum(spatial_dists, axis=0)[None, :]
|
910
|
+
p_voxel_g_topic = np.nan_to_num(p_voxel_g_topic, 0) # might be unnecessary
|
911
|
+
|
912
|
+
n_word_tokens_per_topic = np.sum(self.topics["n_word_tokens_word_by_topic"], axis=0)
|
913
|
+
p_word_g_topic = (
|
914
|
+
self.topics["n_word_tokens_word_by_topic"] / n_word_tokens_per_topic[None, :]
|
915
|
+
)
|
916
|
+
p_word_g_topic = np.nan_to_num(p_word_g_topic, 0)
|
917
|
+
|
918
|
+
n_topics_per_word_token = np.sum(self.topics["n_word_tokens_word_by_topic"], axis=1)
|
919
|
+
p_topic_g_word = (
|
920
|
+
self.topics["n_word_tokens_word_by_topic"] / n_topics_per_word_token[:, None]
|
921
|
+
)
|
922
|
+
p_topic_g_word = np.nan_to_num(p_topic_g_word, 0)
|
923
|
+
|
924
|
+
return p_topic_g_voxel, p_voxel_g_topic, p_topic_g_word, p_word_g_topic
|