本文整理匯總了Python中numpy.argmax方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.argmax方法的具體用法?Python numpy.argmax怎麽用?Python numpy.argmax使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.argmax方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _peaks1D
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def _peaks1D(self):
if self.num_src == 1:
self.src_idx[0] = np.argmax(self.P)
self.sources[:, 0] = self.loc[:, self.src_idx[0]]
self.phi_recon = self.theta[self.src_idx[0]]
else:
peak_idx = []
n = self.P.shape[0]
for i in range(self.num_loc):
# straightforward peak finding
if self.P[i] >= self.P[(i-1)%n] and self.P[i] > self.P[(i+1)%n]:
if len(peak_idx) == 0 or peak_idx[-1] != i-1:
if not (i == self.num_loc and self.P[i] == self.P[0]):
peak_idx.append(i)
peaks = self.P[peak_idx]
max_idx = np.argsort(peaks)[-self.num_src:]
self.src_idx = [peak_idx[k] for k in max_idx]
self.sources = self.loc[:, self.src_idx]
self.phi_recon = self.theta[self.src_idx]
self.num_src = len(self.src_idx)
# ------------------Miscellaneous Functions---------------------#
示例2: process_box
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def process_box(self, b, h, w, threshold):
max_indx = np.argmax(b.probs)
max_prob = b.probs[max_indx]
label = self.meta['labels'][max_indx]
if max_prob > threshold:
left = int ((b.x - b.w/2.) * w)
right = int ((b.x + b.w/2.) * w)
top = int ((b.y - b.h/2.) * h)
bot = int ((b.y + b.h/2.) * h)
if left < 0 : left = 0
if right > w - 1: right = w - 1
if top < 0 : top = 0
if bot > h - 1: bot = h - 1
mess = '{}'.format(label)
return (left, right, top, bot, mess, max_indx, max_prob)
return None
示例3: train
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def train(self):
while (self.epoch < self.option.max_epoch and not self.early_stopped):
self.one_epoch_train()
self.one_epoch_valid()
self.one_epoch_test()
self.epoch += 1
model_path = self.saver.save(self.sess,
self.option.model_path,
global_step=self.epoch)
print("Model saved at %s" % model_path)
if self.early_stop():
self.early_stopped = True
print("Early stopped at epoch %d" % (self.epoch))
all_test_in_top = [np.mean(x[1]) for x in self.test_stats]
best_test_epoch = np.argmax(all_test_in_top)
best_test = all_test_in_top[best_test_epoch]
msg = "Best test in top: %0.4f at epoch %d." % (best_test, best_test_epoch + 1)
print(msg)
self.log_file.write(msg + "\n")
pickle.dump([self.train_stats, self.valid_stats, self.test_stats],
open(os.path.join(self.option.this_expsdir, "results.pckl"), "w"))
示例4: __getitem__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def __getitem__(self, index):
img=self.adv_flat[self.sample_num,:]
if(self.shuff == False):
# shuff is true for non-pgd attacks
img = torch.from_numpy(np.reshape(img,(3,32,32)))
else:
img = torch.from_numpy(img).type(torch.FloatTensor)
target = np.argmax(self.adv_dict["adv_labels"],axis=1)[self.sample_num]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
self.sample_num = self.sample_num + 1
return img, target
示例5: __getitem__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def __getitem__(self, index):
img=self.adv_flat[self.sample_num,:]
if(self.transp == False):
# shuff is true for non-pgd attacks
img = torch.from_numpy(np.reshape(img,(28,28)))
else:
img = torch.from_numpy(img).type(torch.FloatTensor)
target = np.argmax(self.adv_dict["adv_labels"],axis=1)[self.sample_num]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
self.sample_num = self.sample_num + 1
return img, target
示例6: binary_refinement
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def binary_refinement(sess,Best_X_adv,
X_adv, Y, ALPHA, ub, lb, model, dataset='cifar'):
num_samples = np.shape(X_adv)[0]
print(dataset)
if(dataset=="mnist"):
X_place = tf.placeholder(tf.float32, shape=[1, 1, 28, 28])
else:
X_place = tf.placeholder(tf.float32, shape=[1, 3, 32, 32])
pred = model(X_place)
for i in range(num_samples):
logits_op = sess.run(pred,feed_dict={X_place:X_adv[i:i+1,:,:,:]})
if(not np.argmax(logits_op) == np.argmax(Y[i,:])):
# Success, increase alpha
Best_X_adv[i,:,:,:] = X_adv[i,:,:,]
lb[i] = ALPHA[i,0]
else:
ub[i] = ALPHA[i,0]
ALPHA[i] = 0.5*(lb[i] + ub[i])
return ALPHA, Best_X_adv
示例7: test_attack_strength
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def test_attack_strength(self):
"""
If clipping is not done at each iteration (not passing clip_min and
clip_max to fgm), this attack fails by
np.mean(orig_labels == new_labels) == .39.
"""
x_val = np.random.rand(100, 2)
x_val = np.array(x_val, dtype=np.float32)
x_adv = self.attack.generate_np(x_val, eps=1.0, ord=np.inf,
clip_min=0.5, clip_max=0.7,
nb_iter=5)
orig_labs = np.argmax(self.sess.run(self.model(x_val)), axis=1)
new_labs = np.argmax(self.sess.run(self.model(x_adv)), axis=1)
self.assertTrue(np.mean(orig_labs == new_labs) < 0.1)
示例8: test_generate_np_targeted_gives_adversarial_example
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def test_generate_np_targeted_gives_adversarial_example(self):
x_val = np.random.rand(100, 2)
x_val = np.array(x_val, dtype=np.float32)
feed_labs = np.zeros((100, 2))
feed_labs[np.arange(100), np.random.randint(0, 1, 100)] = 1
x_adv = self.attack.generate_np(x_val, max_iterations=100,
binary_search_steps=3,
initial_const=1,
clip_min=-5, clip_max=5,
batch_size=100, y_target=feed_labs)
new_labs = np.argmax(self.sess.run(self.model(x_adv)), axis=1)
self.assertTrue(np.mean(np.argmax(feed_labs, axis=1) == new_labs)
> 0.9)
示例9: test_generate_gives_adversarial_example
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def test_generate_gives_adversarial_example(self):
x_val = np.random.rand(100, 2)
x_val = np.array(x_val, dtype=np.float32)
orig_labs = np.argmax(self.sess.run(self.model(x_val)), axis=1)
feed_labs = np.zeros((100, 2))
feed_labs[np.arange(100), orig_labs] = 1
x = tf.placeholder(tf.float32, x_val.shape)
y = tf.placeholder(tf.float32, feed_labs.shape)
x_adv_p = self.attack.generate(x, max_iterations=100,
binary_search_steps=3,
initial_const=1,
clip_min=-5, clip_max=5,
batch_size=100, y=y)
self.assertEqual(x_val.shape, x_adv_p.shape)
x_adv = self.sess.run(x_adv_p, {x: x_val, y: feed_labs})
new_labs = np.argmax(self.sess.run(self.model(x_adv)), axis=1)
self.assertTrue(np.mean(orig_labs == new_labs) < 0.1)
示例10: test_generate_targeted_gives_adversarial_example
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def test_generate_targeted_gives_adversarial_example(self):
x_val = np.random.rand(100, 2)
x_val = np.array(x_val, dtype=np.float32)
feed_labs = np.zeros((100, 2))
feed_labs[np.arange(100), np.random.randint(0, 1, 100)] = 1
x = tf.placeholder(tf.float32, x_val.shape)
y = tf.placeholder(tf.float32, feed_labs.shape)
x_adv_p = self.attack.generate(x, max_iterations=100,
binary_search_steps=3,
initial_const=1,
clip_min=-5, clip_max=5,
batch_size=100, y_target=y)
self.assertEqual(x_val.shape, x_adv_p.shape)
x_adv = self.sess.run(x_adv_p, {x: x_val, y: feed_labs})
new_labs = np.argmax(self.sess.run(self.model(x_adv)), axis=1)
self.assertTrue(np.mean(np.argmax(feed_labs, axis=1) == new_labs)
> 0.9)
示例11: model_argmax
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def model_argmax(sess, x, predictions, samples, feed=None):
"""
Helper function that computes the current class prediction
:param sess: TF session
:param x: the input placeholder
:param predictions: the model's symbolic output
:param samples: numpy array with input samples (dims must match x)
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:return: the argmax output of predictions, i.e. the current predicted class
"""
feed_dict = {x: samples}
if feed is not None:
feed_dict.update(feed)
probabilities = sess.run(predictions, feed_dict)
if samples.shape[0] == 1:
return np.argmax(probabilities)
else:
return np.argmax(probabilities, axis=1)
示例12: predict
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [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
示例13: _get_bp_indexes_labranchor
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def _get_bp_indexes_labranchor(self, soi):
"""
Get indexes of branch point regions in given sequences.
:param soi: batch of sequences of interest for introns (intron-3..intron+6)
:return: array of predicted bp indexes
"""
encoded = [onehot(str(seq)[self.acc_i - 70:self.acc_i]) for seq in np.nditer(soi)]
labr_in = np.stack(encoded, axis=0)
out = self.labranchor.predict_on_batch(labr_in)
# for each row, pick the base with max branchpoint probability, and get its index
max_indexes = np.apply_along_axis(lambda x: self.acc_i - 70 + np.argmax(x), axis=1, arr=out)
# self.write_bp(max_indexes)
return max_indexes
# TODO boilerplate
# def write_bp(self, max_indexes):
# max_indexes = [str(seq) for seq in np.nditer(max_indexes)]
# with open(''.join([this_dir, "/../customBP/example_files/bp_idx_chr21_labr.txt"]), "a") as bp_idx_file:
# bp_idx_file.write('\n'.join(max_indexes))
# bp_idx_file.write('\n')
# bp_idx_file.close()
示例14: forward
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def forward(self, x):
N, C, H, W = x.shape
out_h = int(1 + (H - self.pool_h) / self.stride)
out_w = int(1 + (W - self.pool_w) / self.stride)
col = im2col(x, self.pool_h, self.pool_w, self.stride, self.pad)
col = col.reshape(-1, self.pool_h * self.pool_w)
arg_max = np.argmax(col, axis=1)
out = np.max(col, axis=1)
out = out.reshape(N, out_h, out_w, C).transpose(0, 3, 1, 2)
self.x = x
self.arg_max = arg_max
return out
示例15: predict_all
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argmax [as 別名]
def predict_all(X, all_theta):
rows = X.shape[0]
params = X.shape[1]
num_labels = all_theta.shape[0]
# same as before, insert ones to match the shape
X = np.insert(X, 0, values=np.ones(rows), axis=1)
# convert to matrices
X = np.matrix(X)
all_theta = np.matrix(all_theta)
# compute the class probability for each class on each training instance
h = sigmoid(X * all_theta.T)
# create array of the index with the maximum probability
h_argmax = np.argmax(h, axis=1)
# because our array was zero-indexed we need to add one for the true label prediction
h_argmax = h_argmax + 1
return h_argmax