OpenSpliceai 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- OpenSpliceai-0.0.1.dist-info/LICENSE +674 -0
- OpenSpliceai-0.0.1.dist-info/METADATA +177 -0
- OpenSpliceai-0.0.1.dist-info/RECORD +42 -0
- OpenSpliceai-0.0.1.dist-info/WHEEL +5 -0
- OpenSpliceai-0.0.1.dist-info/entry_points.txt +2 -0
- OpenSpliceai-0.0.1.dist-info/top_level.txt +1 -0
- openspliceai/__init__.py +1 -0
- openspliceai/calibrate/__init__.py +0 -0
- openspliceai/calibrate/calibrate.py +85 -0
- openspliceai/calibrate/calibrate_utils.py +42 -0
- openspliceai/calibrate/model_utils.py +59 -0
- openspliceai/calibrate/temperature_scaling.py +211 -0
- openspliceai/calibrate/visualization.py +99 -0
- openspliceai/constants.py +14 -0
- openspliceai/create_data/__init__.py +0 -0
- openspliceai/create_data/create_datafile.py +159 -0
- openspliceai/create_data/create_dataset.py +64 -0
- openspliceai/create_data/paralogs.py +81 -0
- openspliceai/create_data/utils.py +254 -0
- openspliceai/create_data/verify_h5_file.py +61 -0
- openspliceai/header.py +11 -0
- openspliceai/merge_data/__init__.py +0 -0
- openspliceai/merge_data/merge_dataset.py +103 -0
- openspliceai/openspliceai.py +197 -0
- openspliceai/predict/__init__.py +0 -0
- openspliceai/predict/predict.py +1091 -0
- openspliceai/predict/utils.py +53 -0
- openspliceai/test/__init__.py +0 -0
- openspliceai/test/spliceai.py +45 -0
- openspliceai/test/test.py +92 -0
- openspliceai/train/__init__.py +0 -0
- openspliceai/train/train.py +76 -0
- openspliceai/train_base/__init__.py +0 -0
- openspliceai/train_base/spliceai.py +61 -0
- openspliceai/train_base/utils.py +644 -0
- openspliceai/transfer/__init__.py +0 -0
- openspliceai/transfer/transfer.py +107 -0
- openspliceai/variant/__init__.py +0 -0
- openspliceai/variant/get_anno.py +129 -0
- openspliceai/variant/test.py +31 -0
- openspliceai/variant/utils.py +541 -0
- openspliceai/variant/variant.py +89 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: OpenSpliceai
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: A splice site preditction toolkit
|
|
5
|
+
Home-page: https://github.com/Kuanhao-Chao/OpenSpliceAI
|
|
6
|
+
Author: Kuan-Hao Chao
|
|
7
|
+
Author-email: kh.chao@cs.jhu.edu
|
|
8
|
+
Requires-Python: >=3.6
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Dynamic: author
|
|
12
|
+
Dynamic: author-email
|
|
13
|
+
Dynamic: description
|
|
14
|
+
Dynamic: description-content-type
|
|
15
|
+
Dynamic: home-page
|
|
16
|
+
Dynamic: requires-python
|
|
17
|
+
Dynamic: summary
|
|
18
|
+
|
|
19
|
+
<img alt="My Logo" class="logo header-image only-light align-center" src="logo/logo_black.png" style="width:90%">
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
<a class="reference external image-reference" href="https://img.shields.io/badge/License-GPLv3-yellow.svg"><img alt="https://img.shields.io/badge/License-GPLv3-yellow.svg" src="https://img.shields.io/badge/License-GPLv3-yellow.svg"></a>
|
|
23
|
+
<a class="reference external image-reference" href="https://img.shields.io/badge/version-v.0.0.1-blue"><img alt="https://img.shields.io/badge/version-v.0.0.1-blue" src="https://img.shields.io/badge/version-v.0.0.1-blue"></a>
|
|
24
|
+
<a class="reference external image-reference" href="https://pepy.tech/project/lifton"><img alt="https://static.pepy.tech/personalized-badge/lifton?period=total&units=abbreviation&left_color=grey&right_color=blue&left_text=PyPi%20downloads" src="https://static.pepy.tech/personalized-badge/lifton?period=total&units=abbreviation&left_color=grey&right_color=blue&left_text=PyPi%20downloads"></a>
|
|
25
|
+
<a class="reference external image-reference" href="https://github.com/Kuanhao-Chao/lifton/releases"><img alt="https://img.shields.io/github/downloads/Kuanhao-Chao/lifton/total.svg?style=social&logo=github&label=Download" src="https://img.shields.io/github/downloads/Kuanhao-Chao/lifton/total.svg?style=social&logo=github&label=Download"></a>
|
|
26
|
+
<a class="reference external image-reference" href="https://github.com/Kuanhao-Chao/spliceAI-toolkit/releases"><img alt="https://img.shields.io/badge/platform-macOS_/Linux-green.svg" src="https://img.shields.io/badge/platform-macOS_/Linux-green.svg"></a>
|
|
27
|
+
<a class="reference external image-reference" href="https://colab.research.google.com/github/Kuanhao-Chao/lifton/blob/main/notebook/lifton_example.ipynb"><img alt="https://colab.research.google.com/assets/colab-badge.svg" src="https://colab.research.google.com/assets/colab-badge.svg"></a>
|
|
28
|
+
<div class="line-block">
|
|
29
|
+
<div class="line"><br></div>
|
|
30
|
+
</div>
|
|
31
|
+
<p>OpenSpliceAI is an open-source version of SpliceAI, a highly accurate splice site prediction system that provides researchers with a user-friendly framework to study transcript splicing. It comes with models pre-trained on various species, including humans (MANE database), mice, thale cress (Arabidopsis), honey bees, and zebrafish. Additionally, the OpenSpliceAI is capable of processing genetic variants in VCF format to predict their impact on splicing.</p>
|
|
32
|
+
<div class="line-block">
|
|
33
|
+
<div class="line"><br /></div>
|
|
34
|
+
</div>
|
|
35
|
+
<section id="why-openspliceai">
|
|
36
|
+
<h1>Why OpenSpliceAI❓<a class="headerlink" href="#why-openspliceai" title="Permalink to this heading">#</a></h1>
|
|
37
|
+
<ol class="arabic simple">
|
|
38
|
+
<li><p><strong>Easy-to-retrain framework</strong>: Transitioning from the outdated Python 2.7, along with older versions of TensorFlow and Keras, the OpenSpliceAI is built on Python 3.7 and leverages the powerful PyTorch library. This simplifies the retraining process significantly. Say goodbye to compatibility issues and hello to efficiency — retrain your models with just two simple commands.</p></li>
|
|
39
|
+
<li><p><strong>Retrained on new dataset</strong>: SpliceAI is great, but OpenSpliceAI makes it even better! The newly pretrained SpliceAI-Human model is updated from GRCh37 to GRCh38 human genome and integrates the latest MANE (Matched Annotation from NCBI and EMBL-EBI) annotations, ensuring that research is supported by the most up-to-date and precise genomic data available.</p></li>
|
|
40
|
+
<li><p><strong>Retrained on various species</strong>: Concerned that the SpliceAI model does not generalize to your study species because you are not studying humans? No problem! The OpenSpliceAI is released with models pretrained on various species, including human MANE, mouse, thale cress, honey bee, and zebrafish.</p></li>
|
|
41
|
+
<li><p><strong>Predict the impact of genetic variants on splicing</strong>: Similar to SpliceAI, the OpenSpliceAI can take genetic variants in VCF format and predict the impact of these variants on splicing with any of the pretrained models.</p></li>
|
|
42
|
+
</ol>
|
|
43
|
+
<p>OpenSpliceAI is open-source, free, and combines the ease of Python with the power of PyTorch for accurate splicing predictions.</p>
|
|
44
|
+
<div class="line-block">
|
|
45
|
+
<div class="line"><br /></div>
|
|
46
|
+
</div>
|
|
47
|
+
</section>
|
|
48
|
+
<section id="who-is-it-for">
|
|
49
|
+
<h1>Who is it for❓<a class="headerlink" href="#who-is-it-for" title="Permalink to this heading">#</a></h1>
|
|
50
|
+
<ol class="arabic simple">
|
|
51
|
+
<li><p>If you want to study splicing in humans, just use the newly pretrained human SpliceAI-MANE! Better annotation, better results!</p></li>
|
|
52
|
+
<li><p>If you want to do splicing research in other species, the OpenSpliceAI has you covered! It comes with models pretrained on various species! And you can easily train your own SpliceAI with your own genome & annotation data.</p></li>
|
|
53
|
+
<li><p>If you are interested in predicting the impact of genetic variants on splicing, OpenSpliceAI is the perfect tool for you!</p></li>
|
|
54
|
+
</ol>
|
|
55
|
+
<div class="line-block">
|
|
56
|
+
<div class="line"><br /></div>
|
|
57
|
+
</div>
|
|
58
|
+
</section>
|
|
59
|
+
<section id="what-does-openspliceai-do">
|
|
60
|
+
<h1>What does OpenSpliceAI do❓<a class="headerlink" href="#what-does-openspliceai-do" title="Permalink to this heading">#</a></h1>
|
|
61
|
+
<ul class="simple">
|
|
62
|
+
<li><p>The OpenSpliceAI <code class="code docutils literal notranslate"><span class="pre">create-data</span></code> command takes a genome and annotation file as input and generates a dataset for training and testing your SpliceAI model.</p></li>
|
|
63
|
+
<li><p>The OpenSpliceAI <code class="code docutils literal notranslate"><span class="pre">train</span></code> command uses the created dataset to train your own SpliceAI model.</p></li>
|
|
64
|
+
<li><p>To avoid retraining your SpliceAI model from the ground up, the OpenSpliceAI <code class="code docutils literal notranslate"><span class="pre">fine-tune</span></code> command allows for the fine-tuning of the pretrained human model using your own created dataset. It tailors the model to better generalize to your specific species.</p></li>
|
|
65
|
+
<li><p>The OpenSpliceAI <code class="code docutils literal notranslate"><span class="pre">predict</span></code> command takes a random gene sequence and predicts the score of each position, determining whether it is a donor, acceptor, or neither.</p></li>
|
|
66
|
+
<li><p>The OpenSpliceAI <code class="code docutils literal notranslate"><span class="pre">variant</span></code> command takes a VCF file and predicts the impact of genetic variants on splicing.</p></li>
|
|
67
|
+
</ul>
|
|
68
|
+
<div class="line-block">
|
|
69
|
+
<div class="line"><br /></div>
|
|
70
|
+
</div>
|
|
71
|
+
</section>
|
|
72
|
+
<section id="cite-us">
|
|
73
|
+
<h1>Cite us<a class="headerlink" href="#cite-us" title="Permalink to this heading">#</a></h1>
|
|
74
|
+
<p>Kuan-Hao Chao, Alan Mao, Anqi Liu, Mihaela Pertea, and Steven L. Salzberg. <i>"OpenSpliceAI"</i> <b>bioRxiv coming soon!</b>.
|
|
75
|
+
<a href="https://khchao.com/" target="_blank"> <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> </a> </p>
|
|
76
|
+
|
|
77
|
+
<p>Kishore Jaganathan, Sofia Kyriazopoulou Panagiotopoulou, Jeremy F. McRae, Siavash Fazel Darbandi, David Knowles, Yang I. Li, Jack A. Kosmicki, Juan Arbelaez, Wenwu Cui, Grace B. Schwartz, Eric D. Chow, Efstathios Kanterakis, Hong Gao, Amirali Kia, Serafim Batzoglou, Stephan J. Sanders, and Kyle Kai-How Farh. <i>"Predicting splicing from primary sequence with deep learning"</i> <b>Cell</b>.
|
|
78
|
+
<a href="https://doi.org/10.1016/j.cell.2018.12.015" target="_blank"> <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> </a> </p><div class="line-block">
|
|
79
|
+
<div class="line"><br /></div>
|
|
80
|
+
</div>
|
|
81
|
+
</section>
|
|
82
|
+
<section id="user-support">
|
|
83
|
+
<h1>User support<a class="headerlink" href="#user-support" title="Permalink to this heading">#</a></h1>
|
|
84
|
+
<p>Please go through the <a class="reference internal" href="#table-of-contents"><span class="std std-ref">documentation</span></a> below first. If you have questions about using the package, a bug report, or a feature request, please use the GitHub issue tracker here:</p>
|
|
85
|
+
<p><a class="reference external" href="https://github.com/Kuanhao-Chao/openspliceai/issues">https://github.com/Kuanhao-Chao/openspliceai/issues</a></p>
|
|
86
|
+
<div class="line-block">
|
|
87
|
+
<div class="line"><br /></div>
|
|
88
|
+
</div>
|
|
89
|
+
</section>
|
|
90
|
+
<section id="key-contributors">
|
|
91
|
+
<h1>Key contributors<a class="headerlink" href="#key-contributors" title="Permalink to this heading">#</a></h1>
|
|
92
|
+
<p>OpenSpliceAI was designed and developed by <a class="reference external" href="https://khchao.com/">Kuan-Hao Chao</a> and <a class="reference external" href="https://scholar.google.com/citations?user=4c8UQUUAAAAJ&hl=en">Alan Mao</a>. This documentation was written by <a class="reference external" href="https://khchao.com/">Kuan-Hao Chao</a> and <a class="reference external" href="https://scholar.google.com/citations?user=4c8UQUUAAAAJ&hl=en">Alan Mao</a>. The LiftOn logo was designed by <a class="reference external" href="https://khchao.com/">Kuan-Hao Chao</a>.</p>
|
|
93
|
+
<div class="line-block">
|
|
94
|
+
<div class="line"><br /></div>
|
|
95
|
+
</div>
|
|
96
|
+
</section>
|
|
97
|
+
<section id="table-of-contents">
|
|
98
|
+
<span id="id4"></span><h1>Table of contents<a class="headerlink" href="#table-of-contents" title="Permalink to this heading">#</a></h1>
|
|
99
|
+
<div class="toctree-wrapper compound">
|
|
100
|
+
<ul>
|
|
101
|
+
<li class="toctree-l1"><a class="reference internal" href="content/installation.html">Installation</a><ul>
|
|
102
|
+
<li class="toctree-l2"><a class="reference internal" href="content/installation.html#system-requirements">System requirements</a></li>
|
|
103
|
+
<li class="toctree-l2"><a class="reference internal" href="content/installation.html#install-through-pip">Install through pip</a></li>
|
|
104
|
+
<li class="toctree-l2"><a class="reference internal" href="content/installation.html#install-through-conda">Install through conda</a></li>
|
|
105
|
+
<li class="toctree-l2"><a class="reference internal" href="content/installation.html#install-from-source">Install from source</a></li>
|
|
106
|
+
<li class="toctree-l2"><a class="reference internal" href="content/installation.html#check-openspliceai-installation">Check OpenSpliceAI installation</a></li>
|
|
107
|
+
<li class="toctree-l2"><a class="reference internal" href="content/installation.html#now-you-are-ready-to-go">Now, you are ready to go !</a></li>
|
|
108
|
+
</ul>
|
|
109
|
+
</li>
|
|
110
|
+
<li class="toctree-l1"><a class="reference internal" href="content/quickstart.html">Quick Start Guide</a><ul>
|
|
111
|
+
<li class="toctree-l2"><a class="reference internal" href="content/quickstart.html#super-quick-start-one-liner">Super-Quick Start (one-liner)</a></li>
|
|
112
|
+
<li class="toctree-l2"><a class="reference internal" href="content/quickstart.html#try-lifton-on-google-colab">Try LiftOn on Google Colab</a></li>
|
|
113
|
+
</ul>
|
|
114
|
+
</li>
|
|
115
|
+
</ul>
|
|
116
|
+
</div>
|
|
117
|
+
<div class="toctree-wrapper compound">
|
|
118
|
+
<p class="caption" role="heading"><span class="caption-text">Subcommands usage</span></p>
|
|
119
|
+
<ul>
|
|
120
|
+
<li class="toctree-l1"><a class="reference internal" href="content/openspliceai_create-data.html"><code class="code docutils literal notranslate"><span class="pre">create-data</span></code></a><ul>
|
|
121
|
+
<li class="toctree-l2"><a class="reference internal" href="content/openspliceai_create-data.html#subcommand-description">Subcommand description</a></li>
|
|
122
|
+
<li class="toctree-l2"><a class="reference internal" href="content/openspliceai_create-data.html#example-of-human-mane">Example of human MANE</a></li>
|
|
123
|
+
<li class="toctree-l2"><a class="reference internal" href="content/openspliceai_create-data.html#usage">Usage</a></li>
|
|
124
|
+
</ul>
|
|
125
|
+
</li>
|
|
126
|
+
<li class="toctree-l1"><a class="reference internal" href="content/openspliceai_train.html"><code class="code docutils literal notranslate"><span class="pre">train</span></code></a><ul>
|
|
127
|
+
<li class="toctree-l2"><a class="reference internal" href="content/openspliceai_train.html#subcommand-description">Subcommand description</a></li>
|
|
128
|
+
<li class="toctree-l2"><a class="reference internal" href="content/openspliceai_train.html#example-of-human-mane">Example of human MANE</a></li>
|
|
129
|
+
<li class="toctree-l2"><a class="reference internal" href="content/openspliceai_train.html#usage">Usage</a></li>
|
|
130
|
+
</ul>
|
|
131
|
+
</li>
|
|
132
|
+
<li class="toctree-l1"><a class="reference internal" href="content/openspliceai_transfer.html"><code class="code docutils literal notranslate"><span class="pre">transfer</span></code></a></li>
|
|
133
|
+
<li class="toctree-l1"><a class="reference internal" href="content/openspliceai_calibrate.html"><code class="code docutils literal notranslate"><span class="pre">calibrate</span></code></a></li>
|
|
134
|
+
<li class="toctree-l1"><a class="reference internal" href="content/openspliceai_predict.html"><code class="code docutils literal notranslate"><span class="pre">predict</span></code></a></li>
|
|
135
|
+
<li class="toctree-l1"><a class="reference internal" href="content/openspliceai_variant.html"><code class="code docutils literal notranslate"><span class="pre">variant</span></code></a></li>
|
|
136
|
+
</ul>
|
|
137
|
+
</div>
|
|
138
|
+
<div class="toctree-wrapper compound">
|
|
139
|
+
<p class="caption" role="heading"><span class="caption-text">Train your own model</span></p>
|
|
140
|
+
<ul>
|
|
141
|
+
<li class="toctree-l1"><a class="reference internal" href="content/train_your_own_model/index.html">Steps & Commands to train OpenSpliceAI</a></li>
|
|
142
|
+
</ul>
|
|
143
|
+
</div>
|
|
144
|
+
<div class="toctree-wrapper compound">
|
|
145
|
+
<p class="caption" role="heading"><span class="caption-text">Pretrained models</span></p>
|
|
146
|
+
<ul>
|
|
147
|
+
<li class="toctree-l1"><a class="reference internal" href="content/pretrained_models/index.html">Released OpenSpliceAI models</a></li>
|
|
148
|
+
<li class="toctree-l1"><a class="reference internal" href="content/openspliceai_vs_spliceai.html">OpenSpliceAI vs. SpliceAI</a></li>
|
|
149
|
+
<li class="toctree-l1"><a class="reference internal" href="content/behind_scenes.html">Behind the scenes</a></li>
|
|
150
|
+
<li class="toctree-l1"><a class="reference internal" href="content/how_to_page.html">Q & A ...</a></li>
|
|
151
|
+
<li class="toctree-l1"><a class="reference internal" href="content/function_manual.html">User Manual</a><ul>
|
|
152
|
+
<li class="toctree-l2"><a class="reference internal" href="content/function_manual.html#openspliceai">OpenSpliceAI</a></li>
|
|
153
|
+
</ul>
|
|
154
|
+
</li>
|
|
155
|
+
<li class="toctree-l1"><a class="reference internal" href="content/changelog.html">Changelog</a><ul>
|
|
156
|
+
<li class="toctree-l2"><a class="reference internal" href="content/changelog.html#v1-0-0">v1.0.0</a></li>
|
|
157
|
+
</ul>
|
|
158
|
+
</li>
|
|
159
|
+
<li class="toctree-l1"><a class="reference internal" href="content/license.html">License</a></li>
|
|
160
|
+
<li class="toctree-l1"><a class="reference internal" href="content/contact.html">Contact</a></li>
|
|
161
|
+
</ul>
|
|
162
|
+
</div>
|
|
163
|
+
<div class="line-block">
|
|
164
|
+
<div class="line"><br /></div>
|
|
165
|
+
<div class="line"><br /></div>
|
|
166
|
+
<div class="line"><br /></div>
|
|
167
|
+
<div class="line"><br /></div>
|
|
168
|
+
<div class="line"><br /></div>
|
|
169
|
+
</div>
|
|
170
|
+
|
|
171
|
+
<br>
|
|
172
|
+
<br>
|
|
173
|
+
<br>
|
|
174
|
+
|
|
175
|
+
<img alt="My Logo" class="logo header-image only-light align-center" src="logo/jhu-logo-dark.png">
|
|
176
|
+
|
|
177
|
+
</section>
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
openspliceai/__init__.py,sha256=RZ3isKtV8DkXwOSCGeF0R-jsD6n3bw068ArEdbR4iGk,22
|
|
2
|
+
openspliceai/constants.py,sha256=OddcwWwtb8Uhz78lGTrATwUM_ZLp3mb8A-6SgUIhYHU,356
|
|
3
|
+
openspliceai/header.py,sha256=ojls4lS_rcMWGZoRphbIhcwNIPAuV4avc-a0mFOYB9k,358
|
|
4
|
+
openspliceai/openspliceai.py,sha256=Fsh-X4MwUcqOPeZUKZxF9yIsqLzw77V6ZFUi_1obswA,17342
|
|
5
|
+
openspliceai/calibrate/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
openspliceai/calibrate/calibrate.py,sha256=PzH42spSEXIrscynJeE2w7Fzp23xp1Uft3sK2aXdTSI,3858
|
|
7
|
+
openspliceai/calibrate/calibrate_utils.py,sha256=bVHI6aysY_jdIsMcNf2BdIVxi_lVzLMvViBDR_K9Hk8,1687
|
|
8
|
+
openspliceai/calibrate/model_utils.py,sha256=58dDX7zLjL6JXSpUGDej23sT1Tb3EjPPlGfpF2T2Slw,2351
|
|
9
|
+
openspliceai/calibrate/temperature_scaling.py,sha256=OlfvW-ZlQMD9Wqm-SJqa6kiuosv-aR1t8dSxgCUuoFg,8027
|
|
10
|
+
openspliceai/calibrate/visualization.py,sha256=UmQLOPG5al7zc9HWJ4Ex9AF1-yZuaojM_WmVkhs1xBw,4029
|
|
11
|
+
openspliceai/create_data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
openspliceai/create_data/create_datafile.py,sha256=LYfDYMVV28kqyR9HSorOum0ROr2vEsHCVS3ohlE_YHU,8320
|
|
13
|
+
openspliceai/create_data/create_dataset.py,sha256=FU4Q1KAo-l6wmmujN7xnnMLhXQzDv3aDsWpQO_5t2fU,2827
|
|
14
|
+
openspliceai/create_data/paralogs.py,sha256=LUSuEY84oU4IuU1_UxmD60LtZrxdcyYkydGoEV0ohDQ,3646
|
|
15
|
+
openspliceai/create_data/utils.py,sha256=V9CTTAFuDPGm2Ai6d-og1S8pRYTnim7spdaRuX6munM,9859
|
|
16
|
+
openspliceai/create_data/verify_h5_file.py,sha256=KqONUOt2f6ceMzy6ozBMxZ-uA8LaFhd04kwd0vQlXlc,2578
|
|
17
|
+
openspliceai/merge_data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
18
|
+
openspliceai/merge_data/merge_dataset.py,sha256=C0e5bEdxjucFtQvZNxhs5pSdhFX_OOeNtVWlf2dqjO8,4572
|
|
19
|
+
openspliceai/predict/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
20
|
+
openspliceai/predict/predict.py,sha256=Xnb48VVj1wPbZYjdwysxjeDJ1lR-sT-TE7fGFK65Uuc,43930
|
|
21
|
+
openspliceai/predict/utils.py,sha256=01xE0JNMV_MwGe520MJZsdMyaraUwYgQI7Q9YgSTzL0,2289
|
|
22
|
+
openspliceai/test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
23
|
+
openspliceai/test/spliceai.py,sha256=Bjm8gIOgPHu6P3Chn2skwzAb619KBKLvri9mAMFCw20,1675
|
|
24
|
+
openspliceai/test/test.py,sha256=LVNOhDoJi7NJgCd67-Ywfpu19hAEw-Lvf06HrYrB42U,4496
|
|
25
|
+
openspliceai/train/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
26
|
+
openspliceai/train/train.py,sha256=5ue6JLGm1mziqTgTAPr5WvM43wxBz6t_7uXKRwtOlQU,3521
|
|
27
|
+
openspliceai/train_base/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
28
|
+
openspliceai/train_base/spliceai.py,sha256=GVPyzR4Tw-JpooLQrH0A6hHUBRMTfNSd768Xd3k_yDw,1969
|
|
29
|
+
openspliceai/train_base/utils.py,sha256=jUOhhf6va2_QR1uSaZut5uw7aHSLS7ycgiDbZVM3Q10,29433
|
|
30
|
+
openspliceai/transfer/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
31
|
+
openspliceai/transfer/transfer.py,sha256=q2KlvezP_W9yrEDO2S7N1MjAm8S9p1ycuuyACLaxf5U,4860
|
|
32
|
+
openspliceai/variant/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
33
|
+
openspliceai/variant/get_anno.py,sha256=cEJu78bN90gH87CudUTVfrcTRF0ekb9Q_v8g8kTNHhs,3979
|
|
34
|
+
openspliceai/variant/test.py,sha256=moSb-4bXnZmQwrTYSj3-T0I-Qj-wqwfW3bpg7x7J3xI,883
|
|
35
|
+
openspliceai/variant/utils.py,sha256=7MkvENqnt0KVO2bU6rh35IaZkGercvoIzzKzFWXJhWo,23319
|
|
36
|
+
openspliceai/variant/variant.py,sha256=whoDC_BMYzNJoU766CziHVWVZYMnv9g1ZGRunDld_RM,3636
|
|
37
|
+
OpenSpliceai-0.0.1.dist-info/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
|
|
38
|
+
OpenSpliceai-0.0.1.dist-info/METADATA,sha256=y7ypxtPdp6sVQPyG0X-Wehu-cvy4i6WxkS5VDu_b21U,15846
|
|
39
|
+
OpenSpliceai-0.0.1.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
|
|
40
|
+
OpenSpliceai-0.0.1.dist-info/entry_points.txt,sha256=nHFWn862pZ4sHYB64NWv5E8vY7idYPC-CG8p85y3Y38,64
|
|
41
|
+
OpenSpliceai-0.0.1.dist-info/top_level.txt,sha256=Mek05Qa4FlQ2DCVRNfou8cZww_MnWi-9BosZDLPGe1o,13
|
|
42
|
+
OpenSpliceai-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
openspliceai
|
openspliceai/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = 'v0.0.1'
|
|
File without changes
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# calibrate.py
|
|
2
|
+
import os
|
|
3
|
+
import time
|
|
4
|
+
import torch
|
|
5
|
+
import numpy as np
|
|
6
|
+
from torch.nn import functional as F
|
|
7
|
+
from openspliceai.train_base.utils import *
|
|
8
|
+
from openspliceai.calibrate.calibrate_utils import *
|
|
9
|
+
from openspliceai.calibrate.visualization import *
|
|
10
|
+
from openspliceai.calibrate.temperature_scaling import *
|
|
11
|
+
from openspliceai.calibrate.model_utils import initialize_model_and_optim
|
|
12
|
+
|
|
13
|
+
def calibrate(args):
|
|
14
|
+
print('Running OpenSpliceAI calibration')
|
|
15
|
+
start_time = time.time()
|
|
16
|
+
os.makedirs(f"{args.output_dir}/calibration", exist_ok=True)
|
|
17
|
+
|
|
18
|
+
# Initialize model
|
|
19
|
+
device = setup_environment(args)
|
|
20
|
+
train_h5f, test_h5f, batch_num = load_datasets(args)
|
|
21
|
+
train_idxs, val_idxs, test_idxs = generate_indices(batch_num, args.random_seed, test_h5f)
|
|
22
|
+
model, params = initialize_model_and_optim(device, args.flanking_size, args.pretrained_model)
|
|
23
|
+
scaled_model = ModelWithTemperature(model)
|
|
24
|
+
# Check if temperature_file is provided
|
|
25
|
+
valid_loader = get_validation_loader(test_h5f, test_idxs, params["BATCH_SIZE"])
|
|
26
|
+
|
|
27
|
+
# Load/calculate temperature
|
|
28
|
+
if args.temperature_file:
|
|
29
|
+
scaled_model.load_temperature(args.temperature_file, valid_loader, params)
|
|
30
|
+
print(f"Loaded temperature from {args.temperature_file}: {scaled_model.temperature.item()}")
|
|
31
|
+
end_time = time.time()
|
|
32
|
+
print(f"Time taken to load the calibrated model: {end_time - start_time:.2f} seconds")
|
|
33
|
+
else:
|
|
34
|
+
# Train the temperature
|
|
35
|
+
scaled_model.set_temperature(valid_loader, params)
|
|
36
|
+
# Save the temperature parameter
|
|
37
|
+
temperature_save_path = f"{args.output_dir}/temperature.pt"
|
|
38
|
+
scaled_model.save_temperature(temperature_save_path)
|
|
39
|
+
print(f"Saved temperature to {temperature_save_path}")
|
|
40
|
+
end_time = time.time()
|
|
41
|
+
print(f"Time taken to calibrate the model: {end_time - start_time:.2f} seconds")
|
|
42
|
+
|
|
43
|
+
temperature_txt_save_path = f"{args.output_dir}/temperature.txt"
|
|
44
|
+
with open(temperature_txt_save_path, 'w') as f:
|
|
45
|
+
f.write(f"{scaled_model.temperature.item()}\n")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# Generate predictions
|
|
49
|
+
with torch.no_grad():
|
|
50
|
+
logits, labels = scaled_model.logits, scaled_model.labels
|
|
51
|
+
logits_scaled = scaled_model.temperature_scale(logits)
|
|
52
|
+
|
|
53
|
+
# Convert logits to probabilities
|
|
54
|
+
probs = F.softmax(logits, 1).cpu().numpy()
|
|
55
|
+
probs_scaled = F.softmax(logits_scaled, 1).cpu().numpy()
|
|
56
|
+
labels = labels.cpu().numpy()
|
|
57
|
+
|
|
58
|
+
##########################################
|
|
59
|
+
# Plotting the score distribution
|
|
60
|
+
##########################################
|
|
61
|
+
for idx in [0, 1, 2]:
|
|
62
|
+
plot_score_distribution(probs, probs_scaled, labels, args.output_dir, idx)
|
|
63
|
+
|
|
64
|
+
calibration_data = []
|
|
65
|
+
calibration_data_scaled = []
|
|
66
|
+
for i in range(3):
|
|
67
|
+
class_labels = (labels == i).astype(int)
|
|
68
|
+
ct = compute_calibration_curve(class_labels, probs[:, i], 30, 'uniform')
|
|
69
|
+
ct_scaled = compute_calibration_curve(class_labels, probs_scaled[:, i], 30, 'uniform')
|
|
70
|
+
calibration_data.append(ct)
|
|
71
|
+
calibration_data_scaled.append(ct_scaled)
|
|
72
|
+
save_calibration_data(args.output_dir, ['Non-splice', 'Acceptor', 'Donor'][i],
|
|
73
|
+
args.flanking_size, *ct, 'original')
|
|
74
|
+
save_calibration_data(args.output_dir, ['Non-splice', 'Acceptor', 'Donor'][i],
|
|
75
|
+
args.flanking_size, *ct_scaled, 'calibrated')
|
|
76
|
+
|
|
77
|
+
plot_calibration_curves(calibration_data, calibration_data_scaled,
|
|
78
|
+
['Non-splice', 'Acceptor', 'Donor'], args.output_dir)
|
|
79
|
+
|
|
80
|
+
brier_uncal, brier_cal = calculate_brier_scores(labels, probs, probs_scaled)
|
|
81
|
+
plot_brier_scores(brier_uncal, brier_cal, ['Non-splice', 'Acceptor', 'Donor'], args.output_dir)
|
|
82
|
+
|
|
83
|
+
plot_calibration_map(scaled_model, device, args.output_dir)
|
|
84
|
+
|
|
85
|
+
print(f"Calibration completed in {time.time()-start_time:.2f}s")
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# calibration_utils.py
|
|
2
|
+
import torch
|
|
3
|
+
import numpy as np
|
|
4
|
+
from sklearn.calibration import calibration_curve
|
|
5
|
+
from sklearn.metrics import brier_score_loss
|
|
6
|
+
|
|
7
|
+
def compute_calibration_curve(labels, probs, n_bins=10, strategy='quantile'):
|
|
8
|
+
prob_true, prob_pred = calibration_curve(labels, probs, n_bins=n_bins, strategy=strategy)
|
|
9
|
+
if strategy == 'quantile':
|
|
10
|
+
quantiles = np.linspace(0, 1, n_bins + 1)
|
|
11
|
+
bin_edges = np.quantile(probs, quantiles)
|
|
12
|
+
else:
|
|
13
|
+
bin_edges = np.linspace(0, 1, n_bins + 1)
|
|
14
|
+
bin_indices = np.digitize(probs, bin_edges) - 1
|
|
15
|
+
bin_counts = np.array([np.sum(bin_indices == i) for i in range(n_bins)])
|
|
16
|
+
return prob_true, prob_pred, bin_counts
|
|
17
|
+
|
|
18
|
+
def compute_confidence_intervals(prob_true, bin_counts, z=1.96):
|
|
19
|
+
ci_lower, ci_upper = [], []
|
|
20
|
+
for p, n in zip(prob_true, bin_counts):
|
|
21
|
+
std_error = np.sqrt(p * (1 - p) / n) if n > 0 else 0
|
|
22
|
+
delta = z * std_error
|
|
23
|
+
ci_lower.append(max(p - delta, 0))
|
|
24
|
+
ci_upper.append(min(p + delta, 1))
|
|
25
|
+
return np.array(ci_lower), np.array(ci_upper)
|
|
26
|
+
|
|
27
|
+
def reverse_softmax(probs):
|
|
28
|
+
return np.log(np.clip(probs, 1e-8, 1.0))
|
|
29
|
+
|
|
30
|
+
def save_calibration_data(output_dir, class_name, flanking_size, prob_true, prob_pred, bin_counts, suffix):
|
|
31
|
+
np.savez(
|
|
32
|
+
f"{output_dir}/calibration_data_{class_name}_{suffix}_{flanking_size}nt.npz",
|
|
33
|
+
prob_true=prob_true,
|
|
34
|
+
prob_pred=prob_pred,
|
|
35
|
+
bin_counts=bin_counts
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
def calculate_brier_scores(labels, probs, probs_scaled):
|
|
39
|
+
return (
|
|
40
|
+
[brier_score_loss((labels == i).astype(int), probs[:, i]) for i in range(3)],
|
|
41
|
+
[brier_score_loss((labels == i).astype(int), probs_scaled[:, i]) for i in range(3)]
|
|
42
|
+
)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# model_utils.py
|
|
2
|
+
import torch
|
|
3
|
+
import numpy as np
|
|
4
|
+
from openspliceai.constants import *
|
|
5
|
+
from openspliceai.train_base.spliceai import SpliceAI
|
|
6
|
+
|
|
7
|
+
def initialize_model_and_optim(device, flanking_size, pretrained_model):
|
|
8
|
+
L = 32
|
|
9
|
+
N_GPUS = 2
|
|
10
|
+
W = np.asarray([11, 11, 11, 11])
|
|
11
|
+
AR = np.asarray([1, 1, 1, 1])
|
|
12
|
+
BATCH_SIZE = 18 * N_GPUS
|
|
13
|
+
if int(flanking_size) == 80:
|
|
14
|
+
W = np.asarray([11, 11, 11, 11])
|
|
15
|
+
AR = np.asarray([1, 1, 1, 1])
|
|
16
|
+
BATCH_SIZE = 18 * N_GPUS
|
|
17
|
+
elif int(flanking_size) == 400:
|
|
18
|
+
W = np.asarray([11, 11, 11, 11, 11, 11, 11, 11])
|
|
19
|
+
AR = np.asarray([1, 1, 1, 1, 4, 4, 4, 4])
|
|
20
|
+
BATCH_SIZE = 18 * N_GPUS
|
|
21
|
+
elif int(flanking_size) == 2000:
|
|
22
|
+
W = np.asarray([11, 11, 11, 11, 11, 11, 11, 11,
|
|
23
|
+
21, 21, 21, 21])
|
|
24
|
+
AR = np.asarray([1, 1, 1, 1, 4, 4, 4, 4,
|
|
25
|
+
10, 10, 10, 10])
|
|
26
|
+
BATCH_SIZE = 12 * N_GPUS
|
|
27
|
+
elif int(flanking_size) == 10000:
|
|
28
|
+
W = np.asarray([11, 11, 11, 11, 11, 11, 11, 11,
|
|
29
|
+
21, 21, 21, 21, 41, 41, 41, 41])
|
|
30
|
+
AR = np.asarray([1, 1, 1, 1, 4, 4, 4, 4,
|
|
31
|
+
10, 10, 10, 10, 25, 25, 25, 25])
|
|
32
|
+
BATCH_SIZE = 6 * N_GPUS
|
|
33
|
+
CL = 2 * np.sum(AR * (W - 1))
|
|
34
|
+
print("\033[1mContext nucleotides: %d\033[0m" % (CL))
|
|
35
|
+
print("\033[1mSequence length (output): %d\033[0m" % (SL))
|
|
36
|
+
# Initialize the model
|
|
37
|
+
model = SpliceAI(L, W, AR).to(device)
|
|
38
|
+
# Print the shapes of the parameters in the initialized model
|
|
39
|
+
print("\nInitialized model parameter shapes:")
|
|
40
|
+
for name, param in model.named_parameters():
|
|
41
|
+
print(f"{name}: {param.shape}", end=", ")
|
|
42
|
+
|
|
43
|
+
# Load the pretrained model
|
|
44
|
+
state_dict = torch.load(pretrained_model, map_location=device)
|
|
45
|
+
|
|
46
|
+
# Filter out unnecessary keys and load matching keys into model
|
|
47
|
+
model_dict = model.state_dict()
|
|
48
|
+
state_dict = {k: v for k, v in state_dict.items() if k in model_dict and v.size() == model_dict[k].size()}
|
|
49
|
+
|
|
50
|
+
# Load state dict into the model
|
|
51
|
+
missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
|
|
52
|
+
|
|
53
|
+
# Print missing and unexpected keys
|
|
54
|
+
print("\nMissing keys:", missing_keys)
|
|
55
|
+
print("Unexpected keys:", unexpected_keys)
|
|
56
|
+
|
|
57
|
+
params = {'L': L, 'W': W, 'AR': AR, 'CL': CL, 'SL': SL, 'BATCH_SIZE': BATCH_SIZE, 'N_GPUS': N_GPUS}
|
|
58
|
+
return model, params
|
|
59
|
+
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import torch
|
|
3
|
+
from torch import nn, optim
|
|
4
|
+
import torch.nn.functional as F
|
|
5
|
+
import numpy as np
|
|
6
|
+
from openspliceai.train_base.utils import *
|
|
7
|
+
from torch.utils.data import TensorDataset, DataLoader
|
|
8
|
+
from tqdm import tqdm
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def load_data_from_shard(h5f, shard_idx):
|
|
12
|
+
X = h5f[f'X{shard_idx}'][:].transpose(0, 2, 1)
|
|
13
|
+
Y = h5f[f'Y{shard_idx}'][0, ...].transpose(0, 2, 1)
|
|
14
|
+
return X, Y
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def get_validation_loader(h5f, idxs, batch_size):
|
|
18
|
+
"""
|
|
19
|
+
Create a DataLoader for the validation data.
|
|
20
|
+
"""
|
|
21
|
+
X_list, Y_list = [], []
|
|
22
|
+
for shard_idx in idxs:
|
|
23
|
+
X, Y = load_data_from_shard(h5f, shard_idx)
|
|
24
|
+
X_list.append(X)
|
|
25
|
+
Y_list.append(Y)
|
|
26
|
+
X = np.concatenate(X_list, axis=0)
|
|
27
|
+
Y = np.concatenate(Y_list, axis=0)
|
|
28
|
+
X = torch.tensor(X, dtype=torch.float32)
|
|
29
|
+
Y = torch.tensor(Y, dtype=torch.float32)
|
|
30
|
+
print("X:", X.shape)
|
|
31
|
+
print("Y:", Y.shape)
|
|
32
|
+
dataset = TensorDataset(X, Y)
|
|
33
|
+
loader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
|
|
34
|
+
return loader
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ModelWithTemperature(nn.Module):
|
|
38
|
+
"""
|
|
39
|
+
Wraps a model with temperature scaling for better calibration.
|
|
40
|
+
"""
|
|
41
|
+
def __init__(self, model):
|
|
42
|
+
super().__init__()
|
|
43
|
+
self.model = model
|
|
44
|
+
self.temperature = nn.Parameter(torch.ones(1) * 1.1) # Initialized to 1.5
|
|
45
|
+
|
|
46
|
+
def forward(self, input):
|
|
47
|
+
logits = self.model(input)
|
|
48
|
+
return self.temperature_scale(logits)
|
|
49
|
+
|
|
50
|
+
def temperature_scale(self, logits):
|
|
51
|
+
"""
|
|
52
|
+
Apply temperature scaling to the logits.
|
|
53
|
+
"""
|
|
54
|
+
temperature = torch.clamp(self.temperature, min=0.05, max=5.0)
|
|
55
|
+
return logits / temperature
|
|
56
|
+
|
|
57
|
+
def save_temperature(self, filepath):
|
|
58
|
+
"""
|
|
59
|
+
Save the temperature parameter to a file.
|
|
60
|
+
"""
|
|
61
|
+
os.makedirs(os.path.dirname(filepath), exist_ok=True)
|
|
62
|
+
torch.save(self.temperature.detach().cpu(), filepath)
|
|
63
|
+
print(f"Temperature saved to {filepath}")
|
|
64
|
+
|
|
65
|
+
def load_temperature(self, filepath, valid_loader, params):
|
|
66
|
+
"""
|
|
67
|
+
Load the temperature parameter from a file.
|
|
68
|
+
"""
|
|
69
|
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
|
70
|
+
temperature = torch.load(filepath, map_location=device)
|
|
71
|
+
self.temperature = nn.Parameter(temperature.to(device))
|
|
72
|
+
self.temperature.data = torch.clamp(self.temperature.data, min=0.05, max=5.0)
|
|
73
|
+
print(f"Loaded temperature: {self.temperature.item()}")
|
|
74
|
+
|
|
75
|
+
# Collect logits and labels
|
|
76
|
+
logits_list, labels_list = [], []
|
|
77
|
+
with torch.no_grad():
|
|
78
|
+
for input, label in tqdm(valid_loader, desc='Collecting logits and labels'):
|
|
79
|
+
input, label = input.to(device), label.to(device)
|
|
80
|
+
input, label = clip_datapoints(input, label, params["CL"], CL_max, params["N_GPUS"])
|
|
81
|
+
logits = self.model(input)
|
|
82
|
+
logits_list.append(logits.detach().cpu())
|
|
83
|
+
labels_list.append(label.detach().cpu())
|
|
84
|
+
|
|
85
|
+
logits = torch.cat(logits_list).permute(0, 2, 1).contiguous()
|
|
86
|
+
labels = torch.cat(labels_list).permute(0, 2, 1).contiguous().argmax(dim=-1)
|
|
87
|
+
|
|
88
|
+
# Flatten logits and labels
|
|
89
|
+
N, L, C = logits.shape
|
|
90
|
+
logits = logits.view(-1, C).to(device)
|
|
91
|
+
labels = labels.view(-1).long().to(device)
|
|
92
|
+
|
|
93
|
+
self.logits, self.labels = logits, labels
|
|
94
|
+
|
|
95
|
+
def set_temperature(self, valid_loader, params):
|
|
96
|
+
"""
|
|
97
|
+
Tune the temperature parameter using the validation set.
|
|
98
|
+
"""
|
|
99
|
+
print("Setting temperature using the validation loader...")
|
|
100
|
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
|
101
|
+
self.to(device)
|
|
102
|
+
self.model.eval()
|
|
103
|
+
|
|
104
|
+
# Collect class weights
|
|
105
|
+
# class_weights = torch.tensor([10000.0, 10000.0, 1.0], dtype=torch.float32).to(device)
|
|
106
|
+
nll_criterion = nn.CrossEntropyLoss().to(device)
|
|
107
|
+
ece_criterion = _ECELoss().to(device)
|
|
108
|
+
|
|
109
|
+
# Collect logits and labels
|
|
110
|
+
logits_list, labels_list = [], []
|
|
111
|
+
with torch.no_grad():
|
|
112
|
+
for inputs, labels in tqdm(valid_loader, desc='Collecting logits and labels'):
|
|
113
|
+
inputs, labels = inputs.to(device), labels.to(device)
|
|
114
|
+
inputs, labels = clip_datapoints(inputs, labels, params["CL"], CL_max, params["N_GPUS"])
|
|
115
|
+
logits = self.model(inputs)
|
|
116
|
+
logits_list.append(logits)
|
|
117
|
+
labels_list.append(labels)
|
|
118
|
+
|
|
119
|
+
logits = torch.cat(logits_list).permute(0, 2, 1).contiguous()
|
|
120
|
+
labels = torch.cat(labels_list).permute(0, 2, 1).contiguous().argmax(dim=-1)
|
|
121
|
+
|
|
122
|
+
# Flatten logits and labels
|
|
123
|
+
N, L, C = logits.shape
|
|
124
|
+
logits = logits.view(-1, C)
|
|
125
|
+
labels = labels.view(-1).long()
|
|
126
|
+
|
|
127
|
+
self.logits = logits
|
|
128
|
+
self.labels = labels
|
|
129
|
+
|
|
130
|
+
# Compute NLL and ECE before temperature scaling
|
|
131
|
+
self._compute_and_log_metrics(nll_criterion, ece_criterion, 'Before temperature scaling')
|
|
132
|
+
|
|
133
|
+
# Optimize temperature using Adam
|
|
134
|
+
optimizer = optim.Adam([self.temperature], lr=0.01)
|
|
135
|
+
|
|
136
|
+
# Learning rate scheduler
|
|
137
|
+
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=5, verbose=True)
|
|
138
|
+
|
|
139
|
+
# Early stopping parameters
|
|
140
|
+
patience = 10
|
|
141
|
+
min_delta = 1e-6
|
|
142
|
+
best_loss = float('inf')
|
|
143
|
+
patience_counter = 0
|
|
144
|
+
max_epochs = 2000
|
|
145
|
+
|
|
146
|
+
for epoch in range(max_epochs):
|
|
147
|
+
optimizer.zero_grad()
|
|
148
|
+
loss = nll_criterion(self.temperature_scale(self.logits), self.labels)
|
|
149
|
+
loss.backward()
|
|
150
|
+
optimizer.step()
|
|
151
|
+
|
|
152
|
+
# Clamp temperature to the desired range
|
|
153
|
+
self.temperature.data = torch.clamp(self.temperature.data, min=0.05, max=5.0)
|
|
154
|
+
|
|
155
|
+
current_loss = loss.item()
|
|
156
|
+
current_lr = optimizer.param_groups[0]['lr']
|
|
157
|
+
print(f"Epoch {epoch+1}/{max_epochs}, Loss: {current_loss:.6f}, Temperature: {self.temperature.item():.4f}, Learning Rate: {current_lr:.6f}")
|
|
158
|
+
|
|
159
|
+
# Step the scheduler
|
|
160
|
+
scheduler.step(current_loss)
|
|
161
|
+
|
|
162
|
+
# Check for early stopping
|
|
163
|
+
if best_loss - current_loss > min_delta:
|
|
164
|
+
best_loss = current_loss
|
|
165
|
+
patience_counter = 0
|
|
166
|
+
else:
|
|
167
|
+
patience_counter += 1
|
|
168
|
+
|
|
169
|
+
if patience_counter >= patience:
|
|
170
|
+
print("Early stopping due to no improvement in loss.")
|
|
171
|
+
break
|
|
172
|
+
|
|
173
|
+
print(f"Optimized temperature: {self.temperature.item()}")
|
|
174
|
+
|
|
175
|
+
# Compute NLL and ECE after temperature scaling
|
|
176
|
+
self._compute_and_log_metrics(nll_criterion, ece_criterion, 'After temperature scaling')
|
|
177
|
+
|
|
178
|
+
def _compute_and_log_metrics(self, nll_criterion, ece_criterion, phase):
|
|
179
|
+
"""
|
|
180
|
+
Compute and log NLL and ECE metrics.
|
|
181
|
+
"""
|
|
182
|
+
logits_scaled = self.temperature_scale(self.logits)
|
|
183
|
+
nll = nll_criterion(logits_scaled, self.labels).item()
|
|
184
|
+
ece = ece_criterion(logits_scaled, self.labels).item()
|
|
185
|
+
print(f'{phase} - NLL: {nll:.4f}, ECE: {ece:.4f}')
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class _ECELoss(nn.Module):
|
|
189
|
+
"""
|
|
190
|
+
Expected Calibration Error (ECE) Loss.
|
|
191
|
+
"""
|
|
192
|
+
def __init__(self, n_bins=15):
|
|
193
|
+
super().__init__()
|
|
194
|
+
bin_boundaries = torch.linspace(0, 1, n_bins + 1)
|
|
195
|
+
self.bin_lowers = bin_boundaries[:-1]
|
|
196
|
+
self.bin_uppers = bin_boundaries[1:]
|
|
197
|
+
|
|
198
|
+
def forward(self, logits, labels):
|
|
199
|
+
softmaxes = F.softmax(logits, dim=1)
|
|
200
|
+
confidences, predictions = torch.max(softmaxes, dim=1)
|
|
201
|
+
accuracies = predictions.eq(labels)
|
|
202
|
+
|
|
203
|
+
ece = torch.zeros(1, device=logits.device)
|
|
204
|
+
for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers):
|
|
205
|
+
in_bin = (confidences > bin_lower) & (confidences <= bin_upper)
|
|
206
|
+
prop_in_bin = in_bin.float().mean()
|
|
207
|
+
if prop_in_bin.item() > 0:
|
|
208
|
+
accuracy_in_bin = accuracies[in_bin].float().mean()
|
|
209
|
+
avg_confidence_in_bin = confidences[in_bin].mean()
|
|
210
|
+
ece += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin
|
|
211
|
+
return ece
|