tensorplay 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) [2025] [Welog]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,182 @@
1
+ Metadata-Version: 2.4
2
+ Name: tensorplay
3
+ Version: 0.1.1
4
+ Summary: 一个用于深度学习验证的工具包
5
+ Author-email: Welog <2095774200@shu.edu.cn>
6
+ License: MIT License
7
+
8
+ Copyright (c) [2025] [Welog]
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Project-URL: Homepage, https://github.com/bluemoon-o2/TensorPlay
28
+ Classifier: Programming Language :: Python :: 3
29
+ Classifier: Programming Language :: Python :: 3.8
30
+ Classifier: Programming Language :: Python :: 3.9
31
+ Classifier: Programming Language :: Python :: 3.10
32
+ Classifier: Programming Language :: Python :: 3.11
33
+ Classifier: Programming Language :: Python :: 3.12
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Operating System :: OS Independent
36
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
37
+ Classifier: Intended Audience :: Developers
38
+ Classifier: Intended Audience :: Education
39
+ Requires-Python: >=3.8
40
+ Description-Content-Type: text/markdown
41
+ License-File: LICENSE
42
+ Requires-Dist: numpy>=1.21.0
43
+ Requires-Dist: scikit-learn>=1.0.0
44
+ Dynamic: license-file
45
+
46
+ # TensorPlay
47
+ A simple deep learning framework designed for educational purposes and small-scale experiments. TensorPlay provides basic building blocks for constructing and training neural networks, including tensor operations, layers, optimizers, and training utilities.
48
+
49
+ ## Features
50
+ - **Core Tensor Structure**: Implements a `Tensor` class with automatic gradient computation, supporting basic arithmetic operations and common activation functions (`ReLU`, `Sigmoid`, `Tanh`, `Softmax`, `GELU`).
51
+ - **Neural Network Components**: Includes essential layers like `Dense` (fully connected layer) and a `Module` base class for building custom models.
52
+ - **Training Utilities**: Provides `DataLoader` for batching data, training / validation loop helpers (`train_on_batch`, `valid_on_batch`), and optimization with `Adam` optimizer.
53
+ - **Early Stopping**: Built-in `EarlyStopping` callback to prevent overfitting.
54
+ - **Loss Functions**: Implements common loss functions such as `MSE` (Mean Squared Error), `SSE` (Sum of Squared Errors), and NLL (Negative Log Likelihood).
55
+
56
+ ## Basic Usage
57
+ ### 1. Define a Model
58
+ Create custom models by inheriting from `Module` and defining the forward pass:
59
+ ```python
60
+ from TensorPlay import Module, Dense
61
+
62
+ class MyModel(Module):
63
+ def __init__(self, input_size, hidden_size, output_size):
64
+ super().__init__()
65
+ self.fc1 = Dense(input_size, hidden_size)
66
+ self.fc2 = Dense(hidden_size, output_size)
67
+
68
+ def forward(self, x):
69
+ x = self.fc1(x).relu() # Apply ReLU activation after first layer
70
+ x = self.fc2(x).sigmoid() # Apply Sigmoid for binary classification
71
+ return x
72
+ ```
73
+ ### 2. Prepare Data
74
+ Use `DataLoader` to handle batching and shuffling:
75
+ ```python
76
+ from TensorPlay import DataLoader
77
+
78
+ # Assume data is a list of (input_features, label) tuples
79
+ train_data = [(x1, y1), (x2, y2), ...]
80
+ train_loader = DataLoader(train_data, batch_size=32, shuffle=True)
81
+ ```
82
+ ### 3. Train the Model
83
+ Train the model using the `train_on_batch` function. A typical training loop includes batch training, validation, and early stopping judgment:
84
+ ```python
85
+ from TensorPlay import Adam, EarlyStopping
86
+
87
+ def train(model, loader, val_data, epochs=50, lr=0.01):
88
+ optimizer = Adam(model.params(), lr=lr)
89
+ stoper = EarlyStopping(patience=5, delta=0.1, verbose=True)
90
+
91
+ for epoch in range(epochs):
92
+ # Training phase
93
+ total_loss = 0
94
+ correct = 0
95
+ total_samples = 0
96
+ for batch in loader:
97
+ batch_size = len(batch[0])
98
+ total_samples += batch_size
99
+
100
+ # Batch training and obtaining loss and accuracy
101
+ loss, acc = train_on_batch(model, batch, optimizer)
102
+ total_loss += loss * batch_size # 累计总损失
103
+ correct += acc * batch_size # 累计正确样本数
104
+
105
+ # Calculate the average metrics of the training set
106
+ avg_loss = total_loss / total_samples
107
+ accuracy = correct / total_samples
108
+
109
+ # Verification phase
110
+ total_loss = 0
111
+ correct = 0
112
+ total_samples = 0
113
+ for batch in val_data:
114
+ batch_size = len(batch[0])
115
+ val_loss, val_acc = valid_on_batch(model, batch)
116
+ total_samples += batch_size
117
+ correct += val_acc * batch_size
118
+ total_loss += val_loss * batch_size
119
+
120
+ # Calculate the average metrics of the validation set
121
+ val_avg_loss = total_loss / total_samples
122
+ val_accuracy = correct / total_samples
123
+
124
+ # Print training information
125
+ print(f"Epoch {epoch + 1}/{epochs}")
126
+ print(f"Loss: {avg_loss:.4f} | Accuracy: {accuracy:.4f} "
127
+ f"Val Loss: {val_avg_loss:.4f} | Val Accuracy: {val_accuracy:.4f}")
128
+
129
+ # Early stopping check
130
+ stoper(val_avg_loss, model)
131
+ if stoper.early_stop:
132
+ break
133
+ ```
134
+ ### 4. Evaluate the Model
135
+ ```python
136
+ def test(model, test_loader):
137
+ correct = 0
138
+ total = 0
139
+ for batch_x, batch_y in test_loader:
140
+ for x, y in zip(batch_x, batch_y):
141
+ # Make predictions on a single sample
142
+ # Set the threshold according to the task type
143
+ # (taking binary classification as an example here)
144
+ pred = 1 if model(x).data[0] > 0.5 else 0 # For binary classification
145
+ if pred == y.data[0]:
146
+ correct += 1
147
+ total += 1
148
+ print(f"Test Accuracy: {correct/total:.4f}")
149
+ ```
150
+ ## Example: KRK Chess Endgame Classification
151
+ The `demo/KRK_classify.py` script demonstrates classifying chess endgame positions (King-Rook-King) as either a draw or not. Key steps:
152
+ 1. **Data Loading**: Parses `krkopt.data` into numerical features.
153
+ 2. **Data Preparation**: Splits data into training, validation, and test sets.
154
+ 3. **Model Definition**: Uses a 3-layer fully connected network (`KRKClassifier`).
155
+ 4. **Training**: Uses `Adam` optimizer with early stopping.
156
+ 5. **Evaluation**: Computes test accuracy.
157
+
158
+ Run the example:
159
+ ```bash
160
+ python demo/KRK_classify.py
161
+ ```
162
+ ## Limitations and Future Improvements
163
+ ### Current Limitations
164
+ - Only supports 1D `tensors`, no higher-dimensional data (matrices, images).
165
+ - Limited layer types (only `Dense` is implemented).
166
+ - Basic optimizer support (only `Adam` is available).
167
+ - No `GPU` acceleration; all operations are `CPU`-bound.
168
+ - Limited debugging tools for computation graphs.
169
+
170
+ ### Planned Improvements
171
+ - Add support for n-dimensional tensors (`matrices`, `3D tensors`).
172
+ - Implement more layers (`Dropout`, `BatchNorm`).
173
+ - Support GPU acceleration via `CUDA` for faster training.
174
+ - Improve automatic differentiation efficiency.
175
+ - Include more loss functions (`Cross-Entropy`, `MAE`).
176
+ - Add visualization tools for computation graphs and training metrics.
177
+
178
+ ## Contributing
179
+ Contributions are welcome! Feel free to open issues for bugs or feature requests, or submit pull requests with improvements.
180
+
181
+ ## License
182
+ [MIT](https://opensource.org/licenses/MIT)
@@ -0,0 +1,137 @@
1
+ # TensorPlay
2
+ A simple deep learning framework designed for educational purposes and small-scale experiments. TensorPlay provides basic building blocks for constructing and training neural networks, including tensor operations, layers, optimizers, and training utilities.
3
+
4
+ ## Features
5
+ - **Core Tensor Structure**: Implements a `Tensor` class with automatic gradient computation, supporting basic arithmetic operations and common activation functions (`ReLU`, `Sigmoid`, `Tanh`, `Softmax`, `GELU`).
6
+ - **Neural Network Components**: Includes essential layers like `Dense` (fully connected layer) and a `Module` base class for building custom models.
7
+ - **Training Utilities**: Provides `DataLoader` for batching data, training / validation loop helpers (`train_on_batch`, `valid_on_batch`), and optimization with `Adam` optimizer.
8
+ - **Early Stopping**: Built-in `EarlyStopping` callback to prevent overfitting.
9
+ - **Loss Functions**: Implements common loss functions such as `MSE` (Mean Squared Error), `SSE` (Sum of Squared Errors), and NLL (Negative Log Likelihood).
10
+
11
+ ## Basic Usage
12
+ ### 1. Define a Model
13
+ Create custom models by inheriting from `Module` and defining the forward pass:
14
+ ```python
15
+ from TensorPlay import Module, Dense
16
+
17
+ class MyModel(Module):
18
+ def __init__(self, input_size, hidden_size, output_size):
19
+ super().__init__()
20
+ self.fc1 = Dense(input_size, hidden_size)
21
+ self.fc2 = Dense(hidden_size, output_size)
22
+
23
+ def forward(self, x):
24
+ x = self.fc1(x).relu() # Apply ReLU activation after first layer
25
+ x = self.fc2(x).sigmoid() # Apply Sigmoid for binary classification
26
+ return x
27
+ ```
28
+ ### 2. Prepare Data
29
+ Use `DataLoader` to handle batching and shuffling:
30
+ ```python
31
+ from TensorPlay import DataLoader
32
+
33
+ # Assume data is a list of (input_features, label) tuples
34
+ train_data = [(x1, y1), (x2, y2), ...]
35
+ train_loader = DataLoader(train_data, batch_size=32, shuffle=True)
36
+ ```
37
+ ### 3. Train the Model
38
+ Train the model using the `train_on_batch` function. A typical training loop includes batch training, validation, and early stopping judgment:
39
+ ```python
40
+ from TensorPlay import Adam, EarlyStopping
41
+
42
+ def train(model, loader, val_data, epochs=50, lr=0.01):
43
+ optimizer = Adam(model.params(), lr=lr)
44
+ stoper = EarlyStopping(patience=5, delta=0.1, verbose=True)
45
+
46
+ for epoch in range(epochs):
47
+ # Training phase
48
+ total_loss = 0
49
+ correct = 0
50
+ total_samples = 0
51
+ for batch in loader:
52
+ batch_size = len(batch[0])
53
+ total_samples += batch_size
54
+
55
+ # Batch training and obtaining loss and accuracy
56
+ loss, acc = train_on_batch(model, batch, optimizer)
57
+ total_loss += loss * batch_size # 累计总损失
58
+ correct += acc * batch_size # 累计正确样本数
59
+
60
+ # Calculate the average metrics of the training set
61
+ avg_loss = total_loss / total_samples
62
+ accuracy = correct / total_samples
63
+
64
+ # Verification phase
65
+ total_loss = 0
66
+ correct = 0
67
+ total_samples = 0
68
+ for batch in val_data:
69
+ batch_size = len(batch[0])
70
+ val_loss, val_acc = valid_on_batch(model, batch)
71
+ total_samples += batch_size
72
+ correct += val_acc * batch_size
73
+ total_loss += val_loss * batch_size
74
+
75
+ # Calculate the average metrics of the validation set
76
+ val_avg_loss = total_loss / total_samples
77
+ val_accuracy = correct / total_samples
78
+
79
+ # Print training information
80
+ print(f"Epoch {epoch + 1}/{epochs}")
81
+ print(f"Loss: {avg_loss:.4f} | Accuracy: {accuracy:.4f} "
82
+ f"Val Loss: {val_avg_loss:.4f} | Val Accuracy: {val_accuracy:.4f}")
83
+
84
+ # Early stopping check
85
+ stoper(val_avg_loss, model)
86
+ if stoper.early_stop:
87
+ break
88
+ ```
89
+ ### 4. Evaluate the Model
90
+ ```python
91
+ def test(model, test_loader):
92
+ correct = 0
93
+ total = 0
94
+ for batch_x, batch_y in test_loader:
95
+ for x, y in zip(batch_x, batch_y):
96
+ # Make predictions on a single sample
97
+ # Set the threshold according to the task type
98
+ # (taking binary classification as an example here)
99
+ pred = 1 if model(x).data[0] > 0.5 else 0 # For binary classification
100
+ if pred == y.data[0]:
101
+ correct += 1
102
+ total += 1
103
+ print(f"Test Accuracy: {correct/total:.4f}")
104
+ ```
105
+ ## Example: KRK Chess Endgame Classification
106
+ The `demo/KRK_classify.py` script demonstrates classifying chess endgame positions (King-Rook-King) as either a draw or not. Key steps:
107
+ 1. **Data Loading**: Parses `krkopt.data` into numerical features.
108
+ 2. **Data Preparation**: Splits data into training, validation, and test sets.
109
+ 3. **Model Definition**: Uses a 3-layer fully connected network (`KRKClassifier`).
110
+ 4. **Training**: Uses `Adam` optimizer with early stopping.
111
+ 5. **Evaluation**: Computes test accuracy.
112
+
113
+ Run the example:
114
+ ```bash
115
+ python demo/KRK_classify.py
116
+ ```
117
+ ## Limitations and Future Improvements
118
+ ### Current Limitations
119
+ - Only supports 1D `tensors`, no higher-dimensional data (matrices, images).
120
+ - Limited layer types (only `Dense` is implemented).
121
+ - Basic optimizer support (only `Adam` is available).
122
+ - No `GPU` acceleration; all operations are `CPU`-bound.
123
+ - Limited debugging tools for computation graphs.
124
+
125
+ ### Planned Improvements
126
+ - Add support for n-dimensional tensors (`matrices`, `3D tensors`).
127
+ - Implement more layers (`Dropout`, `BatchNorm`).
128
+ - Support GPU acceleration via `CUDA` for faster training.
129
+ - Improve automatic differentiation efficiency.
130
+ - Include more loss functions (`Cross-Entropy`, `MAE`).
131
+ - Add visualization tools for computation graphs and training metrics.
132
+
133
+ ## Contributing
134
+ Contributions are welcome! Feel free to open issues for bugs or feature requests, or submit pull requests with improvements.
135
+
136
+ ## License
137
+ [MIT](https://opensource.org/licenses/MIT)
@@ -0,0 +1,38 @@
1
+ """
2
+ TensorPlay - 一个用于深度学习验证的工具包
3
+
4
+ 版本: 0.1.1
5
+ 作者: Welog
6
+ 日期: 2025年9月3日
7
+
8
+ 功能特点:
9
+ - 提供多阶自动微分处理能力
10
+ - 提供计算图可视化功能
11
+ - 支持多维度的模型组件管理
12
+ - 支持JSON格式保存和加载
13
+ - 支持模型结构打印
14
+ - 支持钩子调试
15
+ """
16
+ __version__ = "0.1.1"
17
+ __author__ = "Welog"
18
+ __email__ = "2095774200@shu.edu.cn"
19
+ __description__ = "一个用于深度学习验证的工具包"
20
+ __url__ = "https://github.com/bluemoon-o2/TensorPlay"
21
+ __license__ = "MIT"
22
+
23
+
24
+ # =============================================================================
25
+ # 全局接口
26
+ # =============================================================================
27
+ from .core import (config, no_grad, to_data, Tensor, Layer, Operator, Optimizer)
28
+ from .layer import (Dense, BatchNorm, LayerNorm, Conv2D)
29
+ from .module import (Module, Sequential)
30
+ from .optimizer import (SGD, Adam, Momentum, AdamW, Nadam, Lookahead, RMSprop)
31
+ from .operator import (concatenate, load_operator)
32
+ from .func import (mse, sse, nll, cross_entropy, sphere)
33
+ from .initializer import (he_init, xavier_init, uniform_init, my_init)
34
+ from .utils import (plot_dot_graph, accuracy)
35
+ from .data import (DataLoader)
36
+ from .scheduler import (StepLR, MultiStepLR, ExponentialLR, EarlyStopping)
37
+
38
+ load_operator()