本文整理汇总了Python中lasagne.utils.floatX方法的典型用法代码示例。如果您正苦于以下问题:Python utils.floatX方法的具体用法?Python utils.floatX怎么用?Python utils.floatX使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lasagne.utils
的用法示例。
在下文中一共展示了utils.floatX方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_adaptivegaussian_layer
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def test_adaptivegaussian_layer(self, filter_size, init_std):
input = floatX(np.ones((10, 1, 1000)))
# test the case with one channel
assert(input.shape[1] == 1)
input_layer = self.input_layer(input.shape)
input_theano = theano.shared(input)
layer = self.adaptivegaussian_layer(input_layer, filter_size, init_std)
layer_result = layer.get_output_for(input_theano).eval()
# theano gaussian filter
theano_gf = layer.W.eval()
# numpy gaussian filter
np_gf = self.make_numpy_gaussian_filter_v2(filter_size, init_std)
numpy_result = self.convolve_numpy_array(input, np_gf)
assert np.all(numpy_result.shape == layer.output_shape)
assert np.all(numpy_result.shape == layer_result.shape)
assert np.allclose(theano_gf[0, 0, :], np_gf[0, 0, :])
assert np.allclose(numpy_result, layer_result)
示例2: test_fixedgaussian_layer
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def test_fixedgaussian_layer(self, filter_size, init_std):
input = floatX(np.ones((10, 1, 1000)))
# test the case with one channel
assert(input.shape[1] == 1)
input_layer = self.input_layer(input.shape)
input_theano = theano.shared(input)
layer = self.fixedgaussian_layer(input_layer, filter_size, init_std)
layer_result = layer.get_output_for(input_theano).eval()
# theano gaussian filter
theano_gf = layer.W.eval()
# numpy gaussian filter
np_gf = self.make_numpy_gaussian_filter_v2(filter_size, init_std)
numpy_result = self.convolve_numpy_array(input, np_gf)
assert np.all(numpy_result.shape == layer.output_shape)
assert np.all(numpy_result.shape == layer_result.shape)
assert np.allclose(theano_gf[0, 0, :], np_gf[0, 0, :])
assert np.allclose(numpy_result, layer_result)
示例3: transform_im
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def transform_im(x, npx=64, nc=3):
if nc == 3:
x1 = (x + sharedX(1.0)) * sharedX(127.5)
else:
x1 = T.tile(x, [1, 1, 1, 3]) * sharedX(255.0) # [hack] to-be-tested
mean_channel = np.load(os.path.join(pkg_dir, 'ilsvrc_2012_mean.npy')).mean(1).mean(1)
mean_im = mean_channel[np.newaxis, :, np.newaxis, np.newaxis]
mean_im = floatX(np.tile(mean_im, [1, 1, npx, npx]))
x2 = x1[:, [2, 1, 0], :, :]
y = x2 - mean_im
return y
示例4: get_stepwise
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def get_stepwise(k=10, factor=0.5):
"""
Stepwise learning rate update every k epochs
"""
def update(lr, epoch):
if epoch >= 0 and np.mod(epoch, k) == 0:
return floatX(factor * lr)
else:
return floatX(lr)
return update
示例5: get_predefined
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def get_predefined(schedule):
"""
Predefined learn rate changes at specified epochs
:param schedule: dictionary that maps epochs to to learn rate values.
"""
def update(lr, epoch):
if epoch in schedule:
return floatX(schedule[epoch])
else:
return floatX(lr)
return update
示例6: get_linear
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def get_linear(start_at, ini_lr, decrease_epochs):
""" linear learn rate schedule"""
def update(lr, epoch):
if epoch < start_at:
return floatX(lr)
else:
k = ini_lr / decrease_epochs
return floatX(np.max([0.0, lr - k]))
return update
示例7: get_cosine
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def get_cosine(lr_min, lr_max, t_max):
def update(lr, epoch):
lr_t = lr_min + 0.5 * (lr_max - lr_min) * (1 + np.cos(np.pi * epoch / t_max))
# lr_t = lr_min + 0.5 * (lr_max - lr_min) * (1 + np.cos(np.pi + 2.0 * np.pi * epoch / t_max))
return floatX(lr_t)
return update
示例8: sample
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def sample(self, shape):
if len(shape) != 2 or shape[0] != shape[1]:
raise ValueError('LeInit initializer can only be used for 2D square matrices.')
off_diag_part = self.offdiag_val * np.random.randn(shape[0], shape[1])
return floatX(np.eye(shape[0]) * self.diag_val + off_diag_part - np.diag(np.diag(off_diag_part)))
示例9: sample
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def sample(self, shape):
if len(shape) != 2:
raise ValueError('The OneHot initializer '
'only works with 2D arrays.')
M = np.min(shape)
arr = np.zeros(shape)
arr[:M, :M] += 1 * np.eye(M)
return floatX(arr)
示例10: prepare_image
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def prepare_image(img, width, means):
# if not RGB, force 3 channels
if len(img.shape) == 2:
img = img[:, :, np.newaxis]
img = np.repeat(img, 3, axis=2)
h, w, _ = img.shape
if h < w:
img = skimage.transform.resize(img, (width, w*width/h), preserve_range=True)
else:
img = skimage.transform.resize(img, (h*width/w, width), preserve_range=True)
# crop the center
h, w, _ = img.shape
img = img[h//2 - width//2:h//2 + width//2, w//2 - width//2:w//2 + width//2]
rawim = np.copy(img).astype('uint8')
# shuffle axes to c01
img = np.swapaxes(np.swapaxes(img, 1, 2), 0, 1)
# convert RGB to BGR
img = img[::-1, :, :]
# zero mean scaling
img = img - means
return rawim, floatX(img[np.newaxis])
示例11: eval_loss
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def eval_loss(x0, width):
# Helper function to interface with scipy.optimize
x0 = floatX(x0.reshape((1, 3, width, width)))
generated.set_value(x0)
return f_loss().astype('float64')
示例12: eval_grad
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def eval_grad(x0, width):
# Helper function to interface with scipy.optimize
x0 = floatX(x0.reshape((1, 3, width, width)))
generated.set_value(x0)
return np.array(f_grad()).flatten().astype('float64')
示例13: retrieve_proposals
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def retrieve_proposals(self, c3d_stack, f_init_array, override=False):
"""Retrieve proposals for multiple streams.
Parameters
----------
c3d_stack : ndarray
3d-ndarray [num-streams, seq-length, input-size] with visual
encoder representation of each stream.
Note that the first dimension is sequence agnostic so you can
push as many videos as your HW allows it.
f_init_array : ndarray.
1d-ndarray with initial frame of each stream.
override : bool, optional.
If True, override predicted locations with anchors. Make sure of
initialize your instance properly in order to use the anchors.
Returns
-------
proposals : ndarray
3d-ndarray [num-streams, num-outputs, 2] with proposal locations in
terms of f-init, f-end.
conf : ndarray
2d-ndarray [num-streams, num-outputs] action likelihood of each
proposal
Raises
------
ValueError
Mistmatch between c3d_stack.shape[0] and f_init_array.size
"""
if c3d_stack.ndim == 2 and c3d_stack.shape[0] == self.seq_length:
c3d_stack = c3d_stack[np.newaxis, ...]
if c3d_stack.shape[0] != f_init_array.size:
raise ValueError('Mismatch between c3d_stack and f_init_array')
n_streams = c3d_stack.shape[0]
loc, score = self.forward_pass(floatX(c3d_stack))
if override and self.anchors is not None:
loc[:, ...] = self.anchors.reshape(-1)
# Clip proposals inside receptive field
loc.clip(0, 1, out=loc)
loc *= self.receptive_field
# Shift center to absolute location in the video
loc = loc.reshape((n_streams, -1, 2))
loc[:, :, 0] += f_init_array.reshape((n_streams, 1))
# Transform center 2 boundaries
proposals = np.reshape(
segment_format(loc.reshape((-1, 2)), 'c2b'),
(n_streams, -1, 2)).astype(int)
return proposals, score
示例14: adv
# 需要导入模块: from lasagne import utils [as 别名]
# 或者: from lasagne.utils import floatX [as 别名]
def adv(i, C_value):
img = X_test[i][np.newaxis]
print "True class:\t", y_test[i]
input_img = T.tensor4()
#plot("orig_img_"+str(i),img)
l_noise.b.set_value(np.random.uniform(-1e-8, 1e-8, size=(3,32,32)).astype(np.float32))
pred = np.array(lasagne.layers.get_output(network, img, deterministic=True).eval())
top1 = np.argmax(pred)
target = np.zeros(pred.shape)
adv_class = np.random.randint(0, 10)
while adv_class == top1:
adv_class = np.random.randint(0, 10)
target[0,adv_class] = 1.0
print "Before ADV top1:\t", top1
bayesian_prob = lasagne.layers.get_output(network, input_img, deterministic=False)
bayesian_function = theano.function([input_img], [bayesian_prob])
bayesian_pred = np.zeros(pred.shape)
for _ in range(25):
bayesian_pred[0, np.argmax(bayesian_function(img))] += 1
print "Before ADV Bayesian top1:\t", np.argmax(bayesian_pred)
print "Adversarial class:\t", adv_class
prob = lasagne.layers.get_output(network, input_img, deterministic=False)
C = T.scalar()
adv_loss = lasagne.objectives.categorical_crossentropy(prob, floatX(target)).mean() + C*lasagne.regularization.l2(l_noise.b)
adv_grad = T.grad(adv_loss, l_noise.b)
adv_function = theano.function([input_img, C], [adv_loss, adv_grad, prob])
# Optimization function for L-BFGS-B
def fmin_func(x, T = 25):
l_noise.b.set_value(x.reshape(3, 32, 32).astype(np.float32))
f, g, _ = adv_function(np.repeat(img, T, 0), C_value)
return float(f), g.flatten().astype(np.float64)
# Noise bounds (pixels cannot exceed 0-1)
#bounds = zip(-(mean_cifar-img).flatten(), ((255.0-mean_cifar)-img).flatten())
# L-BFGS-B optimization to find adversarial noise
x, f, d = scipy.optimize.fmin_l_bfgs_b(fmin_func, l_noise.b.get_value().flatten(), bounds = None, fprime = None, factr = 1e10, m = 15)
l_noise.b.set_value(x.reshape(3, 32, 32).astype(np.float32))
_, _, pred = adv_function(img, 0.0)
top1 = np.argmax(pred)
print "After ADV top1:\t", top1
#plot("adv_img_"+str(i), img + l_noise.b.get_value())
bayesian_pred = np.zeros(pred.shape)
for _ in range(25):
bayesian_pred[0, np.argmax(bayesian_function(img))] += 1
print "After ADV Bayesian top1:\t", np.argmax(bayesian_pred)
print
print