1
1
"""
2
- Log using `neptune-logger <https://www. neptune.ml >`_
2
+ Log using `neptune-logger <https://neptune.ai >`_
3
3
4
4
.. _neptune:
5
5
@@ -30,12 +30,13 @@ class NeptuneLogger(LightningLoggerBase):
30
30
"""
31
31
32
32
def __init__ (self , api_key : Optional [str ] = None , project_name : Optional [str ] = None ,
33
- offline_mode : bool = False , experiment_name : Optional [str ] = None ,
33
+ close_after_fit : Optional [bool ] = True , offline_mode : bool = False ,
34
+ experiment_name : Optional [str ] = None ,
34
35
upload_source_files : Optional [List [str ]] = None , params : Optional [Dict [str , Any ]] = None ,
35
36
properties : Optional [Dict [str , Any ]] = None , tags : Optional [List [str ]] = None , ** kwargs ):
36
37
r"""
37
38
38
- Initialize a neptune.ml logger.
39
+ Initialize a neptune.ai logger.
39
40
40
41
.. note:: Requires either an API Key (online mode) or a local directory path (offline mode)
41
42
@@ -44,10 +45,11 @@ def __init__(self, api_key: Optional[str] = None, project_name: Optional[str] =
44
45
# ONLINE MODE
45
46
from pytorch_lightning.loggers import NeptuneLogger
46
47
# arguments made to NeptuneLogger are passed on to the neptune.experiments.Experiment class
48
+ # We are using an api_key for the anonymous user "neptuner" but you can use your own.
47
49
48
50
neptune_logger = NeptuneLogger(
49
- api_key=os.environ["NEPTUNE_API_TOKEN"],
50
- project_name="USER_NAME/PROJECT_NAME ",
51
+ api_key="ANONYMOUS"
52
+ project_name="shared/pytorch-lightning-integration ",
51
53
experiment_name="default", # Optional,
52
54
params={"max_epochs": 10}, # Optional,
53
55
tags=["pytorch-lightning","mlp"] # Optional,
@@ -85,40 +87,91 @@ def any_lightning_module_function_or_hook(...):
85
87
self.logger.experiment.log_artifact("model_checkpoint.pt", prediction_image) # log model checkpoint
86
88
self.logger.experiment.whatever_neptune_supports(...)
87
89
90
+ If you want to log objects after the training is finished use close_after_train=False:
91
+
92
+ .. code-block:: python
93
+
94
+ neptune_logger = NeptuneLogger(
95
+ ...
96
+ close_after_fit=False,
97
+ ...)
98
+ trainer = Trainer(logger=neptune_logger)
99
+ trainer.fit()
100
+
101
+ # Log test metrics
102
+ trainer.test(model)
103
+
104
+ # Log additional metrics
105
+ from sklearn.metrics import accuracy_score
106
+
107
+ accuracy = accuracy_score(y_true, y_pred)
108
+ neptune_logger.experiment.log_metric('test_accuracy', accuracy)
109
+
110
+ # Log charts
111
+ from scikitplot.metrics import plot_confusion_matrix
112
+ import matplotlib.pyplot as plt
113
+
114
+ fig, ax = plt.subplots(figsize=(16, 12))
115
+ plot_confusion_matrix(y_true, y_pred, ax=ax)
116
+ neptune_logger.experiment.log_image('confusion_matrix', fig)
117
+
118
+ # Save checkpoints folder
119
+ neptune_logger.experiment.log_artifact('my/checkpoints')
120
+
121
+ # When you are done, stop the experiment
122
+ neptune_logger.experiment.stop()
123
+
124
+ You can go and see an example experiment here:
125
+ https://ui.neptune.ai/o/shared/org/pytorch-lightning-integration/e/PYTOR-66/charts
126
+
88
127
Args:
89
- api_key (str | None): Required in online mode. Neputne API token, found on https://neptune.ml.
128
+ api_key: Required in online mode.
129
+ Neputne API token, found on https://neptune.ai
90
130
Read how to get your API key
91
- https://docs.neptune.ml/python-api/tutorials/get-started.html#copy-api-token.
92
- project_name (str): Required in online mode. Qualified name of a project in a form of
131
+ https://docs.neptune.ai/python-api/tutorials/get-started.html#copy-api-token.
132
+ It is recommended to keep it in the `NEPTUNE_API_TOKEN`
133
+ environment variable and then you can leave `api_key=None`
134
+ project_name: Required in online mode. Qualified name of a project in a form of
93
135
"namespace/project_name" for example "tom/minst-classification".
94
136
If None, the value of NEPTUNE_PROJECT environment variable will be taken.
95
- You need to create the project in https://neptune.ml first.
96
- offline_mode (bool): Optional default False. If offline_mode=True no logs will be send to neptune.
97
- Usually used for debug purposes.
98
- experiment_name (str|None): Optional. Editable name of the experiment.
99
- Name is displayed in the experiment’s Details (Metadata section) and in experiments view as a column.
100
- upload_source_files (list|None): Optional. List of source files to be uploaded.
101
- Must be list of str or single str. Uploaded sources are displayed in the experiment’s Source code tab.
137
+ You need to create the project in https://neptune.ai first.
138
+ offline_mode: Optional default False. If offline_mode=True no logs will be send
139
+ to neptune. Usually used for debug purposes.
140
+ close_after_fit: Optional default True. If close_after_fit=False the experiment
141
+ will not be closed after training and additional metrics,
142
+ images or artifacts can be logged. Also, remember to close the experiment explicitly
143
+ by running neptune_logger.experiment.stop().
144
+ experiment_name: Optional. Editable name of the experiment.
145
+ Name is displayed in the experiment’s Details (Metadata section) and i
146
+ n experiments view as a column.
147
+ upload_source_files: Optional. List of source files to be uploaded.
148
+ Must be list of str or single str. Uploaded sources are displayed
149
+ in the experiment’s Source code tab.
102
150
If None is passed, Python file from which experiment was created will be uploaded.
103
- Pass empty list ([]) to upload no files. Unix style pathname pattern expansion is supported.
151
+ Pass empty list ([]) to upload no files.
152
+ Unix style pathname pattern expansion is supported.
104
153
For example, you can pass '\*.py'
105
154
to upload all python source files from the current directory.
106
155
For recursion lookup use '\**/\*.py' (for Python 3.5 and later).
107
156
For more information see glob library.
108
- params (dict|None): Optional. Parameters of the experiment. After experiment creation params are read-only.
109
- Parameters are displayed in the experiment’s Parameters section and each key-value pair can be
110
- viewed in experiments view as a column.
111
- properties (dict|None): Optional default is {}. Properties of the experiment.
112
- They are editable after experiment is created. Properties are displayed in the experiment’s Details and
157
+ params: Optional. Parameters of the experiment.
158
+ After experiment creation params are read-only.
159
+ Parameters are displayed in the experiment’s Parameters section and
160
+ each key-value pair can be viewed in experiments view as a column.
161
+ properties: Optional default is {}. Properties of the experiment.
162
+ They are editable after experiment is created.
163
+ Properties are displayed in the experiment’s Details and
113
164
each key-value pair can be viewed in experiments view as a column.
114
- tags (list|None) : Optional default []. Must be list of str. Tags of the experiment.
165
+ tags: Optional default []. Must be list of str. Tags of the experiment.
115
166
They are editable after experiment is created (see: append_tag() and remove_tag()).
116
- Tags are displayed in the experiment’s Details and can be viewed in experiments view as a column.
167
+ Tags are displayed in the experiment’s Details and can be viewed
168
+ in experiments view as a column.
117
169
"""
118
170
super ().__init__ ()
119
171
self .api_key = api_key
120
172
self .project_name = project_name
121
173
self .offline_mode = offline_mode
174
+ self .close_after_fit = close_after_fit
122
175
self .experiment_name = experiment_name
123
176
self .upload_source_files = upload_source_files
124
177
self .params = params
@@ -138,6 +191,12 @@ def any_lightning_module_function_or_hook(...):
138
191
139
192
log .info (f'NeptuneLogger was initialized in { self .mode } mode' )
140
193
194
+ def __getstate__ (self ):
195
+ state = self .__dict__ .copy ()
196
+ # cannot be pickled
197
+ state ['_experiment' ] = None
198
+ return state
199
+
141
200
@property
142
201
def experiment (self ) -> Experiment :
143
202
r"""
@@ -150,15 +209,14 @@ def experiment(self) -> Experiment:
150
209
151
210
"""
152
211
153
- if self ._experiment is not None :
154
- return self ._experiment
155
- else :
156
- self ._experiment = neptune .create_experiment (name = self .experiment_name ,
157
- params = self .params ,
158
- properties = self .properties ,
159
- tags = self .tags ,
160
- upload_source_files = self .upload_source_files ,
161
- ** self ._kwargs )
212
+ if self ._experiment is None :
213
+ self ._experiment = neptune .create_experiment (
214
+ name = self .experiment_name ,
215
+ params = self .params ,
216
+ properties = self .properties ,
217
+ tags = self .tags ,
218
+ upload_source_files = self .upload_source_files ,
219
+ ** self ._kwargs )
162
220
return self ._experiment
163
221
164
222
@rank_zero_only
@@ -184,7 +242,8 @@ def log_metrics(
184
242
185
243
@rank_zero_only
186
244
def finalize (self , status : str ) -> None :
187
- self .experiment .stop ()
245
+ if self .close_after_fit :
246
+ self .experiment .stop ()
188
247
189
248
@property
190
249
def name (self ) -> str :
0 commit comments