本文整理汇总了Python中chainer.Variable方法的典型用法代码示例。如果您正苦于以下问题:Python chainer.Variable方法的具体用法?Python chainer.Variable怎么用?Python chainer.Variable使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类chainer
的用法示例。
在下文中一共展示了chainer.Variable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: predict
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def predict(limit):
_limit = limit if limit > 0 else 5
td = TrainingData(LABEL_FILE, img_root=IMAGES_ROOT, mean_image_file=MEAN_IMAGE_FILE, image_property=IMAGE_PROP)
label_def = LabelingMachine.read_label_def(LABEL_DEF_FILE)
model = alex.Alex(len(label_def))
serializers.load_npz(MODEL_FILE, model)
i = 0
for arr, im in td.generate():
x = np.ndarray((1,) + arr.shape, arr.dtype)
x[0] = arr
x = chainer.Variable(np.asarray(x), volatile="on")
y = model.predict(x)
p = np.argmax(y.data)
print("predict {0}, actual {1}".format(label_def[p], label_def[im.label]))
im.image.show()
i += 1
if i >= _limit:
break
示例2: test
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def test(self):
a = chainer.Variable(np.random.rand(1).astype(np.float32))
b = chainer.Variable(np.random.rand(1).astype(np.float32))
# No old-style function
y = 2 * a + b
old_style_funcs = trpo._find_old_style_function([y])
self.assertEqual(old_style_funcs, [])
# One old-style function
y = 2 * old_style_identity(a) + b
old_style_funcs = trpo._find_old_style_function([y])
self.assertEqual(len(old_style_funcs), 1)
self.assertTrue(all(isinstance(f, OldStyleIdentity)
for f in old_style_funcs))
# Three old-style functions
y = (2 * old_style_identity(old_style_identity(a))
+ old_style_identity(b))
old_style_funcs = trpo._find_old_style_function([y])
self.assertEqual(len(old_style_funcs), 3)
self.assertTrue(all(isinstance(f, OldStyleIdentity)
for f in old_style_funcs))
示例3: test_compute_advantage
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def test_compute_advantage(self):
sample_actions = np.random.randint(self.action_size,
size=self.batch_size)
greedy_actions = self.q_values.argmax(axis=1)
ret = self.qout.compute_advantage(sample_actions)
self.assertIsInstance(ret, chainer.Variable)
for b in range(self.batch_size):
if sample_actions[b] == greedy_actions[b]:
self.assertAlmostEqual(ret.array[b], 0)
else:
# An advantage to the optimal policy must be always negative
self.assertLess(ret.array[b], 0)
q = self.q_values[b, sample_actions[b]]
v = self.q_values[b, greedy_actions[b]]
adv = q - v
self.assertAlmostEqual(ret.array[b], adv)
示例4: test_max_unbounded
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def test_max_unbounded(self):
n_batch = 7
ndim_action = 3
mu = np.random.randn(n_batch, ndim_action).astype(np.float32)
mat = np.broadcast_to(
np.eye(ndim_action, dtype=np.float32)[None],
(n_batch, ndim_action, ndim_action))
v = np.random.randn(n_batch).astype(np.float32)
q_out = action_value.QuadraticActionValue(
chainer.Variable(mu),
chainer.Variable(mat),
chainer.Variable(v))
v_out = q_out.max
self.assertIsInstance(v_out, chainer.Variable)
v_out = v_out.array
np.testing.assert_almost_equal(v_out, v)
示例5: test_getitem
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def test_getitem(self):
n_batch = 7
ndim_action = 3
mu = np.random.randn(n_batch, ndim_action).astype(np.float32)
mat = np.broadcast_to(
np.eye(ndim_action, dtype=np.float32)[None],
(n_batch, ndim_action, ndim_action))
v = np.random.randn(n_batch).astype(np.float32)
min_action, max_action = -1, 1
qout = action_value.QuadraticActionValue(
chainer.Variable(mu),
chainer.Variable(mat),
chainer.Variable(v),
min_action,
max_action,
)
sliced = qout[:3]
np.testing.assert_equal(sliced.mu.array, mu[:3])
np.testing.assert_equal(sliced.mat.array, mat[:3])
np.testing.assert_equal(sliced.v.array, v[:3])
np.testing.assert_equal(sliced.min_action, min_action)
np.testing.assert_equal(sliced.max_action, max_action)
示例6: setUp
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def setUp(self):
def evaluator(actions):
# negative square norm of actions
return -F.sum(actions ** 2, axis=1)
self.evaluator = evaluator
if self.has_maximizer:
def maximizer():
return chainer.Variable(np.zeros(
(self.batch_size, self.action_size), dtype=np.float32))
else:
maximizer = None
self.maximizer = maximizer
self.av = action_value.SingleActionValue(
evaluator=evaluator, maximizer=maximizer)
示例7: test_boltzmann
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def test_boltzmann(self):
# T=1
q_values = chainer.Variable(np.asarray([[-1, 1, 0]], dtype=np.float32))
action_count = count_actions_selected_by_boltzmann(1, q_values)
print('T=1', action_count)
# Actions with larger values must be selected more often
self.assertGreater(action_count[1], action_count[2])
self.assertGreater(action_count[2], action_count[0])
# T=0.5
action_count_t05 = count_actions_selected_by_boltzmann(0.5, q_values)
print('T=0.5', action_count_t05)
# Actions with larger values must be selected more often
self.assertGreater(action_count_t05[1], action_count_t05[2])
self.assertGreater(action_count_t05[2], action_count_t05[0])
# T=0.5 must be more greedy than T=1
self.assertGreater(action_count_t05[1], action_count[1])
示例8: test_copy_param
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def test_copy_param(self):
a = L.Linear(1, 5)
b = L.Linear(1, 5)
s = chainer.Variable(np.random.rand(1, 1).astype(np.float32))
a_out = list(a(s).array.ravel())
b_out = list(b(s).array.ravel())
self.assertNotEqual(a_out, b_out)
# Copy b's parameters to a
copy_param.copy_param(a, b)
a_out_new = list(a(s).array.ravel())
b_out_new = list(b(s).array.ravel())
self.assertEqual(a_out_new, b_out)
self.assertEqual(b_out_new, b_out)
示例9: __call__
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def __call__(self, x, recurrent_state):
"""One-step batch forward computation.
Args:
x (chainer.Variable, ndarray, or tuple): One-step batched input.
recurrent_state (object): Batched recurrent state.
Returns:
chainer.Variable, ndarray, or tuple: One-step batched output.
object: New batched recurrent state.
"""
assert isinstance(x, (chainer.Variable, self.xp.ndarray))
return self.n_step_forward(
split_one_step_batch_input(x),
recurrent_state,
output_mode='concat',
)
示例10: concatenate_sequences
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def concatenate_sequences(sequences):
"""Concatenate sequences.
Args:
sequences (list): List of sequences. The following two cases are
supported:
- (a) Each sequence is a Variable or ndarray.
- (b) Each sequence is tuple of a Variable or ndarray.
Returns:
chainer.Variable, ndarray or tuple: Concatenated sequences.
"""
if isinstance(sequences[0], tuple):
tuple_size = len(sequences[0])
return tuple(
F.concat([seq[i] for seq in sequences], axis=0)
for i in range(tuple_size))
raise NotImplementedError
else:
return F.concat(sequences, axis=0)
示例11: __call__
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def __call__(self, x, update=True):
"""Normalize mean and variance of values based on emprical values.
Args:
x (ndarray or Variable): Input values
update (bool): Flag to learn the input values
Returns:
ndarray or Variable: Normalized output values
"""
xp = self.xp
mean = xp.broadcast_to(self._mean, x.shape)
std_inv = xp.broadcast_to(self._std_inverse, x.shape)
if update:
self.experience(x)
normalized = (x - mean) * std_inv
if self.clip_threshold is not None:
normalized = xp.clip(
normalized, -self.clip_threshold, self.clip_threshold)
return normalized
示例12: bound_by_tanh
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def bound_by_tanh(x, low, high):
"""Bound a given value into [low, high] by tanh.
Args:
x (chainer.Variable): value to bound
low (numpy.ndarray): lower bound
high (numpy.ndarray): upper bound
Returns: chainer.Variable
"""
assert isinstance(x, chainer.Variable)
assert low is not None
assert high is not None
xp = cuda.get_array_module(x.array)
x_scale = (high - low) / 2
x_scale = xp.expand_dims(xp.asarray(x_scale), axis=0)
x_mean = (high + low) / 2
x_mean = xp.expand_dims(xp.asarray(x_mean), axis=0)
return F.tanh(x) * x_scale + x_mean
示例13: __test
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def __test(self, model, batchsize):
model.train = False
test_accuracy = test_loss = 0
for i in six.moves.range(0, self.test_data_num, batchsize):
x = chainer.Variable(cuda.to_gpu(self.x_test[i:i + batchsize]), volatile=True)
t = chainer.Variable(cuda.to_gpu(self.y_test[i:i + batchsize]), volatile=True)
loss = model(x, t)
test_loss += float(loss.data) * len(t.data)
test_accuracy += float(model.accuracy.data) * len(t.data)
model.train = True
return test_accuracy, test_loss
示例14: train
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def train(epoch=10, batch_size=32, gpu=False):
if gpu:
cuda.check_cuda_available()
xp = cuda.cupy if gpu else np
td = TrainingData(LABEL_FILE, img_root=IMAGES_ROOT, image_property=IMAGE_PROP)
# make mean image
if not os.path.isfile(MEAN_IMAGE_FILE):
print("make mean image...")
td.make_mean_image(MEAN_IMAGE_FILE)
else:
td.mean_image_file = MEAN_IMAGE_FILE
# train model
label_def = LabelingMachine.read_label_def(LABEL_DEF_FILE)
model = alex.Alex(len(label_def))
optimizer = optimizers.MomentumSGD(lr=0.01, momentum=0.9)
optimizer.setup(model)
epoch = epoch
batch_size = batch_size
print("Now our model is {0} classification task.".format(len(label_def)))
print("begin training the model. epoch:{0} batch size:{1}.".format(epoch, batch_size))
if gpu:
model.to_gpu()
for i in range(epoch):
print("epoch {0}/{1}: (learning rate={2})".format(i + 1, epoch, optimizer.lr))
td.shuffle(overwrite=True)
for x_batch, y_batch in td.generate_batches(batch_size):
x = chainer.Variable(xp.asarray(x_batch))
t = chainer.Variable(xp.asarray(y_batch))
optimizer.update(model, x, t)
print("loss: {0}, accuracy: {1}".format(float(model.loss.data), float(model.accuracy.data)))
serializers.save_npz(MODEL_FILE, model)
optimizer.lr *= 0.97
示例15: __call__
# 需要导入模块: import chainer [as 别名]
# 或者: from chainer import Variable [as 别名]
def __call__(self, x):
"""Applies the linear layer.
Args:
x (~chainer.Variable): Batch of input vectors.
Returns:
~chainer.Variable: Output of the linear layer.
"""
if self.W.data is None:
self._initialize_params(x.size // x.shape[0])
return linear.linear(x, self.W_bar, self.b)