本文整理匯總了Python中numpy.fromfunction方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.fromfunction方法的具體用法?Python numpy.fromfunction怎麽用?Python numpy.fromfunction使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.fromfunction方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: getArrayRegion
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def getArrayRegion(self, arr, img=None, axes=(0, 1), **kwds):
"""
Return the result of ROI.getArrayRegion() masked by the elliptical shape
of the ROI. Regions outside the ellipse are set to 0.
"""
# Note: we could use the same method as used by PolyLineROI, but this
# implementation produces a nicer mask.
arr = ROI.getArrayRegion(self, arr, img, axes, **kwds)
if arr is None or arr.shape[axes[0]] == 0 or arr.shape[axes[1]] == 0:
return arr
w = arr.shape[axes[0]]
h = arr.shape[axes[1]]
## generate an ellipsoidal mask
mask = np.fromfunction(lambda x,y: (((x+0.5)/(w/2.)-1)**2+ ((y+0.5)/(h/2.)-1)**2)**0.5 < 1, (w, h))
# reshape to match array axes
if axes[0] > axes[1]:
mask = mask.T
shape = [(n if i in axes else 1) for i,n in enumerate(arr.shape)]
mask = mask.reshape(shape)
return arr * mask
示例2: fromfunction
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def fromfunction(function, shape, **kwargs):
""" Constructs an array by executing a function over each coordinate.
This is currently equivalent to :func:`numpy.fromfunction`
wrapped by :func:`chainerx.array`, given the device argument.
Note:
Keywords other than ``dtype`` and ``device`` are passed to
```function```.
.. seealso:: :func:`numpy.fromfunction`
"""
dtype = kwargs.pop('dtype', float)
device = kwargs.pop('device', None)
return chainerx.array(
numpy.fromfunction(
function, shape, dtype=dtype, **kwargs),
device=device)
# TODO(hvy): Optimize with pre-allocated memory using count for non-native
# devices.
示例3: permute_graph
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def permute_graph(graph, label, permutation):
"""Permutes the graph and labels based on permutation.
Args:
graph: np.ndarray adjacency matrix.
label: list of labels of same length as graph dimensions.
permutation: a permutation list of ints of same length as graph dimensions.
Returns:
np.ndarray where vertex permutation[v] is vertex v from the original graph
"""
# vertex permutation[v] in new graph is vertex v in the old graph
forward_perm = zip(permutation, list(range(len(permutation))))
inverse_perm = [x[1] for x in sorted(forward_perm)]
edge_fn = lambda x, y: graph[inverse_perm[x], inverse_perm[y]] == 1
new_matrix = np.fromfunction(np.vectorize(edge_fn),
(len(label), len(label)),
dtype=np.int8)
new_label = [label[inverse_perm[i]] for i in range(len(label))]
return new_matrix, new_label
示例4: permute_graph
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def permute_graph(graph, label, permutation):
"""Permutes the graph and labels based on permutation.
Args:
graph: np.ndarray adjacency matrix.
label: list of labels of same length as graph dimensions.
permutation: a permutation list of ints of same length as graph dimensions.
Returns:
np.ndarray where vertex permutation[v] is vertex v from the original graph
"""
# vertex permutation[v] in new graph is vertex v in the old graph
forward_perm = zip(permutation, list(range(len(permutation))))
inverse_perm = [x[1] for x in sorted(forward_perm)]
edge_fn = lambda x, y: graph[inverse_perm[x], inverse_perm[y]] == 1
new_matrix = np.fromfunction(np.vectorize(edge_fn),
(len(label), len(label)),
dtype=np.int8)
new_label = [label[inverse_perm[i]] for i in range(len(label))]
return new_matrix, new_label
示例5: test_nearest_masked_swath_target
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def test_nearest_masked_swath_target(self):
"""Test that a masked array works as a target."""
data = np.fromfunction(lambda y, x: y * x, (50, 10))
lons = np.fromfunction(lambda y, x: 3 + x, (50, 10))
lats = np.fromfunction(lambda y, x: 75 - y, (50, 10))
mask = np.ones_like(lons, dtype=np.bool)
mask[::2, ::2] = False
swath_def = geometry.SwathDefinition(
lons=np.ma.masked_array(lons, mask=mask),
lats=np.ma.masked_array(lats, mask=False)
)
res = kd_tree.resample_nearest(swath_def, data.ravel(),
swath_def, 50000, segments=3)
cross_sum = res.sum()
# expected = 12716 # if masks aren't respected
expected = 12000
self.assertEqual(cross_sum, expected)
示例6: test_gauss_multi
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def test_gauss_multi(self):
data = np.fromfunction(lambda y, x: (y + x) * 10 ** -6, (5000, 100))
lons = np.fromfunction(
lambda y, x: 3 + (10.0 / 100) * x, (5000, 100))
lats = np.fromfunction(
lambda y, x: 75 - (50.0 / 5000) * y, (5000, 100))
swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
data_multi = np.column_stack((data.ravel(), data.ravel(),
data.ravel()))
with catch_warnings(UserWarning) as w:
res = kd_tree.resample_gauss(swath_def, data_multi,
self.area_def, 50000, [25000, 15000, 10000], segments=1)
self.assertFalse(len(w) != 1)
self.assertFalse(('Possible more' not in str(w[0].message)))
cross_sum = res.sum()
expected = 1461.8429990248171
self.assertAlmostEqual(cross_sum, expected)
示例7: test_gauss_multi_mp
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def test_gauss_multi_mp(self):
data = np.fromfunction(lambda y, x: (y + x) * 10 ** -6, (5000, 100))
lons = np.fromfunction(
lambda y, x: 3 + (10.0 / 100) * x, (5000, 100))
lats = np.fromfunction(
lambda y, x: 75 - (50.0 / 5000) * y, (5000, 100))
swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
data_multi = np.column_stack((data.ravel(), data.ravel(),
data.ravel()))
with catch_warnings(UserWarning) as w:
res = kd_tree.resample_gauss(swath_def, data_multi,
self.area_def, 50000, [
25000, 15000, 10000],
nprocs=2, segments=1)
self.assertFalse(len(w) != 1)
self.assertFalse(('Possible more' not in str(w[0].message)))
cross_sum = res.sum()
expected = 1461.8429990248171
self.assertAlmostEqual(cross_sum, expected)
示例8: test_gauss_multi_mp_segments
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def test_gauss_multi_mp_segments(self):
data = np.fromfunction(lambda y, x: (y + x) * 10 ** -6, (5000, 100))
lons = np.fromfunction(
lambda y, x: 3 + (10.0 / 100) * x, (5000, 100))
lats = np.fromfunction(
lambda y, x: 75 - (50.0 / 5000) * y, (5000, 100))
swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
data_multi = np.column_stack((data.ravel(), data.ravel(),
data.ravel()))
with catch_warnings(UserWarning) as w:
res = kd_tree.resample_gauss(swath_def, data_multi,
self.area_def, 50000, [
25000, 15000, 10000],
nprocs=2, segments=1)
self.assertFalse(len(w) != 1)
self.assertFalse('Possible more' not in str(w[0].message))
cross_sum = res.sum()
expected = 1461.8429990248171
self.assertAlmostEqual(cross_sum, expected)
示例9: test_masked_gauss
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def test_masked_gauss(self):
data = np.ones((50, 10))
data[:, 5:] = 2
lons = np.fromfunction(lambda y, x: 3 + x, (50, 10))
lats = np.fromfunction(lambda y, x: 75 - y, (50, 10))
swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
mask = np.ones((50, 10))
mask[:, :5] = 0
masked_data = np.ma.array(data, mask=mask)
res = kd_tree.resample_gauss(swath_def, masked_data.ravel(),
self.area_def, 50000, 25000, segments=1)
expected_mask = np.fromfile(os.path.join(os.path.dirname(__file__),
'test_files',
'mask_test_mask.dat'),
sep=' ').reshape((800, 800))
expected_data = np.fromfile(os.path.join(os.path.dirname(__file__),
'test_files',
'mask_test_data.dat'),
sep=' ').reshape((800, 800))
expected = expected_data.sum()
cross_sum = res.data.sum()
self.assertTrue(np.array_equal(expected_mask, res.mask))
self.assertAlmostEqual(cross_sum, expected, places=3)
示例10: test_masked_full
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def test_masked_full(self):
data = np.ones((50, 10))
data[:, 5:] = 2
mask = np.ones((50, 10))
mask[:, :5] = 0
masked_data = np.ma.array(data, mask=mask)
lons = np.fromfunction(lambda y, x: 3 + x, (50, 10))
lats = np.fromfunction(lambda y, x: 75 - y, (50, 10))
swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
res = kd_tree.resample_nearest(swath_def,
masked_data.ravel(
), self.area_def, 50000,
fill_value=None, segments=1)
expected_fill_mask = np.fromfile(os.path.join(os.path.dirname(__file__),
'test_files',
'mask_test_full_fill.dat'),
sep=' ').reshape((800, 800))
fill_mask = res.mask
self.assertTrue(np.array_equal(fill_mask, expected_fill_mask))
示例11: initializeGL
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def initializeGL(self):
## Generate texture for rendering points
w = 64
def fn(x,y):
r = ((x-w/2.)**2 + (y-w/2.)**2) ** 0.5
return 255 * (w/2. - np.clip(r, w/2.-1.0, w/2.))
pData = np.empty((w, w, 4))
pData[:] = 255
pData[:,:,3] = np.fromfunction(fn, pData.shape[:2])
#print pData.shape, pData.min(), pData.max()
pData = pData.astype(np.ubyte)
if getattr(self, "pointTexture", None) is None:
self.pointTexture = glGenTextures(1)
glActiveTexture(GL_TEXTURE0)
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, self.pointTexture)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pData.shape[0], pData.shape[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, pData)
self.shader = shaders.getShaderProgram('pointSprite')
#def getVBO(self, name):
#if name not in self.vbo:
#self.vbo[name] = vbo.VBO(getattr(self, name).astype('f'))
#return self.vbo[name]
#def setupGLState(self):
#"""Prepare OpenGL state for drawing. This function is called immediately before painting."""
##glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ## requires z-sorting to render properly.
#glBlendFunc(GL_SRC_ALPHA, GL_ONE)
#glEnable( GL_BLEND )
#glEnable( GL_ALPHA_TEST )
#glDisable( GL_DEPTH_TEST )
##glEnable( GL_POINT_SMOOTH )
##glHint(GL_POINT_SMOOTH_HINT, GL_NICEST)
##glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, (0, 0, -1e-3))
##glPointParameterfv(GL_POINT_SIZE_MAX, (65500,))
##glPointParameterfv(GL_POINT_SIZE_MIN, (0,))
示例12: __call__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def __call__(self, sample):
if 'flow' not in sample.keys():
return sample
applied_angle = random.uniform(-self.angle,self.angle)
diff = random.uniform(-self.diff_angle,self.diff_angle)
angle1 = applied_angle - diff/2
angle2 = applied_angle + diff/2
angle1_rad = angle1*np.pi/180
h, w = sample['leftImage'].shape[-2:]
def rotate_flow(k, i, j):
return -k*(j-w/2)*(diff*np.pi/180) + (1-k)*(i-h/2)*(diff*np.pi/180)
rotate_flow_map = np.fromfunction(rotate_flow, sample['flow'].shape)
sample['flow'] += rotate_flow_map
sample['leftImage'] = ndimage.interpolation.rotate(sample['leftImage'], angle1, axes=(-2, -1), reshape=self.reshape, order=self.order)
sample['rightImage'] = ndimage.interpolation.rotate(sample['rightImage'], angle2, axes=(-2, -1), reshape=self.reshape, order=self.order)
sample['flow'] = ndimage.interpolation.rotate(sample['flow'], angle1, axes=(-2, -1), reshape=self.reshape, order=self.order)
# flow vectors must be rotated too! careful about Y flow which is upside down, clockwise
flow = np.copy(sample['flow'])
sample['flow'][0,:,:] = np.cos(angle1_rad)*flow[0,:,:] + np.sin(angle1_rad)*flow[1,:,:]
sample['flow'][1,:,:] = -np.sin(angle1_rad)*flow[0,:,:] + np.cos(angle1_rad)*flow[1,:,:]
return sample
示例13: objective_function
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def objective_function(self, config, budget=108):
if self.multi_fidelity is False:
assert budget == 108
bitlist = [0] * (VERTICES * (VERTICES - 1) // 2)
for i in range(MAX_EDGES):
bitlist[config["edge_%d" % i]] = 1
out = 0
for bit in bitlist:
out = (out << 1) | bit
matrix = np.fromfunction(graph_util.gen_is_edge_fn(out),
(VERTICES, VERTICES),
dtype=np.int8)
# if not graph_util.is_full_dag(matrix) or graph_util.num_edges(matrix) > MAX_EDGES:
if graph_util.num_edges(matrix) > MAX_EDGES:
self.record_invalid(config, 1, 1, 0)
return 1, 0
labeling = [config["op_node_%d" % i] for i in range(5)]
labeling = ['input'] + list(labeling) + ['output']
model_spec = api.ModelSpec(matrix, labeling)
try:
data = self.dataset.query(model_spec, epochs=budget)
except api.OutOfDomainError:
self.record_invalid(config, 1, 1, 0)
return 1, 0
self.record_valid(config, data, model_spec)
return 1 - data["validation_accuracy"], data["training_time"]
示例14: fromfunction
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def fromfunction(shape, dimensions, type=None, typecode=None, dtype=None):
dtype = type2dtype(typecode, type, dtype, 1)
return np.fromfunction(shape, dimensions, dtype=dtype)
示例15: fromfunction
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fromfunction [as 別名]
def fromfunction(args, dimensions):
return np.fromfunction(args, dimensions, dtype=int)