irtorch 0.0.1__tar.gz

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.
Files changed (82) hide show
  1. irtorch-0.0.1/LICENSE.txt +19 -0
  2. irtorch-0.0.1/PKG-INFO +52 -0
  3. irtorch-0.0.1/README.md +40 -0
  4. irtorch-0.0.1/irtorch/__init__.py +10 -0
  5. irtorch-0.0.1/irtorch/_internal_utils.py +328 -0
  6. irtorch-0.0.1/irtorch/activation_functions.py +91 -0
  7. irtorch-0.0.1/irtorch/config.py +31 -0
  8. irtorch-0.0.1/irtorch/cross_validation.py +129 -0
  9. irtorch-0.0.1/irtorch/datasets/big_five/big_five.pt +0 -0
  10. irtorch-0.0.1/irtorch/datasets/national_mathematics/mathematics_1.pt +0 -0
  11. irtorch-0.0.1/irtorch/datasets/national_mathematics/mathematics_2.pt +0 -0
  12. irtorch-0.0.1/irtorch/estimation_algorithms/__init__.py +3 -0
  13. irtorch-0.0.1/irtorch/estimation_algorithms/aeirt.py +379 -0
  14. irtorch-0.0.1/irtorch/estimation_algorithms/base_irt_algorithm.py +98 -0
  15. irtorch-0.0.1/irtorch/estimation_algorithms/encoders/__init__.py +4 -0
  16. irtorch-0.0.1/irtorch/estimation_algorithms/encoders/base_encoder.py +36 -0
  17. irtorch-0.0.1/irtorch/estimation_algorithms/encoders/bounded_encoder.py +40 -0
  18. irtorch-0.0.1/irtorch/estimation_algorithms/encoders/standard_encoder.py +39 -0
  19. irtorch-0.0.1/irtorch/estimation_algorithms/encoders/variational_encoder.py +41 -0
  20. irtorch-0.0.1/irtorch/estimation_algorithms/vaeirt.py +381 -0
  21. irtorch-0.0.1/irtorch/gaussian_mixture_torch.py +95 -0
  22. irtorch-0.0.1/irtorch/irt.py +1215 -0
  23. irtorch-0.0.1/irtorch/irt_evaluator.py +718 -0
  24. irtorch-0.0.1/irtorch/irt_plotter.py +1166 -0
  25. irtorch-0.0.1/irtorch/irt_scorer.py +1007 -0
  26. irtorch-0.0.1/irtorch/latent_variable_functions.py +82 -0
  27. irtorch-0.0.1/irtorch/layers.py +173 -0
  28. irtorch-0.0.1/irtorch/load_dataset.py +140 -0
  29. irtorch-0.0.1/irtorch/models/__init__.py +3 -0
  30. irtorch-0.0.1/irtorch/models/base_irt_model.py +219 -0
  31. irtorch-0.0.1/irtorch/models/monotone_nn.py +262 -0
  32. irtorch-0.0.1/irtorch/models/parametric.py +274 -0
  33. irtorch-0.0.1/irtorch/outlier_detector.py +163 -0
  34. irtorch-0.0.1/irtorch/quantile_mv_normal.py +100 -0
  35. irtorch-0.0.1/irtorch/timer.py +27 -0
  36. irtorch-0.0.1/irtorch/utils.py +159 -0
  37. irtorch-0.0.1/irtorch.egg-info/PKG-INFO +52 -0
  38. irtorch-0.0.1/irtorch.egg-info/SOURCES.txt +61 -0
  39. irtorch-0.0.1/irtorch.egg-info/dependency_links.txt +1 -0
  40. irtorch-0.0.1/irtorch.egg-info/not-zip-safe +1 -0
  41. irtorch-0.0.1/irtorch.egg-info/requires.txt +7 -0
  42. irtorch-0.0.1/irtorch.egg-info/top_level.txt +1 -0
  43. irtorch-0.0.1/setup.cfg +4 -0
  44. irtorch-0.0.1/setup.py +36 -0
  45. irtorch-0.0.1/tests/__pycache__/test_activation_functions.cpython-311-pytest-7.3.1.pyc +0 -0
  46. irtorch-0.0.1/tests/__pycache__/test_aeirt.cpython-311-pytest-7.3.1.pyc +0 -0
  47. irtorch-0.0.1/tests/__pycache__/test_base_irt_model.cpython-311-pytest-7.3.1.pyc +0 -0
  48. irtorch-0.0.1/tests/__pycache__/test_config.cpython-311-pytest-7.3.1.pyc +0 -0
  49. irtorch-0.0.1/tests/__pycache__/test_gaussian_mixture_torch.cpython-311-pytest-7.3.1.pyc +0 -0
  50. irtorch-0.0.1/tests/__pycache__/test_integration.cpython-311-pytest-7.3.1.pyc +0 -0
  51. irtorch-0.0.1/tests/__pycache__/test_internal_utils.cpython-311-pytest-7.3.1.pyc +0 -0
  52. irtorch-0.0.1/tests/__pycache__/test_irt_evaluator.cpython-311-pytest-7.3.1.pyc +0 -0
  53. irtorch-0.0.1/tests/__pycache__/test_irt_plotter.cpython-311-pytest-7.3.1.pyc +0 -0
  54. irtorch-0.0.1/tests/__pycache__/test_irt_scorer.cpython-311-pytest-7.3.1.pyc +0 -0
  55. irtorch-0.0.1/tests/__pycache__/test_latent_variable_functions.cpython-311-pytest-7.3.1.pyc +0 -0
  56. irtorch-0.0.1/tests/__pycache__/test_layers.cpython-311-pytest-7.3.1.pyc +0 -0
  57. irtorch-0.0.1/tests/__pycache__/test_load_dataset.cpython-311-pytest-7.3.1.pyc +0 -0
  58. irtorch-0.0.1/tests/__pycache__/test_monotone_nn.cpython-311-pytest-7.3.1.pyc +0 -0
  59. irtorch-0.0.1/tests/__pycache__/test_outlier_detector.cpython-311-pytest-7.3.1.pyc +0 -0
  60. irtorch-0.0.1/tests/__pycache__/test_parametric.cpython-311-pytest-7.3.1.pyc +0 -0
  61. irtorch-0.0.1/tests/__pycache__/test_quantile_mv_normal.cpython-311-pytest-7.3.1.pyc +0 -0
  62. irtorch-0.0.1/tests/__pycache__/test_utils.cpython-311-pytest-7.3.1.pyc +0 -0
  63. irtorch-0.0.1/tests/__pycache__/test_vaeirt.cpython-311-pytest-7.3.1.pyc +0 -0
  64. irtorch-0.0.1/tests/test_activation_functions.py +25 -0
  65. irtorch-0.0.1/tests/test_aeirt.py +105 -0
  66. irtorch-0.0.1/tests/test_base_irt_model.py +108 -0
  67. irtorch-0.0.1/tests/test_config.py +29 -0
  68. irtorch-0.0.1/tests/test_gaussian_mixture_torch.py +33 -0
  69. irtorch-0.0.1/tests/test_integration.py +148 -0
  70. irtorch-0.0.1/tests/test_internal_utils.py +229 -0
  71. irtorch-0.0.1/tests/test_irt_evaluator.py +419 -0
  72. irtorch-0.0.1/tests/test_irt_plotter.py +99 -0
  73. irtorch-0.0.1/tests/test_irt_scorer.py +232 -0
  74. irtorch-0.0.1/tests/test_latent_variable_functions.py +94 -0
  75. irtorch-0.0.1/tests/test_layers.py +118 -0
  76. irtorch-0.0.1/tests/test_load_dataset.py +49 -0
  77. irtorch-0.0.1/tests/test_monotone_nn.py +202 -0
  78. irtorch-0.0.1/tests/test_outlier_detector.py +62 -0
  79. irtorch-0.0.1/tests/test_parametric.py +268 -0
  80. irtorch-0.0.1/tests/test_quantile_mv_normal.py +83 -0
  81. irtorch-0.0.1/tests/test_utils.py +131 -0
  82. irtorch-0.0.1/tests/test_vaeirt.py +184 -0
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2018 The Python Packaging Authority
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
irtorch-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,52 @@
1
+ Metadata-Version: 2.1
2
+ Name: irtorch
3
+ Version: 0.0.1
4
+ Summary: IRTorch: An item response theory package for python.
5
+ Home-page: https://github.com/joakimwallmark/irtorch
6
+ Author: Joakim Wallmark
7
+ Author-email: wallmark.joakim@gmail.com
8
+ License: MIT
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE.txt
12
+
13
+ [![tests](https://github.com/joakimwallmark/irtorch/actions/workflows/tests.yml/badge.svg)](https://github.com/joakimwallmark/irtorch/actions/workflows/tests.yml)
14
+ [![codecov](https://codecov.io/github/joakimwallmark/irtorch/graph/badge.svg?token=0TPDVGIUZ2)](https://codecov.io/github/joakimwallmark/irtorch)
15
+ [![Documentation Status](https://readthedocs.org/projects/irtorch/badge/?version=latest)](https://irtorch.readthedocs.io/en/latest/?badge=latest)
16
+
17
+ <img src="https://raw.githubusercontent.com/joakimwallmark/irtorch/main/docs/source/_static/logo_readme.png" alt="IRTorch" style="width: 50%;">
18
+
19
+ `IRTorch` is a Python package for item response theory (IRT). It utilizes [PyTorch](https://pytorch.org/) for model optimization and GPU support.
20
+ Check out our [documentation page](https://irtorch.readthedocs.io/en/latest/) for usage examples and API reference.
21
+
22
+ ## Installation
23
+ Install from Python Package Index (PyPI)
24
+ ```bash
25
+ pip install irtorch
26
+ ```
27
+
28
+ Install from GitHub
29
+ ```bash
30
+ pip install git+https://github.com/joakimwallmark/irtorch.git
31
+ ```
32
+
33
+ ## Citation
34
+ Citations hold great value to us since they allow us to explore the various ways the software is being used. Additionally, citations serve as proof of usage, which can assist in securing grant funding.
35
+
36
+ To cite IRTorch in publications use:
37
+
38
+ Wallmark, J. (2024). IRTorch: Item response theory with Python (Version X.X) [Software]. GitHub. https://github.com/joakimwallmark/irtorch
39
+
40
+ Or use the following BibTeX entry:
41
+
42
+ ```bibtex
43
+ @misc{irtorch2024,
44
+ author = {Wallmark, Joakim},
45
+ title = {IRTorch: Item response theory with Python},
46
+ year = {2024},
47
+ publisher = {GitHub},
48
+ journal = {GitHub repository},
49
+ howpublished = {\url{https://github.com/joakimwallmark/irtorch}},
50
+ version = {X.X}
51
+ }
52
+ ```
@@ -0,0 +1,40 @@
1
+ [![tests](https://github.com/joakimwallmark/irtorch/actions/workflows/tests.yml/badge.svg)](https://github.com/joakimwallmark/irtorch/actions/workflows/tests.yml)
2
+ [![codecov](https://codecov.io/github/joakimwallmark/irtorch/graph/badge.svg?token=0TPDVGIUZ2)](https://codecov.io/github/joakimwallmark/irtorch)
3
+ [![Documentation Status](https://readthedocs.org/projects/irtorch/badge/?version=latest)](https://irtorch.readthedocs.io/en/latest/?badge=latest)
4
+
5
+ <img src="https://raw.githubusercontent.com/joakimwallmark/irtorch/main/docs/source/_static/logo_readme.png" alt="IRTorch" style="width: 50%;">
6
+
7
+ `IRTorch` is a Python package for item response theory (IRT). It utilizes [PyTorch](https://pytorch.org/) for model optimization and GPU support.
8
+ Check out our [documentation page](https://irtorch.readthedocs.io/en/latest/) for usage examples and API reference.
9
+
10
+ ## Installation
11
+ Install from Python Package Index (PyPI)
12
+ ```bash
13
+ pip install irtorch
14
+ ```
15
+
16
+ Install from GitHub
17
+ ```bash
18
+ pip install git+https://github.com/joakimwallmark/irtorch.git
19
+ ```
20
+
21
+ ## Citation
22
+ Citations hold great value to us since they allow us to explore the various ways the software is being used. Additionally, citations serve as proof of usage, which can assist in securing grant funding.
23
+
24
+ To cite IRTorch in publications use:
25
+
26
+ Wallmark, J. (2024). IRTorch: Item response theory with Python (Version X.X) [Software]. GitHub. https://github.com/joakimwallmark/irtorch
27
+
28
+ Or use the following BibTeX entry:
29
+
30
+ ```bibtex
31
+ @misc{irtorch2024,
32
+ author = {Wallmark, Joakim},
33
+ title = {IRTorch: Item response theory with Python},
34
+ year = {2024},
35
+ publisher = {GitHub},
36
+ journal = {GitHub repository},
37
+ howpublished = {\url{https://github.com/joakimwallmark/irtorch}},
38
+ version = {X.X}
39
+ }
40
+ ```
@@ -0,0 +1,10 @@
1
+ import logging
2
+ from .irt import IRT
3
+
4
+ __version__ = '0.0.1'
5
+
6
+ logging.basicConfig(level=logging.INFO,
7
+ format='%(levelname)s: %(message)s',
8
+ datefmt='%Y-%m-%d %H:%M:%S')
9
+
10
+ logger = logging.getLogger('irtorch')
@@ -0,0 +1,328 @@
1
+ import torch
2
+
3
+ def linear_regression(x, y):
4
+ """
5
+ Performs linear regression.
6
+
7
+ Parameters
8
+ -----------
9
+ x : torch.Tensor
10
+ Design matrix of shape (m, n), where m is the number of samples and n is the number of features.
11
+ y : torch.Tensor
12
+ Target vector of shape (m, o), where m is the number of samples and o is the number response variables.
13
+
14
+ Returns
15
+ -----------
16
+ w : torch.Tensor
17
+ A tensor vector with the bias and the weights of shape (n+1, o).
18
+ """
19
+ # Add a bias term (1) to each sample in x
20
+ bias = torch.cat([torch.ones(x.size(0), 1), x], dim=1)
21
+
22
+ # Compute the weights using the normal equation
23
+ w = torch.inverse(bias.t().mm(bias)).mm(bias.t()).mm(y)
24
+
25
+ return w
26
+
27
+
28
+ def impute_missing(data: torch.tensor, mc_correct: list[int] = None, item_categories: list[int] = None):
29
+ """
30
+ Impute missing values in the data. For multiple choice data for which missing is not modeled, imputes randomly from incorrect responses.
31
+
32
+ Parameters
33
+ -----------
34
+ data : torch.Tensor
35
+ A 2D tensor where each row represents one respondent and each column represents an item.
36
+ The values should be the scores/possible responses on the items, starting from 0.
37
+ Missing item responses need to be coded as -1 or 'nan'.
38
+ mc_correct : list[int], optional
39
+ A list of integers where each integer is the correct response for the corresponding item. If None, the data is assumed to be non multiple choice (or dichotomously scored multiple choice with only 0's and 1's). (default is None)
40
+ item_categories : list[int], optional
41
+ A list of integers where each integer is the number of possible responses for the corresponding item. If None, the number of possible responses is calculated from the data. (default is None)
42
+
43
+ Returns
44
+ ----------
45
+ torch.Tensor
46
+ A 2D tensor with missing values imputed. Rows are respondents and columns are items.
47
+ """
48
+ if data.isnan().any():
49
+ data[data.isnan()] = -1
50
+
51
+ if mc_correct is None:
52
+ data[data==-1] = 0
53
+ return data
54
+ else:
55
+ if item_categories is None:
56
+ raise ValueError("item_categories are required for multiple choice imputation")
57
+ for col in range(data.shape[1]):
58
+ # Get the incorrect non-missing responses from the column
59
+ incorrect_responses = torch.arange(0, item_categories[col])
60
+ incorrect_responses = incorrect_responses[incorrect_responses != mc_correct[col]-1]
61
+
62
+ # Find the indices of -1 values in the column
63
+ missing_indices = (data[:, col] == -1).squeeze()
64
+
65
+ # randomly sample from the incorrect responses and replace missing
66
+ data[missing_indices, col] = incorrect_responses[torch.randint(0, incorrect_responses.size(0), (missing_indices.sum(),))].float()
67
+
68
+ return data
69
+
70
+ def random_guessing_data(
71
+ item_categories: list[int],
72
+ size: int,
73
+ guessing_probabilities: list[float] = None,
74
+ mc_correct: list[int] = None
75
+ ):
76
+ """
77
+ Create random test data based on guessing.
78
+
79
+ Parameters
80
+ ----------
81
+ item_categories : list[int]
82
+ A list of integers where each integer is the number of possible responses for the corresponding item, excluding missing responses.
83
+ size : int
84
+ The number of rows in the returned tensor.
85
+ guessing_probabilities: list[float], optional
86
+ The guessing probability for each item. The same length as the number of items. Guessing is not supported for polytomously scored items and the probabilities for them will be ignored by setting all responses to 0. (default is None and uses no guessing or, for multiple choice models, 1 over the number of item categories)
87
+ mc_correct : list[int], optional
88
+ Only for multiple choice data with guessing_probabilities supplied. A list of integers where each integer is the correct response for the corresponding item. If None, the data is assumed to be non multiple choice (or dichotomously scored multiple choice with only 0's and 1's). (default is None)
89
+
90
+ Returns
91
+ -------
92
+ torch.Tensor
93
+ A 2D tensor with test data. Rows are respondents and columns are items.
94
+ """
95
+ num_items = len(item_categories)
96
+ if (
97
+ guessing_probabilities is not None and \
98
+ isinstance(guessing_probabilities, list) and \
99
+ all(isinstance(item, float) for item in guessing_probabilities) and \
100
+ len(guessing_probabilities) == num_items
101
+ ):
102
+ if not all(0 <= num < 1 for num in guessing_probabilities):
103
+ raise ValueError("The guessing probabilities must be between 0 and 1.")
104
+ else:
105
+ raise ValueError("guessing_probabilities must be list of floats with the same length as the number of items.")
106
+
107
+
108
+ if guessing_probabilities is None:
109
+ # Use default guessing probabilities
110
+ guessing_probabilities = [1.0 / cats for cats in item_categories]
111
+
112
+ # Initialize the response matrix with zeros
113
+ response_matrix = torch.zeros(size, num_items)
114
+
115
+ # Process each item
116
+ for item_idx, num_categories in enumerate(item_categories):
117
+ guessing_prob = guessing_probabilities[item_idx]
118
+
119
+ if num_categories == 2:
120
+ # Dichotomous item, generate responses based on the guessing probability
121
+ responses = torch.bernoulli(torch.full((size,), guessing_prob))
122
+ else:
123
+ if mc_correct is not None:
124
+ # Create a tensor to hold probabilities for all choices
125
+ probs = torch.full((num_categories,), (1 - guessing_prob) / (num_categories - 1))
126
+
127
+ # Assign the guessing probability to the correct option
128
+ probs[mc_correct[item_idx]-1] = guessing_prob
129
+
130
+ # Now, for the incorrect answers, we distribute the remaining probability
131
+ # We've taken the guessing_prob for the correct answer, so we distribute what's left
132
+ incorrect_total_prob = 1.0 - guessing_prob
133
+ probs[probs != guessing_prob] = incorrect_total_prob / (num_categories - 1) # distribute among others
134
+
135
+ # Randomly choose options based on the probabilities
136
+ responses = torch.multinomial(probs.repeat(size, 1), 1).squeeze()
137
+ else:
138
+ # Polytomous item which is not mcmc, keep at 0
139
+ responses = torch.zeros(size, dtype=torch.long)
140
+
141
+ response_matrix[:, item_idx] = responses
142
+
143
+ return response_matrix
144
+
145
+ def conditional_score_distribution(
146
+ probabilities: torch.Tensor,
147
+ item_categories: list[int],
148
+ ):
149
+ """
150
+ Compute total score distribution conditional on z as by (Thissen et. al. 1995).
151
+
152
+ Parameters
153
+ ----------
154
+ probabilities : torch.Tensor
155
+ A 3D tensor containing item score probabilities for each z quadrature point.
156
+ The first dimension represents the quadrature points, the second dimension represents the items and the third dimension represents the item categories.
157
+ item_categories : list[list]
158
+ A list of integers where each integer is the number of possible responses for the corresponding item.
159
+
160
+ Returns
161
+ -------
162
+ torch.Tensor
163
+ A 2D torch tensor of total score probabilities, rows being quadrature z points and columns being total scores. (rows sum to 1)
164
+ """
165
+ no_items = probabilities.shape[1]
166
+ q_points = probabilities.shape[0]
167
+ max_score = sum(item_categories) - no_items
168
+
169
+ # Rows are quadrature points, columns are total scores
170
+ nsprobs = torch.zeros(q_points, max_score + 1).to(probabilities.device)
171
+ nsprobs[:, : item_categories[0]] = probabilities[:, 0, :item_categories[0]]
172
+
173
+ if no_items > 1:
174
+ for item in range(1, no_items):
175
+ item_max = sum(item_categories[: item + 1]) - len(
176
+ item_categories[: item + 1]
177
+ )
178
+ sprobs = nsprobs.clone()
179
+ nsprobs = torch.zeros_like(nsprobs)
180
+ for j in range(item_max - item_categories[item] + 2):
181
+ nsprobs[:, j : item_categories[item] + j] = (
182
+ torch.t(sprobs[:, j] * torch.t(probabilities[:, item, :item_categories[item]]))
183
+ + nsprobs[:, j : item_categories[item] + j]
184
+ )
185
+ return nsprobs
186
+
187
+
188
+ def sum_incorrect_probabilities(
189
+ probabilities: list[torch.Tensor],
190
+ modeled_item_responses: list[int],
191
+ mc_correct: list[int],
192
+ missing_modeled: bool,
193
+ ):
194
+ """
195
+ Sum incorrect score probabilities for multiple choice items. Useful for approximating sum scores.
196
+
197
+ Parameters
198
+ ----------
199
+ probabilities : list[torch.Tensor]
200
+ A list of 2D tensors containing item score probabilities for each item.
201
+ Rows are z quadrature points from the z density and columns correspond to item responses. (rows sum to 1)
202
+ modeled_item_responses : list[int]
203
+ A list of integers where each integer is the number of possible responses for the corresponding item.
204
+ mc_correct : list[int]
205
+ A list of integers where each integer is correct response for the corresponding item.
206
+ missing_modeled : bool
207
+ Whether probabilities come from a model that modeled missing responses.
208
+
209
+ Returns
210
+ -------
211
+ torch.Tensor
212
+ A 2D torch tensor correct/incorrect response probabilities
213
+ """
214
+ mc_correct = [corr + 1 for corr in mc_correct] if missing_modeled else mc_correct
215
+ new_probs = torch.zeros(probabilities.shape[0], probabilities.shape[1], 2)
216
+ for item in range(0, len(modeled_item_responses)):
217
+ item_score_0_probs = torch.cat(
218
+ (
219
+ probabilities[:, item, :mc_correct[item] - 1],
220
+ probabilities[:, item, mc_correct[item]:]
221
+ ),
222
+ dim=1,
223
+ ).sum(dim=1)
224
+ new_probs[:, item, :] = torch.cat(
225
+ (
226
+ item_score_0_probs.unsqueeze(1),
227
+ probabilities[:, item, mc_correct[item] - 1].unsqueeze(1),
228
+ ),
229
+ dim=1,
230
+ )
231
+ return new_probs
232
+
233
+
234
+ def entropy(probabilities: torch.Tensor, log_base: int = 2):
235
+ """
236
+ Calculate the entropy of a set of probabilities.
237
+
238
+ The entropy is a measure of the uncertainty or randomness of a set of probabilities. It is calculated as the sum of the product of each probability and its surprisal (negative log probability).
239
+
240
+ Parameters
241
+ -------------
242
+ probabilities: torch.Tensor
243
+ A tensor of probabilities. The last tensor dimension should represent a discrete probability distribution and should sum to 1.
244
+ log_base: int, optional
245
+ The base of the logarithm used in the calculation. (default is 2, which gives entropy in bits)
246
+
247
+ Returns
248
+ -------------
249
+ entropy: torch.Tensor
250
+ The entropy of each row of probabilities.
251
+ """
252
+ if not torch.allclose(probabilities.sum(dim=-1), torch.tensor(1.0)):
253
+ raise RuntimeError("Each row of probabilities must sum to 1.")
254
+
255
+ surprisal = -torch.log(probabilities) / torch.log(torch.tensor(log_base))
256
+ surprisal[surprisal.isinf()] = 0 # is surprisal is Inf, set to finite value to get correct entropy instead of NaN
257
+ entropies = (probabilities * surprisal).sum(dim=-1)
258
+ return entropies
259
+
260
+
261
+ def output_to_item_entropy(output, item_categories: list[int]):
262
+ """
263
+ Calculate the entropy for each respondent for each item from autoencoder output logits.
264
+
265
+ Parameters
266
+ ----------
267
+ output : torch.Tensor
268
+ The outputted logits from the autoencoder. It should be a 2D tensor where the first dimension
269
+ is the number of respondents and the second dimension is the number of items times the number of categories.
270
+ item_categories : list of int
271
+ A list of integers where each integer represents the number of categories for an item. The list length should
272
+ be equal to the number of items.
273
+
274
+ Returns
275
+ -------
276
+ torch.Tensor
277
+ A 2D tensor with the entropy for each respondent for each item. The first dimension is the number of test
278
+ takers and the second dimension is the number of items.
279
+
280
+ Raises
281
+ ------
282
+ ValueError
283
+ If the length of item_categories is not equal to the second dimension of output divided by the sum of item_categories.
284
+ """
285
+ if output.shape[1] != max(item_categories)*len(item_categories):
286
+ raise ValueError(
287
+ "Length of item_categories must be equal to the second dimension of output divided by the sum of item_categories."
288
+ )
289
+
290
+ reshaped_output = output.reshape(output.shape[0], len(item_categories), max(item_categories))
291
+ probabilities = reshaped_output.softmax(dim=2)
292
+ return entropy(probabilities)
293
+
294
+ class PytorchIRTDataset(torch.utils.data.Dataset):
295
+ def __init__(self, data: torch.Tensor):
296
+ super().__init__()
297
+ self.data = data
298
+ # set missing responses to 0 in the response mask (all non-missing are ones)
299
+ self.mask = torch.zeros_like(data, dtype=torch.int)
300
+ self.mask[data == -1] = 1
301
+
302
+ def __len__(self) -> int:
303
+ return len(self.data)
304
+
305
+ def __getitem__(self, index: int):
306
+ return self.data[index], self.mask[index]
307
+
308
+ def is_jupyter():
309
+ try:
310
+ from IPython import get_ipython
311
+ if 'IPKernelApp' not in get_ipython().config:
312
+ raise ImportError("Not in IPython")
313
+ return True
314
+ except Exception:
315
+ return False
316
+
317
+ def dynamic_print(string_to_print):
318
+ """
319
+ Dynamically update terminal printout.
320
+
321
+ Parameters
322
+ ----------
323
+ *args : str
324
+ Strings to print
325
+
326
+ """
327
+ formatted_string = f"\r{string_to_print} " # small space after to make it look better in terminal
328
+ print(formatted_string, end='', flush=True)
@@ -0,0 +1,91 @@
1
+ import logging
2
+ import torch
3
+
4
+ logger = logging.getLogger('irtorch')
5
+
6
+ class BoundedELU(torch.autograd.Function):
7
+ # Set generate_vmap_rule to True to ask PyTorch to automatically generate a vmap rule.
8
+ generate_vmap_rule = True
9
+
10
+ @staticmethod
11
+ def forward(input_tensor: torch.Tensor, alpha=1.0):
12
+ """
13
+ Applies the bounded ELU function element-wise to the input tensor.
14
+
15
+ The bounded ELU function is defined as:
16
+
17
+ .. math::
18
+ f(x) = \\begin{cases}
19
+ \\alpha (e^x - 1) & \\text{if } x \\leq 0 \\\\
20
+ x & \\text{if } 0 < x < 1 \\\\
21
+ -\\alpha (e^{-x} - 1) & \\text{if } x \\geq 1
22
+ \\end{cases}
23
+
24
+ Parameters
25
+ ----------
26
+ input_tensor : torch.Tensor
27
+ The input tensor.
28
+ alpha : float, optional
29
+ The alpha parameter. Default is 1.0.
30
+
31
+ Returns
32
+ -------
33
+ torch.Tensor
34
+ The output tensor.
35
+ """
36
+ neg_mask = (input_tensor <= -1).float()
37
+ pos_mask = (input_tensor >= 1).float()
38
+ middle_mask = 1 - neg_mask - pos_mask
39
+
40
+ neg_part = alpha * (torch.exp(input_tensor + 1) - 1) - 1
41
+ pos_part = -alpha * (torch.exp(-input_tensor + 1) - 1) + 1
42
+ middle_part = input_tensor
43
+
44
+ # we need to remove possible infinities to avoid nan in the output
45
+ neg_part = torch.where(neg_part == float('inf'), torch.zeros_like(neg_part), neg_part)
46
+ pos_part = torch.where(pos_part == float('-inf'), torch.zeros_like(pos_part), pos_part)
47
+
48
+ output = neg_mask * neg_part + pos_mask * pos_part + middle_mask * middle_part
49
+
50
+ return output
51
+
52
+ @staticmethod
53
+ def setup_context(ctx, inputs, output):
54
+ # Method needed for functorch compatibility (vmap etc.)
55
+ # Setup any necessary context for functorch transforms
56
+ input_tensor, alpha = inputs
57
+ ctx.save_for_backward(input_tensor)
58
+ ctx.alpha = alpha
59
+
60
+ @staticmethod
61
+ def backward(ctx, grad_output):
62
+ """
63
+ Computes the gradient of the bounded ELU function.
64
+
65
+ Parameters
66
+ ----------
67
+ grad_output : torch.Tensor
68
+ The gradient of the loss with respect to the output of the bounded ELU function.
69
+
70
+ Returns
71
+ -------
72
+ torch.Tensor
73
+ The gradient of the loss with respect to the input of the bounded ELU function.
74
+ """
75
+ input_tensor, = ctx.saved_tensors
76
+ alpha = ctx.alpha
77
+
78
+ neg_mask = (input_tensor <= -1).float()
79
+ pos_mask = (input_tensor >= 1).float()
80
+ middle_mask = 1 - neg_mask - pos_mask
81
+
82
+ neg_part_grad = alpha * torch.exp(input_tensor + 1)
83
+ pos_part_grad = alpha * torch.exp(-input_tensor + 1)
84
+ middle_part_grad = 1
85
+
86
+ # Ensuring gradient is not infinite
87
+ neg_part_grad = torch.where(neg_part_grad == float('inf'), torch.zeros_like(neg_part_grad), neg_part_grad)
88
+ pos_part_grad = torch.where(pos_part_grad == float('inf'), torch.zeros_like(pos_part_grad), pos_part_grad)
89
+
90
+ grad_input = neg_mask * neg_part_grad + pos_mask * pos_part_grad + middle_mask * middle_part_grad
91
+ return grad_input * grad_output, None
@@ -0,0 +1,31 @@
1
+ import logging
2
+ logger = logging.getLogger('irtorch')
3
+
4
+ def set_verbosity(level) -> None:
5
+ """
6
+ Specifies the severity of log messages that the package will display.
7
+
8
+ Parameters
9
+ ----------
10
+ level : int
11
+ The verbosity level. Possible values are:
12
+
13
+ - 1: to only display critical messages
14
+ - 2: to display critical messages and error messages
15
+ - 3: to display everything from 2 and warning messages
16
+ - 4: to display everything from 3 and info messages
17
+ - 5: to display everything from 4 and debug messages
18
+ """
19
+ if level == 1:
20
+ logger.setLevel(logging.CRITICAL)
21
+ elif level == 2:
22
+ logger.setLevel(logging.ERROR)
23
+ elif level == 3:
24
+ logger.setLevel(logging.WARNING)
25
+ elif level == 4:
26
+ logger.setLevel(logging.INFO)
27
+ elif level == 5:
28
+ logger.setLevel(logging.DEBUG)
29
+ else:
30
+ raise ValueError("Invalid verbosity level. Level should be 1, 2, 3, 4 or 5.")
31
+