本文整理汇总了Python中numpy.ndenumerate方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.ndenumerate方法的具体用法?Python numpy.ndenumerate怎么用?Python numpy.ndenumerate使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.ndenumerate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: hinton
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def hinton(matrix, max_weight=None, ax=None):
"""Draw Hinton diagram for visualizing a weight matrix."""
ax = ax if ax is not None else plt.gca()
if not max_weight:
max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))
ax.patch.set_facecolor('gray')
ax.set_aspect('equal', 'box')
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(matrix):
color = 'white' if w > 0 else 'black'
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
facecolor=color, edgecolor=color)
ax.add_patch(rect)
ax.autoscale_view()
ax.invert_yaxis()
示例2: xenumerate
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def xenumerate(arr):
"""
Multidimensional index iterator for xarray objects
Return an iterator yielding pairs of array indexers (dicts) and values.
Parameters
----------
arr : xarray.DataArray
Input array.
See Also
--------
numpy.ndenumerate
"""
for index, _ in np.ndenumerate(arr):
xindex = dict(zip(arr.dims, index))
yield xindex, arr.isel(**xindex)
示例3: draw_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def draw_image(image):
fig, ax = plt.subplots()
ax.set_axis_off()
tb = Table(ax, bbox=[0, 0, 1, 1])
nrows, ncols = image.shape
width, height = 1.0 / ncols, 1.0 / nrows
# Add cells
for (i, j), val in np.ndenumerate(image):
tb.add_cell(i, j, width, height, text=val,
loc='center', facecolor='white')
# Row and column labels...
for i in range(len(image)):
tb.add_cell(i, -1, width, height, text=i+1, loc='right',
edgecolor='none', facecolor='none')
tb.add_cell(-1, i, width, height/2, text=i+1, loc='center',
edgecolor='none', facecolor='none')
ax.add_table(tb)
示例4: draw_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def draw_image(image):
fig, ax = plt.subplots()
ax.set_axis_off()
tb = Table(ax, bbox=[0, 0, 1, 1])
nrows, ncols = image.shape
width, height = 1.0 / ncols, 1.0 / nrows
# Add cells
for (i, j), val in np.ndenumerate(image):
tb.add_cell(i, j, width, height, text=val,
loc='center', facecolor='white')
# Row and column labels...
for i in range(len(image)):
tb.add_cell(i, -1, width, height, text=i+1, loc='right',
edgecolor='none', facecolor='none')
tb.add_cell(-1, i, width, height/2, text=i+1, loc='center',
edgecolor='none', facecolor='none')
ax.add_table(tb)
示例5: load_flattened
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def load_flattened(self, max_list_elements: int = 24) -> tp.List[tp.Dict[str, tp.Any]]:
"""Loads data from the log file, and splits lists (arrays) into multiple arguments
Parameters
----------
max_list_elements: int
Maximum number of elements displayed from the array, each element is given a
unique id of type list_name#i0_i1_...
"""
data = self.load()
flat_data: tp.List[tp.Dict[str, tp.Any]] = []
for element in data:
list_keys = {key for key, val in element.items() if isinstance(val, list)}
flat_data.append({key: val for key, val in element.items() if key not in list_keys})
for key in list_keys:
for k, (indices, value) in enumerate(np.ndenumerate(element[key])):
if k >= max_list_elements:
break
flat_data[-1][key + "#" + "_".join(str(i) for i in indices)] = value
return flat_data
示例6: add_outline
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def add_outline(mat: np.ndarray) -> np.ndarray:
"""Pad the matrix"""
m = np.ones(mat.shape)
for idx, orig_val in np.ndenumerate(mat):
x, y = idx
neighbors = [(x, y + 1), (x + 1, y), (x, y - 1), (x - 1, y)]
if orig_val == 0:
m[idx] = 0 # Set the coordinate in the new matrix as 0
for n_coord in neighbors:
try:
m[n_coord] = 0.5 if mat[n_coord] == 1 else 0
except IndexError:
pass
m = np.pad(m, mode="constant", pad_width=1, constant_values=1)
# Let's do a switcheroo, I know this isn't elegant but please feel free to
# do a PR to make this more efficient!
m[m == 1] = np.inf
m[m == 0.5] = 1
m[m == np.inf] = 0.5
return m
示例7: transform
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def transform(self, input_: list) -> list:
"""Transform the input text."""
text_left, text_right = input_
matching_hist = np.ones((len(text_left), self._hist_bin_size),
dtype=np.float32)
embed_left = self._embedding_matrix[text_left]
embed_right = self._embedding_matrix[text_right]
matching_matrix = embed_left.dot(np.transpose(embed_right))
for (i, j), value in np.ndenumerate(matching_matrix):
bin_index = int((value + 1.) / 2. * (self._hist_bin_size - 1.))
matching_hist[i][bin_index] += 1.0
if self._mode == 'NH':
matching_sum = matching_hist.sum(axis=1)
matching_hist = matching_hist / matching_sum[:, np.newaxis]
elif self._mode == 'LCH':
matching_hist = np.log(matching_hist)
return matching_hist.tolist()
示例8: test_ndindex
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def test_ndindex():
x = list(np.ndindex(1, 2, 3))
expected = [ix for ix, e in np.ndenumerate(np.zeros((1, 2, 3)))]
assert_array_equal(x, expected)
x = list(np.ndindex((1, 2, 3)))
assert_array_equal(x, expected)
# Test use of scalars and tuples
x = list(np.ndindex((3,)))
assert_array_equal(x, list(np.ndindex(3)))
# Make sure size argument is optional
x = list(np.ndindex())
assert_equal(x, [()])
x = list(np.ndindex(()))
assert_equal(x, [()])
# Make sure 0-sized ndindex works correctly
x = list(np.ndindex(*[0]))
assert_equal(x, [])
示例9: reduce_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def reduce_data(self,p_grid,data):
"""reduce data to the domain indicated by p_grid"""
assert data.shape == p_grid.shape, 'Shape of x and shape of partition vector must match.'
#get out_shape
if p_grid.ndim == 1:
out_shape =(len(numpy.unique(p_grid)), )
else:
out = []
for i in range(p_grid.ndim):
ind_slice = [0] * p_grid.ndim
ind_slice[i] = slice(0, p_grid.shape[i])
out.append(len(numpy.unique(p_grid[ind_slice])))
# This is doesn't work for dimension >2, the compressed array is not a strip of the domain,
# but the first element along the axis. It could be an nd array itself.
#out = [len(numpy.unique(numpy.compress([True], p_grid, axis=i))) for i in range(p_grid.ndim)]
#out.reverse() # rows/cols need to be reversed here
out_shape = tuple(out)
#reduce
unique, indices, inverse, counts = numpy.unique(p_grid, return_index=True, return_inverse=True, return_counts=True)
res = numpy.zeros_like(unique, dtype=float)
for index, c in numpy.ndenumerate(data.ravel()): # needs to be flattened for parallel indexing with output of unique
res[ inverse[index] ] += c
return numpy.array(res).reshape(out_shape)
示例10: grad_check_hierarchicalU
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def grad_check_hierarchicalU(self,node,grad_computed,grad_approx,eps,x,y):
if node.isLeaf == True:
return
if node.grad == None:
return
theta = node.hActs
for ij,v in np.ndenumerate(node.hActs):
tij = theta[ij]
theta[ij] = tij + eps
Jplus = self.compute_loss(x,y)
theta[ij] = tij - eps
Jminus = self.compute_loss(x, y)
theta[ij] = tij # reset
approx = (Jplus - Jminus)/(2*eps)
grad_computed.append(node.grad[ij])
grad_approx.append(approx)
self.grad_check_hierarchicalU(node.left,grad_computed,grad_approx,eps,x,y)
self.grad_check_hierarchicalU(node.right,grad_computed,grad_approx,eps,x,y)
示例11: export_thermal_to_csv
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def export_thermal_to_csv(self, csv_filename):
"""
Convert thermal data in numpy to json
:return:
"""
with open(csv_filename, 'w') as fh:
writer = csv.writer(fh, delimiter=',')
writer.writerow(['x', 'y', 'temp (c)'])
pixel_values = []
for e in np.ndenumerate(self.thermal_image_np):
x, y = e[0]
c = e[1]
pixel_values.append([x, y, c])
writer.writerows(pixel_values)
示例12: calculate_edge_lengths
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def calculate_edge_lengths(G, verbose=True):
# Calculate the lengths of the edges
if verbose:
print('Calculating edge lengths...')
x = np.matrix(G.nodes.data('x'))[:, 1]
y = np.matrix(G.nodes.data('y'))[:, 1]
node_coordinates = np.concatenate([x, y], axis=1)
node_distances = squareform(pdist(node_coordinates, 'euclidean'))
adjacency_matrix = np.array(nx.adjacency_matrix(G).todense())
adjacency_matrix = adjacency_matrix.astype('float')
adjacency_matrix[adjacency_matrix == 0] = np.nan
edge_lengths = np.multiply(node_distances, adjacency_matrix)
edge_attr_dict = {index: v for index, v in np.ndenumerate(edge_lengths) if ~np.isnan(v)}
nx.set_edge_attributes(G, edge_attr_dict, 'length')
return G
示例13: hinton
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def hinton(matrix, max_weight=None, ax=None):
"""Draw Hinton diagram for visualizing a weight matrix."""
ax = ax if ax is not None else plt.gca()
if not max_weight:
max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))
ax.patch.set_facecolor('gray')
ax.set_aspect('equal', 'box')
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(matrix):
color = 'white' if w > 0 else 'black'
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
facecolor=color, edgecolor=color)
ax.add_patch(rect)
ax.autoscale_view()
ax.invert_yaxis()
return ax
示例14: _flatten_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def _flatten_data(data, chart_cfg, switch_zy=False):
plot_axes_def = [(0, XAxis), (1, YAxis)]
# Inject categories into the axis definitions of the plot
if isinstance(data, NDFrame):
for i, plot_axis in plot_axes_def[:data.ndim]:
categories = data.axes[i]
# Skip numeric indices
if not categories.is_numeric():
chart_cfg = chart_cfg.inherit_many(plot_axis(categories=list(categories)))
data = [list(index) + [value] for index, value in list(np.ndenumerate(data))]
if switch_zy:
for i in range(len(data)):
tmp = data[i][-1]
data[i][-1] = data[i][-2]
data[i][-2] = tmp
return data, chart_cfg
示例15: generateDistanceMatrix
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ndenumerate [as 别名]
def generateDistanceMatrix(width, height):
"""
Generates a matrix specifying the distance of each point in a window to its centre.
"""
# Determine the coordinates of the exact centre of the window
originX = width / 2
originY = height / 2
# Generate the distance matrix
distances = zerosFactory((height,width), dtype=np.float)
for index, val in np.ndenumerate(distances):
y,x = index
distances[(y,x)] = math.sqrt( math.pow(x - originX, 2) + math.pow(y - originY, 2) )
return distances