Spaces:
Sleeping
Sleeping
Download model.py from KCCQ/KCCQ_SCD_Predictor: direct link, hf CLI and curl.
- Browser
- Download file 2.09 kB
-
https://huggingface.co/spaces/KCCQ/KCCQ_SCD_Predictor/resolve/main/model.py
- Command line
-
hf download hf://spaces/KCCQ/KCCQ_SCD_Predictor/model.py
-
curl -L -o model.py https://huggingface.co/spaces/KCCQ/KCCQ_SCD_Predictor/resolve/main/model.py
2.09 kB
| import torch | |
| from torch import nn | |
| import numpy as np | |
| import torch.nn.utils as utils | |
| class Conv(nn.Module): | |
| def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1): | |
| super().__init__() | |
| self.conv = nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding) | |
| def forward(self, x): | |
| if len(x.shape) == 2: | |
| x = x.unsqueeze(1) | |
| return self.conv(x) | |
| class CNN(nn.Module): | |
| def __init__(self, input_dim=13, negative_slope=0.1,hidden_dim=32, n_layers=4, channels=64, DEVICE=torch.device('cpu')): | |
| super(CNN, self).__init__() | |
| self.fc = nn.ModuleList() | |
| self.fc.append(Conv(1, channels, 3, 1, 1)) | |
| self.fc.append(nn.LeakyReLU(negative_slope=negative_slope)) | |
| for _ in range(n_layers): | |
| self.fc.append(Conv(channels, channels, 3, 1, 1)) | |
| self.fc.append(nn.LeakyReLU(negative_slope)) | |
| self.fc.append(nn.Flatten(1)) | |
| self.fc.append(nn.Linear(channels*input_dim, hidden_dim)) | |
| self.fc.append(nn.LeakyReLU(negative_slope)) | |
| self.fc.append(nn.Linear(hidden_dim, 1)) | |
| self.device = DEVICE | |
| def forward(self, x): | |
| for m in self.fc: | |
| x = m(x) | |
| return x | |
| def predict_proba(self, test_data): | |
| self.eval() | |
| # 修复:确保输入转为 Tensor 并移动到正确的设备 | |
| if isinstance(test_data, np.ndarray): | |
| data = torch.tensor(test_data, dtype=torch.float32).to(self.device) | |
| else: | |
| data = test_data.to(self.device) # 假设已经是 Tensor | |
| # 数据维度调整:Conv1d 需要 (N, C, L) | |
| # 如果当前是 (N, Features),unsqueeze(-2) 变成 (N, 1, Features) | |
| if len(data.shape) == 2: | |
| data = data.unsqueeze(-2) | |
| with torch.no_grad(): | |
| logits = self.forward(data) | |
| outputs = torch.sigmoid(logits).cpu().numpy() | |
| return outputs |