When arranged in certain ways or orders, stereochemical functional groups can cause health risks upon entering the human body. Interacting with proteins of specific organs, different forms of the same chemical may bind to various proteins causing malicious expression of teratogenic hormones. This project develops a machine learning workflow to predict molecular toxicity from chemical structure. Molecules are first imported as SMILES strings paired with toxicity vectors, then checked with a custom `SMILESQ` function so invalid molecules can be removed. Valid molecules are converted into molecular fingerprints using `MoleculeFingerprint`, allowing each structure to be represented numerically for classification. The dataset is split into training and testing groups so the model can be evaluated on molecules it has not seen before. After designing two Machine Learning functions for general toxicity based on 12 assays from Tox21, a unique fingerprint designed specifically in the presence of toxicity is then designed and tested. WIth now three Machine Learning functions, an interface is then designed to choose what type of prediction to run as well as highlighting the possible malicious chemicals groups within the molecule while plotting the molecule out, specifically with accuracy rates as high as 97% for predicting toxicity simply just based on the SMILES string of the molecule.

1. Introduction

Toxicity is central to developing pharmaceutical drugs. Toxicity prediction is important because molecules must be evaluated for potential biological harm before they can be used in medicine, research, or industry. For example, epimerization with thalidomide led to the auto-conversion between R-thalidomide to S-thalidomide and the SDE of R-Thalidomide and S-Thalidomide, ultimately causing over 100,000 babies to suffer from limb defects despite thalidomide being designed as a neutralizer. Traditional toxicity testing can require extensive lab work, so computational models provide a faster way to screen molecules and identify possible risks. Thus, this model intends to support safer and more efficient chemical research by providing a computational screening tool that can help identify potentially harmful molecules before extensive laboratory testing, reducing risk, cost, and time in pharmaceutical and toxicological development.
​
To make molecular structures usable for computation, this project represents each chemical using a SMILES string, which is short for Simplified Molecular Input Line Entry System. A SMILES string is a text-based way to describe a molecule’s atoms and bonds. For example water can be written as “O”, carbon dioxide as “O=C=O”, and ethanol as “CCO”. This allows a computer to understand a molecule as structured chemical information. The toxicity labels used in this project come from the Tox21 dataset, a public toxicology screening dataset that reports whether chemicals activate or interfere with specific biological pathways. In this essay, each molecule is treated as an input, and each toxicity assay label, such as estrogen receptor activity or p53 stress response, is treated as an output to be predicted.
​
Since machine learning models cannot directly interpret chemical structures, SMILES strings must first be validated and transformed into numerical molecular fingerprints. SMILES strings are text representations of a chemical molecule which virtually allows the computer to treat the SMILES string as an input for a certain structure or property of that specific chemical.
​
In this project, each molecule is represented as a SMILES string paired with a toxicity vector. After invalid SMILES strings are removed, the valid molecules are converted into fingerprint vectors that describe structural patterns such as atom environments, substructures, and bonding relationships. A machine learning classifier is then trained on part of the dataset and tested on the remaining molecules to measure how well it predicts toxicity outside the training set.

2. Methodology

2.1 Cleaning the Data

First, I imported toxicology data from Tox21, a U.S. federal research group partnered with the FDA, EPA, NIEHS, and NIH, to evaluate the safety of commercial chemicals. Tox21 is a public toxicology screening dataset that includes chemical structures and 12 assay outcomes for different possible toxic biological pathways. Each molecule is represented by a SMILES STRING, which stands for Simplified Molecular Input Line Entry System. A SMILES String is a text-based way to write molecular structure so that a computer can read it.Toxicology data relevant to specific harmful activity of hormones e.g. Estrogen, was measured with Booleans, (0 or 1), 1 affirming the activity of the hormone in presence of the chemical, which was written in SMILES. This data from tox21 data was imported at first.
The toxicity labels in this project are binary outcomes, where 1 means that a molecule showed activity in a particular assay and 0 means that it did not show detected activity. However, a molecule is not simply “toxic” or “not toxic” in one universal way. The dataset includes multiple assay categories, such as androgen receptor activity, estrogen receptor activity, oxidative stress response, DNA damage response, mitochondrial membrane disruption, and p53 stress response. This means the model is predicting several different biological mechanisms rather than one general toxicity label.
Before machine learning could be performed, the dataset needed to be cleaned. Some entries in the original Tox21 file were blank because experimental data were missing or unavailable for those molecule-assay pairs. I first imported the original dataset and then performed the replacements programmatically in Wolfram Language instead of editing and re-importing a separate cleaned file. This is important because the cleaning process becomes reproducible: another reader can see exactly how the raw dataset became the model-ready dataset.
Import and save Tox21 toxicity data:
In[]:=
data=CloudGet[CloudObject[
https://www.wolframcloud.com/obj/67f7a578-d6ef-4403-817e-9ec3b412f14a
]]
Out[]=
{{NR-AR,NR-AR-LBD,NR-AhR,NR-Aromatase,NR-ER,NR-ER-LBD,NR-PPAR-gamma,SR-ARE,SR-ATAD5,SR-HSE,SR-MMP,SR-p53,smiles},{0,0,1,Missing[NotAvailable],Missing[NotAvailable],0,0,1,0,0,0,0,CCOc1ccc2nc(S(N)(=O)=O)sc2c1},{0,0,0,0,0,0,0,Missing[NotAvailable],0,Missing[NotAvailable],0,0,CCN1C(=O)NC(c2ccccc2)C1=O},{Missing[NotAvailable],Missing[NotAvailable],Missing[NotAvailable],Missing[NotAvailable],Missing[NotAvailable],Missing[NotAvailable],Missing[NotAvailable],0,Missing[NotAvailable],0,Missing[NotAvailable],Missing[NotAvailable],CC[C@]1(O)CC[C@H]2[C@@H]3CCC4=CCCC[C@@H]4[C@H]3CC[C@@]21C},
⋯7823⋯
,{1,1,0,0,1,0,Missing[NotAvailable],Missing[NotAvailable],0,0,Missing[NotAvailable],0,CC(=O)[C@H]1CC[C@H]2[C@@H]3CCC4=CC(=O)CC[C@]4(C)[C@H]3CC[C@]12C},{1,1,0,0,1,1,0,1,0,0,0,0,C[C@]12CC[C@H]3[C@@H](CCC4=CC(=O)CC[C@@]43C)[C@@H]1CC[C@@H]2O},{1,1,0,Missing[NotAvailable],1,1,0,0,0,0,1,1,C[C@]12CC[C@@H]3c4ccc(O)cc4CC[C@H]3[C@@H]1CC[C@H]2O},{0,0,Missing[NotAvailable],0,0,0,0,0,0,0,1,0,COc1ccc2c(c1OC)CN1CCc3cc4c(cc3C1C2)OCO4}}
Full expression not available
(
original memory size:
4.4 MB)
In the first cleaning step, blank entries were replaced with 2 so that missing values could be explicitly identified. In the second step, those 2 values were replaced with 0 for this version of the binary model. This is a simplifying modeling assumption. A blank result does not necessarily prove that a molecule is inactive; it may only mean that the assay result was unavailable. Therefore, treating missing values as 0 makes the model easier to train, but it should also be listed as a limitation because it may under count true toxic activity.​
Replace blanks with 2:
In[]:=
dataMissingAs2=Replace[data,(""|_Missing)->2,{2}]
Out[]=
{{NR-AR,NR-AR-LBD,NR-AhR,NR-Aromatase,NR-ER,NR-ER-LBD,NR-PPAR-gamma,SR-ARE,SR-ATAD5,SR-HSE,SR-MMP,SR-p53,smiles},{0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C@H]3[C@@H]1CC[C@H]2O},{0,0,0,0,0,0,0,0,0,0,1,0,COc1ccc2c(c1OC)CN1CCc3cc4c(cc3C1C2)OCO4}}
Full expression not available
(
original memory size:
3.2 MB)
After cleaning the assay values, the SMILES strings also had to be checked. A SMILES string is only useful if Wolfram Language can interpret it as a valid molecule. To test this, each SMILES string was converted into a Molecule object and checked using MoleculeQ. This step removes invalid molecular entries before fingerprint generation. The purpose is not just to avoid errors in the code, but also to make sure that the machine learning model is trained only on molecules whose structures can actually be interpreted computationally.
Create a validSmilesQ function:
In[]:=
validSmilesQ:=Quiet[MoleculeQ[Molecule[#]]]&
An example of validSmilesQ is below:
In[]:=
validSmilesQ["CCOc1ccc2nc(S(N)(=O)=O)sc2c1"]
Out[]=
True
Show an example of an invalid molecule with validSmilesQ:
In[]:=
validSmilesQ["CCc1nc(S(N)(=O)=O)sc2c1"]
Out[]=
False
Display the 12 toxicity endpoint as a framed table:
In[]:=
Map[<|"Label"->First[#],"Toxicity trigger"->Last[#]|>&,{{"NR-AR","Tests whether a chemical affects the androgen receptor, a hormone receptor involved in testosterone signaling and endocrine disruption."},{"NR-AR-LBD","Focuses on whether a chemical binds to the androgen receptor ligand-binding domain, suggesting direct receptor interaction."},{"NR-AhR","Detects activation of the aryl hydrocarbon receptor, which responds to pollutants, dioxins, and other foreign chemicals."},{"NR-Aromatase","Measures whether a chemical affects aromatase, the enzyme that converts androgens into estrogens."},{"NR-ER","Tests whether a chemical activates or disrupts the full estrogen receptor alpha pathway."},{"NR-ER-LBD","Checks whether a chemical binds directly to the estrogen receptor alpha ligand-binding domain."},{"NR-PPAR-gamma","Tests whether a chemical activates PPAR-gamma, a nuclear receptor involved in fat-cell development, metabolism, and endocrine signaling."},{"SR-ARE","Detects activation of the Nrf2 antioxidant response pathway, often linked to oxidative stress."},{"SR-ATAD5","Measures activation of ATAD5, which is linked to DNA damage repair and replication stress."},{"SR-HSE","Detects activation of the heat shock response, which occurs when proteins are damaged or misfolded."},{"SR-MMP","Measures disruption of mitochondrial membrane potential, suggesting possible mitochondrial toxicity."},{"SR-p53","Detects activation of the p53 pathway, a major response to DNA damage and cellular stress."}}]//Dataset
Out[]=
Label
Toxicity trigger
NR-AR
Tests whether a chemical affects the androgen receptor, a hormone receptor involved in testosterone signaling and endocrine disruption.
NR-AR-LBD
Focuses on whether a chemical binds to the androgen receptor ligand-binding domain, suggesting direct receptor interaction.
NR-AhR
Detects activation of the aryl hydrocarbon receptor, which responds to pollutants, dioxins, and other foreign chemicals.
NR-Aromatase
Measures whether a chemical affects aromatase, the enzyme that converts androgens into estrogens.
NR-ER
Tests whether a chemical activates or disrupts the full estrogen receptor alpha pathway.
NR-ER-LBD
Checks whether a chemical binds directly to the estrogen receptor alpha ligand-binding domain.
NR-PPAR-gamma
Tests whether a chemical activates PPAR-gamma, a nuclear receptor involved in fat-cell development, metabolism, and endocrine signaling.
SR-ARE
Detects activation of the Nrf2 antioxidant response pathway, often linked to oxidative stress.
SR-ATAD5
Measures activation of ATAD5, which is linked to DNA damage repair and replication stress.
SR-HSE
Detects activation of the heat shock response, which occurs when proteins are damaged or misfolded.
SR-MMP
Measures disruption of mitochondrial membrane potential, suggesting possible mitochondrial toxicity.
SR-p53
Detects activation of the p53 pathway, a major response to DNA damage and cellular stress.

2.3 Rudimentary Toxicity Prediction through Machine Learning

A supervised machine learning model can be used to predict molecular toxicity by learning patterns between chemical structure and known toxicological outcomes. Each molecule is first represented using a SMILES string as mentioned earlier, which is then converted into a molecular fingerprint, or numerical vector, that the computer can analyze. The Wolfram Language Classify function is a supervised classification tool because it is trained on examples where the correct toxicity labels are already known. After learning from molecules with known 0 or 1 toxicity outcomes, the classifier can predict whether new molecules are likely to show toxic activity in each assay. Although this model is less complex than a neural network, it provides a clear and efficient starting point for computational toxicity screening.
Establish 12 categories of toxicity and the SMILES within the data:
In[]:=
nameC=testingData[[1,1;;12]];
Trim the data to avoid being skewed:
In[]:=
trainingDataC=testingData[[220;;238]];
Pull all SMILES from the data:
In[]:=
smilesC0=trainingDataC[[All,13]];
Pull all toxicity vectors for each SMILES string:
In[]:=
yC0=N[trainingDataC[[All,1;;12]]/.s_String:>ToExpression[s]];
Once the valid molecules were identified, each molecule was converted into a molecular fingerprint. A molecular fingerprint is a numerical representation of molecular structure. Instead of giving the model a drawing of a molecule, the fingerprint turns that structural information into a vector that machine learning functions can process. Wolfram Language’s MoleculeFingerprint function generates a vector that encodes molecular structure and features for similarity comparison or machine learning. Some fingerprint methods also use predefined substructure patterns, meaning that the fingerprint can already contain information about atom connectivity and recurring molecular fragments. In this case “ExtendedConnectiivty” fingerprint tells the machine about nearby connectivity of the atom and the atoms around it.
Apply “ExtendedConnectivity” Fingerprint on all smilesC in trainingData:
In[]:=
xCraw=Quiet[MoleculeFingerprint[Molecule[#],"ExtendedConnectivity","List"]]&/@smilesC0;
This cell identifies the rows where fingerprint generation succeeded so invalid or failed molecules can be excluded:
In[]:=
goodC=Flatten[Position[xCraw,_List,{1}]];
Keep only rows with successful fingerprint vectors :
In[]:=
xC=N[xCraw[[goodC]]];
Keep only rows with successful toxicity vectors:
In[]:=
yC=yC0[[goodC]];
Keep only successful SMILES:
In[]:=
smilesC=smilesC0[[goodC]];
The first machine learning model in this project used Wolfram Language’s Classify function. This should be described as a supervised classification model, not just a “simple” model. Supervised learning means that the model is trained using examples where both the input and the correct output are already known. In this project, the inputs are molecular fingerprint vectors, and the outputs are known 0 or 1 toxicity labels from the dataset. The goal is for the model to learn patterns between structure-based fingerprints and biological assay outcomes, then apply those learned patterns to molecules that were not used during training.
​
Because the dataset contains 12 toxicity categories, I trained 12 classifiers rather than one single classifier. Each classifier corresponds to one biological assay. This is necessary because different assays represent different toxicological mechanisms. For example, a molecule could activate the estrogen receptor but have no effect on mitochondrial membrane potential, or it could trigger oxidative stress without activating the androgen receptor. Training separate classifiers allows each toxicity pathway to be predicted independently instead of forcing many different mechanisms into one broad “toxic” label.
Make the Machine Learning with built in Classifier group specific to the 12 assays from Tox21:
In[]:=
toxClassifierC=Table[If[Length[Union[yC[[All,i]]]]>1,Classify[Thread[xC->yC[[All,i]]]],First[yC[[All,i]]]],{i,12}];
Train the Classifier Machine Learning specific to the 12 assays from Tox21:
After the classifiers were trained, they had to be evaluated on held - out testing data . This is one of the most important parts of the project because a model is only useful if it can make predictions on molecules it has not already seen . The testing set provides a way to measure generalization . For each toxicity category, the predicted labels can be compared with the experimental labels to calculate accuracy . These accuracy values become the baseline for the project .
Obtain accuracy from the Classify Machine Learning:
Make a function to predict Toxicity based on the Classifier machine learning, specifically using “ExtendedConnectivity” as the fingerprint input:
An example of predictToxicityC:
Visualize the test SMILES string:

2.4 NetChain Toxicity Prediction

Although the Classify function provides a strong and simple starting point, the Classify function was way too simple for toxicity prediction with certain categories out of the 12 biologically toxic assays only having 50% accuracy for SR-ARE.
​
A neural network can be used to improve toxicity prediction because it is better at learning complex, nonlinear relationships. Toxicity is rarely caused by one simple feature of a molecule; typically, it often depends on combinations of functional groups, molecular shape, charge distribution, receptor binding ability, and other structural patterns. A neural network is useful because it can process the molecular fingerprint as a large numerical input and is then able to identify the hidden patterns that may not be obvious through simpler classification methods. In this project, a neural network can be trained using the molecular fingerprints as inputs specifically with the use of “ExtendedConnectivity” as the fingerprint choice and the toxicity categories as outputs, allowing the model to predict whether a molecule is active or inactive in each toxicological pathway. Since the dataset contains multiple toxicity labels, the neural network could be designed as a multi-output model that predicts several categories at once, such as androgen receptor activity, estrogen receptor activity, oxidative stress response, DNA damage response, and mitochondrial toxicity.
Define the Categories as “names”:
Define rows as valid molecules from the data list:
Keep only the valid rows with successful SMILES:
Pull all Toxicity Vector from the data:
Pull all SMILES from the data:
For the neural network model, I used the “ExtendedConnectivity” fingerprint again. ExtendedConnectivity fingerprints describe atom neighborhoods by repeatedly encoding the atoms connected around each atom. This is useful for toxicity prediction because toxicological activity often depends on local structural patterns. However, the fingerprint is still an approximation as it does not fully replace experimental information about charge distribution, 3D conformation, receptor binding, or metabolism.
Use “ExtendedConnectivity” fingerprint as input instead of SMILES:
Flatten the data:
Keep only the fingerprints from valid SMILES :
Keep only the toxicity vectors from valid SMILES:
Keep only valid SMILES:
Fix random seed so train-test split is reproducible:
Randomly ordering the valid molecules before splitting them into training/testing sets:
Select training row indices from shuffled molecule list:
In this project, the neural network uses molecular fingerprints as inputs and toxicity labels as outputs. The fingerprint already contains structural information, so the neural network is not discovering functional groups from scratch. Instead, it is learning patterns within the fingerprint vector that may correspond to chemical features associated with biological activity. A fair comparison requires using the same training and testing split, then comparing the neural network’s accuracy against the Classify baseline for each toxicity category.
Design the layers of the NeuralNet:
Train neural network using fingerprint vectors as inputs and the 12 assays as output:
Define the variables to pull for the test scores and predictions:
Determine NeuralNet prediction accuracy:
Make a new prediction function via the NeuralNet:
Here’s an example of predictNet usage:
Visualize the molecule:
Comparing with the actual experimental data:
Plot the Neural Net prediction vs. experimental points in 3D:
code text:
code text:
Plot the experimental data from Tox21 of toxic (red) v.s. not toxic (gray) for the 12 assays:
Plot the predicted data from Tox21 of toxic (red) v . s . not toxic (gray) for the 12 assays:
These 3D plots compare the neural network’s predictions with the experimental Tox21 labels for each of the 12 toxicity assays. This is because the original molecular fingerprints are high-dimensional vectors, principal component analysis was used to reduce each molecule into three coordinates that can be plotted visually. In each assay, gray points represent molecules labeled or predicted as 0, meaning no detected activity, while red points represent molecules labeled or predicted as 0, which means detected activity. The “actual” plots show the experimental Tox21 results, while the “predicted” plots show the neural network’s outputs after rounding them into binary values. If the red and gray regions in the predicted plot resemble the red and gray regions in the actual plot, it suggests that the neural network learned meaningful structure-toxicity patterns for that assay. Fundamentally, these plots provide a visual way to evaluate accuracy across the 12 assays, not just by looking at numbers, but by seeing whether the model’s predicted toxic and non-toxic regions match the experimental distribution.

3 SkinSensDB Analysis

3.1 Identifying potentially malignant categories in a chemical

This section expands the project from general toxicity prediction into skin sensitization, which is a lot more mechanism-focused toxicological endpoint. In this pathway, many sensitizers begin by covalently binding to skin proteins, but before this this sensitizer must first permeate through the skin. Then, protein binding can activate keratinocytes, activate dendritic cells, and then maybe eventually lead to allergic contact dermatitis. Because this pathway connects chemical reactivity to a biological immune response, it gives my model a more chemically interpretable target than a generic toxicity label.
SkinSensDB was chosen as my source and database because it is a curated database for skin sensitization assays and was designed to support AOP-based computational models. This makes it more appropriate for this than a random list of chemicals because the database connects molecular structures with experimental skin sensitization information. SkinSensDB includes assay-related information such as LLNA data, which is useful because LLNA measures whether a chemical can induce lymph node cell proliferation after skin exposure. Fundamentally, SkinSensDB provides a bridge between chemical structure and the immune-response endpoint that the extension is trying to model.

A. Permeability

The permeability part of the extension is included because a molecule cannot cause skin sensitization only by being reactive in theory. It also has to reach the relevant biological environment. Specifically, the molecule has to first be able to go through the skin to be even considered for skin sensitization. Therefore factors sch as molecular weight, LogP, topological polar surface area, hydrogen-bond donors, hydrogen-bond acceptors, formal charge, rotatable bonds, aromatic ring count, and halogen count help predict whether the molecule has properties consistent with skin penetration or biological access.
Define molecular descriptors:
Define threshold rules for permeability-related properties referenced from SkinSensDB:
Define halogens that will be considered in the permeability/alert feature set:
Convert into numeric values so descriptors are considered vectors:
Molecular weight was included because very large molecules generally have more difficulty crossing biological barriers.
Pull MolecularMass of the molecule:
LogP was included because it estimates lipophilicity, or how strongly a molecule prefers nonpolar environments compared with water. This matters for skin exposure because the outer skin barrier contains lipid-rich layers, so a molecule usually needs some lipophilic character to partition into the skin.
Pull the LogPC value for an inputted SMILES:
Topological polar surface area, or TPSA, was included because highly polar molecules often interact strongly with water and may have more difficulty crossing lipid-rich barriers.
Pull Topological Polar Surface Area value for an inputted SMILES:
Hydrogen-bond donors and acceptors were included because molecules with many hydrogen-bonding groups can become too polar or too strongly solvated, which may reduce passive permeability.
Calculate the Hydrogen Bond acceptor and Donor numbers:
Formal charge was included because charged molecules usually cross lipid barriers less easily than neutral molecules.
Calculate the formal charge for an inputted SMILES:
Rotatable bonds were included because molecular flexibility can affect molecular shape, conformational freedom, and barrier crossing.
Calculate Rotatable Bond for an inputted SMILES:
Aromatic ring count was included because aromatic systems can influence molecular shape, hydrophobicity, and binding behavior.
Count amount of Aromatic RIngs for an inputted SMILES:
Halogen count was included because halogens can increase lipophilicity and affect how strongly a molecule interacts with nonpolar environments.
Recognize Halogens from an inputted SMILES:
Let PermeabilityValues accept a SMILES string by converting it into a Wolfram Molecule:
Redefine it as a function to put in SMILES:
Convert the Permeability for a SMILES string into machine-readable 0/1 bits:
Define the PermeabilityBits:
Define the thresholds for the PermeabilityBits based on SkinSensDB:
Joins the reaction-alert bits into one compact bitString so the permeability fingerprint can be viewed easily:
The permeability fingerprint therefore acts as an accessibility layer . It asks whether the molecule has physical properties that make skin exposure biologically plausible . This is different from the toxicophore alerts, which ask whether the molecule contains chemically reactive structures . A molecule with strong permeability properties but no reactive alert may be less concerning for sensitization than a molecule that is both skin - accessible and chemically reactive .
Sets the default output format of PermeabilityFingerprint to an association:
Build the full Permeability fingerprint for a SMILES string by calculating permeability values, converting them into bits, and formatting the output:
An example of PermeabilityFingerprint
Visualize the molecule

B. Electrophilic toxicophore alerts

This section is included because many skin sensitizers act as electrophiles or at least somewhat become electrophiles after metabolism. Electrophiles are fundamentally electron-poor molecules or molecular regions that can react with electron-rich nucleophiles. In skin proteins, important nucleophilic residues include cysteine and lysine. If a chemical reacts covalently with these protein residues, it could then possibly form a hapten-protein complex that the immune system recognizes as foreign. OECD skin sensitization guidance also emphasizes covalent binding to proteins as the molecular initiating event in the skin sensitization AOP.
Define the Bits for the toxicophore alerts:
Define all the SMILES that are related with the toxicophore alerts so it’s detectable:
Turns a fragment SMILES string into a molecule pattern that Wolfram can search for inside a larger molecule:
Checks whether a molecule contains any of the toxicophore fragments in a given list:
Check whether a molecule contains the toxicophore fragments connected to a specific alert key:
Epoxides were included because they are strained three-membered cyclic ethers. Their ring strain makes them more reactive than ordinary ethers, and nucleophiles can attack the ring to form covalent adducts. In skin sensitization, this matters because epoxides can potentially modify protein residues. In broader toxicology, some epoxides or epoxide metabolites may also react with DNA, which is why they can sometimes be associated with mutagenic risk. However, in this project, the main reason for including epoxides is their ability to act as protein-reactive electrophiles.
Check if epoxide is present:
Aldehydes were included because they contain an electrophilic carbonyl carbon that can react with nucleophilic amines, especially lysine residues in proteins. This can lead to Schiff base formation, where an amine reacts with a carbonyl compound to form an imine-like linkage. Aldehydes are generally more reactive than many ketones, so they are important structural alerts for possible protein modification.
Check if aldehyde is present:
Michael acceptors were included because they contain electron-poor double bonds activated by nearby electron-withdrawing groups such as carbonyls, nitriles, nitro groups, or sulfones. These structures can react with nucleophiles through conjugate addition. This is relevant because cysteine residues in proteins contain thiol groups that can act as nucleophiles.
Check if Michael Acceptor is present:
Alpha,beta-unsaturated carbonyls were included as a more specific Michael acceptor category because they are common examples of electrophilic structures involved in protein-binding mechanisms.
Check if an Unsaturated Carbonyl with the Alpha/Beta carbon is present:
Isocyanates were included because the N=C=O group is highly electrophilic and can react with nucleophilic groups in proteins, including amines and thiols.
Check for isocyanate:
Acid chlorides and anhydrides were included because they are acylating agents . They can transfer acyl groups to nucleophilic residues on proteins, forming covalent modifications . These structures are chemically important because they provide clear mechanisms for protein binding.
Check for acylating agents:
Quinones were included because they can act as electrophiles and react with nucleophilic residues such as cysteine. They can also participate in redox cycling, which may contribute to oxidative stress.
Check for Quinone:
Alkyl halides and sulfonate esters were included because they may act as leaving-group-containing electrophiles that undergo nucleophilic substitution.
Check for Alkyl Halides:
Aziridines were included because, like epoxides, they are strained three-membered rings that can undergo nucleophilic ring opening.
Check for Aziridines:
Sulfonate esters are potent skin sensitizers because they act as strong alkylating agents. This chemical property allows them to easily transfer an alkyl group to a protein within your skin
Check for Sulfonate Esters:
Create an association showing whether each electrophile alert is present in the molecule:
Convert the toxicophore results for a SMILES string into machine-readable 0/1 bits:
Join the toxicophore bits into one compact bitString so the synthetic reaction fingerprint can be viewed easily:
The toxicophore fingerprint does not claim that every molecule containing one of these structures is toxic. Instead, it flags molecules that contain chemically plausible sensitization-related features. This makes the model more interpretable because it connects structural patterns to possible biological mechanisms.
Set the default output format of SyntheticReactionFingerprint to an association:
Build the full Skin Toxicophore reaction fingerprint for a SMILES string by calculating toxicophore values, converting them into bits, and formatting the output:
An example of SkinToxicophoreFingerprint:
Visualize the molecule
This extension therefore combines two ideas: permeability and reactivity. Permeability asks whether the molecule has properties consistent with reaching skin-relevant biological targets. Reactivity asks whether the molecule contains structural alerts that could covalently bind to proteins once it reaches those targets. A molecule with both favorable skin access and an electrophilic alert may be more concerning than a molecule with only one of those features. This makes the extension more interpretable than a pure machine learning output because it explains not just what the model predicts, but also to an extent how certain chemical structures may be toxicologically important.

C. Synthetic Chemistry Alerts

The synthetic chemistry alert section help identify structural features that may be reactive, unstable, or difficult to synthesize. In a real drug-discovery or safety-screening workflow, toxicity prediction is not the only concern. A molecule also has to be chemically reasonable, synthetically accessible, and stable enough to study. By adding synthetic chemistry alerts, the extension begins to connect toxicology prediction with practical molecular design.
Define the Bits for the Synthetic Chemistry Reaction Bits:
Define the SMILES for each reaction alert:
Detect the already-defined fragments in a molecule:
Check if those fragments that are capable of performing a defined Reaction Alert are present or not:
Let the reaction-alert detector accept a SMILES string by converting it into a molecule before checking for the selected reaction mechanism:
The Michael addition alert was included because activated alkenes can react with nucleophiles through conjugate addition. This mechanism is important for skin sensitization because cysteine residues in proteins can act as nucleophiles and form covalent adducts with Michael acceptors.
Check for Michael Addition:
The Schiff base formation alert was included because aldehydes and some ketones can react with amine groups, especially lysine residues, to form imine-like products. This provides a second major protein-binding route beyond cysteine reactivity.
Check for Schiff Base:
The acylation alert was included because acid chlorides, anhydrides, isocyanates, and activated esters can transfer acyl or carbonyl-derived groups to nucleophilic residues in proteins. This is chemically important because acylation can permanently modify a protein’s structure.
Check for acylation:
The SN2 alkylation alert was included because alkyl halides and sulfonate esters can sometimes react by nucleophilic substitution, where a nucleophile attacks a carbon attached to a leaving group. This can lead to covalent alkylation of biological nucleophiles.
Check for SN2 Alkylation:
The ring-opening electrophile alert was included because strained rings such as epoxides and aziridines can be opened by nucleophilic attack. Their ring strain makes them more reactive and this would let them to form covalent adducts with proteins and, in some broader toxicology contexts, DNA.
Check for a Ring-Opening Electrophile:
The redox-cycling quinone alert was included because quinone-like structures may generate oxidative stress by repeatedly accepting and donating electrons. This connects chemical structure not only to covalent binding but also to stress-response toxicity.
Check for Redox-cycling quinone:
The pre/pro-hapten alert was included because some molecules are not strongly reactive in their original form but can become reactive after oxidation, air exposure, or metabolism. For example, phenols and anilines may be transformed into quinone-like or quinone-imine-like species that are more electrophilic. This matters because a molecule’s toxicological behavior may depend on what it becomes inside the body or on the skin, not only on its starting structure.
Let ReactionAlertValues accept a SMILES string by converting it into a Wolfram Molecule:
Create an association showing whether each reaction mechanism alert is present in the molecule:
Convert the reaction-alert results for a SMILES string into machine-readable 0/1 bits:
Turn each reaction-alert True or False value into a numerical bit using the reaction-alert order:
Joins the reaction-alert bits into one compact bitstring so the synthetic reaction fingerprint can be viewed easily:
Overall, the synthetic chemistry reaction fingerprint was included to make the extension more mechanism-based. Instead of only saying that a molecule has a toxicophore, this section tries to explain the chemical reaction that could make the toxicophore biologically relevant. This helps move the project from black-box prediction toward explainable computational toxicology.
Sets the default output format of SyntheticReactionFingerprint to an association:
Build the full synthetic reaction fingerprint for a SMILES string by calculating reaction-alert values, converting them into bits, and formatting the output:
An example of SyntheticReactionFingerprint:
Visualize the molecule

3.2 Molecular Fingerprint Theory directly Related with Toxicity in a NeuralNet

I used human skin sensitization data from SkinSensDB as mentioned earlier, labeled as positive or negative. The labels were rounded into binary values so that the neural network could treat the problem as a classification task, where 1 represents a positive or toxic result and 0 represents a negative or non-toxic result. This makes the extension different from the earlier Tox21 section. Instead of predicting 12 separate pathway labels, this section focuses on one skin-sensitization-related human endpoint.
Pull the data from SkinSensDB:
Get the category name from SkinSensDB:
Get the SMILES from SkinSensDB:
Turn rowsS into a list:
Get the 0/1 for the Toxicity specific to each SMILES String from SkinSensDB:
After defining the permeability, toxicophore, and reaction-alert fingerprints separately, I combined them into one final toxicity fingerprint. The purpose of this step was to create a single numerical representation that includes multiple layers of toxicological reasoning. The permeability portion estimates whether the molecule has physicochemical properties consistent with skin access. The toxicophore portion checks whether the molecule contains reactive structural alerts associated with skin sensitization. The synthetic reaction portion connects those alerts to possible chemical mechanisms, such as Michael addition, Schiff base formation, acylation, SN2 alkylation, ring opening, redox cycling, or pre/pro-hapten activation. By joining these three fingerprint groups, the model uses both general molecular properties and mechanism-based chemical alerts.
Converts the molecule’s permeability-related properties into scaled numerical values between 0 and 1 so they can be used fairly as part of the neural network fingerprint based on SkinSensDB:
The final fingerprint includes both binary alert bits and scaled numerical descriptor values . The binary bits indicate whether a molecule passes certain permeability ranges or contains particular toxicophore/reaction alerts . The numerical values preserve more detailed information about properties such as molecular weight, LogP, TPSA, hydrogen - bond donors, hydrogen - bond acceptors, charge, rotatable bonds, aromatic rings, and halogen count . These numerical values were scaled between 0 and 1 so that no single property would dominate the neural network only because it had a larger numerical range .
Define the final ToxicityFingerprint by joining Permeability, Electrophile, and Synthetic fingerprints from earlier:
Apply ToxicityFingerprint to all smiles:
Choose the valid and non-overlapping ToxicityFingerprints from valid SMILES:
Pick out the valid, non-overlapping ToxicityFingerprints:
Pick out the Toxic/Non-Toxic data related with those Fingerprints from Data:
Pick out the valid SMILES:
Define random seed so predictions are reproducible:
Before training the neural network, the code removed unusable molecules by checking that each fingerprint was a numeric vector and that each toxicity label was numeric. This filtering step is important because machine learning models require consistent input-output pairs. If a molecule cannot be converted into a valid fingerprint, or if its label is missing or non-numeric, it cannot be used reliably for training. After this cleaning step, the data were randomly split into training and testing groups, with 80% used for training and 20% held out for testing.
Randomly ordering the valid molecules before splitting them into training/testing sets:
Select the training row indices from shuffled molecule list:
The neural network was designed as a supervised classification model. It takes the final toxicity fingerprint as input and predicts whether the molecule is labeled positive or negative in the human skin sensitization dataset. The network contains two hidden layers, which allows it to learn nonlinear relationships among permeability properties, toxicophore alerts, and reaction mechanisms. A dropout layer was included to reduce overfitting by preventing the model from relying too heavily on any single pathway through the network during training.
Design layers of the NeuralNet:
Train the Neural Net using ToxicityFingerprint as the input and the toxic/non-toxic vector from SkinSensDB as the output:
The model reached a training accuracy of about 94.4%, meaning that it correctly classified most of the molecules in the training set. However, training accuracy alone is not enough to prove that the model generalizes well. A model can perform strongly on the data it learned from while still performing worse on new molecules. For that reason, this result should be treated as an initial performance measurement, and the essay should also report testing accuracy using the held-out 20% of the dataset.
Determine NeuralNet based on ToxicityFingerprint accuracy:
The prediction function allows the trained neural network to classify a new molecule from its SMILES string. For example, when the model was given the SMILES string C=CC(=O)OCCCCCCOC(=O)C=C, it returned a predicted label of 0 for the human dataset. This means that, according to this trained model, the molecule was predicted as negative or non-toxic for this specific endpoint. This prediction should not be interpreted as an experimental safety conclusion; it is a computational estimate based on the fingerprint patterns learned from the dataset.
Define function to predict Toxicity for Skin Sensitization based on ToxicityFingerprint:
An example of the prediction based on ToxicityFingerprint
Visualize the molecule
To visualize the model, I used dimension reduction to compress the high-dimensional toxicity fingerprints into three dimensions. The first 3D plot shows the experimental labels, while the second 3D plot shows the neural network’s predicted labels. This visualization helps compare whether the model’s predicted toxic and non-toxic regions resemble the experimental distribution. If the red and gray points appear in similar regions across both plots, it suggests that the model is learning some structure from the fingerprint space. If the plots differ strongly, it suggests that the model may be missing important patterns or overgeneralizing.
Plot experimental v.s predicted vectors in 3D:
Similarity between the experimental and predicted plots suggests that the neural network captured some relationship between the engineered fingerprint and the human toxicity label.

3.3 Applying the machine learning functions into an interface

Now, I have 3 predictions of toxicity through Machine Learning. With the first 2 being predicting general toxicity through 12 assays pulled from Tox21 as a rudimentary classify machine learning and a NeuralNet machine learning model while the 3rd being a NeuralNet machine learning model through my own designed ToxicityFingerprint. I now put these 3 predictions in an interface so you can choose what type of prediction to run as well as highlighting possibly malignant functional groups while the molecule is plotted out.
Define the endpoint names for the Tox21 Classifier, using those 12 assay labels:
Converts SMILES string into molecule and returns failure if invalid:
Use “ExtendedConnectivity” fingerprint vectors as the numeric input:
Use the toxicity fingerprint as a vector from the extension:
Build the predicting aspect based on what type of prediction they choose:
Define the B/C alert groups:
Add a function to check for detected possibly toxic alerts:
Draw the molecule from SMILES string so structural features can be highlighted:
Format the matched B/C alert groups into readable tables:
Make the predictions as bar chart and yes/no endpoint table:
Check the number of data rows:
Convert a SMILES string into a Wolfram molecule and returning a failure marker when string is invalid for the interface:

4. Conclusion

This project used computational toxicology to predict molecular toxicity from chemical structure . Molecules were first represented as SMILES strings, converted into molecular fingerprints, and then used to train supervised machine learning models on known toxicity labels . The project began with Tox21 pathway prediction and then expanded into a more interpretable skin sensitization extension . By combining permeability properties, skin toxicophore alerts, and synthetic reaction - mechanism alerts, the extension connected machine learning predictions to chemical reasoning . Overall, this project shows how computational models can act as early screening tools by predicting possible toxicity while also helping explain which molecular features or mechanisms may contribute to that risk .

5 Limitations & Future Directions

This project has several limitations. One limitation was the MissingData in Tox21 Dataset. Although the missingData meant neutral, and I assumed a missingData functions the same as non-toxic, this could very possibly skew the data while testing in a NeuralNet. More importantly, real toxicity depends on dose, exposure time, metabolism, tissue type, and biological context. In addition, molecular fingerprints and toxicophore alerts are useful approximations, but they do not fully capture three-dimensional structure, charge distribution, stereochemistry, receptor binding, or metabolic transformation. Future versions of this project could improve the model by using better missing-data handling, reporting testing accuracy and confusion matrices, comparing different fingerprint types, and adding more biological data such as skin permeability, peptide reactivity, KeratinoSens, LLNA dose-response values, or taking into considerations of epimerization or natural conversion between R/S or even the self disproportionality of enantiomers. Eventually, the model could also be used for safer molecule design by suggesting structural changes that reduce reactive alerts while preserving useful chemical properties.

6 Acknowledgements

This project would be impossible without the help of my mentor Jason Sonnenberg and my mentor group peers. I would also like to thank mentors Renata and JunSeo Lee for helping me design the NeuralNet/Machine Learning part of my project. Also, I want to thank TAs Daniel Xu, Hendry Xu, Bryan Chen, and Arnay Garhyan for their constant support as well as the directors of the Wolfram Summer Research Program, Rory Foulger, Eryn Gillam, Megan Davis and Stephen Wolfram.
Additional thanks to Stephen Wolfram for suggesting this project.

7 References

◼
  • Barratt, M. D. (2000). Prediction of toxicity from chemical structure. Cell Biology and Toxicology, 16, 1–13. https://doi.org/10.1023/A:1007676602908
  • ◼
  • DeepChem. (n.d.). Molecular fingerprints. Retrieved July 9, 2026, from https://deepchem.io/tutorials/molecular-fingerprints/
  • ◼
  • National Center for Advancing Translational Sciences. (n.d.). Tox21 data. National Institutes of Health. Retrieved July 9, 2026, from https://tripod.nih.gov/pubdata/
  • ◼
  • National Institutes of Health. (n.d.). Tox21 data challenge: About the challenge. Retrieved July 9, 2026, from https://tripod.nih.gov/tox21/challenge/about.jspNational
  • ◼
  • Health Research Institutes. (n.d.). SkinSensDB: A curated database for skin sensitization assays. BioCompLab. Retrieved July 9, 2026, from https://cwtung.nhri.edu.tw/skinsensdb/
  • ◼
  • ResearchGate. (n.d.). Skin collagen, triple peptide chains, and the chemical structure of skin collagen [Figure]. Uploaded by Hassan Kamal Abdel-Rahman. Retrieved July 9, 2026, from https://www.researchgate.net/figure/Skin-collagen-triple-peptide-chains-and-the-chemical-structure-of-skin-collagen_fig5_393435871
  • CITE THIS NOTEBOOK

    Analyzing the effects of molecular structure on chemical toxicity​
    by Aris Tsai​
    Wolfram Community, STAFF PICKS, July 9, 2026
    https://community.wolfram.com/groups/-/m/t/3754299