lib.py 8.6 KB
Newer Older
J
Jeff Wang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2017 VisualDL Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =======================================================================

O
Oraoto 已提交
16
from __future__ import absolute_import
Y
Yan Chunwei 已提交
17
import sys
18
import time
S
superjom 已提交
19
import numpy as np
20
from visualdl.server.log import logger
走神的阿圆's avatar
走神的阿圆 已提交
21
from visualdl.io import bfile
22
from visualdl.utils.string_util import encode_tag, decode_tag
23

S
superjom 已提交
24

走神的阿圆's avatar
走神的阿圆 已提交
25 26 27 28
def s2ms(timestamp):
    return timestamp * 1000 if timestamp < 2000000000 else timestamp


29
def get_components(log_reader):
30 31 32
    components = log_reader.components(update=True)
    components.add('graph')
    return list(components)
S
superjom 已提交
33

S
superjom 已提交
34

35
def get_runs(log_reader):
走神的阿圆's avatar
走神的阿圆 已提交
36 37 38 39 40 41 42
    runs = []
    for item in log_reader.runs():
        if item in log_reader.tags2name:
            runs.append(log_reader.tags2name[item])
        else:
            runs.append(item)
    return runs
43 44


45 46
def get_tags(log_reader):
    return log_reader.tags()
S
superjom 已提交
47 48


49 50 51 52 53 54 55 56 57
def get_logs(log_reader, component):
    all_tag = log_reader.data_manager.get_reservoir(component).keys
    tags = {}
    for item in all_tag:
        index = item.rfind('/')
        run = item[0:index]
        tag = encode_tag(item[index + 1:])
        if run in tags.keys():
            tags[run].append(tag)
58
        else:
59
            tags[run] = [tag]
走神的阿圆's avatar
走神的阿圆 已提交
60 61 62 63 64 65 66
    fake_tags = {}
    for key, value in tags.items():
        if key in log_reader.tags2name:
            fake_tags[log_reader.tags2name[key]] = value
        else:
            fake_tags[key] = value

走神的阿圆's avatar
走神的阿圆 已提交
67 68 69 70 71 72
    run2tag = {'runs': [], 'tags': []}
    for run, tags in fake_tags.items():
        run2tag['runs'].append(run)
        run2tag['tags'].append(tags)

    return run2tag
73 74


75 76
def get_scalar_tags(log_reader):
    return get_logs(log_reader, "scalar")
77 78


79
def get_scalar(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
80
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
81 82 83
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("scalar").get_items(
        run, decode_tag(tag))
走神的阿圆's avatar
走神的阿圆 已提交
84
    results = [[s2ms(item.timestamp), item.id, item.value] for item in records]
85
    return results
86 87


88 89
def get_image_tags(log_reader):
    return get_logs(log_reader, "image")
90 91


92
def get_image_tag_steps(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
93
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
94 95 96 97 98
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("image").get_items(
        run, decode_tag(tag))
    result = [{
        "step": item.id,
走神的阿圆's avatar
走神的阿圆 已提交
99
        "wallTime": s2ms(item.timestamp)
100 101
    } for item in records]
    return result
102 103


104
def get_individual_image(log_reader, run, tag, step_index):
走神的阿圆's avatar
走神的阿圆 已提交
105
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
106 107 108 109
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("image").get_items(
        run, decode_tag(tag))
    return records[step_index].image.encoded_image_string
110 111


112 113
def get_audio_tags(log_reader):
    return get_logs(log_reader, "audio")
114 115


116
def get_audio_tag_steps(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
117
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
118 119 120 121 122
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("audio").get_items(
        run, decode_tag(tag))
    result = [{
        "step": item.id,
走神的阿圆's avatar
走神的阿圆 已提交
123
        "wallTime": s2ms(item.timestamp)
124 125
    } for item in records]
    return result
126 127


128
def get_individual_audio(log_reader, run, tag, step_index):
走神的阿圆's avatar
走神的阿圆 已提交
129
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
130 131 132
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("audio").get_items(
        run, decode_tag(tag))
P
Peter Pan 已提交
133
    result = records[step_index].audio.encoded_audio_string
134
    return result
135 136


137 138 139 140
def get_embeddings_tags(log_reader):
    return get_logs(log_reader, "embeddings")


141 142 143 144
def get_histogram_tags(log_reader):
    return get_logs(log_reader, "histogram")


走神的阿圆's avatar
走神的阿圆 已提交
145 146 147 148 149
def get_pr_curve_tags(log_reader):
    return get_logs(log_reader, "pr_curve")


def get_pr_curve(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
150
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
走神的阿圆's avatar
走神的阿圆 已提交
151 152 153 154 155 156 157 158
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("pr_curve").get_items(
        run, decode_tag(tag))
    results = []
    for item in records:
        pr_curve = item.pr_curve
        length = len(pr_curve.precision)
        num_thresholds = [float(v) / length for v in range(1, length + 1)]
走神的阿圆's avatar
走神的阿圆 已提交
159
        results.append([s2ms(item.timestamp),
走神的阿圆's avatar
走神的阿圆 已提交
160 161 162 163 164 165 166 167 168 169 170 171
                        item.id,
                        list(pr_curve.precision),
                        list(pr_curve.recall),
                        list(pr_curve.TP),
                        list(pr_curve.FP),
                        list(pr_curve.TN),
                        list(pr_curve.FN),
                        num_thresholds])
    return results


def get_pr_curve_step(log_reader, run, tag=None):
走神的阿圆's avatar
走神的阿圆 已提交
172
    fake_run = run
走神的阿圆's avatar
走神的阿圆 已提交
173
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
走神的阿圆's avatar
走神的阿圆 已提交
174
    run2tag = get_pr_curve_tags(log_reader)
走神的阿圆's avatar
走神的阿圆 已提交
175
    tag = run2tag['tags'][run2tag['runs'].index(fake_run)][0]
走神的阿圆's avatar
走神的阿圆 已提交
176 177 178
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("pr_curve").get_items(
        run, decode_tag(tag))
走神的阿圆's avatar
走神的阿圆 已提交
179
    results = [[s2ms(item.timestamp), item.id] for item in records]
走神的阿圆's avatar
走神的阿圆 已提交
180 181 182
    return results


183
def get_embeddings(log_reader, run, tag, reduction, dimension=2):
走神的阿圆's avatar
走神的阿圆 已提交
184
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
185 186 187
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("embeddings").get_items(
        run, decode_tag(tag))
188

189 190 191 192 193 194
    labels = []
    vectors = []
    for item in records[0].embeddings.embeddings:
        labels.append(item.label)
        vectors.append(item.vectors)
    vectors = np.array(vectors)
195

196 197 198 199
    if reduction == 'tsne':
        import visualdl.server.tsne as tsne
        low_dim_embs = tsne.tsne(
            vectors, dimension, initial_dims=50, perplexity=30.0)
200

201 202
    elif reduction == 'pca':
        low_dim_embs = simple_pca(vectors, dimension)
203

204
    return {"embedding": low_dim_embs.tolist(), "labels": labels}
205 206


207
def get_histogram(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
208
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
209 210 211 212 213 214 215 216 217 218 219 220
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("histogram").get_items(
        run, decode_tag(tag))

    results = []
    for item in records:
        histogram = item.histogram
        hist = histogram.hist
        bin_edges = histogram.bin_edges
        histogram_data = []
        for index in range(len(hist)):
            histogram_data.append([bin_edges[index], bin_edges[index+1], hist[index]])
走神的阿圆's avatar
走神的阿圆 已提交
221
        results.append([s2ms(item.timestamp), item.id, histogram_data])
222 223 224 225

    return results


226 227 228
def get_graph(log_reader):
    result = b""
    if log_reader.model:
走神的阿圆's avatar
走神的阿圆 已提交
229 230
        with bfile.BFile(log_reader.model, 'rb') as bfp:
            result = bfp.read_file(log_reader.model)
231 232 233
    return result


234
def retry(ntimes, function, time2sleep, *args, **kwargs):
235
    """
236 237
    try to execute `function` `ntimes`, if exception catched, the thread will
    sleep `time2sleep` seconds.
238
    """
O
Oraoto 已提交
239
    for i in range(ntimes):
240 241
        try:
            return function(*args, **kwargs)
T
Thuan Nguyen 已提交
242
        except Exception:
243 244 245 246 247 248 249
            if i < ntimes-1:
                error_info = '\n'.join(map(str, sys.exc_info()))
                logger.error("Unexpected error: %s" % error_info)
                time.sleep(time2sleep)
            else:
                import traceback
                traceback.print_exc()
250

T
Thuan Nguyen 已提交
251

252 253 254 255 256 257 258 259 260
def cache_get(cache):
    def _handler(key, func, *args, **kwargs):
        data = cache.get(key)
        if data is None:
            logger.warning('update cache %s' % key)
            data = func(*args, **kwargs)
            cache.set(key, data)
            return data
        return data
T
Thuan Nguyen 已提交
261

262
    return _handler
J
Jeff Wang 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285


def simple_pca(x, dimension):
    """
    A simple PCA implementation to do the dimension reduction.
    """

    # Center the data.
    x -= np.mean(x, axis=0)

    # Computing the Covariance Matrix
    cov = np.cov(x, rowvar=False)

    # Get eigenvectors and eigenvalues from the covariance matrix
    eigvals, eigvecs = np.linalg.eig(cov)

    # Sort the eigvals from high to low
    order = np.argsort(eigvals)[::-1]

    # Drop the eigenvectors with low eigenvalues
    eigvecs = eigvecs[:, order[:dimension]]

    return np.dot(x, eigvecs)