-
Notifications
You must be signed in to change notification settings - Fork 1
/
wasserstein Distance [ TF ].py
254 lines (208 loc) · 10.8 KB
/
wasserstein Distance [ TF ].py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
"""
https://github.com/google/wasserstein-dist/blob/master/wasserstein.py
batch size를 변행해서 넣어서 작동함
http://220.67.120.131:8888/notebooks/SR/homework/Churn%20GAN_Wasserstein_Corr_%EC%B6%94%EA%B0%80.ipynb 참조하면 됨
"""
class Wasserstein(object):
"""Class to hold (ref to) data and compute Wasserstein distance."""
def __init__(self, source_gen, target_gen, batch_size , basedist=None):
"""Inits Wasserstein with source and target data."""
self.source_gen = source_gen
self.target_gen = target_gen
self.source_bs = batch_size
self.target_bs = batch_size
if basedist is None:
basedist = self.l2dist
self.basedist = basedist
def add_summary_montage(self, images, name, num=9):
vis_images = tf.split(images[:num], num_or_size_splits=num, axis=0)
vis_images = tf.concat(vis_images, axis=2)
tf.summary.image(name, vis_images)
return vis_images
def add_summary_images(self, num=9):
"""Visualize source images and nearest neighbors from target."""
source_ims = self.source_gen.get_batch(bs=num, reuse=True)
vis_images = self.add_summary_montage(source_ims, 'source_ims', num)
target_ims = self.target_gen.get_batch()
_ = self.add_summary_montage(target_ims, 'target_ims', num)
c_xy = self.basedist(source_ims, target_ims) # pairwise cost
idx = tf.argmin(c_xy, axis=1) # find nearest neighbors
matches = tf.gather(target_ims, idx)
vis_matches = self.add_summary_montage(matches, 'neighbors_ims', num)
vis_both = tf.concat([vis_images, vis_matches], axis=1)
tf.summary.image('matches_ims', vis_both)
return
def l2dist(self, source, target):
"""Computes pairwise Euclidean distances in tensorflow."""
def flatten_batch(x):
dim = tf.reduce_prod(tf.shape(x)[1:])
return tf.reshape(x, [-1, dim])
def scale_batch(x):
dim = tf.reduce_prod(tf.shape(x)[1:])
return x/tf.sqrt(tf.cast(dim, tf.float32))
def prepare_batch(x):
return scale_batch(flatten_batch(x))
target_flat = prepare_batch(target) # shape: [bs, nt]
target_sqnorms = tf.reduce_sum(tf.square(target_flat), axis=1, keep_dims=True)
target_sqnorms_t = tf.transpose(target_sqnorms)
source_flat = prepare_batch(source) # shape: [bs, ns]
source_sqnorms = tf.reduce_sum(tf.square(source_flat), axis=1, keep_dims=True)
dotprod = tf.matmul(source_flat, target_flat, transpose_b=True) # [ns, nt]
sqdist = source_sqnorms - 2*dotprod + target_sqnorms_t
dist = tf.sqrt(tf.nn.relu(sqdist)) # potential tiny negatives are suppressed
return dist # shape: [ns, nt]
def grad_hbar(self, v,reuse=True):
"""Compute gradient of hbar function for Wasserstein iteration."""
source_ims = self.source_gen
target_data = self.target_gen
c_xy = self.basedist(source_ims, target_data)
c_xy -= v # [gradbs, trnsize]
idx = tf.argmin(c_xy, axis=1) # [1] (index of subgradient)
target_bs = self.target_bs
xi_ij = tf.one_hot(idx, target_bs) # find matches, [gradbs, trnsize]
xi_ij = tf.reduce_mean(xi_ij, axis=0, keep_dims=True) # [1, trnsize]
grad = 1./target_bs - xi_ij # output: [1, trnsize]
return grad
def hbar(self, v, reuse=True):
"""Compute value of hbar function for Wasserstein iteration."""
source_ims = self.source_gen
target_data = self.target_gen
c_xy = self.basedist(source_ims, target_data)
c_avg = tf.reduce_mean(c_xy)
c_xy -= c_avg
c_xy -= v
c_xy_min = tf.reduce_min(c_xy, axis=1) # min_y[ c(x, y) - v(y) ]
c_xy_min = tf.reduce_mean(c_xy_min) # expectation wrt x
return tf.reduce_mean(v, axis=1) + c_xy_min + c_avg # avg wrt y
def k_step(self, k, v, vt, c, reuse=True):
"""Perform one update step of Wasserstein computation."""
grad_h = self.grad_hbar(vt, reuse=reuse)
vt = tf.assign_add(vt, c/tf.sqrt(k)*grad_h, name='vt_assign_add')
v = ((k-1.)*v + vt)/k
return k+1, v, vt, c
def dist(self, C=.1, nsteps=10, reset=False):
"""Compute Wasserstein distance (Alg.2 in [Genevay etal, NIPS'16])."""
target_bs = self.target_bs
vtilde = tf.Variable(tf.zeros([1, target_bs]), name='vtilde')
v = tf.Variable(tf.zeros([1, target_bs]), name='v')
k = tf.Variable(1., name='k')
k = k.assign(1.) # restart averaging from 1 in each call
if reset: # used for randomly sampled target data, otherwise warmstart
v = v.assign(tf.zeros([1, target_bs])) # reset every time graph is evaluated
vtilde = vtilde.assign(tf.zeros([1, target_bs]))
# (unrolled) optimization loop. first iteration, create variables
k, v, vtilde, C = self.k_step(k, v, vtilde, C, reuse=False)
# (unrolled) optimization loop. other iterations, reuse variables
k, v, vtilde, C = tf.while_loop(cond=lambda k, *_: k < nsteps,
body=self.k_step,
loop_vars=[k, v, vtilde, C])
v = tf.stop_gradient(v) # only transmit gradient through cost
val = self.hbar(v)
return tf.reduce_mean(val)
## 위에 수정
# from __future__ import absolute_import
# from __future__ import division
# from __future__ import print_function
# import tensorflow as tf
# """https://github.com/google/wasserstein-dist/blob/master/wasserstein.py"""
# class Wasserstein(object):
# """Class to hold (ref to) data and compute Wasserstein distance."""
# def __init__(self, source_gen, target_gen, basedist=None):
# """Inits Wasserstein with source and target data."""
# self.source_gen = source_gen
# self.source_bs = source_gen.bs
# self.target_gen = target_gen
# self.target_bs = target_gen.bs
# self.gradbs = self.source_bs # number of source sample to compute gradient
# if basedist is None:
# basedist = self.l2dist
# self.basedist = basedist
# def add_summary_montage(self, images, name, num=9):
# vis_images = tf.split(images[:num], num_or_size_splits=num, axis=0)
# vis_images = tf.concat(vis_images, axis=2)
# tf.summary.image(name, vis_images)
# return vis_images
# def add_summary_images(self, num=9):
# """Visualize source images and nearest neighbors from target."""
# source_ims = self.source_gen.get_batch(bs=num, reuse=True)
# vis_images = self.add_summary_montage(source_ims, 'source_ims', num)
# target_ims = self.target_gen.get_batch()
# _ = self.add_summary_montage(target_ims, 'target_ims', num)
# c_xy = self.basedist(source_ims, target_ims) # pairwise cost
# idx = tf.argmin(c_xy, axis=1) # find nearest neighbors
# matches = tf.gather(target_ims, idx)
# vis_matches = self.add_summary_montage(matches, 'neighbors_ims', num)
# vis_both = tf.concat([vis_images, vis_matches], axis=1)
# tf.summary.image('matches_ims', vis_both)
# return
# def l2dist(self, source, target):
# """Computes pairwise Euclidean distances in tensorflow."""
# def flatten_batch(x):
# dim = tf.reduce_prod(tf.shape(x)[1:])
# return tf.reshape(x, [-1, dim])
# def scale_batch(x):
# dim = tf.reduce_prod(tf.shape(x)[1:])
# return x/tf.sqrt(tf.cast(dim, tf.float32))
# def prepare_batch(x):
# return scale_batch(flatten_batch(x))
# target_flat = prepare_batch(target) # shape: [bs, nt]
# target_sqnorms = tf.reduce_sum(tf.square(target_flat), axis=1, keep_dims=True)
# target_sqnorms_t = tf.transpose(target_sqnorms)
# source_flat = prepare_batch(source) # shape: [bs, ns]
# source_sqnorms = tf.reduce_sum(tf.square(source_flat), axis=1, keep_dims=True)
# dotprod = tf.matmul(source_flat, target_flat, transpose_b=True) # [ns, nt]
# sqdist = source_sqnorms - 2*dotprod + target_sqnorms_t
# dist = tf.sqrt(tf.nn.relu(sqdist)) # potential tiny negatives are suppressed
# return dist # shape: [ns, nt]
# def grad_hbar(self, v, gradbs, reuse=True):
# """Compute gradient of hbar function for Wasserstein iteration."""
# source_ims = self.source_gen.get_batch(bs=gradbs, reuse=reuse)
# target_data = self.target_gen.get_batch()
# c_xy = self.basedist(source_ims, target_data)
# c_xy -= v # [gradbs, trnsize]
# idx = tf.argmin(c_xy, axis=1) # [1] (index of subgradient)
# target_bs = self.target_bs
# xi_ij = tf.one_hot(idx, target_bs) # find matches, [gradbs, trnsize]
# xi_ij = tf.reduce_mean(xi_ij, axis=0, keep_dims=True) # [1, trnsize]
# grad = 1./target_bs - xi_ij # output: [1, trnsize]
# return grad
# def hbar(self, v, reuse=True):
# """Compute value of hbar function for Wasserstein iteration."""
# source_ims = self.source_gen.get_batch(bs=None, reuse=reuse)
# target_data = self.target_gen.get_batch()
# c_xy = self.basedist(source_ims, target_data)
# c_avg = tf.reduce_mean(c_xy)
# c_xy -= c_avg
# c_xy -= v
# c_xy_min = tf.reduce_min(c_xy, axis=1) # min_y[ c(x, y) - v(y) ]
# c_xy_min = tf.reduce_mean(c_xy_min) # expectation wrt x
# return tf.reduce_mean(v, axis=1) + c_xy_min + c_avg # avg wrt y
# def k_step(self, k, v, vt, c, reuse=True):
# """Perform one update step of Wasserstein computation."""
# grad_h = self.grad_hbar(vt, gradbs=self.gradbs, reuse=reuse)
# vt = tf.assign_add(vt, c/tf.sqrt(k)*grad_h, name='vt_assign_add')
# v = ((k-1.)*v + vt)/k
# return k+1, v, vt, c
# def dist(self, C=.1, nsteps=10, reset=False):
# """Compute Wasserstein distance (Alg.2 in [Genevay etal, NIPS'16])."""
# target_bs = self.target_bs
# vtilde = tf.Variable(tf.zeros([1, target_bs]), name='vtilde')
# v = tf.Variable(tf.zeros([1, target_bs]), name='v')
# k = tf.Variable(1., name='k')
# k = k.assign(1.) # restart averaging from 1 in each call
# if reset: # used for randomly sampled target data, otherwise warmstart
# v = v.assign(tf.zeros([1, target_bs])) # reset every time graph is evaluated
# vtilde = vtilde.assign(tf.zeros([1, target_bs]))
# # (unrolled) optimization loop. first iteration, create variables
# k, v, vtilde, C = self.k_step(k, v, vtilde, C, reuse=False)
# # (unrolled) optimization loop. other iterations, reuse variables
# k, v, vtilde, C = tf.while_loop(cond=lambda k, *_: k < nsteps,
# body=self.k_step,
# loop_vars=[k, v, vtilde, C])
# v = tf.stop_gradient(v) # only transmit gradient through cost
# val = self.hbar(v)
# return tf.reduce_mean(val)