本文整理汇总了Python中theano.tensor.argmax方法的典型用法代码示例。如果您正苦于以下问题:Python tensor.argmax方法的具体用法?Python tensor.argmax怎么用?Python tensor.argmax使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类theano.tensor
的用法示例。
在下文中一共展示了tensor.argmax方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build_cost
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def build_cost(logits, targets):
"""
Build a classification cost function.
"""
# Clip gradients coming from the cost function.
logits = theano.gradient.grad_clip(
logits, -1. * FLAGS.clipping_max_value, FLAGS.clipping_max_value)
predicted_dist = T.nnet.softmax(logits)
costs = T.nnet.categorical_crossentropy(predicted_dist, targets)
cost = costs.mean()
pred = T.argmax(logits, axis=1)
acc = 1. - T.mean(T.cast(T.neq(pred, targets), theano.config.floatX))
return cost, acc
示例2: __init__
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def __init__(self, input, n_in, n_out, W=None):
self.input = input
if W is None:
self.W = theano.shared(
value = numpy.zeros(
(n_in, n_out),
dtype = theano.config.floatX),
name = 'W',
borrow = True
)
else:
self.W = W
self.s_y_given_x = T.dot(input, self.W)
self.p_y_given_x = T.nnet.softmax(self.s_y_given_x) #+ self.b)
self.pred = T.argmax(self.s_y_given_x, axis=1)
self.params = [ self.W ]
示例3: on_epoch_end
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def on_epoch_end(self, epoch, logs={}):
if epoch % self.interval == 0:
y_pred = self.model.predict(self.X_val, verbose=0)
#print(np.sum(y_pred[:,1]))
#y_true = np.argmax(self.y_val, axis=1)
#y_pred = np.argmax(y_pred, axis=1)
#print(y_true.shape, y_pred.shape)
if self.mymil:
score = roc_auc_score(self.y_val.max(axis=1), y_pred.max(axis=1))
else: score = roc_auc_score(self.y_val[:,1], y_pred[:,1])
print("interval evaluation - epoch: {:d} - auc: {:.2f}".format(epoch, score))
if score > self.auc:
self.auc = score
for f in os.listdir('./'):
if f.startswith(self.filepath+'auc'):
os.remove(f)
self.model.save(self.filepath+'auc'+str(score)+'ep'+str(epoch)+'.hdf5')
示例4: generative_sampling
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def generative_sampling(self, seed, emb_data, sample_length):
fruit = theano.shared(value=seed)
def step(h_tm, y_tm):
h_t = self.activation(T.dot(emb_data[y_tm], self.W) +
T.dot(h_tm, self.U) + self.bh)
y_t = T.nnet.softmax(T.dot(h_t, self.V) + self.by)
y = T.argmax(y_t, axis=1)
return h_t, y[0]
[_, samples], _ = theano.scan(fn=step,
outputs_info=[self.h0, fruit],
n_steps=sample_length)
get_samples = theano.function(inputs=[],
outputs=samples)
return get_samples()
示例5: score_metrics
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def score_metrics(out, target_var, weight_map, l2_loss=0):
_EPSILON=1e-8
out_flat = out.dimshuffle(1,0,2,3).flatten(ndim=2).dimshuffle(1,0)
target_flat = target_var.dimshuffle(1,0,2,3).flatten(ndim=1)
weight_flat = weight_map.dimshuffle(1,0,2,3).flatten(ndim=1)
prediction = lasagne.nonlinearities.softmax(out_flat)
prediction_binary = T.argmax(prediction, axis=1)
dice_score = (T.sum(T.eq(2, prediction_binary+target_flat))*2.0 /
(T.sum(prediction_binary) + T.sum(target_flat)))
loss = lasagne.objectives.categorical_crossentropy(T.clip(prediction,_EPSILON,1-_EPSILON), target_flat)
loss = loss * weight_flat
loss = loss.mean()
loss += l2_loss
accuracy = T.mean(T.eq(prediction_binary, target_flat),
dtype=theano.config.floatX)
return loss, accuracy, dice_score, target_flat, prediction, prediction_binary
示例6: categorical_crossentropy_nll
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def categorical_crossentropy_nll(predicted_values, true_values):
""" Returns likelihood compared to one hot category labels """
indices = tensor.argmax(true_values, axis=-1)
rows = tensor.arange(true_values.shape[0])
if predicted_values.ndim < 3:
return -tensor.log(predicted_values)[rows, indices]
elif predicted_values.ndim == 3:
d0 = true_values.shape[0]
d1 = true_values.shape[1]
pred = predicted_values.reshape((d0 * d1, -1))
ind = indices.reshape((d0 * d1,))
s = tensor.arange(pred.shape[0])
correct = -tensor.log(pred)[s, ind]
return correct.reshape((d0, d1,))
else:
raise AttributeError("Tensor dim not supported")
示例7: argmax
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def argmax(x, axis=-1):
return T.argmax(x, axis=axis, keepdims=False)
示例8: categorical_best
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def categorical_best(tensor):
"""
tensor should be a tensor of shape (..., categories)
Return a new tensor of the same shape but one-hot at position of best category
"""
flat_tensor = tensor.reshape([-1, tensor.shape[-1]])
argmax_posns = T.argmax(flat_tensor, 1)
flat_snapped = T.zeros_like(flat_tensor)
flat_snapped = T.set_subtensor(flat_snapped[T.arange(flat_tensor.shape[0]), argmax_posns], 1.0)
snapped = flat_snapped.reshape(tensor.shape)
return snapped
示例9: build_transition_cost
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def build_transition_cost(logits, targets, num_transitions):
"""
Build a parse action prediction cost function.
"""
# swap seq_length dimension to front so that we can scan per timestep
logits = T.swapaxes(logits, 0, 1)
targets = targets.T
def cost_t(logits, tgt, num_transitions):
# TODO(jongauthier): Taper down xent cost as we proceed through
# sequence?
predicted_dist = T.nnet.softmax(logits)
cost = T.nnet.categorical_crossentropy(predicted_dist, tgt)
pred = T.argmax(logits, axis=1)
error = T.neq(pred, tgt)
return cost, error
results, _ = theano.scan(cost_t, [logits, targets], non_sequences=[num_transitions])
costs, errors = results
# Create a mask that selects only transitions that involve real data.
unrolling_length = T.shape(costs)[0]
padding = unrolling_length - num_transitions
padding = T.reshape(padding, (1, -1))
rng = T.arange(unrolling_length) + 1
rng = T.reshape(rng, (-1, 1))
mask = T.gt(rng, padding)
# Compute acc using the mask
acc = 1.0 - (T.sum(errors * mask, dtype=theano.config.floatX)
/ T.sum(num_transitions, dtype=theano.config.floatX))
# Compute cost directly, since we *do* want a cost incentive to get the padding
# transitions right.
cost = T.mean(costs)
return cost, acc
示例10: standardize_weights
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def standardize_weights(y, sample_weight=None, class_weight=None):
if sample_weight is not None:
return standardize_y(sample_weight)
elif isinstance(class_weight, dict):
if len(y.shape) > 2:
raise Exception('class_weight not supported for 3+ dimensional targets.')
if y.shape[1] > 1:
y_classes = y.argmax(axis=1)
elif y.shape[1] == 1:
y_classes = np.reshape(y, y.shape[0])
else:
y_classes = y
return np.expand_dims(np.array(list(map(lambda x: class_weight[x], y_classes))), 1)
else:
return np.ones(y.shape[:-1] + (1,))
示例11: predict_classes
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def predict_classes(self, X, batch_size=128, verbose=1):
proba = self.predict(X, batch_size=batch_size, verbose=verbose)
if self.class_mode == "categorical":
return proba.argmax(axis=-1)
else:
return (proba > 0.5).astype('int32')
示例12: omniglot
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def omniglot():
input_var = T.tensor3('input') # input_var has dimensions (batch_size, time, input_dim)
target_var = T.imatrix('target') # target_var has dimensions (batch_size, time) (label indices)
# Load data
generator = OmniglotGenerator(data_folder='./data/omniglot', batch_size=16, \
nb_samples=5, nb_samples_per_class=10, max_rotation=0., max_shift=0, max_iter=None)
output_var, output_var_flatten, params = memory_augmented_neural_network(input_var, \
target_var, batch_size=generator.batch_size, nb_class=generator.nb_samples, \
memory_shape=(128, 40), controller_size=200, input_size=20 * 20, nb_reads=4)
cost = T.mean(T.nnet.categorical_crossentropy(output_var_flatten, target_var.flatten()))
updates = lasagne.updates.adam(cost, params, learning_rate=1e-3)
accuracies = accuracy_instance(T.argmax(output_var, axis=2), target_var, batch_size=generator.batch_size)
print('Compiling the model...')
train_fn = theano.function([input_var, target_var], cost, updates=updates)
accuracy_fn = theano.function([input_var, target_var], accuracies)
print('Done')
print('Training...')
t0 = time.time()
all_scores, scores, accs = [], [], np.zeros(generator.nb_samples_per_class)
try:
for i, (example_input, example_output) in generator:
score = train_fn(example_input, example_output)
acc = accuracy_fn(example_input, example_output)
all_scores.append(score)
scores.append(score)
accs += acc
if i > 0 and not (i % 100):
print('Episode %05d: %.6f' % (i, np.mean(score)))
print(accs / 100.)
scores, accs = [], np.zeros(generator.nb_samples_per_class)
except KeyboardInterrupt:
print(time.time() - t0)
pass
示例13: test_none_Constant
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def test_none_Constant():
""" Tests equals
We had an error in the past with unpickling
"""
o1 = Constant(NoneTypeT(), None, name='NoneConst')
o2 = Constant(NoneTypeT(), None, name='NoneConst')
assert o1.equals(o2)
assert NoneConst.equals(o1)
assert o1.equals(NoneConst)
assert NoneConst.equals(o2)
assert o2.equals(NoneConst)
# This trigger equals that returned the wrong answer in the past.
import six.moves.cPickle as pickle
import theano
from theano import tensor
x = tensor.vector('x')
y = tensor.argmax(x)
kwargs = {}
# We can't pickle DebugMode
if theano.config.mode in ["DebugMode", "DEBUG_MODE"]:
kwargs = {'mode': 'FAST_RUN'}
f = theano.function([x], [y], **kwargs)
pickle.loads(pickle.dumps(f))
示例14: __init__
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def __init__(self, input, n_in, n_out, name_prefix=''):
""" Initialize the parameters of the logistic regression
:type input: theano.tensor.TensorType
:param input: symbolic variable that describes the input of the
architecture (one minibatch)
:type n_in: int
:param n_in: number of input units, the dimension of the space in
which the datapoints lie
:type n_out: int
:param n_out: number of output units, the dimension of the space in
which the labels lie
"""
# initialize with 0 the weights W as a matrix of shape (n_in, n_out)
self.W = theano.shared(value=numpy.zeros((n_in, n_out), dtype=theano.config.floatX),
name=name_prefix+'W')
# compute vector of class-membership probabilities in symbolic form
self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W))
# compute prediction as class whose probability is maximal in
# symbolic form
self.y_pred = T.argmax(self.p_y_given_x, axis=1)
# parameters of the model
self.params = [self.W]
示例15: test_argmax
# 需要导入模块: from theano import tensor [as 别名]
# 或者: from theano.tensor import argmax [as 别名]
def test_argmax(self):
self.check_nondiff_rop(tensor.argmax(self.mx, axis=1))