def _two_element_tuple(int_or_tuple):
"""Converts `int_or_tuple` to height, width.
Several of the functions that follow accept arguments as either
a tuple of 2 integers or a single integer. A single integer
indicates that the 2 values of the tuple are the same.
This functions normalizes the input value by always returning a tuple.
Args:
int_or_tuple: A list of 2 ints, a single int or a tf.TensorShape.
Returns:
A tuple with 2 values.
Raises:
ValueError: If `int_or_tuple` it not well formed.
"""
if isinstance(int_or_tuple, (list, tuple)):
if len(int_or_tuple) != 2:
raise ValueError('Must be a list with 2 elements: %s' % int_or_tuple)
return int(int_or_tuple[0]), int(int_or_tuple[1])
if isinstance(int_or_tuple, int):
return int(int_or_tuple), int(int_or_tuple)
if isinstance(int_or_tuple, tf.TensorShape):
if len(int_or_tuple) == 2:
return int_or_tuple[0], int_or_tuple[1]
raise ValueError('Must be an int, a list with 2 elements or a TensorShape of '
'length 2')
python类TensorShape()的实例源码
def _init_inception():
global softmax
if not os.path.exists(MODEL_DIR):
os.makedirs(MODEL_DIR)
filename = DATA_URL.split('/')[-1]
filepath = os.path.join(MODEL_DIR, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> Downloading %s %.1f%%' % (
filename, float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
print()
statinfo = os.stat(filepath)
print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
tarfile.open(filepath, 'r:gz').extractall(MODEL_DIR)
with tf.gfile.FastGFile(os.path.join(
MODEL_DIR, 'classify_image_graph_def.pb'), 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
# Works with an arbitrary minibatch size.
with tf.Session() as sess:
pool3 = sess.graph.get_tensor_by_name('pool_3:0')
ops = pool3.graph.get_operations()
for op_idx, op in enumerate(ops):
for o in op.outputs:
shape = o.get_shape()
shape = [s.value for s in shape]
new_shape = []
for j, s in enumerate(shape):
if s == 1 and j == 0:
new_shape.append(None)
else:
new_shape.append(s)
o._shape = tf.TensorShape(new_shape)
w = sess.graph.get_operation_by_name("softmax/logits/MatMul").inputs[1]
logits = tf.matmul(tf.squeeze(pool3), w)
softmax = tf.nn.softmax(logits)
def _init_inception():
global softmax
if not os.path.exists(MODEL_DIR):
os.makedirs(MODEL_DIR)
filename = DATA_URL.split('/')[-1]
filepath = os.path.join(MODEL_DIR, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> Downloading %s %.1f%%' % (
filename, float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
print()
statinfo = os.stat(filepath)
print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
tarfile.open(filepath, 'r:gz').extractall(MODEL_DIR)
with tf.gfile.FastGFile(os.path.join(
MODEL_DIR, 'classify_image_graph_def.pb'), 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
# Works with an arbitrary minibatch size.
with tf.Session() as sess:
pool3 = sess.graph.get_tensor_by_name('pool_3:0')
ops = pool3.graph.get_operations()
for op_idx, op in enumerate(ops):
for o in op.outputs:
shape = o.get_shape()
shape = [s.value for s in shape]
new_shape = []
for j, s in enumerate(shape):
if s == 1 and j == 0:
new_shape.append(None)
else:
new_shape.append(s)
o._shape = tf.TensorShape(new_shape)
w = sess.graph.get_operation_by_name("softmax/logits/MatMul").inputs[1]
logits = tf.matmul(tf.squeeze(pool3), w)
softmax = tf.nn.softmax(logits)
inception_score.py 文件源码
项目:Unsupervised-Anomaly-Detection-with-Generative-Adversarial-Networks
作者: xtarx
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def _init_inception():
global softmax
if not os.path.exists(MODEL_DIR):
os.makedirs(MODEL_DIR)
filename = DATA_URL.split('/')[-1]
filepath = os.path.join(MODEL_DIR, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> Downloading %s %.1f%%' % (
filename, float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
print()
statinfo = os.stat(filepath)
print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
tarfile.open(filepath, 'r:gz').extractall(MODEL_DIR)
with tf.gfile.FastGFile(os.path.join(
MODEL_DIR, 'classify_image_graph_def.pb'), 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
# Works with an arbitrary minibatch size.
with tf.Session() as sess:
pool3 = sess.graph.get_tensor_by_name('pool_3:0')
ops = pool3.graph.get_operations()
for op_idx, op in enumerate(ops):
for o in op.outputs:
shape = o.get_shape()
shape = [s.value for s in shape]
new_shape = []
for j, s in enumerate(shape):
if s == 1 and j == 0:
new_shape.append(None)
else:
new_shape.append(s)
o._shape = tf.TensorShape(new_shape)
w = sess.graph.get_operation_by_name("softmax/logits/MatMul").inputs[1]
logits = tf.matmul(tf.squeeze(pool3), w)
softmax = tf.nn.softmax(logits)
def cwt(wav, widthCwt, wavelet):
length = wav.shape[0]
wav = tf.to_float(wav)
wav = tf.reshape(wav, [1,length,1,1])
# While loop functions
def body(i, m):
v = conv1DWavelet(wav, i, wavelet)
v = tf.reshape(v, [length, 1])
m = tf.concat([m,v], 1)
return [1 + i, m]
def cond_(i, m):
return tf.less_equal(i, widthCwt)
# Initialize and run while loop
emptyCwtMatrix = tf.zeros([length, 0], dtype='float32')
i = tf.constant(1)
_, result = tf.while_loop(
cond_,
body,
[i, emptyCwtMatrix],
shape_invariants=[i.get_shape(), tf.TensorShape([length, None])],
back_prop=False,
parallel_iterations=1024,
)
result = tf.transpose(result)
return result
# ------------------------------------------------------
# wavelets
def get_distorted_inputs(original_image, bboxes, cfg, add_summaries):
distorter = DistortedInputs(cfg, add_summaries)
num_bboxes = tf.shape(bboxes)[0]
distorted_inputs = tf.TensorArray(
dtype=tf.float32,
size=num_bboxes,
element_shape=tf.TensorShape([1, cfg.INPUT_SIZE, cfg.INPUT_SIZE, 3])
)
if add_summaries:
image_summaries = tf.TensorArray(
dtype=tf.float32,
size=4,
element_shape=tf.TensorShape([1, cfg.INPUT_SIZE, cfg.INPUT_SIZE, 3])
)
else:
image_summaries = tf.constant([])
current_index = tf.constant(0, dtype=tf.int32)
loop_vars = [original_image, bboxes, distorted_inputs, image_summaries, current_index]
original_image, bboxes, distorted_inputs, image_summaries, current_index = tf.while_loop(
cond=bbox_crop_loop_cond,
body=distorter.apply,
loop_vars=loop_vars,
parallel_iterations=10, back_prop=False, swap_memory=False
)
distorted_inputs = distorted_inputs.concat()
if add_summaries:
tf.summary.image('0.original_image', image_summaries.read(0))
tf.summary.image('1.image_with_random_crop', image_summaries.read(1))
tf.summary.image('2.cropped_resized_image', image_summaries.read(2))
tf.summary.image('3.final_distorted_image', image_summaries.read(3))
return distorted_inputs
def test_tensor_shape(self):
self.assertConverts(tf.TensorShape([]), tdt.TensorType(()))
self.assertConverts(tf.TensorShape([1]), tdt.TensorType((1,)))
self.assertConverts(tf.TensorShape([1, 2]), tdt.TensorType((1, 2)))
self.assertConverts(tf.TensorShape([1, 2, 3]), tdt.TensorType((1, 2, 3)))
def _create_queue(self, queue_id, ctor=tf.RandomShuffleQueue):
# The enqueuing workers transform inputs into serialized loom
# weaver messages, which are represented as strings.
return ctor(
capacity=self.queue_capacity or 4 * self.batch_size,
min_after_dequeue=0, dtypes=[tf.string], shapes=[tf.TensorShape([])],
shared_name='tensorflow_fold_plan_queue%s' % queue_id)
def _get_value_shape(self):
if self._shape_fully_defined:
return tf.TensorShape([5])
return tf.TensorShape(None)
def _get_batch_shape(self):
if self._shape_fully_defined:
return tf.TensorShape([2, 3, 4])
return tf.TensorShape([None, 3, 4])
def _get_value_shape(self):
return tf.TensorShape([])
def _sample(self, n_samples):
mean, std = self.mean, self.std
if not self.is_reparameterized:
mean = tf.stop_gradient(mean)
std = tf.stop_gradient(std)
shape = tf.concat([[n_samples], self.batch_shape], 0)
samples = tf.random_normal(shape, dtype=self.dtype) * std + mean
static_n_samples = n_samples if isinstance(n_samples, int) else None
samples.set_shape(
tf.TensorShape([static_n_samples]).concatenate(
self.get_batch_shape()))
return samples
def _get_value_shape(self):
return tf.TensorShape([])
def _get_value_shape(self):
return tf.TensorShape([])
def _sample(self, n_samples):
p = tf.sigmoid(self.logits)
shape = tf.concat([[n_samples], self.batch_shape], 0)
alpha = tf.random_uniform(
shape, minval=0, maxval=1, dtype=self.param_dtype)
samples = tf.cast(tf.less(alpha, p), dtype=self.dtype)
static_n_samples = n_samples if isinstance(n_samples, int) else None
samples.set_shape(
tf.TensorShape([static_n_samples]).concatenate(
self.get_batch_shape()))
return samples
def _get_value_shape(self):
return tf.TensorShape([])
def _get_batch_shape(self):
if self.logits.get_shape():
return self.logits.get_shape()[:-1]
return tf.TensorShape(None)
def _sample(self, n_samples):
minval, maxval = self.minval, self.maxval
if not self.is_reparameterized:
minval = tf.stop_gradient(minval)
maxval = tf.stop_gradient(maxval)
shape = tf.concat([[n_samples], self.batch_shape], 0)
samples = tf.random_uniform(shape, 0, 1, dtype=self.dtype) * \
(maxval - minval) + minval
static_n_samples = n_samples if isinstance(n_samples, int) else None
samples.set_shape(
tf.TensorShape([static_n_samples]).concatenate(
self.get_batch_shape()))
return samples
def _get_value_shape(self):
return tf.TensorShape([])
def _get_value_shape(self):
return tf.TensorShape([])