Downloads · 30 days
15
6% of all-time downloads
jimnoneill/CarD-T
CarD-T is a token classification model from jimnoneill. Use it when you need labels on individual words, such as names. It is set up for transformers. The card lists the license as apache-2.0.
CarD-T (Carcinogen Detection via Transformers) is a novel text analytics approach that combines transformer-based machine learning with probabilistic statistical analysis to efficiently nominate carcinogens from scien…
Downloads · 30 days
15
6% of all-time downloads
All-time downloads
235
Public
Parameters
332M
33.2 GB on disk
Likes
2
Public
Click a slice to open those files.
.pt21.3 GB · 64%
From the Hugging Face model README
CarD-T (Carcinogen Detection via Transformers) is a novel text analytics approach that combines transformer-based machine learning with probabilistic statistical analysis to efficiently nominate carcinogens from scientific texts. This model is designed to address the challenges faced by current systems in managing the burgeoning biomedical literature related to carcinogen identification and classification.
The model recognizes 4 entity types using BIO (Beginning-Inside-Outside) tagging scheme, resulting in 9 total labels:
| Label ID | Label | Description |
|---|---|---|
| 0 | O | Outside any entity |
| 1 | B-carcinogen | Beginning of carcinogen entity |
| 2 | I-carcinogen | Inside carcinogen entity |
| 3 | B-negative | Beginning of negative/exculpatory evidence |
| 4 | I-negative | Inside negative evidence |
| 5 | B-cancertype | Beginning of cancer type/metadata |
| 6 | I-cancertype | Inside cancer type/metadata |
| 7 | B-antineoplastic | Beginning of anti-cancer agent |
| 8 | I-antineoplastic | Inside anti-cancer agent |
pip install transformers torch datasets
from transformers import AutoTokenizer, AutoModelForTokenClassification
import torch
# Load model and tokenizer
model_name = "jimnoneill/CarD-T"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForTokenClassification.from_pretrained(model_name)
# Define label mappings
id2label = {
0: "O",
1: "B-carcinogen",
2: "I-carcinogen",
3: "B-negative",
4: "I-negative",
5: "B-cancertype",
6: "I-cancertype",
7: "B-antineoplastic",
8: "I-antineoplastic"
}
def predict_entities(text):
# Tokenize input
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
# Get predictions
with torch.no_grad():
outputs = model(**inputs)
predictions = outputs.logits.argmax(dim=2)
# Convert tokens and predictions to entities
tokens = tokenizer.convert_ids_to_tokens(inputs.input_ids[0])
entities = []
current_entity = None
current_tokens = []
for token, pred_id in zip(tokens, predictions[0]):
pred_label = id2label[pred_id.item()]
if pred_label == "O":
if current_entity:
entities.append({
"entity": current_entity,
"text": tokenizer.convert_tokens_to_string(current_tokens)
})
current_entity = None
current_tokens = []
elif pred_label.startswith("B-"):
if current_entity:
entities.append({
"entity": current_entity,
"text": tokenizer.convert_tokens_to_string(current_tokens)
})
current_entity = pred_label[2:]
current_tokens = [token]
elif pred_label.startswith("I-") and current_entity:
current_tokens.append(token)
# Don't forget the last entity
if current_entity:
entities.append({
"entity": current_entity,
"text": tokenizer.convert_tokens_to_string(current_tokens)
})
return entities
# Example usage
text = "Benzene exposure has been linked to acute myeloid leukemia, while vitamin D shows antineoplastic properties."
entities = predict_entities(text)
for entity in entities:
print(f"{entity['entity']}: {entity['text']}")
from transformers import pipeline
# Create NER pipeline
ner_pipeline = pipeline(
"token-classification",
model=model_name,
aggregation_strategy="simple"
)
# Analyze text
text = "Studies show asbestos causes mesothelioma in humans, but aspirin may have protective effects."
results = ner_pipeline(text)
# Display results
for entity in results:
print(f"{entity['entity_group']}: {entity['word']} (confidence: {entity['score']:.3f})")
def analyze_abstract(abstract):
"""Analyze a scientific abstract for cancer-related entities."""
entities = predict_entities(abstract)
# Organize by entity type
results = {
"carcinogens": [],
"protective_agents": [],
"cancer_types": [],
"negative_findings": []
}
for entity in entities:
if entity['entity'] == "carcinogen":
results["carcinogens"].append(entity['text'])
elif entity['entity'] == "antineoplastic":
results["protective_agents"].append(entity['text'])
elif entity['entity'] == "cancertype":
results["cancer_types"].append(entity['text'])
elif entity['entity'] == "negative":
results["negative_findings"].append(entity['text'])
return results
# Example with a scientific abstract
abstract = """
Recent studies in male rats exposed to compound X showed increased incidence of
hepatocellular carcinoma. However, concurrent administration of resveratrol
demonstrated significant protective effects against liver tumor development.
No carcinogenic activity was observed in female mice under similar conditions.
"""
analysis = analyze_abstract(abstract)
print("Analysis Results:")
for category, items in analysis.items():
if items:
print(f"\n{category.replace('_', ' ').title()}:")
for item in items:
print(f" - {item}")
The model was fine-tuned using the following configuration:
from transformers import TrainingArguments
training_args = TrainingArguments(
output_dir="./card-t-model",
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=16,
num_train_epochs=5,
weight_decay=0.01,
evaluation_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="f1",
push_to_hub=True,
)
If you use this model in your research, please cite:
@article{oneill2024cardt,
title={CarD-T: Interpreting Carcinomic Lexicon via Transformers},
author={O'Neill, Jamey and Reddy, G.A. and Dhillon, N. and Tripathi, O. and Alexandrov, L. and Katira, P.},
journal={MedRxiv},
year={2024},
doi={10.1101/2024.08.13.24311948}
}
This model is released under the Apache License 2.0, matching the license of the training dataset.
We thank the biomedical research community for making their findings publicly available through PubMed, enabling the creation of this model. Special thanks to the Bio-ELECTRA team for the base model architecture.
For questions, feedback, or collaborations:
This model is intended for research purposes only. It should not be used as a sole source for medical decisions or clinical diagnoses. Always consult with qualified healthcare professionals and validate findings through appropriate experimental methods.