We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
PEP8 compliance?
I notice sometimes snake_case, sometimes mixedCase are used for class methods
```python
def on_end_epoch(state):
        mlog.printMeter(mode="Train", iepoch=state['epoch'])
        mlog.resetMeter(mode="Train", iepoch=state['epoch'])
```
WIll tnt codebase 100% comply with PEP8?

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `example/mnist_with_meterlogger.py`
Content:
```
1 """ Run MNIST example and log to visdom
2     Notes:
3         - Visdom must be installed (pip works)
4         - the Visdom server must be running at start!
5 
6     Example:
7         $ python -m visdom.server -port 8097 &
8         $ python mnist_with_visdom.py
9 """
10 from tqdm import tqdm
11 import torch
12 import torch.optim
13 import torchnet as tnt
14 from torch.autograd import Variable
15 import torch.nn.functional as F
16 from torch.nn.init import kaiming_normal
17 from torchnet.engine import Engine
18 from torchnet.logger import MeterLogger
19 from torchvision.datasets.mnist import MNIST
20 
21 
22 def get_iterator(mode):
23     ds = MNIST(root='./', download=True, train=mode)
24     data = getattr(ds, 'train_data' if mode else 'test_data')
25     labels = getattr(ds, 'train_labels' if mode else 'test_labels')
26     tds = tnt.dataset.TensorDataset([data, labels])
27     return tds.parallel(batch_size=128, num_workers=4, shuffle=mode)
28 
29 
30 def conv_init(ni, no, k):
31     return kaiming_normal(torch.Tensor(no, ni, k, k))
32 
33 
34 def linear_init(ni, no):
35     return kaiming_normal(torch.Tensor(no, ni))
36 
37 
38 def f(params, inputs, mode):
39     o = inputs.view(inputs.size(0), 1, 28, 28)
40     o = F.conv2d(o, params['conv0.weight'], params['conv0.bias'], stride=2)
41     o = F.relu(o)
42     o = F.conv2d(o, params['conv1.weight'], params['conv1.bias'], stride=2)
43     o = F.relu(o)
44     o = o.view(o.size(0), -1)
45     o = F.linear(o, params['linear2.weight'], params['linear2.bias'])
46     o = F.relu(o)
47     o = F.linear(o, params['linear3.weight'], params['linear3.bias'])
48     return o
49 
50 
51 def main():
52     params = {
53         'conv0.weight': conv_init(1, 50, 5), 'conv0.bias': torch.zeros(50),
54         'conv1.weight': conv_init(50, 50, 5), 'conv1.bias': torch.zeros(50),
55         'linear2.weight': linear_init(800, 512), 'linear2.bias': torch.zeros(512),
56         'linear3.weight': linear_init(512, 10), 'linear3.bias': torch.zeros(10),
57     }
58     params = {k: Variable(v, requires_grad=True) for k, v in params.items()}
59 
60     optimizer = torch.optim.SGD(
61         params.values(), lr=0.01, momentum=0.9, weight_decay=0.0005)
62 
63     engine = Engine()
64 
65     mlog = MeterLogger(server='10.10.30.91', port=9917, nclass=10, title="mnist_meterlogger")
66 
67     def h(sample):
68         inputs = Variable(sample[0].float() / 255.0)
69         targets = Variable(torch.LongTensor(sample[1]))
70         o = f(params, inputs, sample[2])
71         return F.cross_entropy(o, targets), o
72 
73     def on_sample(state):
74         state['sample'].append(state['train'])
75 
76     def on_forward(state):
77         loss = state['loss']
78         output = state['output']
79         target = state['sample'][1]
80         # online ploter
81         mlog.updateLoss(loss, meter='loss')
82         mlog.updateMeter(output, target, meters={'accuracy', 'map', 'confusion'})
83 
84     def on_start_epoch(state):
85         mlog.timer.reset()
86         state['iterator'] = tqdm(state['iterator'])
87 
88     def on_end_epoch(state):
89         mlog.printMeter(mode="Train", iepoch=state['epoch'])
90         mlog.resetMeter(mode="Train", iepoch=state['epoch'])
91 
92         # do validation at the end of each epoch
93         engine.test(h, get_iterator(False))
94         mlog.printMeter(mode="Test", iepoch=state['epoch'])
95         mlog.resetMeter(mode="Test", iepoch=state['epoch'])
96 
97     engine.hooks['on_sample'] = on_sample
98     engine.hooks['on_forward'] = on_forward
99     engine.hooks['on_start_epoch'] = on_start_epoch
100     engine.hooks['on_end_epoch'] = on_end_epoch
101     engine.train(h, get_iterator(True), maxepoch=10, optimizer=optimizer)
102 
103 
104 if __name__ == '__main__':
105     main()
106
```

Path: `torchnet/logger/meterlogger.py`
Content:
```
1 # Copyright (c) 2017, Kui.
2 #
3 # xukui.cs@gmail.com
4 # Tsinghua Univ.
5 # Modified at Dec 12 2017
6 #
7 import torch
8 import torchnet as tnt
9 from torchnet.logger import VisdomPlotLogger, VisdomLogger
10 
11 
12 class MeterLogger(object):
13 
14     def __init__(self, server="http://localhost", port=8097, nclass=21, title="DNN"):
15         self.nclass = nclass
16         self.meter = {}
17         self.server = server
18         self.port = port
19         self.nclass = nclass
20         self.topk = 5 if nclass > 5 else nclass
21         self.title = title
22         self.logger = {'Train': {}, 'Test': {}}
23         self.timer = tnt.meter.TimeMeter(None)
24 
25     def __ver2Tensor(self, target):
26         target_mat = torch.zeros(target.shape[0], self.nclass)
27         for i, j in enumerate(target):
28             target_mat[i][j] = 1
29         return target_mat
30 
31     def __toTensor(self, var):
32         if isinstance(var, torch.autograd.Variable):
33             var = var.data
34         if not torch.is_tensor(var):
35             var = torch.from_numpy(var)
36         return var
37 
38     def __addlogger(self, meter, ptype):
39         if ptype == 'line':
40             opts = {'title': self.title + ' Train ' + meter}
41             self.logger['Train'][meter] = VisdomPlotLogger(ptype, server=self.server, port=self.port, opts=opts)
42             opts = {'title': self.title + ' Test ' + meter}
43             self.logger['Test'][meter] = VisdomPlotLogger(ptype, server=self.server, port=self.port, opts=opts)
44         elif ptype == 'heatmap':
45             names = list(range(self.nclass))
46             opts = {'title': self.title + ' Train ' + meter, 'columnnames': names, 'rownames': names}
47             self.logger['Train'][meter] = VisdomLogger('heatmap', server=self.server, port=self.port, opts=opts)
48             opts = {'title': self.title + ' Test ' + meter, 'columnnames': names, 'rownames': names}
49             self.logger['Test'][meter] = VisdomLogger('heatmap', server=self.server, port=self.port, opts=opts)
50 
51     def __addloss(self, meter):
52         self.meter[meter] = tnt.meter.AverageValueMeter()
53         self.__addlogger(meter, 'line')
54 
55     def __addmeter(self, meter):
56         if meter == 'accuracy':
57             self.meter[meter] = tnt.meter.ClassErrorMeter(topk=(1, self.topk), accuracy=True)
58             self.__addlogger(meter, 'line')
59         elif meter == 'map':
60             self.meter[meter] = tnt.meter.mAPMeter()
61             self.__addlogger(meter, 'line')
62         elif meter == 'auc':
63             self.meter[meter] = tnt.meter.AUCMeter()
64             self.__addlogger(meter, 'line')
65         elif meter == 'confusion':
66             self.meter[meter] = tnt.meter.ConfusionMeter(self.nclass, normalized=True)
67             self.__addlogger(meter, 'heatmap')
68 
69     def updateMeter(self, output, target, meters={'accuracy'}):
70         output = self.__toTensor(output)
71         target = self.__toTensor(target)
72         for meter in meters:
73             if meter not in self.meter.keys():
74                 self.__addmeter(meter)
75             if meter in ['ap', 'map', 'confusion']:
76                 target_th = self.__ver2Tensor(target)
77                 self.meter[meter].add(output, target_th)
78             else:
79                 self.meter[meter].add(output, target)
80 
81     def updateLoss(self, loss, meter='loss'):
82         loss = self.__toTensor(loss)
83         if meter not in self.meter.keys():
84             self.__addloss(meter)
85         self.meter[meter].add(loss[0])
86 
87     def resetMeter(self, iepoch, mode='Train'):
88         self.timer.reset()
89         for key in self.meter.keys():
90             val = self.meter[key].value()
91             val = val[0] if isinstance(val, (list, tuple)) else val
92             if key in ['confusion', 'histogram', 'image']:
93                 self.logger[mode][key].log(val)
94             else:
95                 self.logger[mode][key].log(iepoch, val)
96             self.meter[key].reset()
97 
98     def printMeter(self, mode, iepoch, ibatch=1, totalbatch=1, meterlist=None):
99         pstr = "%s:\t[%d][%d/%d] \t"
100         tval = []
101         tval.extend([mode, iepoch, ibatch, totalbatch])
102         if meterlist is None:
103             meterlist = self.meter.keys()
104             for meter in meterlist:
105                 if meter in ['confusion', 'histogram', 'image']:
106                     continue
107             if meter == 'accuracy':
108                 pstr += "Acc@1 %.2f%% \t Acc@" + str(self.topk) + " %.2f%% \t"
109                 tval.extend([self.meter[meter].value()[0], self.meter[meter].value()[1]])
110             elif meter == 'map':
111                 pstr += "mAP %.3f \t"
112                 tval.extend([self.meter[meter].value()])
113             elif meter == 'auc':
114                 pstr += "AUC %.3f \t"
115                 tval.extend([self.meter[meter].value()])
116             else:
117                 pstr += meter + " %.3f (%.3f)\t"
118                 tval.extend([self.meter[meter].val, self.meter[meter].mean])
119                 pstr += " %.2fs/its\t"
120                 tval.extend([self.timer.value()])
121                 print(pstr % tuple(tval))
122
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/example/mnist_with_meterlogger.py b/example/mnist_with_meterlogger.py
--- a/example/mnist_with_meterlogger.py
+++ b/example/mnist_with_meterlogger.py
@@ -78,21 +78,21 @@
         output = state['output']
         target = state['sample'][1]
         # online ploter
-        mlog.updateLoss(loss, meter='loss')
-        mlog.updateMeter(output, target, meters={'accuracy', 'map', 'confusion'})
+        mlog.update_loss(loss, meter='loss')
+        mlog.update_meter(output, target, meters={'accuracy', 'map', 'confusion'})
 
     def on_start_epoch(state):
         mlog.timer.reset()
         state['iterator'] = tqdm(state['iterator'])
 
     def on_end_epoch(state):
-        mlog.printMeter(mode="Train", iepoch=state['epoch'])
-        mlog.resetMeter(mode="Train", iepoch=state['epoch'])
+        mlog.print_meter(mode="Train", iepoch=state['epoch'])
+        mlog.reset_meter(mode="Train", iepoch=state['epoch'])
 
         # do validation at the end of each epoch
         engine.test(h, get_iterator(False))
-        mlog.printMeter(mode="Test", iepoch=state['epoch'])
-        mlog.resetMeter(mode="Test", iepoch=state['epoch'])
+        mlog.print_meter(mode="Test", iepoch=state['epoch'])
+        mlog.reset_meter(mode="Test", iepoch=state['epoch'])
 
     engine.hooks['on_sample'] = on_sample
     engine.hooks['on_forward'] = on_forward
diff --git a/torchnet/logger/meterlogger.py b/torchnet/logger/meterlogger.py
--- a/torchnet/logger/meterlogger.py
+++ b/torchnet/logger/meterlogger.py
@@ -22,13 +22,13 @@
         self.logger = {'Train': {}, 'Test': {}}
         self.timer = tnt.meter.TimeMeter(None)
 
-    def __ver2Tensor(self, target):
+    def _ver2tensor(self, target):
         target_mat = torch.zeros(target.shape[0], self.nclass)
         for i, j in enumerate(target):
             target_mat[i][j] = 1
         return target_mat
 
-    def __toTensor(self, var):
+    def __to_tensor(self, var):
         if isinstance(var, torch.autograd.Variable):
             var = var.data
         if not torch.is_tensor(var):
@@ -66,25 +66,25 @@
             self.meter[meter] = tnt.meter.ConfusionMeter(self.nclass, normalized=True)
             self.__addlogger(meter, 'heatmap')
 
-    def updateMeter(self, output, target, meters={'accuracy'}):
-        output = self.__toTensor(output)
-        target = self.__toTensor(target)
+    def update_meter(self, output, target, meters={'accuracy'}):
+        output = self.__to_tensor(output)
+        target = self.__to_tensor(target)
         for meter in meters:
             if meter not in self.meter.keys():
                 self.__addmeter(meter)
             if meter in ['ap', 'map', 'confusion']:
-                target_th = self.__ver2Tensor(target)
+                target_th = self._ver2tensor(target)
                 self.meter[meter].add(output, target_th)
             else:
                 self.meter[meter].add(output, target)
 
-    def updateLoss(self, loss, meter='loss'):
-        loss = self.__toTensor(loss)
+    def update_loss(self, loss, meter='loss'):
+        loss = self.__to_tensor(loss)
         if meter not in self.meter.keys():
             self.__addloss(meter)
         self.meter[meter].add(loss[0])
 
-    def resetMeter(self, iepoch, mode='Train'):
+    def reset_meter(self, iepoch, mode='Train'):
         self.timer.reset()
         for key in self.meter.keys():
             val = self.meter[key].value()
@@ -95,7 +95,7 @@
                 self.logger[mode][key].log(iepoch, val)
             self.meter[key].reset()
 
-    def printMeter(self, mode, iepoch, ibatch=1, totalbatch=1, meterlist=None):
+    def print_meter(self, mode, iepoch, ibatch=1, totalbatch=1, meterlist=None):
         pstr = "%s:\t[%d][%d/%d] \t"
         tval = []
         tval.extend([mode, iepoch, ibatch, totalbatch])

{"golden_diff": "diff --git a/example/mnist_with_meterlogger.py b/example/mnist_with_meterlogger.py\n--- a/example/mnist_with_meterlogger.py\n+++ b/example/mnist_with_meterlogger.py\n@@ -78,21 +78,21 @@\n         output = state['output']\n         target = state['sample'][1]\n         # online ploter\n-        mlog.updateLoss(loss, meter='loss')\n-        mlog.updateMeter(output, target, meters={'accuracy', 'map', 'confusion'})\n+        mlog.update_loss(loss, meter='loss')\n+        mlog.update_meter(output, target, meters={'accuracy', 'map', 'confusion'})\n \n     def on_start_epoch(state):\n         mlog.timer.reset()\n         state['iterator'] = tqdm(state['iterator'])\n \n     def on_end_epoch(state):\n-        mlog.printMeter(mode=\"Train\", iepoch=state['epoch'])\n-        mlog.resetMeter(mode=\"Train\", iepoch=state['epoch'])\n+        mlog.print_meter(mode=\"Train\", iepoch=state['epoch'])\n+        mlog.reset_meter(mode=\"Train\", iepoch=state['epoch'])\n \n         # do validation at the end of each epoch\n         engine.test(h, get_iterator(False))\n-        mlog.printMeter(mode=\"Test\", iepoch=state['epoch'])\n-        mlog.resetMeter(mode=\"Test\", iepoch=state['epoch'])\n+        mlog.print_meter(mode=\"Test\", iepoch=state['epoch'])\n+        mlog.reset_meter(mode=\"Test\", iepoch=state['epoch'])\n \n     engine.hooks['on_sample'] = on_sample\n     engine.hooks['on_forward'] = on_forward\ndiff --git a/torchnet/logger/meterlogger.py b/torchnet/logger/meterlogger.py\n--- a/torchnet/logger/meterlogger.py\n+++ b/torchnet/logger/meterlogger.py\n@@ -22,13 +22,13 @@\n         self.logger = {'Train': {}, 'Test': {}}\n         self.timer = tnt.meter.TimeMeter(None)\n \n-    def __ver2Tensor(self, target):\n+    def _ver2tensor(self, target):\n         target_mat = torch.zeros(target.shape[0], self.nclass)\n         for i, j in enumerate(target):\n             target_mat[i][j] = 1\n         return target_mat\n \n-    def __toTensor(self, var):\n+    def __to_tensor(self, var):\n         if isinstance(var, torch.autograd.Variable):\n             var = var.data\n         if not torch.is_tensor(var):\n@@ -66,25 +66,25 @@\n             self.meter[meter] = tnt.meter.ConfusionMeter(self.nclass, normalized=True)\n             self.__addlogger(meter, 'heatmap')\n \n-    def updateMeter(self, output, target, meters={'accuracy'}):\n-        output = self.__toTensor(output)\n-        target = self.__toTensor(target)\n+    def update_meter(self, output, target, meters={'accuracy'}):\n+        output = self.__to_tensor(output)\n+        target = self.__to_tensor(target)\n         for meter in meters:\n             if meter not in self.meter.keys():\n                 self.__addmeter(meter)\n             if meter in ['ap', 'map', 'confusion']:\n-                target_th = self.__ver2Tensor(target)\n+                target_th = self._ver2tensor(target)\n                 self.meter[meter].add(output, target_th)\n             else:\n                 self.meter[meter].add(output, target)\n \n-    def updateLoss(self, loss, meter='loss'):\n-        loss = self.__toTensor(loss)\n+    def update_loss(self, loss, meter='loss'):\n+        loss = self.__to_tensor(loss)\n         if meter not in self.meter.keys():\n             self.__addloss(meter)\n         self.meter[meter].add(loss[0])\n \n-    def resetMeter(self, iepoch, mode='Train'):\n+    def reset_meter(self, iepoch, mode='Train'):\n         self.timer.reset()\n         for key in self.meter.keys():\n             val = self.meter[key].value()\n@@ -95,7 +95,7 @@\n                 self.logger[mode][key].log(iepoch, val)\n             self.meter[key].reset()\n \n-    def printMeter(self, mode, iepoch, ibatch=1, totalbatch=1, meterlist=None):\n+    def print_meter(self, mode, iepoch, ibatch=1, totalbatch=1, meterlist=None):\n         pstr = \"%s:\\t[%d][%d/%d] \\t\"\n         tval = []\n         tval.extend([mode, iepoch, ibatch, totalbatch])\n", "issue": "PEP8 compliance?\nI notice sometimes snake_case, sometimes mixedCase are used for class methods\r\n```python\r\ndef on_end_epoch(state):\r\n        mlog.printMeter(mode=\"Train\", iepoch=state['epoch'])\r\n        mlog.resetMeter(mode=\"Train\", iepoch=state['epoch'])\r\n```\r\nWIll tnt codebase 100% comply with PEP8?\n", "before_files": [{"content": "\"\"\" Run MNIST example and log to visdom\n    Notes:\n        - Visdom must be installed (pip works)\n        - the Visdom server must be running at start!\n\n    Example:\n        $ python -m visdom.server -port 8097 &\n        $ python mnist_with_visdom.py\n\"\"\"\nfrom tqdm import tqdm\nimport torch\nimport torch.optim\nimport torchnet as tnt\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch.nn.init import kaiming_normal\nfrom torchnet.engine import Engine\nfrom torchnet.logger import MeterLogger\nfrom torchvision.datasets.mnist import MNIST\n\n\ndef get_iterator(mode):\n    ds = MNIST(root='./', download=True, train=mode)\n    data = getattr(ds, 'train_data' if mode else 'test_data')\n    labels = getattr(ds, 'train_labels' if mode else 'test_labels')\n    tds = tnt.dataset.TensorDataset([data, labels])\n    return tds.parallel(batch_size=128, num_workers=4, shuffle=mode)\n\n\ndef conv_init(ni, no, k):\n    return kaiming_normal(torch.Tensor(no, ni, k, k))\n\n\ndef linear_init(ni, no):\n    return kaiming_normal(torch.Tensor(no, ni))\n\n\ndef f(params, inputs, mode):\n    o = inputs.view(inputs.size(0), 1, 28, 28)\n    o = F.conv2d(o, params['conv0.weight'], params['conv0.bias'], stride=2)\n    o = F.relu(o)\n    o = F.conv2d(o, params['conv1.weight'], params['conv1.bias'], stride=2)\n    o = F.relu(o)\n    o = o.view(o.size(0), -1)\n    o = F.linear(o, params['linear2.weight'], params['linear2.bias'])\n    o = F.relu(o)\n    o = F.linear(o, params['linear3.weight'], params['linear3.bias'])\n    return o\n\n\ndef main():\n    params = {\n        'conv0.weight': conv_init(1, 50, 5), 'conv0.bias': torch.zeros(50),\n        'conv1.weight': conv_init(50, 50, 5), 'conv1.bias': torch.zeros(50),\n        'linear2.weight': linear_init(800, 512), 'linear2.bias': torch.zeros(512),\n        'linear3.weight': linear_init(512, 10), 'linear3.bias': torch.zeros(10),\n    }\n    params = {k: Variable(v, requires_grad=True) for k, v in params.items()}\n\n    optimizer = torch.optim.SGD(\n        params.values(), lr=0.01, momentum=0.9, weight_decay=0.0005)\n\n    engine = Engine()\n\n    mlog = MeterLogger(server='10.10.30.91', port=9917, nclass=10, title=\"mnist_meterlogger\")\n\n    def h(sample):\n        inputs = Variable(sample[0].float() / 255.0)\n        targets = Variable(torch.LongTensor(sample[1]))\n        o = f(params, inputs, sample[2])\n        return F.cross_entropy(o, targets), o\n\n    def on_sample(state):\n        state['sample'].append(state['train'])\n\n    def on_forward(state):\n        loss = state['loss']\n        output = state['output']\n        target = state['sample'][1]\n        # online ploter\n        mlog.updateLoss(loss, meter='loss')\n        mlog.updateMeter(output, target, meters={'accuracy', 'map', 'confusion'})\n\n    def on_start_epoch(state):\n        mlog.timer.reset()\n        state['iterator'] = tqdm(state['iterator'])\n\n    def on_end_epoch(state):\n        mlog.printMeter(mode=\"Train\", iepoch=state['epoch'])\n        mlog.resetMeter(mode=\"Train\", iepoch=state['epoch'])\n\n        # do validation at the end of each epoch\n        engine.test(h, get_iterator(False))\n        mlog.printMeter(mode=\"Test\", iepoch=state['epoch'])\n        mlog.resetMeter(mode=\"Test\", iepoch=state['epoch'])\n\n    engine.hooks['on_sample'] = on_sample\n    engine.hooks['on_forward'] = on_forward\n    engine.hooks['on_start_epoch'] = on_start_epoch\n    engine.hooks['on_end_epoch'] = on_end_epoch\n    engine.train(h, get_iterator(True), maxepoch=10, optimizer=optimizer)\n\n\nif __name__ == '__main__':\n    main()\n", "path": "example/mnist_with_meterlogger.py"}, {"content": "# Copyright (c) 2017, Kui.\n#\n# xukui.cs@gmail.com\n# Tsinghua Univ.\n# Modified at Dec 12 2017\n#\nimport torch\nimport torchnet as tnt\nfrom torchnet.logger import VisdomPlotLogger, VisdomLogger\n\n\nclass MeterLogger(object):\n\n    def __init__(self, server=\"http://localhost\", port=8097, nclass=21, title=\"DNN\"):\n        self.nclass = nclass\n        self.meter = {}\n        self.server = server\n        self.port = port\n        self.nclass = nclass\n        self.topk = 5 if nclass > 5 else nclass\n        self.title = title\n        self.logger = {'Train': {}, 'Test': {}}\n        self.timer = tnt.meter.TimeMeter(None)\n\n    def __ver2Tensor(self, target):\n        target_mat = torch.zeros(target.shape[0], self.nclass)\n        for i, j in enumerate(target):\n            target_mat[i][j] = 1\n        return target_mat\n\n    def __toTensor(self, var):\n        if isinstance(var, torch.autograd.Variable):\n            var = var.data\n        if not torch.is_tensor(var):\n            var = torch.from_numpy(var)\n        return var\n\n    def __addlogger(self, meter, ptype):\n        if ptype == 'line':\n            opts = {'title': self.title + ' Train ' + meter}\n            self.logger['Train'][meter] = VisdomPlotLogger(ptype, server=self.server, port=self.port, opts=opts)\n            opts = {'title': self.title + ' Test ' + meter}\n            self.logger['Test'][meter] = VisdomPlotLogger(ptype, server=self.server, port=self.port, opts=opts)\n        elif ptype == 'heatmap':\n            names = list(range(self.nclass))\n            opts = {'title': self.title + ' Train ' + meter, 'columnnames': names, 'rownames': names}\n            self.logger['Train'][meter] = VisdomLogger('heatmap', server=self.server, port=self.port, opts=opts)\n            opts = {'title': self.title + ' Test ' + meter, 'columnnames': names, 'rownames': names}\n            self.logger['Test'][meter] = VisdomLogger('heatmap', server=self.server, port=self.port, opts=opts)\n\n    def __addloss(self, meter):\n        self.meter[meter] = tnt.meter.AverageValueMeter()\n        self.__addlogger(meter, 'line')\n\n    def __addmeter(self, meter):\n        if meter == 'accuracy':\n            self.meter[meter] = tnt.meter.ClassErrorMeter(topk=(1, self.topk), accuracy=True)\n            self.__addlogger(meter, 'line')\n        elif meter == 'map':\n            self.meter[meter] = tnt.meter.mAPMeter()\n            self.__addlogger(meter, 'line')\n        elif meter == 'auc':\n            self.meter[meter] = tnt.meter.AUCMeter()\n            self.__addlogger(meter, 'line')\n        elif meter == 'confusion':\n            self.meter[meter] = tnt.meter.ConfusionMeter(self.nclass, normalized=True)\n            self.__addlogger(meter, 'heatmap')\n\n    def updateMeter(self, output, target, meters={'accuracy'}):\n        output = self.__toTensor(output)\n        target = self.__toTensor(target)\n        for meter in meters:\n            if meter not in self.meter.keys():\n                self.__addmeter(meter)\n            if meter in ['ap', 'map', 'confusion']:\n                target_th = self.__ver2Tensor(target)\n                self.meter[meter].add(output, target_th)\n            else:\n                self.meter[meter].add(output, target)\n\n    def updateLoss(self, loss, meter='loss'):\n        loss = self.__toTensor(loss)\n        if meter not in self.meter.keys():\n            self.__addloss(meter)\n        self.meter[meter].add(loss[0])\n\n    def resetMeter(self, iepoch, mode='Train'):\n        self.timer.reset()\n        for key in self.meter.keys():\n            val = self.meter[key].value()\n            val = val[0] if isinstance(val, (list, tuple)) else val\n            if key in ['confusion', 'histogram', 'image']:\n                self.logger[mode][key].log(val)\n            else:\n                self.logger[mode][key].log(iepoch, val)\n            self.meter[key].reset()\n\n    def printMeter(self, mode, iepoch, ibatch=1, totalbatch=1, meterlist=None):\n        pstr = \"%s:\\t[%d][%d/%d] \\t\"\n        tval = []\n        tval.extend([mode, iepoch, ibatch, totalbatch])\n        if meterlist is None:\n            meterlist = self.meter.keys()\n            for meter in meterlist:\n                if meter in ['confusion', 'histogram', 'image']:\n                    continue\n            if meter == 'accuracy':\n                pstr += \"Acc@1 %.2f%% \\t Acc@\" + str(self.topk) + \" %.2f%% \\t\"\n                tval.extend([self.meter[meter].value()[0], self.meter[meter].value()[1]])\n            elif meter == 'map':\n                pstr += \"mAP %.3f \\t\"\n                tval.extend([self.meter[meter].value()])\n            elif meter == 'auc':\n                pstr += \"AUC %.3f \\t\"\n                tval.extend([self.meter[meter].value()])\n            else:\n                pstr += meter + \" %.3f (%.3f)\\t\"\n                tval.extend([self.meter[meter].val, self.meter[meter].mean])\n                pstr += \" %.2fs/its\\t\"\n                tval.extend([self.timer.value()])\n                print(pstr % tuple(tval))\n", "path": "torchnet/logger/meterlogger.py"}], "after_files": [{"content": "\"\"\" Run MNIST example and log to visdom\n    Notes:\n        - Visdom must be installed (pip works)\n        - the Visdom server must be running at start!\n\n    Example:\n        $ python -m visdom.server -port 8097 &\n        $ python mnist_with_visdom.py\n\"\"\"\nfrom tqdm import tqdm\nimport torch\nimport torch.optim\nimport torchnet as tnt\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch.nn.init import kaiming_normal\nfrom torchnet.engine import Engine\nfrom torchnet.logger import MeterLogger\nfrom torchvision.datasets.mnist import MNIST\n\n\ndef get_iterator(mode):\n    ds = MNIST(root='./', download=True, train=mode)\n    data = getattr(ds, 'train_data' if mode else 'test_data')\n    labels = getattr(ds, 'train_labels' if mode else 'test_labels')\n    tds = tnt.dataset.TensorDataset([data, labels])\n    return tds.parallel(batch_size=128, num_workers=4, shuffle=mode)\n\n\ndef conv_init(ni, no, k):\n    return kaiming_normal(torch.Tensor(no, ni, k, k))\n\n\ndef linear_init(ni, no):\n    return kaiming_normal(torch.Tensor(no, ni))\n\n\ndef f(params, inputs, mode):\n    o = inputs.view(inputs.size(0), 1, 28, 28)\n    o = F.conv2d(o, params['conv0.weight'], params['conv0.bias'], stride=2)\n    o = F.relu(o)\n    o = F.conv2d(o, params['conv1.weight'], params['conv1.bias'], stride=2)\n    o = F.relu(o)\n    o = o.view(o.size(0), -1)\n    o = F.linear(o, params['linear2.weight'], params['linear2.bias'])\n    o = F.relu(o)\n    o = F.linear(o, params['linear3.weight'], params['linear3.bias'])\n    return o\n\n\ndef main():\n    params = {\n        'conv0.weight': conv_init(1, 50, 5), 'conv0.bias': torch.zeros(50),\n        'conv1.weight': conv_init(50, 50, 5), 'conv1.bias': torch.zeros(50),\n        'linear2.weight': linear_init(800, 512), 'linear2.bias': torch.zeros(512),\n        'linear3.weight': linear_init(512, 10), 'linear3.bias': torch.zeros(10),\n    }\n    params = {k: Variable(v, requires_grad=True) for k, v in params.items()}\n\n    optimizer = torch.optim.SGD(\n        params.values(), lr=0.01, momentum=0.9, weight_decay=0.0005)\n\n    engine = Engine()\n\n    mlog = MeterLogger(server='10.10.30.91', port=9917, nclass=10, title=\"mnist_meterlogger\")\n\n    def h(sample):\n        inputs = Variable(sample[0].float() / 255.0)\n        targets = Variable(torch.LongTensor(sample[1]))\n        o = f(params, inputs, sample[2])\n        return F.cross_entropy(o, targets), o\n\n    def on_sample(state):\n        state['sample'].append(state['train'])\n\n    def on_forward(state):\n        loss = state['loss']\n        output = state['output']\n        target = state['sample'][1]\n        # online ploter\n        mlog.update_loss(loss, meter='loss')\n        mlog.update_meter(output, target, meters={'accuracy', 'map', 'confusion'})\n\n    def on_start_epoch(state):\n        mlog.timer.reset()\n        state['iterator'] = tqdm(state['iterator'])\n\n    def on_end_epoch(state):\n        mlog.print_meter(mode=\"Train\", iepoch=state['epoch'])\n        mlog.reset_meter(mode=\"Train\", iepoch=state['epoch'])\n\n        # do validation at the end of each epoch\n        engine.test(h, get_iterator(False))\n        mlog.print_meter(mode=\"Test\", iepoch=state['epoch'])\n        mlog.reset_meter(mode=\"Test\", iepoch=state['epoch'])\n\n    engine.hooks['on_sample'] = on_sample\n    engine.hooks['on_forward'] = on_forward\n    engine.hooks['on_start_epoch'] = on_start_epoch\n    engine.hooks['on_end_epoch'] = on_end_epoch\n    engine.train(h, get_iterator(True), maxepoch=10, optimizer=optimizer)\n\n\nif __name__ == '__main__':\n    main()\n", "path": "example/mnist_with_meterlogger.py"}, {"content": "# Copyright (c) 2017, Kui.\n#\n# xukui.cs@gmail.com\n# Tsinghua Univ.\n# Modified at Dec 12 2017\n#\nimport torch\nimport torchnet as tnt\nfrom torchnet.logger import VisdomPlotLogger, VisdomLogger\n\n\nclass MeterLogger(object):\n\n    def __init__(self, server=\"http://localhost\", port=8097, nclass=21, title=\"DNN\"):\n        self.nclass = nclass\n        self.meter = {}\n        self.server = server\n        self.port = port\n        self.nclass = nclass\n        self.topk = 5 if nclass > 5 else nclass\n        self.title = title\n        self.logger = {'Train': {}, 'Test': {}}\n        self.timer = tnt.meter.TimeMeter(None)\n\n    def _ver2tensor(self, target):\n        target_mat = torch.zeros(target.shape[0], self.nclass)\n        for i, j in enumerate(target):\n            target_mat[i][j] = 1\n        return target_mat\n\n    def __to_tensor(self, var):\n        if isinstance(var, torch.autograd.Variable):\n            var = var.data\n        if not torch.is_tensor(var):\n            var = torch.from_numpy(var)\n        return var\n\n    def __addlogger(self, meter, ptype):\n        if ptype == 'line':\n            opts = {'title': self.title + ' Train ' + meter}\n            self.logger['Train'][meter] = VisdomPlotLogger(ptype, server=self.server, port=self.port, opts=opts)\n            opts = {'title': self.title + ' Test ' + meter}\n            self.logger['Test'][meter] = VisdomPlotLogger(ptype, server=self.server, port=self.port, opts=opts)\n        elif ptype == 'heatmap':\n            names = list(range(self.nclass))\n            opts = {'title': self.title + ' Train ' + meter, 'columnnames': names, 'rownames': names}\n            self.logger['Train'][meter] = VisdomLogger('heatmap', server=self.server, port=self.port, opts=opts)\n            opts = {'title': self.title + ' Test ' + meter, 'columnnames': names, 'rownames': names}\n            self.logger['Test'][meter] = VisdomLogger('heatmap', server=self.server, port=self.port, opts=opts)\n\n    def __addloss(self, meter):\n        self.meter[meter] = tnt.meter.AverageValueMeter()\n        self.__addlogger(meter, 'line')\n\n    def __addmeter(self, meter):\n        if meter == 'accuracy':\n            self.meter[meter] = tnt.meter.ClassErrorMeter(topk=(1, self.topk), accuracy=True)\n            self.__addlogger(meter, 'line')\n        elif meter == 'map':\n            self.meter[meter] = tnt.meter.mAPMeter()\n            self.__addlogger(meter, 'line')\n        elif meter == 'auc':\n            self.meter[meter] = tnt.meter.AUCMeter()\n            self.__addlogger(meter, 'line')\n        elif meter == 'confusion':\n            self.meter[meter] = tnt.meter.ConfusionMeter(self.nclass, normalized=True)\n            self.__addlogger(meter, 'heatmap')\n\n    def update_meter(self, output, target, meters={'accuracy'}):\n        output = self.__to_tensor(output)\n        target = self.__to_tensor(target)\n        for meter in meters:\n            if meter not in self.meter.keys():\n                self.__addmeter(meter)\n            if meter in ['ap', 'map', 'confusion']:\n                target_th = self._ver2tensor(target)\n                self.meter[meter].add(output, target_th)\n            else:\n                self.meter[meter].add(output, target)\n\n    def update_loss(self, loss, meter='loss'):\n        loss = self.__to_tensor(loss)\n        if meter not in self.meter.keys():\n            self.__addloss(meter)\n        self.meter[meter].add(loss[0])\n\n    def reset_meter(self, iepoch, mode='Train'):\n        self.timer.reset()\n        for key in self.meter.keys():\n            val = self.meter[key].value()\n            val = val[0] if isinstance(val, (list, tuple)) else val\n            if key in ['confusion', 'histogram', 'image']:\n                self.logger[mode][key].log(val)\n            else:\n                self.logger[mode][key].log(iepoch, val)\n            self.meter[key].reset()\n\n    def print_meter(self, mode, iepoch, ibatch=1, totalbatch=1, meterlist=None):\n        pstr = \"%s:\\t[%d][%d/%d] \\t\"\n        tval = []\n        tval.extend([mode, iepoch, ibatch, totalbatch])\n        if meterlist is None:\n            meterlist = self.meter.keys()\n            for meter in meterlist:\n                if meter in ['confusion', 'histogram', 'image']:\n                    continue\n            if meter == 'accuracy':\n                pstr += \"Acc@1 %.2f%% \\t Acc@\" + str(self.topk) + \" %.2f%% \\t\"\n                tval.extend([self.meter[meter].value()[0], self.meter[meter].value()[1]])\n            elif meter == 'map':\n                pstr += \"mAP %.3f \\t\"\n                tval.extend([self.meter[meter].value()])\n            elif meter == 'auc':\n                pstr += \"AUC %.3f \\t\"\n                tval.extend([self.meter[meter].value()])\n            else:\n                pstr += meter + \" %.3f (%.3f)\\t\"\n                tval.extend([self.meter[meter].val, self.meter[meter].mean])\n                pstr += \" %.2fs/its\\t\"\n                tval.extend([self.timer.value()])\n                print(pstr % tuple(tval))\n", "path": "torchnet/logger/meterlogger.py"}]}