本文整理汇总了Python中numpy.expand_dims方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.expand_dims方法的具体用法?Python numpy.expand_dims怎么用?Python numpy.expand_dims使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.expand_dims方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def __init__(self, input_wave_file, output_wave_file, target_phrase):
self.pop_size = 100
self.elite_size = 10
self.mutation_p = 0.005
self.noise_stdev = 40
self.noise_threshold = 1
self.mu = 0.9
self.alpha = 0.001
self.max_iters = 3000
self.num_points_estimate = 100
self.delta_for_gradient = 100
self.delta_for_perturbation = 1e3
self.input_audio = load_wav(input_wave_file).astype(np.float32)
self.pop = np.expand_dims(self.input_audio, axis=0)
self.pop = np.tile(self.pop, (self.pop_size, 1))
self.output_wave_file = output_wave_file
self.target_phrase = target_phrase
self.funcs = self.setup_graph(self.pop, np.array([toks.index(x) for x in target_phrase]))
示例2: predict
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def predict(self, f, k=5, resize_mode='fill'):
from keras.preprocessing import image
from vergeml.img import resize_image
filename = os.path.basename(f)
if not os.path.exists(f):
return dict(filename=filename, prediction=[])
img = image.load_img(f)
img = resize_image(img, self.image_size, self.image_size, 'antialias', resize_mode)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = self.preprocess_input(x)
preds = self.model.predict(x)
pred = self._decode(preds, top=k)[0]
prediction=[dict(probability=np.asscalar(perc), label=klass) for _, klass, perc in pred]
return dict(filename=filename, prediction=prediction)
示例3: transform
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def transform(self, sample):
if not self.model:
if not self.architecture.startswith("@"):
_, self.preprocess_input, self.model = \
get_imagenet_architecture(self.architecture, self.variant, self.size, self.alpha, self.output_layer)
else:
self.model = get_custom_architecture(self.architecture, self.trainings_dir, self.output_layer)
self.preprocess_input = generic_preprocess_input
x = sample.x
x = x.convert('RGB')
x = resize_image(x, self.image_size, self.image_size, 'antialias', 'aspect-fill')
#x = x.resize((self.image_size, self.image_size))
x = np.asarray(x)
x = np.expand_dims(x, axis=0)
x = self.preprocess_input(x)
features = self.model.predict(x)
features = features.flatten()
sample.x = features
sample.y = None
return sample
示例4: calculate_fdiff_stress
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def calculate_fdiff_stress(self, x, u, nu, side=1, dx=1e-6):
"""
Calculate the derivative of the Von Mises stress using finite
differences given the densities x, displacements u, and young modulus
nu. Optionally, provide the side length (default: 1) and delta x
(default: 1e-6).
"""
ds = self.calculate_diff_stress(x, u, nu, side)
dsf = numpy.zeros(x.shape)
x = numpy.expand_dims(x, -1)
for i in range(x.shape[0]):
delta = scipy.sparse.coo_matrix(([dx], [[i], [0]]), shape=x.shape)
s1 = self.calculate_stress((x + delta.A).squeeze(), u, nu, side)
s2 = self.calculate_stress((x - delta.A).squeeze(), u, nu, side)
dsf[i] = ((s1 - s2) / (2. * dx))[i]
print("finite differences: {:g}".format(numpy.linalg.norm(dsf - ds)))
return dsf
示例5: __call__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def __call__(self, results):
"""Call function to convert image in results to :obj:`torch.Tensor` and
transpose the channel order.
Args:
results (dict): Result dict contains the image data to convert.
Returns:
dict: The result dict contains the image converted
to :obj:`torch.Tensor` and transposed to (C, H, W) order.
"""
for key in self.keys:
img = results[key]
if len(img.shape) < 3:
img = np.expand_dims(img, -1)
results[key] = to_tensor(img.transpose(2, 0, 1))
return results
示例6: _prepro_cpg
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def _prepro_cpg(self, states, dists):
"""Preprocess the state and distance of neighboring CpG sites."""
prepro_states = []
prepro_dists = []
for state, dist in zip(states, dists):
nan = state == dat.CPG_NAN
if np.any(nan):
state[nan] = np.random.binomial(1, state[~nan].mean(),
nan.sum())
dist[nan] = self.cpg_max_dist
dist = np.minimum(dist, self.cpg_max_dist) / self.cpg_max_dist
prepro_states.append(np.expand_dims(state, 1))
prepro_dists.append(np.expand_dims(dist, 1))
prepro_states = np.concatenate(prepro_states, axis=1)
prepro_dists = np.concatenate(prepro_dists, axis=1)
if self.cpg_wlen:
center = prepro_states.shape[2] // 2
delta = self.cpg_wlen // 2
tmp = slice(center - delta, center + delta)
prepro_states = prepro_states[:, :, tmp]
prepro_dists = prepro_dists[:, :, tmp]
return (prepro_states, prepro_dists)
示例7: predict_on_batch
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def predict_on_batch(self, inputs):
# write test fasta file
temp_input = tempfile.NamedTemporaryFile(suffix = ".txt")
test_fname = temp_input.name
encode_sequence_into_fasta_file(ofname = test_fname, seq = inputs.tolist())
# test gkmsvm
temp_ofp = tempfile.NamedTemporaryFile(suffix = ".txt")
threads_option = '-T %s' % (str(self.threads))
verbosity_option = '-v 0'
command = ' '.join(['gkmpredict',
test_fname,
self.model_file,
temp_ofp.name,
threads_option,
verbosity_option])
#process = subprocess.Popen(command, shell=True)
#process.wait() # wait for it to finish
exit_code = os.system(command)
temp_input.close()
assert exit_code == 0
# get classification results
temp_ofp.seek(0)
y = np.array([line.split()[-1] for line in temp_ofp], dtype=float)
temp_ofp.close()
return np.expand_dims(y, 1)
示例8: reward
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def reward(tsptw_sequence,speed):
# Convert sequence to tour (end=start)
tour = np.concatenate((tsptw_sequence,np.expand_dims(tsptw_sequence[0],0)))
# Compute tour length
inter_city_distances = np.sqrt(np.sum(np.square(tour[:-1,:2]-tour[1:,:2]),axis=1))
distance = np.sum(inter_city_distances)
# Compute develiry times at each city and count late cities
elapsed_time = -10
late_cities = 0
for i in range(tsptw_sequence.shape[0]-1):
travel_time = inter_city_distances[i]/speed
tw_open = tour[i+1,2]
tw_close = tour[i+1,3]
elapsed_time += travel_time
if elapsed_time <= tw_open:
elapsed_time = tw_open
elif elapsed_time > tw_close:
late_cities += 1
# Reward
return distance + 100000000*late_cities
# Swap city[i] with city[j] in sequence
示例9: iterate_minibatches
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def iterate_minibatches(dataset,batch_len):
start = 0
for i in batch_len:
tokens = []
caseing = []
char = []
labels = []
data = dataset[start:i]
start = i
for dt in data:
t,c,ch,l = dt
l = np.expand_dims(l,-1)
tokens.append(t)
caseing.append(c)
char.append(ch)
labels.append(l)
yield np.asarray(labels),np.asarray(tokens),np.asarray(caseing),np.asarray(char)
示例10: get_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def get_data(img_path):
"""get the (1, 3, h, w) np.array data for the supplied image
Args:
img_path (string): the input image path
Returns:
np.array: image data in a (1, 3, h, w) shape
"""
mean = np.array([123.68, 116.779, 103.939]) # (R,G,B)
img = Image.open(img_path)
img = np.array(img, dtype=np.float32)
reshaped_mean = mean.reshape(1, 1, 3)
img = img - reshaped_mean
img = np.swapaxes(img, 0, 2)
img = np.swapaxes(img, 1, 2)
img = np.expand_dims(img, axis=0)
return img
示例11: preprocess
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def preprocess(self, img):
"""
Preprocess a 210x160x3 uint8 frame into a 6400 (80x80) (1 x input_size)
float vector.
"""
# Crop, down-sample, erase background and set foreground to 1.
# See https://gist.github.com/karpathy/a4166c7fe253700972fcbc77e4ea32c5
img = img[35:195]
img = img[::2, ::2, 0]
img[img == 144] = 0
img[img == 109] = 0
img[img != 0] = 1
curr = np.expand_dims(img.astype(np.float).ravel(), axis=0)
# Subtract the last preprocessed image.
diff = (curr - self.prev if self.prev is not None
else np.zeros((1, curr.shape[1])))
self.prev = curr
return diff
示例12: get_point_cloud_from_z
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def get_point_cloud_from_z(Y, camera_matrix):
"""Projects the depth image Y into a 3D point cloud.
Inputs:
Y is ...xHxW
camera_matrix
Outputs:
X is positive going right
Y is positive into the image
Z is positive up in the image
XYZ is ...xHxWx3
"""
x, z = np.meshgrid(np.arange(Y.shape[-1]),
np.arange(Y.shape[-2]-1, -1, -1))
for i in range(Y.ndim-2):
x = np.expand_dims(x, axis=0)
z = np.expand_dims(z, axis=0)
X = (x-camera_matrix.xc) * Y / camera_matrix.f
Z = (z-camera_matrix.zc) * Y / camera_matrix.f
XYZ = np.concatenate((X[...,np.newaxis], Y[...,np.newaxis],
Z[...,np.newaxis]), axis=X.ndim)
return XYZ
示例13: iou
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def iou(boxes1, boxes2):
"""Computes pairwise intersection-over-union between box collections.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes.
boxes2: a numpy array with shape [M, 4] holding N boxes.
Returns:
a numpy array with shape [N, M] representing pairwise iou scores.
"""
intersect = intersection(boxes1, boxes2)
area1 = area(boxes1)
area2 = area(boxes2)
union = np.expand_dims(area1, axis=1) + np.expand_dims(
area2, axis=0) - intersect
return intersect / union
示例14: ioa
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def ioa(boxes1, boxes2):
"""Computes pairwise intersection-over-area between box collections.
Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
their intersection area over box2's area. Note that ioa is not symmetric,
that is, IOA(box1, box2) != IOA(box2, box1).
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes.
boxes2: a numpy array with shape [M, 4] holding N boxes.
Returns:
a numpy array with shape [N, M] representing pairwise ioa scores.
"""
intersect = intersection(boxes1, boxes2)
areas = np.expand_dims(area(boxes2), axis=0)
return intersect / areas
示例15: optimize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import expand_dims [as 别名]
def optimize(self, sess, feed_dict):
reg_input, reg_weight, old_values, targets = sess.run(
[self.inputs, self.regression_weight, self.values, self.targets],
feed_dict=feed_dict)
intended_values = targets * self.mix_frac + old_values * (1 - self.mix_frac)
# taken from rllab
reg_coeff = 1e-5
for _ in range(5):
best_fit_weight = np.linalg.lstsq(
reg_input.T.dot(reg_input) +
reg_coeff * np.identity(reg_input.shape[1]),
reg_input.T.dot(intended_values))[0]
if not np.any(np.isnan(best_fit_weight)):
break
reg_coeff *= 10
if len(best_fit_weight.shape) == 1:
best_fit_weight = np.expand_dims(best_fit_weight, -1)
sess.run(self.update_regression_weight,
feed_dict={self.new_regression_weight: best_fit_weight})