deeplotx 0.5.1__py3-none-any.whl → 0.5.3__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.
@@ -17,6 +17,8 @@ class TextBinaryClassifierTrainer(BaseTrainer):
17
17
  super().__init__(batch_size=batch_size, train_ratio=train_ratio)
18
18
  self._long_text_encoder = long_text_encoder
19
19
  self.device = self._long_text_encoder.device
20
+ self.train_dataset_loader = None
21
+ self.valid_dataset_loader = None
20
22
 
21
23
  @override
22
24
  def train(self, positive_texts: list[str], negative_texts: list[str],
@@ -40,8 +42,9 @@ class TextBinaryClassifierTrainer(BaseTrainer):
40
42
  train_size = int(self._train_ratio * dataset_size)
41
43
  train_dataset = TensorDataset(inputs[:train_size], labels[:train_size])
42
44
  valid_dataset = TensorDataset(inputs[train_size:], labels[train_size:])
43
- train_loader = DataLoader(train_dataset, batch_size=self._batch_size, shuffle=True)
44
- valid_loader = DataLoader(valid_dataset, batch_size=self._batch_size, shuffle=True)
45
+ self.train_dataset_loader = DataLoader(train_dataset, batch_size=self._batch_size, shuffle=True)
46
+ self.valid_dataset_loader = DataLoader(valid_dataset, batch_size=self._batch_size, shuffle=True)
47
+
45
48
  if self.model is not None and self.model.fc1.in_features != feature_dim:
46
49
  logger.warning("The dimension of features doesn't match. A new model instance will be created.")
47
50
  self.model = None
@@ -55,7 +58,7 @@ class TextBinaryClassifierTrainer(BaseTrainer):
55
58
  for epoch in range(num_epochs):
56
59
  self.model.train()
57
60
  total_loss = 0.0
58
- for batch_texts, batch_labels in train_loader:
61
+ for batch_texts, batch_labels in self.train_dataset_loader:
59
62
  outputs = torch.sigmoid(self.model.forward(batch_texts, self.model.initial_state(batch_texts.shape[0]))[0])
60
63
  loss = loss_function(outputs, batch_labels) + self.model.elastic_net(alpha=alpha, rho=rho)
61
64
  optimizer.zero_grad()
@@ -64,7 +67,7 @@ class TextBinaryClassifierTrainer(BaseTrainer):
64
67
  total_loss += loss.item()
65
68
  if epoch % 3 == 0:
66
69
  total_valid_loss = 0.0
67
- for batch_texts, batch_labels in valid_loader:
70
+ for batch_texts, batch_labels in self.valid_dataset_loader:
68
71
  with torch.no_grad():
69
72
  self.model.eval()
70
73
  outputs = torch.sigmoid(self.model.forward(batch_texts, self.model.initial_state(batch_texts.shape[0]))[0])
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deeplotx
3
- Version: 0.5.1
3
+ Version: 0.5.3
4
4
  Summary: Easy-2-use long text NLP toolkit.
5
5
  Requires-Python: >=3.10
6
6
  Description-Content-Type: text/markdown
@@ -166,7 +166,10 @@ Dynamic: license-file
166
166
  LogisticRegression, # 逻辑回归 / 二分类 / 多标签分类
167
167
  SoftmaxRegression, # Softmax 回归 / 多分类
168
168
  RecursiveSequential, # 序列模型 / 循环神经网络
169
- AutoRegression # 自回归模型
169
+ LongContextRecursiveSequential, # 长上下文序列模型 / 自注意力融合循环神经网络
170
+ SelfAttention, # 自注意力模块
171
+ AutoRegression, # 自回归模型 / 循环神经网络
172
+ LongContextAutoRegression # 长上下文自回归模型 / 自注意力融合循环神经网络
170
173
  )
171
174
  ```
172
175
 
@@ -211,3 +214,84 @@ Dynamic: license-file
211
214
  x = self.fc5(x)
212
215
  return x
213
216
  ```
217
+
218
+ 自注意力模块:
219
+
220
+ ```python
221
+ from typing_extensions import override
222
+
223
+ import torch
224
+ from torch import nn, softmax
225
+
226
+ from deeplotx.nn.base_neural_network import BaseNeuralNetwork
227
+
228
+
229
+ class SelfAttention(BaseNeuralNetwork):
230
+ def __init__(self, feature_dim: int, model_name: str | None = None,
231
+ device: str | None = None, dtype: torch.dtype | None = None):
232
+ super().__init__(model_name=model_name, device=device, dtype=dtype)
233
+ self._feature_dim = feature_dim
234
+ self.q_proj = nn.Linear(in_features=self._feature_dim, out_features=self._feature_dim,
235
+ bias=True, device=self.device, dtype=self.dtype)
236
+ self.k_proj = nn.Linear(in_features=self._feature_dim, out_features=self._feature_dim,
237
+ bias=True, device=self.device, dtype=self.dtype)
238
+ self.v_proj = nn.Linear(in_features=self._feature_dim, out_features=self._feature_dim,
239
+ bias=True, device=self.device, dtype=self.dtype)
240
+
241
+ def _attention(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
242
+ q, k = self.q_proj(x), self.k_proj(x)
243
+ attn = torch.matmul(q, k.transpose(-2, -1))
244
+ attn = attn / (self._feature_dim ** 0.5)
245
+ attn = attn.masked_fill(mask == 0, -1e9) if mask is not None else attn
246
+ return softmax(attn, dim=-1)
247
+
248
+ @override
249
+ def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
250
+ x = self.ensure_device_and_dtype(x, device=self.device, dtype=self.dtype)
251
+ if mask is not None:
252
+ mask = self.ensure_device_and_dtype(mask, device=self.device, dtype=self.dtype)
253
+ v = self.v_proj(x)
254
+ return torch.matmul(self._attention(x, mask), v)
255
+ ```
256
+
257
+ - ### 使用预定义训练器实现文本二分类任务
258
+
259
+ ```python
260
+ from deeplotx import TextBinaryClassifierTrainer, LongTextEncoder
261
+ from deeplotx.util import get_files, read_file
262
+
263
+ # 定义向量编码策略 (默认使用 bert-base-uncased 作为嵌入模型)
264
+ long_text_encoder = LongTextEncoder(
265
+ max_length=2048, # 最大文本大小, 超出截断
266
+ chunk_size=448, # 块大小 (按 Token 计)
267
+ overlapping=32 # 块间重叠大小 (按 Token 计)
268
+ )
269
+
270
+ trainer = TextBinaryClassifierTrainer(
271
+ long_text_encoder=long_text_encoder,
272
+ batch_size=2,
273
+ train_ratio=0.9 # 训练集和验证集比例
274
+ )
275
+
276
+ # 读取数据
277
+ pos_data_path = 'path/to/pos_dir'
278
+ neg_data_path = 'path/to/neg_dir'
279
+ pos_data = [read_file(x) for x in get_files(pos_data_path)]
280
+ neg_data = [read_file(x) for x in get_files(neg_data_path)]
281
+
282
+ # 开始训练
283
+ model = trainer.train(pos_data, neg_data,
284
+ num_epochs=36, learning_rate=2e-5, # 设置训练轮数和学习率
285
+ balancing_dataset=True, # 是否平衡数据集
286
+ alpha=1e-4, rho=.2, # 设置 elastic net 正则化的超参数 alpha 和 rho
287
+ hidden_dim=256, recursive_layers=2) # 设置循环神经网络的结构
288
+
289
+ # 保存模型权重
290
+ model.save(model_name='test_model', model_dir='model')
291
+
292
+ # 加载已保存的模型
293
+ model = model.load(model_name='test_model', model_dir='model')
294
+
295
+ # 使用训练好的模型进行预测
296
+ model.predict(long_text_encoder.encode('这是一个测试文本.', flatten=False))
297
+ ```
@@ -19,12 +19,12 @@ deeplotx/similarity/set.py,sha256=zhGFxtSIXlWqvipBYzoiPahp4g0boAIoUiMfG0wl07A,68
19
19
  deeplotx/similarity/vector.py,sha256=WVbDHqykt-fvuILVrhUCtIFAOEjY_zvttrXGM9eylG0,1125
20
20
  deeplotx/trainer/__init__.py,sha256=Fl5DR9UecQc5VtBcczU9sx_HtPNoFohpuELOh-Jrsks,77
21
21
  deeplotx/trainer/base_trainer.py,sha256=z0MeAT-rRYmjeBXt0ckt7J1itYArR0Cx02wHesXUoZE,385
22
- deeplotx/trainer/text_binary_classification_trainer.py,sha256=Ktdk4rCNHgTFdXVFmbTnvIlGIJi1gphGRkuRgL2bVOo,4793
22
+ deeplotx/trainer/text_binary_classification_trainer.py,sha256=BNBQdpaD8nB1dQv8naHNIravNcQC8JjOMqD-WRSrUH0,4931
23
23
  deeplotx/util/__init__.py,sha256=JxqAK_WOOHcYVSTHBT1-WuBwWrPEVDTV3titeVWvNUM,74
24
24
  deeplotx/util/hash.py,sha256=wwsC6kOQvbpuvwKsNQOARd78_wePmW9i3oaUuXRUnpc,352
25
25
  deeplotx/util/read_file.py,sha256=ptzouvEQeeW8KU5BrWNJlXw-vFXVrpS9SkAUxsu6A8A,612
26
- deeplotx-0.5.1.dist-info/licenses/LICENSE,sha256=IwGE9guuL-ryRPEKi6wFPI_zOhg7zDZbTYuHbSt_SAk,35823
27
- deeplotx-0.5.1.dist-info/METADATA,sha256=LatUJZ1YzKrlPMDNI2UiOqSf5h9mP57kf4f5ngnfa8Q,6954
28
- deeplotx-0.5.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
29
- deeplotx-0.5.1.dist-info/top_level.txt,sha256=hKg4pVDXZ-WWxkRfJFczRIll1Sv7VyfKCmzHLXbuh1U,9
30
- deeplotx-0.5.1.dist-info/RECORD,,
26
+ deeplotx-0.5.3.dist-info/licenses/LICENSE,sha256=IwGE9guuL-ryRPEKi6wFPI_zOhg7zDZbTYuHbSt_SAk,35823
27
+ deeplotx-0.5.3.dist-info/METADATA,sha256=T5kkUvG4uoe6i9NKO6JiR8hT1A3sxjbrL-Xwnmn4Lrg,10868
28
+ deeplotx-0.5.3.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
29
+ deeplotx-0.5.3.dist-info/top_level.txt,sha256=hKg4pVDXZ-WWxkRfJFczRIll1Sv7VyfKCmzHLXbuh1U,9
30
+ deeplotx-0.5.3.dist-info/RECORD,,