In the context of the global energy crisis and environmental protection, the search for sustainable energy alternatives has become essential. Solar energy, as an important renewable energy source, offers broad application prospects. Solar panels are the core components of photovoltaic power generation systems, and their performance and reliability directly determine the efficiency of solar power generation. However, due to long-term outdoor exposure and various environmental factors, solar panels may develop multiple types of defects. These defects can lead to reduced energy conversion efficiency, accelerated aging, and even complete failure of the photovoltaic modules. To promptly identify and repair solar panel defects, accurate defect classification has become a critical research area.
Traditional manual inspection methods for solar panels are time-consuming, labor-intensive, and prone to subjective judgment errors. With the rapid development of computer vision and deep learning, automated defect classification methods have attracted increasing attention. Most existing deep learning approaches rely on supervised learning, which requires large-scale manually annotated datasets. However, in practical industrial scenarios, obtaining annotated data for solar panel defects is expensive and difficult. Moreover, a large quantity of unlabeled solar panel images remains underutilized. To overcome this limitation, self-supervised learning has emerged as a promising paradigm that learns useful representations from unlabeled data without manual annotations.
Among self-supervised approaches, contrastive learning has achieved remarkable success due to its high performance and simplicity. In particular, instance-level contrastive learning treats each image as its own class and learns discriminative features by pulling positive pairs together while pushing negative pairs apart. This approach is well-suited for solar panel defect classification due to its strong ability to model complex patterns and its compatibility with limited data resources. However, the native instance-level contrastive learning framework still faces challenges when applied to solar panel defect data: insufficient feature extraction capability, the need for a large number of negative samples, and the lack of global contextual modeling in the classifier. To address these issues, I propose an improved instance-level contrastive learning framework specifically designed for solar panel defect classification.
In this work, I make three main improvements. First, I adopt SE-ResNet50 as the feature extraction backbone, which enhances the channel-wise attention and improves the network’s ability to capture subtle defect characteristics. Second, I replace the original NT-Xent loss with the Contrastive Loss to better utilize the limited available samples and improve convergence during pre-training. Third, I introduce a global self-attention mechanism into the classifier module instead of using only a fully connected layer, which allows the model to capture long-range dependencies and improves the classification accuracy with a minimal increase in parameters. Extensive experiments are conducted on a solar panel defect dataset. The results demonstrate that the proposed method significantly outperforms the baseline in terms of accuracy and convergence stability.
The remainder of this article is organized as follows. I first review the relevant background of contrastive learning and its variants. Then, I describe the proposed improved method in detail, including the feature extraction module, loss function, and classifier. Next, I present experimental results on benchmark datasets and the solar panel defect dataset. Finally, I conclude the article and discuss future directions.
Background and Related Work
Self-Supervised Learning and Contrastive Learning
Self-supervised learning aims to learn useful representations from unlabeled data by designing proxy tasks that provide automatic supervision signals. Representative proxy tasks include image colorization, jigsaw puzzle solving, rotation prediction, and instance discrimination. Contrastive learning is one of the most effective self-supervised paradigms. Its core idea is to learn an embedding space in which similar samples are close together and dissimilar samples are far apart. Formally, for an anchor sample \(x\), a positive sample \(x^+\), and a negative sample \(x^-\), the desired property is:
$$ \text{score}(f(x), f(x^+)) \gg \text{score}(f(x), f(x^-)) $$
where \(f(\cdot)\) denotes the encoder network, and \(\text{score}(\cdot, \cdot)\) is a similarity metric, typically cosine similarity or Euclidean distance.
Contrastive learning can be divided into several categories according to the comparison objects: context-level, instance-level, and cluster-level contrastive learning. Context-level methods (e.g., Deep Infomax) maximize mutual information between global and local features of an image. Cluster-level methods (e.g., Prototypical Contrastive Learning, SwAV) assign samples to cluster prototypes and pull samples toward their corresponding prototypes. Instance-level contrastive learning, such as SimCLR and MoCo, treats each individual image as a distinct class and distinguishes between augmented views of the same image and views from different images.
Instance-Level Contrastive Learning
Instance-level contrastive learning has become a mainstream approach for self-supervised visual representation learning. In a typical framework, an input image is augmented twice to form a positive pair, while other images in the same batch are considered negative samples. The encoder and a projection head map images to a lower-dimensional feature space. The training objective encourages the similarity of positive pairs to be high and the similarity between a positive and negatives to be low.
| Method | Negative Sampling | Key Characteristics | Application to Solar Panel Defects |
|---|---|---|---|
| SimCLR | In-batch negatives | Large batch size, strong augmentation, MLP projection head | Requires large batch size; may be unsuitable for limited GPU memory and small defect datasets |
| MoCo | Dynamic queue | Momentum encoder, large dictionary size | More memory-efficient but still relies on many negatives |
| BYOL | None | Two networks, online prediction, momentum update | Avoids negative pairs but may suffer from training instability |
| SimSiam | None | Simple siamese network with stop-gradient | Useful but can collapse without careful tuning |
Given that solar panel defect datasets are usually limited in size and annotated samples are scarce, instance-level contrastive learning offers an attractive solution because it utilizes unlabeled data effectively. However, the standard approaches often need a large number of negative samples to achieve good performance. In a resource-constrained environment, the batch size cannot be arbitrarily increased, which makes NT-Xent less effective. Additionally, the backbone network and classifier architecture are crucial for extracting robust features and achieving accurate classification.
Proposed Improved Instance-Level Contrastive Learning
Figure 1 shows the high-level pipeline of the proposed approach. The framework consists of two stages: pre-training and classifier training. In the pre-training stage, unlabeled solar panel images are augmented into two views and fed into the SE-ResNet50 backbone. A projection MLP maps the output features into a low-dimensional space, where Contrastive Loss is computed. After pre-training, the projection head is removed, and the backbone is frozen. A global self-attention classifier is then attached and trained on a small labeled set of solar panel defect images.

Feature Extraction with SE-ResNet50
ResNet50 is a widely used deep convolutional neural network that introduces residual connections to address the degradation problem in deep networks. The residual block can be expressed as:
$$ y = \mathcal{F}(x, \{W_i\}) + x $$
where \(x\) is the input feature map, \(\mathcal{F}(\cdot)\) represents the residual mapping to be learned, and \(y\) is the output. This design allows gradients to flow directly through skip connections, making it easier to train deep networks.
To further strengthen the feature extraction capability for solar panel defect images, I incorporate the Squeeze-and-Excitation (SE) block into each residual block. The SE block adaptively recalibrates channel-wise feature responses by explicitly modeling interdependencies between channels. The operations are as follows. First, global average pooling is applied to the feature map \(U\) to obtain a channel descriptor \(z \in \mathbb{R}^{C}\):
$$ z_c = \frac{1}{H \times W} \sum_{i=1}^{H} \sum_{j=1}^{W} U_c(i,j) $$
Then, a gating mechanism with two fully connected layers and activation functions produces the channel weights:
$$ s = \sigma(W_2 \, \delta(W_1 z)) $$
where \(\delta(\cdot)\) is ReLU, \(\sigma(\cdot)\) is the sigmoid function, and \(W_1 \in \mathbb{R}^{C/r \times C}\), \(W_2 \in \mathbb{R}^{C \times C/r}\) are learnable parameters with reduction ratio \(r\). The final output is obtained by rescaling the original feature map:
$$ \tilde{U}_c = s_c \cdot U_c $$
By integrating SE blocks into all residual layers of ResNet50, I construct SE-ResNet50. This backbone can emphasize important defect-related channels and suppress irrelevant ones, making it more suitable for solar panel defect classification where defects may occupy small regions but have distinctive channel patterns.
Contrastive Loss for Pre-training
The original instance-level contrastive learning method often uses the NT-Xent loss, which is based on InfoNCE. For a batch of \(N\) images, each image is augmented twice, resulting in \(2N\) samples. Let \(z_i\) and \(z_j\) be the projected features of a positive pair. The NT-Xent loss for the pair \((i,j)\) is:
$$ l_{i,j} = -\log \frac{\exp(\mathrm{sim}(z_i, z_j)/\tau)}{\sum_{k=1}^{2N} \mathbb{1}_{[k \neq i]} \exp(\mathrm{sim}(z_i, z_k)/\tau)} $$
where \(\mathrm{sim}(u,v) = \frac{u^T v}{\|u\|\|v\|}\) is the cosine similarity and \(\tau\) is a temperature parameter. This loss requires a large number of negative samples to work well. When the batch size is small (e.g., 32), the number of negatives is limited, and the denominator becomes small, resulting in unstable training and suboptimal convergence.
To better accommodate the limited solar panel defect dataset and limited computational resources, I replace NT-Xent with the Contrastive Loss, originally proposed for metric learning. The Contrastive Loss operates on pairs of samples. Let \(d\) be the Euclidean distance between two feature vectors \(x_i\) and \(x_j\):
$$ d(x_i, x_j) = \sqrt{\sum_{n=1}^{D} (x_i^{(n)} – x_j^{(n)})^2} $$
The loss for a pair is defined as:
$$ L = \frac{1}{2N} \sum_{n=1}^{N} \left[ y_n d_n^2 + (1-y_n) \max(margin – d_n, 0)^2 \right] $$
where \(y_n=1\) if the pair is similar (positive pair) and \(y_n=0\) if the pair is dissimilar (negative pair), and \(margin\) is the minimum distance desired for dissimilar pairs. In the context of solar panel defect pre-training, positive pairs consist of two augmented views of the same image, while negative pairs consist of augmented views from different images. The Contrastive Loss directly minimizes the Euclidean distance for positive pairs and maximize it for negative pairs up to the margin. This loss is simpler, requires less memory than NT-Xent when using a small batch, and leads to more stable convergence in the defect classification scenario.
Global Self-Attention Classifier
After pre-training, the projection head is removed and the SE-ResNet50 backbone is frozen. The backbone outputs a feature map with global average pooling applied, resulting in a 2048-dimensional feature vector. In the original method, a single fully connected layer is used for classification. Although simple, a fully connected layer only exploits local feature interactions and cannot effectively model global dependencies among different spatial regions of the solar panel image. To improve classification performance, I introduce a global self-attention mechanism before the final fully connected layer.
The global self-attention mechanism computes query, key, and value representations for each input position. For a flattened feature sequence \(X \in \mathbb{R}^{L \times D}\), the attention output is:
$$ \text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{D_k}}\right) V $$
where \(Q = XW_Q\), \(K = XW_K\), \(V = XW_V\), and \(W_Q, W_K, W_V\) are learnable weight matrices. This mechanism allows the model to weigh the importance of all positions when constructing the representation of a given position, thus capturing global contextual information. In solar panel defect classification, different defect types may appear in various locations, and the relationship between the defect and its surrounding context is vital for accurate classification. The global self-attention classifier can adaptively focus on relevant regions and learn holistic representations.
Using global self-attention only adds a small number of parameters. Table 1 compares the model size and training time between the original fully connected classifier and the self-attention classifier.
| Backbone | Classifier | Model Size (MB) | Training Time (min) |
|---|---|---|---|
| SE-ResNet50 | FC | 99.67 | 53 |
| SE-ResNet50 | Self-Attention | 100.31 | 57 |
The increase in model size is less than 1 MB, and the training time increases by only about 4 minutes, which is negligible compared with the significant improvement in accuracy.
Experiments on Benchmark Dataset
To validate the effectiveness of the proposed improvements, I first perform experiments on the STL-10 benchmark dataset. STL-10 is a widely used dataset for self-supervised learning, containing 10 classes, 5,000 labeled training images, 8,000 test images, and 100,000 unlabeled images. The experimental environment is summarized in Table 2.
| Item | Configuration |
|---|---|
| Operating System | Ubuntu 20.04 |
| Processor | AMD Ryzen 7 5800H 3.20 GHz |
| GPU | RTX 3060 6G |
| Memory | 16 GB |
| Programming Language | Python 3.9.0 (Anaconda) |
| Deep Learning Framework | PyTorch, Scikit-learn, OpenCV |
The SSL pre-training is performed on the unlabeled STL-10 images for 800 epochs. Then, the backbone is frozen, and the classifier is trained for 150 epochs on the labeled training set. The accuracy metrics Top1 and Top5 are reported in Table 3.
| Backbone | Loss | Classifier | Top1 Acc. | Top5 Acc. |
|---|---|---|---|---|
| ResNet50 | NT-Xent | FC | 69.04% | 97.71% |
| ResNet50 | NT-Xent | Self-Attention | 72.01% | 98.48% |
| ResNet50 | Contrastive Loss | FC | 72.37% | 98.50% |
| ResNet50 | Contrastive Loss | Self-Attention | 74.36% | 99.03% |
| SE-ResNet50 | NT-Xent | FC | 72.79% | 98.56% |
| SE-ResNet50 | NT-Xent | Self-Attention | 74.17% | 99.25% |
| SE-ResNet50 | Contrastive Loss | FC | 73.11% | 98.93% |
| SE-ResNet50 | Contrastive Loss | Self-Attention | 75.07% | 99.35% |
From Table 3, several findings can be drawn. First, replacing ResNet50 with SE-ResNet50 consistently improves the Top1 accuracy by about 1%–3% under the same loss and classifier settings. This confirms the stronger feature extraction capability of SE-ResNet50. Second, the use of Contrastive Loss instead of NT-Xent yields higher accuracy in all configurations, demonstrating its advantage in scenarios with limited batch size and sample diversity. Third, the introduction of the global self-attention classifier improves accuracy by approximately 2%–3% compared with the fully connected classifier, while the computational overhead remains moderate.
Experiments on Solar Panel Defect Dataset
Dataset Description and Preprocessing
To evaluate the proposed method in a realistic industrial application, I use a solar panel defect dataset containing 2,624 grayscale images of 300×300 pixels from 44 different photovoltaic modules. The dataset covers 20 common solar panel defect categories, including short circuits, black spots, scratches, pulse crackles, over-welding, light-and-shade, damages, cryptic fissures, bright spots, lobes, stains, black corners, broken grids, chipping, fluff wires, faulty soldering, dislocations, cut angles, black borders, and mismatches. Examples of each defect type are illustrated in the original dataset.
Data augmentation is a crucial component of contrastive learning. However, not all augmentation operations are suitable for solar panel defect images. For instance, random erasing may remove critical defect information; translation or distortion could change the shape and location of defects. Therefore, I use a carefully selected set of augmentations, including random horizontal/vertical flips, random rotations, random cropping, scaling, brightness/contrast adjustments, and noise addition. These transformations improve the diversity of the training data without altering the essential defect characteristics.
Pre-training Stage
In the pre-training stage, the SE-ResNet50 backbone is trained with the Contrastive Loss. I compare the behavior of the four combinations formed by two backbones (ResNet50, SE-ResNet50) and two losses (NT-Xent, Contrastive Loss). The training parameters are listed in Table 4.
| Parameter | Value |
|---|---|
| Pretraining epochs | 800 |
| Batch size | 32 |
| MLP output dimension | 128 |
| Learning rate | 0.0003 |
From the training curves, I observe that the original combination (ResNet50 + NT-Xent) yields poor convergence: the loss fluctuates around 0.5 for a long time, and the accuracy is unstable even after 800 epochs. When SE-ResNet50 is used with NT-Xent, the training becomes more stable but still suffers from oscillations in the later stages. In contrast, when Contrastive Loss is adopted, the loss decreases smoothly and converges to a lower value, regardless of the backbone. This demonstrates that Contrastive Loss is more robust and more suitable for small-batch training on solar panel defect data.
Classifier Training Stage
After pre-training, the projection head is discarded and the backbone parameters are frozen. The global self-attention classifier is trained on a small labeled subset. In this experiment, I manually label 260 images (about 10% of the dataset), with 13 images per defect class. The classifier is trained for 150 epochs with a batch size of 32 and learning rate of 0.0003. The classification accuracy results are presented in Table 5.
| Backbone | Loss | Classifier | Accuracy |
|---|---|---|---|
| ResNet50 | NT-Xent | FC | 67.15% |
| ResNet50 | NT-Xent | Self-Attention | 70.39% |
| ResNet50 | Contrastive Loss | FC | 72.41% |
| ResNet50 | Contrastive Loss | Self-Attention | 73.95% |
| SE-ResNet50 | NT-Xent | FC | 70.25% |
| SE-ResNet50 | NT-Xent | Self-Attention | 73.23% |
| SE-ResNet50 | Contrastive Loss | FC | 72.85% |
| SE-ResNet50 | Contrastive Loss | Self-Attention | 74.80% |
The results confirm the effectiveness of each improvement on the solar panel defect task. The best accuracy of 74.80% is achieved by the full proposed method with SE-ResNet50, Contrastive Loss, and the global self-attention classifier. This combination outperforms the original baseline (ResNet50 + NT-Xent + FC) by 7.65 percentage points. The improvements come from three complementary aspects:
- SE-ResNet50 backbone: Enhances feature extraction by reweighting channels, leading to better representation of defect patterns.
- Contrastive Loss: Provides more stable training with limited batch sizes, fully utilizing the available solar panel defect samples.
- Global self-attention classifier: Captures global dependencies within each image, improving the classification of defects that are spatially distributed.
Conclusion
In this work, I have proposed an improved instance-level contrastive learning framework for solar panel defect classification. The method addresses three major limitations of the original contrastive learning approach: insufficient feature extraction, dependence on a large batch size due to NT-Xent, and lack of global contextual modeling in the classifier. By introducing SE-ResNet50 as the backbone, replacing the loss with Contrastive Loss, and adding a global self-attention mechanism to the classifier, I have achieved significant accuracy improvements on both the STL-10 benchmark and a solar panel defect dataset. Extensive experiments demonstrate that each modification contributes positively to the final performance.
The proposed method offers a practical solution for industrial solar panel defect classification when labeled data are scarce. It shows that self-supervised learning, particularly contrastive learning, can be effectively adapted to specialized domains. However, several challenges remain. Solar panel defects are highly diverse in shape, size, and severity, which may require more sophisticated augmentation strategies or hard negative mining. The selection of negative samples is critical; in instance-level contrastive learning, two different images of the same defect type are treated as negatives, which may push apart semantically similar samples. Future work could incorporate domain knowledge or cluster-level information to better construct positive and negative pairs. Moreover, while the current method reduces the labeled data requirement, a small amount of labels is still necessary for classifier training. Further research could explore fully unsupervised classification or few-shot learning techniques to minimize annotation effort. Finally, deploying the model in real-time inspection systems requires additional engineering optimization for latency and memory consumption. Despite these challenges, the experimental results suggest that improved contrastive learning is a promising direction for automated solar panel defect classification and can be extended to other industrial quality inspection tasks.
