Protein Secondary Structure Prediction
A deep learning framework for residue-level protein secondary structure prediction using bidirectional recurrent networks, hybrid CNN–BiLSTM architectures, variable-length sequence processing, and comparative Q8/Q3 evaluation.
- PyTorch
- PyTorch Lightning
- TrackIO
- KaggleHub
- Scikit-learn
- Pandas

Overview
Protein Secondary Structure Prediction is a deep learning project focused on predicting residue-level secondary structure annotations directly from amino acid sequences.
Developed in December 2025 as part of the Deep Learning and Generative AI coursework at IIT Madras, the project investigates the effectiveness of recurrent neural networks and hybrid convolutional-recurrent architectures for biological sequence modeling.
The system predicts protein secondary structures using two annotation schemes: eight-state (Q8) classification and its simplified three-state (Q3) representation.
The project emphasizes variable-length sequence processing, neural network development from scratch, modular training infrastructure, experiment tracking, and comparative model evaluation.
Problem Statement
Understanding protein structure is an important problem in computational biology because structural characteristics influence protein function, stability, and molecular interactions.
Secondary structure prediction involves identifying local structural patterns, such as helices, strands, and coils, directly from amino acid sequences.
Unlike conventional sequence classification, where an entire input sequence receives a single label, this problem requires assigning a structural category to every individual amino acid residue.
The primary challenges include:
- Processing protein sequences of varying lengths.
- Learning local and long-range dependencies between amino acids.
- Generating predictions aligned with individual input residues.
- Preventing padded sequence positions from influencing training and evaluation.
- Evaluating performance across two levels of structural annotation.
The objective was to investigate different neural architectures trained from scratch, without relying on pretrained protein language models or externally generated evolutionary representations.
My Contribution
I designed and implemented the complete deep learning workflow, covering sequence encoding, dataset preparation, model development, training, evaluation, experiment tracking, and competition inference.
My key contributions include:
- Implemented custom amino acid encoding and secondary structure label mappings.
- Developed a PyTorch Dataset and LightningDataModule for variable-length protein sequences.
- Designed a custom batch collation function for dynamic sequence padding and length preservation.
- Implemented padding-aware cross-entropy loss and masked evaluation metrics.
- Developed four neural architectures from scratch: BiRNN, BiLSTM, BiGRU, and hybrid CNN–BiLSTM.
- Implemented packed sequence processing to prevent recurrent layers from unnecessarily processing padded positions.
- Designed a shared abstract PyTorch Lightning base class for consistent training and evaluation workflows.
- Implemented a harmonic-mean evaluation metric combining Q8 and Q3 Macro F1 scores.
- Integrated TrackIO for experiment logging, hyperparameter tracking, and training performance analysis.
- Implemented model checkpoint management and KaggleHub-based artifact retrieval.
- Developed an automated inference pipeline that generates residue-aligned secondary structure predictions and competition submissions.
System Architecture
The project follows a modular deep learning architecture that separates biological sequence processing, model implementation, training, evaluation, and inference.
| Component | Responsibility |
|---|---|
| Sequence Encoding | Converts amino acids and structural annotations into integer representations |
| Data Pipeline | Dataset loading, partitioning, dynamic batching, and sequence padding |
| Model Layer | Bidirectional recurrent networks and hybrid CNN–BiLSTM architecture |
| Training Infrastructure | Optimization, loss computation, validation, and checkpointing |
| Evaluation | Padding-aware Q8 and Q3 Macro F1 computation |
| Experiment Tracking | TrackIO-based metric logging and hyperparameter tracking |
| Artifact Management | Model checkpoint storage and retrieval through KaggleHub |
| Inference | Residue-level classification, label decoding, and submission generation |
Protein Sequence Representation
Each input consists of a sequence of amino acid residues paired with corresponding secondary structure annotations during training.
The amino acid vocabulary contains:
- 20 standard amino acids.
- A special symbol representing masked or nonstandard residues.
- A dedicated padding token.
Each amino acid is integer-encoded and passed through a learnable embedding layer.
Unlike fixed handcrafted representations, trainable embeddings allow the neural network to learn task-specific numerical representations of amino acids during optimization.
Secondary Structure Annotation
The system operates on two structural annotation schemes.
The Q8 representation distinguishes eight structural categories:
| Label | Structural Category |
|---|---|
| H | Alpha helix |
| G | 3₁₀ helix |
| I | Pi helix |
| E | Extended beta strand |
| B | Beta bridge |
| T | Hydrogen-bonded turn |
| S | Bend |
| C | Coil or irregular structure |
The Q3 representation combines these categories into three broader structural groups.
| Q3 Category | Corresponding Q8 Labels |
|---|---|
| Helix (H) | H, G, I |
| Strand (E) | E, B |
| Coil (C) | C, S, T |
The neural network predicts eight-state labels directly. Three-state predictions are subsequently derived using a deterministic Q8-to-Q3 mapping.
This ensures consistency between both output representations without requiring independently trained classification heads.
Variable-Length Sequence Processing
Protein sequences vary in length, making direct fixed-size batching unsuitable without additional preprocessing.
To address this, I implemented a custom batch collation function that:
- Determines the original length of every sequence.
- Identifies the maximum sequence length within the current batch.
- Dynamically pads shorter input sequences.
- Pads target annotations using a dedicated ignored label.
- Preserves original sequence lengths for recurrent processing and inference.
The embedding layer uses a dedicated padding index, while cross-entropy loss excludes padded target positions using an ignore index of -100.
Recurrent architectures additionally use PyTorch's packed sequence utilities to process valid sequence elements without performing unnecessary recurrent computations over padded positions.
During inference, predictions are truncated to their original sequence lengths before decoding.
This ensures that each predicted secondary structure sequence contains exactly one label per original amino acid residue.
Model Development
Four neural architectures were implemented to investigate progressively different approaches to sequence modeling.
All models were trained from scratch using learnable amino acid embeddings.
Bidirectional RNN
The bidirectional recurrent neural network serves as the initial sequence-modeling baseline.
Its architecture consists of:
- Trainable amino acid embeddings.
- A bidirectional recurrent layer.
- A residue-level linear classification head.
Bidirectional processing allows each residue representation to incorporate contextual information from preceding and succeeding amino acids.
This establishes a baseline for evaluating more expressive recurrent architectures.
Bidirectional LSTM
The BiLSTM architecture introduces gated recurrent mechanisms designed to improve the modeling of longer-range dependencies.
Its architecture consists of:
- Trainable amino acid embeddings.
- Configurable stacked bidirectional LSTM layers.
- Dropout regularization.
- A linear classifier producing eight logits per residue.
The implemented architecture supports configurable embedding dimensions, hidden dimensions, recurrent depth, dropout rates, and learning rates.
This model achieved the highest reported external test score among the evaluated architectures.
Bidirectional GRU
The BiGRU model provides an alternative gated recurrent architecture with fewer gating components than LSTM.
Its implementation follows a similar sequence-processing workflow:
- Amino acid embedding.
- Bidirectional GRU processing.
- Dropout regularization.
- Residue-level classification.
This experiment investigates whether a simpler gated recurrent architecture can provide competitive predictive performance with reduced parameter complexity.
Hybrid CNN–BiLSTM
The hybrid architecture combines one-dimensional convolutional feature extraction with bidirectional recurrent sequence modeling.
Its processing pipeline consists of:
- Trainable amino acid embeddings.
- One-dimensional convolution with a kernel size of five.
- ReLU activation and dropout.
- Bidirectional LSTM processing.
- Dropout regularization.
- Residue-level linear classification.
The convolutional layer is designed to identify local sequence patterns, while the bidirectional LSTM incorporates broader contextual information.
Symmetric convolutional padding preserves the original sequence dimension, allowing the model to generate an output for every input residue.
The hybrid architecture achieved the strongest reported validation performance across both Q8 and Q3 prediction tasks.
Shared Training Infrastructure
A common abstract base model was implemented using PyTorch Lightning to standardize training and evaluation across architectures.
Each model subclass defines its own neural network architecture and forward-pass implementation, while the base class manages shared functionality.
The common infrastructure includes:
- Padding-aware cross-entropy loss.
- Adam optimization.
- Training and validation steps.
- Q8 and Q3 Macro F1 computation.
- Harmonic-mean validation scoring.
- Training duration measurement.
- Per-epoch execution-time logging.
- Experiment tracking integration.
This design reduces duplication between model implementations and enables additional architectures to be evaluated without rewriting the training framework.
The training configuration supports hardware-aware CPU or GPU execution, mixed-precision training, and checkpoint selection based on validation performance.
Experiment Tracking and Model Management
TrackIO was integrated to record and compare experimental configurations.
The logged information includes:
- Training and validation loss.
- Q8 Macro F1.
- Q3 Macro F1.
- Combined harmonic-mean validation score.
- Per-epoch training duration.
- Total training duration.
- Model hyperparameters.
Model checkpoints are selected using the combined validation score, with the training configuration retaining the three highest-scoring checkpoints.
The project also incorporates KaggleHub-based model storage and retrieval, allowing previously trained architectures to be loaded for inference without repeating the training process.
Inference Pipeline
The inference pipeline operates independently of model training.
For each batch of test sequences, the system:
- Retrieves the selected trained model checkpoint.
- Reconstructs the model architecture and restores its parameters.
- Encodes amino acid sequences.
- Dynamically pads sequences and preserves their original lengths.
- Performs inference with gradient computation disabled.
- Selects the highest-scoring Q8 label for every residue.
- Removes predictions corresponding to padded positions.
- Decodes integer predictions into structural annotation symbols.
- Derives Q3 predictions from the predicted Q8 sequence.
- Generates the competition submission CSV.
The final submission contains sequence identifiers and their corresponding Q8 and Q3 predictions.
Engineering Challenges
Handling Variable-Length Biological Sequences
One of the central engineering challenges was processing protein sequences with different lengths while maintaining efficient batch computation.
Padding all sequences to a dataset-wide maximum length would introduce unnecessary memory and computational overhead.
The custom collation function instead pads sequences dynamically within each batch.
Packed sequence processing further reduces unnecessary computation inside recurrent layers while preserving the original sequence lengths.
This approach enables the same neural architecture to process sequences of varying lengths without changing its input or output definitions.
Maintaining Residue-Level Prediction Alignment
Unlike conventional classification systems, the model must preserve the relationship between every input residue and its corresponding output annotation.
Operations such as convolution, sequence padding, recurrent processing, and batch collation can introduce alignment issues if their dimensions are not carefully managed.
The implemented architectures preserve sequence dimensions and restore padded representations after recurrent processing.
During inference, original sequence lengths are used to remove padded predictions before generating the final structural annotations.
Combining Local and Broader Sequence Context
Secondary structure prediction can depend on both neighboring amino acid patterns and broader sequence context.
Pure recurrent models provide contextual sequence representations but do not explicitly introduce a convolutional feature-extraction stage.
The hybrid CNN–BiLSTM architecture investigates this limitation by combining local pattern extraction through one-dimensional convolution with bidirectional recurrent processing.
This experiment provides a practical comparison between purely recurrent and hybrid sequence-modeling approaches.
Consistent Evaluation Across Two Annotation Schemes
The competition requires predictions in both Q8 and Q3 formats.
Training separate classifiers could produce inconsistent predictions between the two structural representations.
Instead, the implemented system predicts Q8 labels and derives Q3 labels through a fixed mapping.
The evaluation framework then computes Macro F1 independently for both representations and combines the results using their harmonic mean.
This establishes a shared objective for comparing model configurations.
Limited Generalization Gains from Extended Training
Across the evaluated architectures, validation performance improved rapidly during the initial three to four epochs.
Subsequent training produced comparatively limited improvements in validation scores, while validation loss largely plateaued.
This observation suggested that additional training epochs alone were unlikely to produce substantial improvements under the existing architecture and input representation choices.
It highlighted the importance of investigating richer sequence representations, alternative architectures, and experimental methodology rather than relying exclusively on increased training duration.
Technical Decisions
| Decision | Rationale |
|---|---|
| Integer-encoded amino acid sequences | Provides a compact representation suitable for embedding layers |
| Learnable embeddings | Enables task-specific amino acid representations |
| Dynamic batch padding | Reduces unnecessary padding across variable-length sequences |
| Packed recurrent sequences | Avoids recurrent computation over padded positions |
| Bidirectional recurrent architectures | Incorporates preceding and succeeding sequence context |
| Hybrid CNN–BiLSTM | Combines local pattern extraction with contextual sequence modeling |
| Q8-first classification | Maintains consistency between fine-grained and simplified structural predictions |
| Padding-aware cross-entropy | Prevents artificial padded labels from contributing to optimization |
| Shared abstract base model | Standardizes reusable training and evaluation functionality |
| PyTorch Lightning | Organizes training, validation, checkpointing, and hardware configuration |
| Harmonic-mean model selection | Rewards balanced performance across Q8 and Q3 predictions |
| TrackIO | Supports structured experiment comparison |
| KaggleHub | Enables trained model artifact management and checkpoint-based inference |
Results & Outcomes
The project evaluated four neural architectures trained from scratch on the protein secondary structure prediction task.
Evaluation Metrics
Model performance was evaluated using three principal metrics:
- Q8 Macro F1: Evaluates predictive performance across the eight structural categories.
- Q3 Macro F1: Evaluates predictive performance across the three simplified structural categories.
- Combined Validation Score: The harmonic mean of Q8 and Q3 Macro F1.
The harmonic mean penalizes imbalanced performance between the two annotation schemes and rewards configurations that perform well across both.
Comparative Model Performance
| Model | Q8 F1 | Q3 F1 | Validation Score | Reported Test Score |
|---|---|---|---|---|
| Bidirectional RNN | 0.343 | 0.679 | 0.456 | 0.435 |
| Bidirectional LSTM | 0.346 | 0.695 | 0.462 | 0.457 |
| Bidirectional GRU | 0.347 | 0.682 | 0.460 | 0.434 |
| CNN–BiLSTM | 0.354 | 0.703 | 0.471 | 0.450 |
Key Experimental Findings
Hybrid architecture improves validation performance. The CNN–BiLSTM model achieved the strongest reported validation score of 0.471, with a Q8 Macro F1 of 0.354 and a Q3 Macro F1 of 0.703.
BiLSTM achieves the strongest external test result. Despite achieving a lower internal validation score than the hybrid architecture, the BiLSTM obtained the highest reported test score of 0.457.
Fine-grained classification remains challenging. All evaluated models achieved substantially higher Q3 F1 scores than Q8 F1 scores, reflecting the difficulty of distinguishing more granular structural categories.
Validation performance plateaued early. Most meaningful validation improvement occurred within the initial three to four epochs, with subsequent training providing comparatively limited gains.
Internal validation does not perfectly predict external performance. The difference between the strongest validation architecture and the strongest test architecture highlights the importance of independent evaluation.
Implementation Outcomes
- Four neural network architectures implemented from scratch.
- Two supported secondary structure annotation schemes.
- Variable-length biological sequence processing.
- Dynamic batch padding and packed recurrent computation.
- Padding-aware loss and evaluation.
- Shared model training and validation infrastructure.
- GPU-accelerated training configuration.
- TrackIO-based experiment logging.
- Checkpoint-based model retrieval and inference.
- Automated competition submission generation.
Lessons Learned
Developing this project strengthened my understanding of sequence modeling, deep learning architecture design, and the application of machine learning to computational biology.
The project provided practical experience in:
- Modeling variable-length sequential data.
- Designing learnable token embeddings.
- Implementing recurrent neural networks from scratch.
- Understanding the differences between RNN, LSTM, and GRU architectures.
- Combining convolutional and recurrent neural networks.
- Managing padding and sequence dimensions in batched computations.
- Designing residue-level classification systems.
- Implementing custom evaluation metrics.
- Building reusable PyTorch Lightning training infrastructure.
- Tracking experimental configurations and model performance.
- Interpreting differences between validation and external evaluation results.
One of the most important findings was that increasing model capacity or training duration does not necessarily improve generalization.
The project established a foundation for further exploration of sequence representation learning, attention mechanisms, protein language models, and computational biology applications.
Future Improvements
Potential directions for further development include:
Model Architecture
- Investigating attention-based sequence modeling.
- Implementing transformer encoders trained from scratch.
- Exploring multi-scale convolutional architectures for local sequence patterns.
- Investigating structured prediction methods to improve consistency between adjacent residue labels.
- Evaluating pretrained protein language model embeddings in experiments where external pretraining is permitted.
Experimental Methodology
- Computing epoch-level metrics over the entire validation dataset.
- Introducing sequence-similarity-aware dataset partitioning.
- Investigating class imbalance across structural annotations.
- Performing controlled architecture and hyperparameter ablation studies.
- Evaluating model performance across different protein sequence lengths.
- Conducting class-specific error analysis.
Engineering Improvements
- Extracting notebook-based implementation into reusable Python modules.
- Introducing automated tests for encoding, sequence padding, and prediction alignment.
- Implementing early stopping based on validation performance.
- Improving experiment reproducibility through deterministic training configurations.
- Benchmarking inference latency and memory consumption.
- Developing a lightweight interactive demonstration for secondary structure prediction.