Views
No views yet

relevance_model): A multi-label classifier that identifies 38 symptom categories from social media sentences.status_model): A model that determines the uncertainty status of the identified symptoms (e.g., distinguishing "I have insomnia" from "I don't have insomnia").disease_model): A CNN-based model that predicts mental disorders (e.g., Depression, Anxiety) based on the symptom feature sequences extracted from user timelines.| Subfolder | Task Description | Input | Output |
|---|---|---|---|
relevance_model/ | Identifies which of the 38 symptoms are present. | Text (Sentence) | Logits (Dim: 38) |
status_model/ | Estimates the uncertainty of the symptom. | Text (Sentence) | Logits (Dim: 1) |
disease_model/{disease_name}/ | Detects a specific mental disease (e.g., depression, anxiety). | Symptom Features Vector | Logits (Dim: 1) |

pip install transformers torch huggingface_hub1import torch
2from torch import nn
3from transformers import AutoModel, AutoConfig
4
5class BERTDiseaseClassifier(nn.Module):
6 def __init__(self, model_type, num_symps) -> None:
7 super().__init__()
8 self.model_type = model_type
9 self.num_symps = num_symps
10 self.encoder = AutoModel.from_pretrained(model_type)
11 self.dropout = nn.Dropout(self.encoder.config.hidden_dropout_prob)
12 self.clf = nn.Linear(self.encoder.config.hidden_size, num_symps)
13
14 def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, **kwargs):
15 outputs = self.encoder(input_ids, attention_mask, token_type_ids)
16 x = outputs.last_hidden_state[:, 0, :] # [CLS] pooling
17 x = self.dropout(x)
18 logits = self.clf(x)
19 return logits1import torch
2from torch import nn
3from torch.nn import functional as F
4from transformers import PreTrainedModel, PretrainedConfig
5
6class DiseaseConfig(PretrainedConfig):
7 model_type = "kmax_mean_cnn"
8 def __init__(self, in_dim=38, filter_num=50, filter_sizes=(2, 3, 4, 5, 6), dropout=0.2, max_pooling_k=5, **kwargs):
9 super().__init__(**kwargs)
10 self.in_dim = in_dim
11 self.filter_num = filter_num
12 self.filter_sizes = filter_sizes
13 self.dropout = dropout
14 self.max_pooling_k = max_pooling_k
15
16def kmax_pooling(x, k):
17 return x.sort(dim = 2)[0][:, :, -k:]
18
19class KMaxMeanCNN(PreTrainedModel):
20 config_class = DiseaseConfig
21 def __init__(self, config):
22 super().__init__(config)
23 self.filter_num = config.filter_num
24 self.filter_sizes = config.filter_sizes
25 self.hidden_size = len(config.filter_sizes) * config.filter_num
26 self.max_pooling_k = config.max_pooling_k
27 self.convs = nn.ModuleList([nn.Conv1d(config.in_dim, config.filter_num, size) for size in config.filter_sizes])
28 self.dropout = nn.Dropout(config.dropout)
29 self.fc = nn.Linear(self.hidden_size, 1)
30 self.post_init()
31
32 def forward(self, input_seqs, **kwargs):
33 # input_seqs shape: [Batch, SeqLen, InDim]
34 input_seqs = input_seqs.transpose(1, 2)
35 x = [F.relu(conv(input_seqs)) for conv in self.convs]
36 x = [kmax_pooling(item, self.max_pooling_k).mean(2) for item in x]
37 x = torch.cat(x, 1)
38 x = self.dropout(x)
39 logits = self.fc(x)
40 return logitsmental-bert-access).1from huggingface_hub import login
2
3login() # Paste your access token when promptedmental/mental-bert-base-uncased is a gated repository.
You must explicitly request access on its Hugging Face model page:1import torch
2from transformers import AutoConfig, AutoTokenizer
3from huggingface_hub import hf_hub_download, login
4# login() # Required when running in an online environment (e.g., Google Colab)
5# from model import BERTDiseaseClassifier
6
7repo_id = "shallowblueQAQ/PsySym-model"
8subfolder = "relevance_model"
9# subfolder = "status_model"
10
11# 1. Load Config & Tokenizer
12config = AutoConfig.from_pretrained(repo_id, subfolder=subfolder)
13tokenizer = AutoTokenizer.from_pretrained(repo_id, subfolder=subfolder)
14
15# 2. Initialize Model Architecture
16# model = BERTDiseaseClassifier(model_type="mental/mental-bert-base-uncased", num_symps=len(config.id2label))
17# Replace `/path/to/mental-bert-base-uncased` with the actual local path where MentalBERT is stored.
18model = BERTDiseaseClassifier(model_type="/path/to/mental-bert-base-uncased", num_symps=len(config.id2label))
19
20# 3. Load Weights
21weights_path = hf_hub_download(repo_id=repo_id, subfolder=subfolder, filename="pytorch_model.bin")
22model.load_state_dict(torch.load(weights_path, map_location="cpu"))
23model.eval()
24
25# 4. Inference
26text = "I had a headache yesterday." if subfolder == "relevance_model" else "Does taking away distractions from some one that has ADD distract the person more or less?"
27inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=128)
28
29with torch.no_grad():
30 logits = model(**inputs)
31 probs = torch.sigmoid(logits)
32
33# Display Predictions (Multi-label)
34threshold = 0.5
35for i, prob in enumerate(probs[0]):
36 if prob > threshold:
37 print(f"Detected: {config.id2label[i]} ({prob:.4f})")1import torch
2from transformers import AutoConfig
3from huggingface_hub import hf_hub_download
4from safetensors.torch import load_file
5
6# 1. Define the Model Architecture (Must match model_hf_disease.py)
7# (Copy the KMaxMeanCNN class definition from the "Define Model Architectures" section above)
8# model = KMaxMeanCNN(config) ...
9
10# 2. Configuration
11repo_id = "shallowblueQAQ/PsySym-model"
12disease_name = "depression" # Options: depression, anxiety, autism, adhd, schizophrenia, bipolar, ocd, ptsd, eating.
13subfolder = f"disease_model/{disease_name}"
14
15# 3. Load Config
16config = DiseaseConfig.from_pretrained(repo_id, subfolder=subfolder)
17
18# 4. Initialize Model
19model = KMaxMeanCNN(config)
20
21# 5. Load Weights
22weights_path = hf_hub_download(repo_id=repo_id, subfolder=subfolder, filename="model.safetensors")
23state_dict = load_file(weights_path)
24model.load_state_dict(state_dict)
25
26model.eval()
27
28# 6. Inference Example
29# Input: A sequence of symptom probabilities (from Relevance Model)
30# Shape: [Batch_Size, Sequence_Length, Feature_Dim(38)]
31# Example: Batch=1, User has 50 posts, each post has 38 symptom features
32dummy_input = torch.randn(1, 50, 38)
33
34with torch.no_grad():
35 # The model expects 'input_seqs'
36 outputs = model(input_seqs=dummy_input)
37 logits = outputs # Shape: [1, 1]
38
39 # Convert logits to probability
40 prob = torch.sigmoid(logits).item()
41
42print(f"Disease Prediction ({disease_name}): {prob:.4f}")
43# Output > 0.5 implies the disease is detected1@inproceedings{zhang2022symptom,
2 title={Symptom Identification for Interpretable Detection of Multiple Mental Disorders on Social Media},
3 author={Zhang, Zhiling and Chen, Siyuan and Wu, Mengyue and Zhu, Kenny},
4 booktitle={Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing},
5 pages={9970--9985},
6 year={2022}
7}