fxtensor-salmon 0.1.4__tar.gz → 0.2.0__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.
- fxtensor_salmon-0.2.0/PKG-INFO +246 -0
- fxtensor_salmon-0.2.0/README.md +222 -0
- {fxtensor_salmon-0.1.4 → fxtensor_salmon-0.2.0}/pyproject.toml +1 -1
- fxtensor_salmon-0.2.0/src/fxtensor_salmon/__init__.py +398 -0
- fxtensor_salmon-0.2.0/src/fxtensor_salmon.egg-info/PKG-INFO +246 -0
- {fxtensor_salmon-0.1.4 → fxtensor_salmon-0.2.0}/tests/test_fxtensor.py +144 -6
- fxtensor_salmon-0.1.4/PKG-INFO +0 -199
- fxtensor_salmon-0.1.4/README.md +0 -175
- fxtensor_salmon-0.1.4/src/fxtensor_salmon/__init__.py +0 -361
- fxtensor_salmon-0.1.4/src/fxtensor_salmon.egg-info/PKG-INFO +0 -199
- {fxtensor_salmon-0.1.4 → fxtensor_salmon-0.2.0}/LICENSE +0 -0
- {fxtensor_salmon-0.1.4 → fxtensor_salmon-0.2.0}/setup.cfg +0 -0
- {fxtensor_salmon-0.1.4 → fxtensor_salmon-0.2.0}/src/fxtensor_salmon.egg-info/SOURCES.txt +0 -0
- {fxtensor_salmon-0.1.4 → fxtensor_salmon-0.2.0}/src/fxtensor_salmon.egg-info/dependency_links.txt +0 -0
- {fxtensor_salmon-0.1.4 → fxtensor_salmon-0.2.0}/src/fxtensor_salmon.egg-info/requires.txt +0 -0
- {fxtensor_salmon-0.1.4 → fxtensor_salmon-0.2.0}/src/fxtensor_salmon.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fxtensor_salmon
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Markov Tensor Module
|
|
5
|
+
Author-email: Tadachika Oki <sakesnare@gmail.com>
|
|
6
|
+
License: Copyright 2025 Tadachika Oki
|
|
7
|
+
|
|
8
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
11
|
+
|
|
12
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
13
|
+
|
|
14
|
+
Project-URL: Homepage, https://github.com/salmonsnare/fxtensor-salmon
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: numpy>=1.20.0
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# FXTensor
|
|
26
|
+
|
|
27
|
+
FXTensor is a Python library for tensor-based computations, particularly suited for modeling probabilistic systems and processes inspired by category theory. It leverages NumPy for efficient numerical computations. The library primarily supports labeled indices for enhanced readability while maintaining compatibility with unlabeled numeric indices.
|
|
28
|
+
|
|
29
|
+
## Core Concepts
|
|
30
|
+
|
|
31
|
+
An FXTensor is defined by its `profile` and `data`, with optional string labels to make tensors more intuitive and meaningful.
|
|
32
|
+
|
|
33
|
+
- **Profile**: A pair `[domain, codomain]` specifying the dimensions of input (domain) and output (codomain) indices. For labeled tensors, e.g., `[[['a', 'b']], [['x', 'y', 'z']]]` represents a 2x3 matrix with labeled rows and columns. For unlabeled tensors, `[[2], [3]]` specifies dimensions numerically.
|
|
34
|
+
- **Labels (Optional)**: String labels can be assigned to each dimension, enhancing interpretability. For example, input axis labeled `['a', 'b']` and output axis labeled `['x', 'y', 'z']`. Unlabeled tensors have `labels` set to `None`.
|
|
35
|
+
- **Data**: A NumPy array holding the tensor’s values. Its shape must match the total number of dimensions in the profile (`len(domain) + len(codomain)`).
|
|
36
|
+
|
|
37
|
+
## Usage Examples
|
|
38
|
+
|
|
39
|
+
### Basic Example: Labeled Tensor
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
import numpy as np
|
|
43
|
+
from fxtensor_salmon import FXTensor
|
|
44
|
+
|
|
45
|
+
# Create a 2x3 matrix with string labels
|
|
46
|
+
profile = [[['a', 'b']], [['x', 'y', 'z']]]
|
|
47
|
+
data = np.array([
|
|
48
|
+
[0.1, 0.2, 0.7], # a -> x, y, z
|
|
49
|
+
[0.3, 0.3, 0.4] # b -> x, y, z
|
|
50
|
+
])
|
|
51
|
+
tensor = FXTensor(profile, data=data)
|
|
52
|
+
|
|
53
|
+
# Access elements using labels
|
|
54
|
+
assert tensor.get_label_index(0, 'a') == 0 # Index of label 'a' on input axis
|
|
55
|
+
assert tensor.get_index_label(1, 2) == 'z' # Label at index 2 on output axis
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Unlabeled Tensor
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
# Create a 2x3 matrix with numeric indices
|
|
62
|
+
profile = [[2], [3]]
|
|
63
|
+
data = np.array([
|
|
64
|
+
[0.1, 0.2, 0.7],
|
|
65
|
+
[0.3, 0.3, 0.4]
|
|
66
|
+
])
|
|
67
|
+
tensor = FXTensor(profile, data=data)
|
|
68
|
+
assert tensor.labels == (None, None) # No labels
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Creating Tensor from Strands
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
# Create a tensor from labeled strands
|
|
75
|
+
profile = [[['a', 'b']], [['x', 'y', 'z']]]
|
|
76
|
+
strands = {
|
|
77
|
+
"[[['a']], [['x']]]": 0.1,
|
|
78
|
+
"[[['a']], [['y']]]": 0.2,
|
|
79
|
+
"[[['a']], [['z']]]": 0.7,
|
|
80
|
+
"[[['b']], [['x']]]": 0.3,
|
|
81
|
+
"[[['b']], [['y']]]": 0.3,
|
|
82
|
+
"[[['b']], [['z']]]": 0.4
|
|
83
|
+
}
|
|
84
|
+
tensor = FXTensor.from_strands(profile, strands)
|
|
85
|
+
assert tensor.labels == ([['a', 'b']], [['x', 'y', 'z']])
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### Labeled Tensor Composition
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
# P(Y|X) where X={a,b}, Y={x,y}
|
|
92
|
+
tensor1 = FXTensor(
|
|
93
|
+
[[['a', 'b']], [['x', 'y']]],
|
|
94
|
+
data=np.array([
|
|
95
|
+
[0.2, 0.8], # a -> x, y
|
|
96
|
+
[0.6, 0.4] # b -> x, y
|
|
97
|
+
])
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
# P(Z|Y) where Y={x,y}, Z={p,q}
|
|
101
|
+
tensor2 = FXTensor(
|
|
102
|
+
[[['x', 'y']], [['p', 'q']]],
|
|
103
|
+
data=np.array([
|
|
104
|
+
[0.3, 0.7], # x -> p, q
|
|
105
|
+
[0.9, 0.1] # y -> p, q
|
|
106
|
+
])
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
# Composition: P(Z|X) = P(Y|X) ; P(Z|Y)
|
|
110
|
+
result = tensor1.composition(tensor2)
|
|
111
|
+
assert result.labels == ([['a', 'b']], [['p', 'q']])
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Labeled Tensor Product
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
# P(X) where X={a,b}
|
|
118
|
+
tensor1 = FXTensor(
|
|
119
|
+
[[], [['a', 'b']]],
|
|
120
|
+
data=np.array([0.3, 0.7])
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
# P(Y) where Y={x,y,z}
|
|
124
|
+
tensor2 = FXTensor(
|
|
125
|
+
[[], [['x', 'y', 'z']]],
|
|
126
|
+
data=np.array([0.2, 0.3, 0.5])
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
# Tensor product: P(X,Y) = P(X) ⊗ P(Y)
|
|
130
|
+
result = tensor1.tensor_product(tensor2)
|
|
131
|
+
assert result.labels == (None, [['a', 'b'], ['x', 'y', 'z']])
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## Simple Example: Weather Forecast (Labeled)
|
|
135
|
+
|
|
136
|
+
Model a weather system with states “Sunny” or “Rainy.”
|
|
137
|
+
|
|
138
|
+
- **State Tensor**: Represents today’s weather probability with labels. If today is certainly sunny, the state is `[1, 0]`.
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
weather_states = ['Sunny', 'Rainy']
|
|
142
|
+
sunny_today = FXTensor([[], [weather_states]], data=np.array([1, 0]))
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
- **Process Tensor**: Represents a weather forecast as a labeled Markov kernel.
|
|
146
|
+
|
|
147
|
+
```python
|
|
148
|
+
forecast_matrix = np.array([
|
|
149
|
+
[0.8, 0.2], # Sunny -> Sunny: 0.8, Rainy: 0.2
|
|
150
|
+
[0.4, 0.6] # Rainy -> Sunny: 0.4, Rainy: 0.6
|
|
151
|
+
])
|
|
152
|
+
forecast_tensor = FXTensor([[weather_states], [weather_states]], data=forecast_matrix)
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
- **Composition**: Predict tomorrow’s weather by composing today’s state with the forecast.
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
sunny_tomorrow = sunny_today.composition(forecast_tensor)
|
|
159
|
+
sunny_idx = sunny_tomorrow.get_label_index(1, 'Sunny')
|
|
160
|
+
p_sunny = sunny_tomorrow.data[sunny_idx] # 0.8
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Advanced Example: Multidimensional System (Labeled)
|
|
164
|
+
|
|
165
|
+
Model the joint probability of **Season** (Spring, Summer, Other) and **Weather** (Sunny, Rainy) given **Location** (Urban, Rural).
|
|
166
|
+
|
|
167
|
+
- **Profile**: `[[['Urban', 'Rural']], [['Spring', 'Summer', 'Other'], ['Sunny', 'Rainy']]]`
|
|
168
|
+
- **Data**: A 3D array of shape `(2, 3, 2)`.
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
location_labels = ['Urban', 'Rural']
|
|
172
|
+
season_labels = ['Spring', 'Summer', 'Other']
|
|
173
|
+
weather_labels = ['Sunny', 'Rainy']
|
|
174
|
+
process_data = np.random.rand(2, 3, 2)
|
|
175
|
+
process_data /= process_data.sum(axis=(1, 2), keepdims=True)
|
|
176
|
+
process_tensor = FXTensor([[location_labels], [season_labels, weather_labels]], data=process_data)
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
### Key Method Applications
|
|
180
|
+
|
|
181
|
+
#### `marginalization(start_B)`
|
|
182
|
+
|
|
183
|
+
```python
|
|
184
|
+
# Get P(Season | Location) by marginalizing Weather
|
|
185
|
+
season_tensor = process_tensor.marginalization(start_B=2)
|
|
186
|
+
assert season_tensor.labels == ([['Urban', 'Rural']], [['Spring', 'Summer', 'Other']])
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
#### `discard_prefix(start_B)`
|
|
190
|
+
|
|
191
|
+
```python
|
|
192
|
+
# Get P(Weather | Location) by marginalizing Season
|
|
193
|
+
weather_tensor = process_tensor.discard_prefix(start_B=2)
|
|
194
|
+
assert weather_tensor.labels == ([['Urban', 'Rural']], [['Sunny', 'Rainy']])
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
#### `conditionalization(start_B)`
|
|
198
|
+
|
|
199
|
+
```python
|
|
200
|
+
# Compute P(Weather | Location, Season)
|
|
201
|
+
cond_tensor = process_tensor.conditionalization(start_B=2)
|
|
202
|
+
assert cond_tensor.labels == ([['Urban', 'Rural'], ['Spring', 'Summer', 'Other']], [['Sunny', 'Rainy']])
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
#### `tensor_product(other)`
|
|
206
|
+
|
|
207
|
+
```python
|
|
208
|
+
# Add Traffic (Low, High) system
|
|
209
|
+
traffic_labels = ['Low', 'High']
|
|
210
|
+
traffic_state = FXTensor([[], [traffic_labels]], data=np.array([0.7, 0.3]))
|
|
211
|
+
joint_tensor = process_tensor.tensor_product(traffic_state)
|
|
212
|
+
assert joint_tensor.labels == (None, [['Urban', 'Rural'], ['Spring', 'Summer', 'Other'], ['Sunny', 'Rainy'], ['Low', 'High']])
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
## Theoretical Background: Relation to Markov Categories
|
|
216
|
+
|
|
217
|
+
The `fxtensor-salmon` library is designed based on the **Markov Category**, a framework for categorical probability theory.
|
|
218
|
+
|
|
219
|
+
### Markov Category Basics
|
|
220
|
+
|
|
221
|
+
- **Objects**: State spaces, represented in `FXTensor` as `domain` or `codomain` (e.g., `[['Urban', 'Rural']]` or `[[2]]`).
|
|
222
|
+
- **Morphisms**: Markov kernels (probabilistic transitions), represented by `FXTensor` instances with profile and data.
|
|
223
|
+
|
|
224
|
+
### Categorical Operations and Methods
|
|
225
|
+
|
|
226
|
+
1. **Composition (`composition`)**: Combines morphisms `f: A -> B` and `g: B -> C`. Corresponds to connecting wires in string diagrams.
|
|
227
|
+
2. **Tensor Product (`tensor_product`)**: Combines independent systems. Represented as side-by-side diagrams.
|
|
228
|
+
3. **Discard (`marginalization`, `discard_prefix`)**: Sums over output axes to eliminate them.
|
|
229
|
+
4. **Copy (`delta_tensor`)**: Deterministic copying operation.
|
|
230
|
+
|
|
231
|
+
### Probabilistic Properties
|
|
232
|
+
|
|
233
|
+
- `is_markov()`: Verifies if the tensor satisfies the normalization condition (sum of outputs equals 1 or 0).
|
|
234
|
+
- Labeled tensors enable intuitive interpretation via `get_label_index` and `get_index_label`.
|
|
235
|
+
|
|
236
|
+
## Testing
|
|
237
|
+
|
|
238
|
+
Tests are implemented in `tests/test_fxtensor.py` using `pytest`.
|
|
239
|
+
|
|
240
|
+
```bash
|
|
241
|
+
pytest
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
## References
|
|
245
|
+
- [1] [檜山正幸のキマイラ飼育記 (はてなBlog), マルコフ圏 A First Look -- 圏論的確率論の最良の定式化](https://m-hiyama.hatenablog.com/entry/2020/06/09/154044)
|
|
246
|
+
- [2] [檜山正幸のキマイラ飼育記 (はてなBlog), マルコフ圏におけるテンソル計算の手順とコツ](https://m-hiyama.hatenablog.com/entry/2021/04/05/153325)
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
# FXTensor
|
|
2
|
+
|
|
3
|
+
FXTensor is a Python library for tensor-based computations, particularly suited for modeling probabilistic systems and processes inspired by category theory. It leverages NumPy for efficient numerical computations. The library primarily supports labeled indices for enhanced readability while maintaining compatibility with unlabeled numeric indices.
|
|
4
|
+
|
|
5
|
+
## Core Concepts
|
|
6
|
+
|
|
7
|
+
An FXTensor is defined by its `profile` and `data`, with optional string labels to make tensors more intuitive and meaningful.
|
|
8
|
+
|
|
9
|
+
- **Profile**: A pair `[domain, codomain]` specifying the dimensions of input (domain) and output (codomain) indices. For labeled tensors, e.g., `[[['a', 'b']], [['x', 'y', 'z']]]` represents a 2x3 matrix with labeled rows and columns. For unlabeled tensors, `[[2], [3]]` specifies dimensions numerically.
|
|
10
|
+
- **Labels (Optional)**: String labels can be assigned to each dimension, enhancing interpretability. For example, input axis labeled `['a', 'b']` and output axis labeled `['x', 'y', 'z']`. Unlabeled tensors have `labels` set to `None`.
|
|
11
|
+
- **Data**: A NumPy array holding the tensor’s values. Its shape must match the total number of dimensions in the profile (`len(domain) + len(codomain)`).
|
|
12
|
+
|
|
13
|
+
## Usage Examples
|
|
14
|
+
|
|
15
|
+
### Basic Example: Labeled Tensor
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
import numpy as np
|
|
19
|
+
from fxtensor_salmon import FXTensor
|
|
20
|
+
|
|
21
|
+
# Create a 2x3 matrix with string labels
|
|
22
|
+
profile = [[['a', 'b']], [['x', 'y', 'z']]]
|
|
23
|
+
data = np.array([
|
|
24
|
+
[0.1, 0.2, 0.7], # a -> x, y, z
|
|
25
|
+
[0.3, 0.3, 0.4] # b -> x, y, z
|
|
26
|
+
])
|
|
27
|
+
tensor = FXTensor(profile, data=data)
|
|
28
|
+
|
|
29
|
+
# Access elements using labels
|
|
30
|
+
assert tensor.get_label_index(0, 'a') == 0 # Index of label 'a' on input axis
|
|
31
|
+
assert tensor.get_index_label(1, 2) == 'z' # Label at index 2 on output axis
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Unlabeled Tensor
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
# Create a 2x3 matrix with numeric indices
|
|
38
|
+
profile = [[2], [3]]
|
|
39
|
+
data = np.array([
|
|
40
|
+
[0.1, 0.2, 0.7],
|
|
41
|
+
[0.3, 0.3, 0.4]
|
|
42
|
+
])
|
|
43
|
+
tensor = FXTensor(profile, data=data)
|
|
44
|
+
assert tensor.labels == (None, None) # No labels
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Creating Tensor from Strands
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
# Create a tensor from labeled strands
|
|
51
|
+
profile = [[['a', 'b']], [['x', 'y', 'z']]]
|
|
52
|
+
strands = {
|
|
53
|
+
"[[['a']], [['x']]]": 0.1,
|
|
54
|
+
"[[['a']], [['y']]]": 0.2,
|
|
55
|
+
"[[['a']], [['z']]]": 0.7,
|
|
56
|
+
"[[['b']], [['x']]]": 0.3,
|
|
57
|
+
"[[['b']], [['y']]]": 0.3,
|
|
58
|
+
"[[['b']], [['z']]]": 0.4
|
|
59
|
+
}
|
|
60
|
+
tensor = FXTensor.from_strands(profile, strands)
|
|
61
|
+
assert tensor.labels == ([['a', 'b']], [['x', 'y', 'z']])
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Labeled Tensor Composition
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
# P(Y|X) where X={a,b}, Y={x,y}
|
|
68
|
+
tensor1 = FXTensor(
|
|
69
|
+
[[['a', 'b']], [['x', 'y']]],
|
|
70
|
+
data=np.array([
|
|
71
|
+
[0.2, 0.8], # a -> x, y
|
|
72
|
+
[0.6, 0.4] # b -> x, y
|
|
73
|
+
])
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
# P(Z|Y) where Y={x,y}, Z={p,q}
|
|
77
|
+
tensor2 = FXTensor(
|
|
78
|
+
[[['x', 'y']], [['p', 'q']]],
|
|
79
|
+
data=np.array([
|
|
80
|
+
[0.3, 0.7], # x -> p, q
|
|
81
|
+
[0.9, 0.1] # y -> p, q
|
|
82
|
+
])
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
# Composition: P(Z|X) = P(Y|X) ; P(Z|Y)
|
|
86
|
+
result = tensor1.composition(tensor2)
|
|
87
|
+
assert result.labels == ([['a', 'b']], [['p', 'q']])
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Labeled Tensor Product
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
# P(X) where X={a,b}
|
|
94
|
+
tensor1 = FXTensor(
|
|
95
|
+
[[], [['a', 'b']]],
|
|
96
|
+
data=np.array([0.3, 0.7])
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
# P(Y) where Y={x,y,z}
|
|
100
|
+
tensor2 = FXTensor(
|
|
101
|
+
[[], [['x', 'y', 'z']]],
|
|
102
|
+
data=np.array([0.2, 0.3, 0.5])
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# Tensor product: P(X,Y) = P(X) ⊗ P(Y)
|
|
106
|
+
result = tensor1.tensor_product(tensor2)
|
|
107
|
+
assert result.labels == (None, [['a', 'b'], ['x', 'y', 'z']])
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Simple Example: Weather Forecast (Labeled)
|
|
111
|
+
|
|
112
|
+
Model a weather system with states “Sunny” or “Rainy.”
|
|
113
|
+
|
|
114
|
+
- **State Tensor**: Represents today’s weather probability with labels. If today is certainly sunny, the state is `[1, 0]`.
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
weather_states = ['Sunny', 'Rainy']
|
|
118
|
+
sunny_today = FXTensor([[], [weather_states]], data=np.array([1, 0]))
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
- **Process Tensor**: Represents a weather forecast as a labeled Markov kernel.
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
forecast_matrix = np.array([
|
|
125
|
+
[0.8, 0.2], # Sunny -> Sunny: 0.8, Rainy: 0.2
|
|
126
|
+
[0.4, 0.6] # Rainy -> Sunny: 0.4, Rainy: 0.6
|
|
127
|
+
])
|
|
128
|
+
forecast_tensor = FXTensor([[weather_states], [weather_states]], data=forecast_matrix)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
- **Composition**: Predict tomorrow’s weather by composing today’s state with the forecast.
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
sunny_tomorrow = sunny_today.composition(forecast_tensor)
|
|
135
|
+
sunny_idx = sunny_tomorrow.get_label_index(1, 'Sunny')
|
|
136
|
+
p_sunny = sunny_tomorrow.data[sunny_idx] # 0.8
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Advanced Example: Multidimensional System (Labeled)
|
|
140
|
+
|
|
141
|
+
Model the joint probability of **Season** (Spring, Summer, Other) and **Weather** (Sunny, Rainy) given **Location** (Urban, Rural).
|
|
142
|
+
|
|
143
|
+
- **Profile**: `[[['Urban', 'Rural']], [['Spring', 'Summer', 'Other'], ['Sunny', 'Rainy']]]`
|
|
144
|
+
- **Data**: A 3D array of shape `(2, 3, 2)`.
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
location_labels = ['Urban', 'Rural']
|
|
148
|
+
season_labels = ['Spring', 'Summer', 'Other']
|
|
149
|
+
weather_labels = ['Sunny', 'Rainy']
|
|
150
|
+
process_data = np.random.rand(2, 3, 2)
|
|
151
|
+
process_data /= process_data.sum(axis=(1, 2), keepdims=True)
|
|
152
|
+
process_tensor = FXTensor([[location_labels], [season_labels, weather_labels]], data=process_data)
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
### Key Method Applications
|
|
156
|
+
|
|
157
|
+
#### `marginalization(start_B)`
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
# Get P(Season | Location) by marginalizing Weather
|
|
161
|
+
season_tensor = process_tensor.marginalization(start_B=2)
|
|
162
|
+
assert season_tensor.labels == ([['Urban', 'Rural']], [['Spring', 'Summer', 'Other']])
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
#### `discard_prefix(start_B)`
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
# Get P(Weather | Location) by marginalizing Season
|
|
169
|
+
weather_tensor = process_tensor.discard_prefix(start_B=2)
|
|
170
|
+
assert weather_tensor.labels == ([['Urban', 'Rural']], [['Sunny', 'Rainy']])
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
#### `conditionalization(start_B)`
|
|
174
|
+
|
|
175
|
+
```python
|
|
176
|
+
# Compute P(Weather | Location, Season)
|
|
177
|
+
cond_tensor = process_tensor.conditionalization(start_B=2)
|
|
178
|
+
assert cond_tensor.labels == ([['Urban', 'Rural'], ['Spring', 'Summer', 'Other']], [['Sunny', 'Rainy']])
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
#### `tensor_product(other)`
|
|
182
|
+
|
|
183
|
+
```python
|
|
184
|
+
# Add Traffic (Low, High) system
|
|
185
|
+
traffic_labels = ['Low', 'High']
|
|
186
|
+
traffic_state = FXTensor([[], [traffic_labels]], data=np.array([0.7, 0.3]))
|
|
187
|
+
joint_tensor = process_tensor.tensor_product(traffic_state)
|
|
188
|
+
assert joint_tensor.labels == (None, [['Urban', 'Rural'], ['Spring', 'Summer', 'Other'], ['Sunny', 'Rainy'], ['Low', 'High']])
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
## Theoretical Background: Relation to Markov Categories
|
|
192
|
+
|
|
193
|
+
The `fxtensor-salmon` library is designed based on the **Markov Category**, a framework for categorical probability theory.
|
|
194
|
+
|
|
195
|
+
### Markov Category Basics
|
|
196
|
+
|
|
197
|
+
- **Objects**: State spaces, represented in `FXTensor` as `domain` or `codomain` (e.g., `[['Urban', 'Rural']]` or `[[2]]`).
|
|
198
|
+
- **Morphisms**: Markov kernels (probabilistic transitions), represented by `FXTensor` instances with profile and data.
|
|
199
|
+
|
|
200
|
+
### Categorical Operations and Methods
|
|
201
|
+
|
|
202
|
+
1. **Composition (`composition`)**: Combines morphisms `f: A -> B` and `g: B -> C`. Corresponds to connecting wires in string diagrams.
|
|
203
|
+
2. **Tensor Product (`tensor_product`)**: Combines independent systems. Represented as side-by-side diagrams.
|
|
204
|
+
3. **Discard (`marginalization`, `discard_prefix`)**: Sums over output axes to eliminate them.
|
|
205
|
+
4. **Copy (`delta_tensor`)**: Deterministic copying operation.
|
|
206
|
+
|
|
207
|
+
### Probabilistic Properties
|
|
208
|
+
|
|
209
|
+
- `is_markov()`: Verifies if the tensor satisfies the normalization condition (sum of outputs equals 1 or 0).
|
|
210
|
+
- Labeled tensors enable intuitive interpretation via `get_label_index` and `get_index_label`.
|
|
211
|
+
|
|
212
|
+
## Testing
|
|
213
|
+
|
|
214
|
+
Tests are implemented in `tests/test_fxtensor.py` using `pytest`.
|
|
215
|
+
|
|
216
|
+
```bash
|
|
217
|
+
pytest
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
## References
|
|
221
|
+
- [1] [檜山正幸のキマイラ飼育記 (はてなBlog), マルコフ圏 A First Look -- 圏論的確率論の最良の定式化](https://m-hiyama.hatenablog.com/entry/2020/06/09/154044)
|
|
222
|
+
- [2] [檜山正幸のキマイラ飼育記 (はてなBlog), マルコフ圏におけるテンソル計算の手順とコツ](https://m-hiyama.hatenablog.com/entry/2021/04/05/153325)
|