data.py 4.61 KB
Newer Older
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
1
2
3
4
5
6
7
8
# Copyright 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.

import torch
import torchnet
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
9
import sparseconvnet as scn
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
10
11
12
import pickle
import math
import random
13
import numpy as np
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
14
15
16
17
18
19
20
21
import os

if not os.path.exists('pickle/'):
    print('Downloading and preprocessing data ...')
    os.system('bash process.sh')
    import process


Benjamin Thomas Graham's avatar
tidy  
Benjamin Thomas Graham committed
22
def train(spatial_size, Scale, precomputeSize):
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
23
24
25
26
27
    d = pickle.load(open('pickle/train.pickle', 'rb'))
    print('Replicating training set 10 times (1 epoch = 10 iterations through the training set = 10x6588 training samples)')
    for i in range(9):
        for j in range(6588):
            d.append(d[j])
28
29
    for i, x in enumerate(d):
        x['idx'] = i
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
30
31
32
33
34
35
36
37
38
39
40
    d = torchnet.dataset.ListDataset(d)
    randperm = torch.randperm(len(d))

    def perm(idx, size):
        return randperm[idx]

    def merge(tbl):
        inp = scn.InputBatch(2, spatial_size)
        center = spatial_size.float().view(1, 2) / 2
        p = torch.LongTensor(2)
        v = torch.FloatTensor([1, 0, 0])
41
        np_random = np.random.RandomState(tbl['idx'])
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
42
        for char in tbl['input']:
Benjamin Thomas Graham's avatar
tidy  
Benjamin Thomas Graham committed
43
            inp.add_sample()
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
44
            m = torch.eye(2)
45
            r = np_random.randint(1, 3)
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
            alpha = random.uniform(-0.2, 0.2)
            if alpha == 1:
                m[0][1] = alpha
            elif alpha == 2:
                m[1][0] = alpha
            else:
                m = torch.mm(m, torch.FloatTensor(
                    [[math.cos(alpha), math.sin(alpha)],
                     [-math.sin(alpha), math.cos(alpha)]]))
            c = center + torch.FloatTensor(1, 2).uniform_(-8, 8)
            for stroke in char:
                stroke = stroke.float() / 255 - 0.5
                stroke = c.expand_as(stroke) + \
                    torch.mm(stroke, m * (Scale - 0.01))
                ###############################################################
                # To avoid GIL problems use a helper function:
                scn.dim_fn(
                    2,
                    'drawCurve')(
                    inp.metadata.ffi,
                    inp.features,
                    stroke)
                ###############################################################
                # Above is equivalent to :
                # x1,x2,y1,y2,l=0,stroke[0][0],0,stroke[0][1],0
                # for i in range(1,stroke.size(0)):
                #     x1=x2
                #     y1=y2
                #     x2=stroke[i][0]
                #     y2=stroke[i][1]
                #     l=1e-10+((x2-x1)**2+(y2-y1)**2)**0.5
                #     v[1]=(x2-x1)/l
                #     v[2]=(y2-y1)/l
                #     l=max(x2-x1,y2-y1,x1-x2,y1-y2,0.9)
80
                #     for j in np.arange(0,1,1/l):
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
81
82
                #         p[0]=math.floor(x1*j+x2*(1-j))
                #         p[1]=math.floor(y1*j+y2*(1-j))
Benjamin Thomas Graham's avatar
tidy  
Benjamin Thomas Graham committed
83
                #         inp.set_location(p,v,False)
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
84
                ###############################################################
Benjamin Thomas Graham's avatar
tidy  
Benjamin Thomas Graham committed
85
        inp.precomputeMetadata(precomputeSize)
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
86
87
88
89
90
        return {'input': inp, 'target': torch.LongTensor(tbl['target']) - 1}
    bd = torchnet.dataset.BatchDataset(d, 108, perm=perm, merge=merge)
    tdi = scn.threadDatasetIterator(bd)

    def iter():
91
        randperm.copy_(torch.randperm(len(d)))
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
92
93
94
95
        return tdi()
    return iter


Benjamin Thomas Graham's avatar
tidy  
Benjamin Thomas Graham committed
96
def val(spatial_size, Scale, precomputeSize):
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
97
98
99
100
101
102
103
104
105
106
107
108
109
    d = pickle.load(open('pickle/test.pickle', 'rb'))
    d = torchnet.dataset.ListDataset(d)
    randperm = torch.randperm(len(d))

    def perm(idx, size):
        return randperm[idx]

    def merge(tbl):
        inp = scn.InputBatch(2, spatial_size)
        center = spatial_size.float().view(1, 2) / 2
        p = torch.LongTensor(2)
        v = torch.FloatTensor([1, 0, 0])
        for char in tbl['input']:
Benjamin Thomas Graham's avatar
tidy  
Benjamin Thomas Graham committed
110
            inp.add_sample()
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
111
112
113
114
115
116
117
118
119
            for stroke in char:
                stroke = stroke.float() * (Scale - 0.01) / 255 - 0.5 * (Scale - 0.01)
                stroke += center.expand_as(stroke)
                scn.dim_fn(
                    2,
                    'drawCurve')(
                    inp.metadata.ffi,
                    inp.features,
                    stroke)
Benjamin Thomas Graham's avatar
tidy  
Benjamin Thomas Graham committed
120
        inp.precomputeMetadata(precomputeSize)
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
121
122
123
124
125
        return {'input': inp, 'target': torch.LongTensor(tbl['target']) - 1}
    bd = torchnet.dataset.BatchDataset(d, 183, perm=perm, merge=merge)
    tdi = scn.threadDatasetIterator(bd)

    def iter():
126
        randperm.copy_(torch.randperm(len(d)))
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
127
128
129
130
        return tdi()
    return iter


Benjamin Thomas Graham's avatar
tidy  
Benjamin Thomas Graham committed
131
def get_iterators(*args):
Benjamin Thomas Graham's avatar
Benjamin Thomas Graham committed
132
    return {'train': train(*args), 'val': val(*args)}