datahandling/data API¶
dnallm.datahandling.data ¶
DNA Dataset handling and processing utilities.
This module provides comprehensive tools for loading, processing, and managing DNA sequence datasets. It supports various file formats, data augmentation techniques, and statistical analysis.
Classes¶
DNADataset ¶
DNADataset(ds, tokenizer=None, max_length=512)
A comprehensive wrapper for DNA sequence datasets with advanced processing capabilities.
This class provides methods for loading DNA datasets from various sources (local files, Hugging Face Hub, ModelScope), encoding sequences with tokenizers, data augmentation, statistical analysis, and more.
Attributes:
Name | Type | Description |
---|---|---|
dataset |
The underlying Hugging Face Dataset or DatasetDict |
|
tokenizer |
Tokenizer for sequence encoding |
|
max_length |
Maximum sequence length for tokenization |
|
sep |
str | None
|
Separator for multi-label data |
multi_label_sep |
str | None
|
Separator for multi-label sequences |
data_type |
str | None
|
Type of the dataset (classification, regression, etc.) |
stats |
dict | None
|
Cached dataset statistics |
stats_for_plot |
DataFrame | None
|
Cached statistics for plotting |
Initialize a DNADataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ds
|
Dataset | DatasetDict
|
A Hugging Face Dataset containing at least 'sequence' and 'label' fields |
required |
tokenizer
|
PreTrainedTokenizerBase | None
|
A Hugging Face tokenizer for encoding sequences |
None
|
max_length
|
int
|
Maximum length for tokenization |
512
|
Source code in dnallm/datahandling/data.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
|
Functions¶
__data_type__ ¶
__data_type__()
Get the data type of the dataset (classification, regression, etc.).
This method analyzes the labels to determine if the dataset is for: - classification (integer or string labels) - regression (float labels) - multi-label (multiple labels per sample) - multi-regression (multiple float values per sample)
Source code in dnallm/datahandling/data.py
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 |
|
__getitem__ ¶
__getitem__(idx)
Get an item from the dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
idx
|
int
|
Index of the item to retrieve |
required |
Returns:
Type | Description |
---|---|
The item at the specified index |
Raises:
Type | Description |
---|---|
ValueError
|
If dataset is a DatasetDict |
Source code in dnallm/datahandling/data.py
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 |
|
__len__ ¶
__len__()
Return the length of the dataset.
Returns:
Type | Description |
---|---|
int
|
Length of the dataset or total length for DatasetDict |
Source code in dnallm/datahandling/data.py
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 |
|
augment_reverse_complement ¶
augment_reverse_complement(reverse=True, complement=True)
Augment the dataset by adding reverse complement sequences.
This method doubles the dataset size.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reverse
|
bool
|
Whether to do reverse |
True
|
complement
|
bool
|
Whether to do complement |
True
|
Source code in dnallm/datahandling/data.py
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 |
|
concat_reverse_complement ¶
concat_reverse_complement(
reverse=True, complement=True, sep=""
)
Augment each sample by concatenating the sequence with its reverse complement.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reverse
|
bool
|
Whether to do reverse |
True
|
complement
|
bool
|
Whether to do complement |
True
|
sep
|
str
|
Separator between the original and reverse complement sequences |
''
|
Source code in dnallm/datahandling/data.py
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 |
|
encode_sequences ¶
encode_sequences(
padding="max_length",
return_tensors="pt",
remove_unused_columns=False,
uppercase=False,
lowercase=False,
task="SequenceClassification",
tokenizer=None,
)
Encode all sequences using the provided tokenizer.
The dataset is mapped to include tokenized fields along with the label, making it directly usable with Hugging Face Trainer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
padding
|
str
|
Padding strategy for sequences. Can be 'max_length' or 'longest'. Use 'longest' to pad to the length of the longest sequence in case of memory outage |
'max_length'
|
return_tensors
|
str
|
Returned tensor types, can be 'pt', 'tf', 'np', or 'jax' |
'pt'
|
remove_unused_columns
|
bool
|
Whether to remove the original 'sequence' and 'label' columns |
False
|
uppercase
|
bool
|
Whether to convert sequences to uppercase |
False
|
lowercase
|
bool
|
Whether to convert sequences to lowercase |
False
|
task
|
str | None
|
Task type for the tokenizer. If not provided, defaults to 'SequenceClassification' |
'SequenceClassification'
|
tokenizer
|
PreTrainedTokenizerBase | None
|
Tokenizer to use for encoding. If not provided, uses the instance's tokenizer |
None
|
Raises:
Type | Description |
---|---|
ValueError
|
If tokenizer is not provided |
Source code in dnallm/datahandling/data.py
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
|
from_huggingface
classmethod
¶
from_huggingface(
dataset_name,
seq_col="sequence",
label_col="labels",
data_dir=None,
tokenizer=None,
max_length=512,
)
Load a dataset from the Hugging Face Hub.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset_name
|
str
|
Name of the dataset |
required |
seq_col
|
str
|
Column name for the DNA sequence |
'sequence'
|
label_col
|
str
|
Column name for the label |
'labels'
|
data_dir
|
str | None
|
Data directory in a dataset |
None
|
tokenizer
|
PreTrainedTokenizerBase | None
|
Tokenizer for sequence encoding |
None
|
max_length
|
int
|
Max token length |
512
|
Returns:
Type | Description |
---|---|
DNADataset
|
An instance wrapping a datasets.Dataset |
Source code in dnallm/datahandling/data.py
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 |
|
from_modelscope
classmethod
¶
from_modelscope(
dataset_name,
seq_col="sequence",
label_col="labels",
data_dir=None,
tokenizer=None,
max_length=512,
)
Load a dataset from the ModelScope.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset_name
|
str
|
Name of the dataset |
required |
seq_col
|
str
|
Column name for the DNA sequence |
'sequence'
|
label_col
|
str
|
Column name for the label |
'labels'
|
data_dir
|
str | None
|
Data directory in a dataset |
None
|
tokenizer
|
PreTrainedTokenizerBase | None
|
Tokenizer for sequence encoding |
None
|
max_length
|
int
|
Max token length |
512
|
Returns:
Type | Description |
---|---|
DNADataset
|
An instance wrapping a datasets.Dataset |
Source code in dnallm/datahandling/data.py
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
|
get_split_lengths ¶
get_split_lengths()
Get lengths of individual splits for DatasetDict.
Returns:
Type | Description |
---|---|
dict | None
|
Dictionary of split names and their lengths, or None for single |
dict | None
|
dataset |
Source code in dnallm/datahandling/data.py
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 |
|
head ¶
head(head=10, show=False)
Fetch the head n data from the dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
head
|
int
|
Number of samples to fetch |
10
|
show
|
bool
|
Whether to print the data or return it |
False
|
Returns:
Type | Description |
---|---|
dict[Any, Any] | None
|
A dictionary containing the first n samples if show=False, |
dict[Any, Any] | None
|
otherwise None |
Source code in dnallm/datahandling/data.py
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 |
|
iter_batches ¶
iter_batches(batch_size)
Generator that yields batches of examples from the dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_size
|
int
|
Size of each batch |
required |
Yields:
Type | Description |
---|---|
A batch of examples |
Raises:
Type | Description |
---|---|
ValueError
|
If dataset is a DatasetDict |
Source code in dnallm/datahandling/data.py
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 |
|
load_local_data
classmethod
¶
load_local_data(
file_paths,
seq_col="sequence",
label_col="labels",
sep=None,
fasta_sep="|",
multi_label_sep=None,
tokenizer=None,
max_length=512,
)
Load DNA sequence datasets from one or multiple local files.
Supports input formats: csv, tsv, json, parquet, arrow, dict, fasta, txt, pkl, pickle.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file_paths
|
str | list | dict
|
Single dataset: Provide one file path (e.g., "data.csv"). Pre-split datasets: Provide a dict like {"train": "train.csv", "test": "test.csv"} |
required |
seq_col
|
str
|
Column name for DNA sequences |
'sequence'
|
label_col
|
str
|
Column name for labels |
'labels'
|
sep
|
str | None
|
Delimiter for CSV, TSV, or TXT |
None
|
fasta_sep
|
str
|
Delimiter for FASTA files |
'|'
|
multi_label_sep
|
str | None
|
Delimiter for multi-label sequences |
None
|
tokenizer
|
PreTrainedTokenizerBase | None
|
A tokenizer for sequence encoding |
None
|
max_length
|
int
|
Max token length |
512
|
Returns:
Type | Description |
---|---|
DNADataset
|
An instance wrapping a Dataset or DatasetDict |
Raises:
Type | Description |
---|---|
ValueError
|
If file type is not supported |
Source code in dnallm/datahandling/data.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
|
plot_statistics ¶
plot_statistics(save_path=None)
Plot statistics of the dataset.
Includes sequence length distribution (histogram), GC content distribution (box plot) for each sequence. If dataset is a DatasetDict, length plots and GC content plots from different datasets will be concatenated into a single chart, respectively. Sequence length distribution is shown as a histogram, with min and max lengths for its' limit.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_path
|
str | None
|
Path to save the plots. If None, plots will be shown interactively |
None
|
Raises:
Type | Description |
---|---|
ValueError
|
If statistics have not been computed yet |
Source code in dnallm/datahandling/data.py
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 |
|
process_missing_data ¶
process_missing_data()
Filter out samples with missing or empty sequences or labels.
Source code in dnallm/datahandling/data.py
926 927 928 929 930 931 932 933 934 935 936 |
|
random_generate ¶
random_generate(
minl,
maxl=0,
samples=1,
gc=(0, 1),
n_ratio=0.0,
padding_size=0,
seed=None,
label_func=None,
append=False,
)
Replace the current dataset with randomly generated DNA sequences.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
minl
|
int
|
Minimum length of the sequences |
required |
maxl
|
int
|
Maximum length of the sequences, default is the same as minl |
0
|
samples
|
int
|
Number of sequences to generate, default 1 |
1
|
gc
|
tuple
|
GC content range, default (0,1) |
(0, 1)
|
N_ratio
|
Include N base in the generated sequence, default 0.0 |
required | |
padding_size
|
int
|
Padding size for sequence length, default 0 |
0
|
seed
|
int | None
|
Random seed, default None |
None
|
label_func
|
Callable | None
|
A function that generates a label from a sequence |
None
|
append
|
bool
|
Append the random generated data to the existing dataset or use the data as a dataset |
False
|
Source code in dnallm/datahandling/data.py
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 |
|
raw_reverse_complement ¶
raw_reverse_complement(ratio=0.5, seed=None)
Do reverse complement of sequences in the dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ratio
|
float
|
Ratio of sequences to reverse complement |
0.5
|
seed
|
int | None
|
Random seed for reproducibility |
None
|
Source code in dnallm/datahandling/data.py
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 |
|
sampling ¶
sampling(ratio=1.0, seed=None, overwrite=False)
Randomly sample a fraction of the dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ratio
|
float
|
Fraction of the dataset to sample. Default is 1.0 (no sampling) |
1.0
|
seed
|
int | None
|
Random seed for reproducibility |
None
|
overwrite
|
bool
|
Whether to overwrite the original dataset with the sampled one |
False
|
Returns:
Type | Description |
---|---|
DNADataset
|
A DNADataset object with sampled data |
Source code in dnallm/datahandling/data.py
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 |
|
show ¶
show(head=10)
Display the dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
head
|
int
|
Number of samples to display |
10
|
Source code in dnallm/datahandling/data.py
1128 1129 1130 1131 1132 1133 1134 |
|
shuffle ¶
shuffle(seed=None)
Shuffle the dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
seed
|
int | None
|
Random seed for reproducibility |
None
|
Source code in dnallm/datahandling/data.py
800 801 802 803 804 805 806 |
|
split_data ¶
split_data(test_size=0.2, val_size=0.1, seed=None)
Split the dataset into train, test, and validation sets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
test_size
|
float
|
Proportion of the dataset to include in the test split |
0.2
|
val_size
|
float
|
Proportion of the dataset to include in the validation split |
0.1
|
seed
|
int | None
|
Random seed for reproducibility |
None
|
Source code in dnallm/datahandling/data.py
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 |
|
statistics ¶
statistics()
Get statistics of the dataset.
Includes number of samples, sequence length (min, max, average, median), label distribution, GC content (by labels), nucleotide composition (by labels).
Returns:
Type | Description |
---|---|
dict
|
A dictionary containing statistics of the dataset |
Raises:
Type | Description |
---|---|
ValueError
|
If statistics have not been computed yet |
Source code in dnallm/datahandling/data.py
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 |
|
validate_sequences ¶
validate_sequences(
minl=20, maxl=6000, gc=(0, 1), valid_chars="ACGTN"
)
Filter the dataset to keep sequences containing valid DNA bases or allowed length.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
minl
|
int
|
Minimum length of the sequences |
20
|
maxl
|
int
|
Maximum length of the sequences |
6000
|
gc
|
tuple
|
GC content range between 0 and 1 |
(0, 1)
|
valid_chars
|
str
|
Allowed characters in the sequences |
'ACGTN'
|
Source code in dnallm/datahandling/data.py
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 |
|
Functions¶
load_preset_dataset ¶
load_preset_dataset(dataset_name, task=None)
Load a preset dataset from Hugging Face or ModelScope.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset_name
|
str
|
Name of the dataset |
required |
task
|
str | None
|
Task directory in a dataset |
None
|
Returns:
Type | Description |
---|---|
DNADataset
|
An instance wrapping a datasets.Dataset |
Raises:
Type | Description |
---|---|
ValueError
|
If dataset is not found in preset datasets |
Source code in dnallm/datahandling/data.py
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 |
|
show_preset_dataset ¶
show_preset_dataset()
Show all preset datasets available in Hugging Face or ModelScope.
Returns:
Type | Description |
---|---|
dict
|
A dictionary containing dataset names and their descriptions |
Source code in dnallm/datahandling/data.py
1667 1668 1669 1670 1671 1672 1673 1674 1675 |
|