def compress_image(img, num_clusters):
# Convert input image into (num_samples, num_features)
# array to run kmeans clustering algorithm
X = img.reshape((-1, 1))
# Run kmeans on input data
kmeans = cluster.KMeans(n_clusters=num_clusters, n_init=4, random_state=5)
kmeans.fit(X)
centroids = kmeans.cluster_centers_.squeeze()
labels = kmeans.labels_
# Assign each value to the nearest centroid and
# reshape it to the original image shape
input_image_compressed = np.choose(labels, centroids).reshape(img.shape)
return input_image_compressed
python类choose()的实例源码
vector_quantization.py 文件源码
项目:Python-Machine-Learning-Cookbook
作者: PacktPublishing
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
color_utils.py 文件源码
项目:house-of-enlightenment
作者: house-of-enlightenment
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def hsv2rgb(hsv):
hsv = np.array(hsv)
input_shape = hsv.shape
hsv = hsv.reshape(-1, 3)
h, s, v = hsv[:, 0] / 255, hsv[:, 1] / 255, hsv[:, 2]
i = np.uint32(h * 6.0) # pylint: disable=no-member
f = (h * 6.0) - i
p = v * (1.0 - s)
q = v * (1.0 - s * f)
t = v * (1.0 - s * (1.0 - f))
i = i % 6
rgb = np.zeros_like(hsv, np.uint8)
v, t, p, q = v.reshape(-1, 1), t.reshape(-1, 1), p.reshape(-1, 1), q.reshape(-1, 1)
# This could probably be much faster if replaced with np.choose
rgb[i == 0] = np.hstack([v, t, p])[i == 0]
rgb[i == 1] = np.hstack([q, v, p])[i == 1]
rgb[i == 2] = np.hstack([p, v, t])[i == 2]
rgb[i == 3] = np.hstack([p, q, v])[i == 3]
rgb[i == 4] = np.hstack([t, p, v])[i == 4]
rgb[i == 5] = np.hstack([v, p, q])[i == 5]
rgb[s == 0.0] = np.hstack([v, v, v])[s == 0.0]
return rgb.reshape(input_shape)
def find_ray_grids(self, coord, axis):
"""
Returns the (objects, indices) of grids that an (x,y) ray intersects
along *axis*
"""
# Let's figure out which grids are on the slice
mask=np.ones(self.num_grids)
# So if gRE > coord, we get a mask, if not, we get a zero
# if gLE > coord, we get a zero, if not, mask
# Thus, if the coordinate is between the two edges, we win!
xax = self.ds.coordinates.x_axis[axis]
yax = self.ds.coordinates.y_axis[axis]
np.choose(np.greater(self.grid_right_edge[:,xax],coord[0]),(0,mask),mask)
np.choose(np.greater(self.grid_left_edge[:,xax],coord[0]),(mask,0),mask)
np.choose(np.greater(self.grid_right_edge[:,yax],coord[1]),(0,mask),mask)
np.choose(np.greater(self.grid_left_edge[:,yax],coord[1]),(mask,0),mask)
ind = np.where(mask == 1)
return self.grids[ind], ind
def forward(self, inputs):
x, t = inputs
if chainer.is_debug():
if not ((0 <= t).all() and
(t < x.shape[1]).all()):
msg = 'Each label `t` need to satisfty `0 <= t < x.shape[1]`'
raise ValueError(msg)
xp = cuda.get_array_module(x)
if xp is numpy:
# This code is equivalent to `t.choose(x.T)`, but `numpy.choose`
# does not work when `x.shape[1] > 32`.
return x[six.moves.range(t.size), t],
else:
y = cuda.elementwise(
'S t, raw T x',
'T y',
'int ind[] = {i, t}; y = x[ind];',
'getitem_fwd'
)(t, x)
return y,
def raster_copy_with_nodata( s_fh, s_xoff, s_yoff, s_xsize, s_ysize, s_band_n,
t_fh, t_xoff, t_yoff, t_xsize, t_ysize, t_band_n,
nodata ):
try:
import numpy as Numeric
except ImportError:
import Numeric
s_band = s_fh.GetRasterBand( s_band_n )
t_band = t_fh.GetRasterBand( t_band_n )
data_src = s_band.ReadAsArray( s_xoff, s_yoff, s_xsize, s_ysize,
t_xsize, t_ysize )
data_dst = t_band.ReadAsArray( t_xoff, t_yoff, t_xsize, t_ysize )
nodata_test = Numeric.equal(data_src,nodata)
to_write = Numeric.choose( nodata_test, (data_src, data_dst) )
t_band.WriteArray( to_write, t_xoff, t_yoff )
return 0
# =============================================================================
def raster_copy_with_mask( s_fh, s_xoff, s_yoff, s_xsize, s_ysize, s_band_n,
t_fh, t_xoff, t_yoff, t_xsize, t_ysize, t_band_n,
m_band ):
try:
import numpy as Numeric
except ImportError:
import Numeric
s_band = s_fh.GetRasterBand( s_band_n )
t_band = t_fh.GetRasterBand( t_band_n )
data_src = s_band.ReadAsArray( s_xoff, s_yoff, s_xsize, s_ysize,
t_xsize, t_ysize )
data_mask = m_band.ReadAsArray( s_xoff, s_yoff, s_xsize, s_ysize,
t_xsize, t_ysize )
data_dst = t_band.ReadAsArray( t_xoff, t_yoff, t_xsize, t_ysize )
mask_test = Numeric.equal(data_mask, 0)
to_write = Numeric.choose( mask_test, (data_src, data_dst) )
t_band.WriteArray( to_write, t_xoff, t_yoff )
return 0
# =============================================================================
def test_broadcasted(self):
a = tensor.scalar(dtype='int32')
b = tensor.matrix(dtype='float32')
# Test when a is broadcastable
A = 3
B = numpy.asarray(numpy.random.rand(4, 4), dtype='float32')
for m in self.modes:
f = function([a, b], choose(a, b, mode=m))
t_c = f(A, B)
n_c = numpy.choose(A, B, mode=m)
assert numpy.allclose(t_c, n_c)
# Test when the result should be broadcastable
b = theano.tensor.col(dtype='float32')
B = numpy.asarray(numpy.random.rand(4, 1), dtype='float32')
for m in self.modes:
f = function([a, b], choose(a, b, mode=m))
assert choose(a, b, mode=m).broadcastable[0]
t_c = f(A, B)
n_c = numpy.choose(A, B, mode=m)
assert numpy.allclose(t_c, n_c)
def ___test_infer_shape_tuple(self):
a = tensor.tensor3(dtype='int32')
b = tensor.tensor3(dtype='int32')
c = tensor.tensor3(dtype='int32')
A = numpy.asarray([1, 0], dtype='int32').reshape((2, 1, 1))
B = numpy.asarray(numpy.random.rand(1, 4, 1), dtype='int32')
C = numpy.asarray(numpy.random.rand(1, 1, 7), dtype='int32')
f = function([a, b, c], choose(a, (b, c)))
shape = (2, 4, 7)
assert numpy.allclose(f(A, B, C).shape, shape)
self._compile_and_check([a, b, c], # theano.function inputs
[self.op(a, (b, c))], # theano.function outputs
# Always use not square matrix!
# inputs data
[A, B, C],
# Op that should be removed from the graph.
self.op_class)
def th_external_dG(self, seqs):
# Make a boolean vector representing which toeholds' external 3' context dG
# is further from the target dG than than their external 5' context dG
dG_external3 = self.th_external_3_dG(seqs)
dG_external5 = self.th_external_5_dG(seqs)
external_further_bool = np.abs(dG_external3 - self.targetdG) >\
np.abs(dG_external5 - self.targetdG)
return np.choose(external_further_bool, [dG_external5, dG_external3])
def matching_uniform(self, seqs):
# Make a boolean vector representing which toeholds' external context dG
# is further from the target dG than than their internal context dG
dG_external = self.th_external_dG(seqs)
dG_internal = self.th_internal_dG(seqs)
external_further_bool = np.abs(dG_external - self.targetdG) >\
np.abs(dG_internal - self.targetdG)
return np.choose(external_further_bool, [dG_internal, dG_external])
def matching_uniform(self, seqs):
# Make a boolean vector representing which toeholds' external context dG
# is further from the target dG than than their internal context dG
dG_external = self.th_external_dG(seqs)
dG_internal = self.th_internal_dG(seqs)
external_further_bool = np.abs(dG_external - self.targetdG) >\
np.abs(dG_internal - self.targetdG)
return np.choose(external_further_bool, [dG_internal, dG_external])
def _get_hidden_layer_connectivity(self, layerIdx):
layer_size = self._hidden_sizes[layerIdx]
if layerIdx == 0:
p_vals = self._get_p(T.min(self.layers_connectivity[layerIdx]))
else:
p_vals = self._get_p(T.min(self.layers_connectivity_updates[layerIdx-1]))
# #Implementations of np.choose in theano GPU
# return T.nonzero(self._mrng.multinomial(pvals=[self._p_vals] * layer_size, dtype=theano.config.floatX))[1].astype(dtype=theano.config.floatX)
# return T.argmax(self._mrng.multinomial(pvals=[self._p_vals] * layer_size, dtype=theano.config.floatX), axis=1)
return T.sum(T.cumsum(self._mrng.multinomial(pvals=T.tile(p_vals[::-1][None, :], (layer_size, 1)), dtype=theano.config.floatX), axis=1), axis=1)
def test_choose(self):
choices = [[0, 1, 2],
[3, 4, 5],
[5, 6, 7]]
tgt = [5, 1, 5]
a = [2, 0, 1]
out = np.choose(a, choices)
assert_equal(out, tgt)
def clip(self, a, m, M, out=None):
# use slow-clip
selector = np.less(a, m) + 2*np.greater(a, M)
return selector.choose((a, m, M), out=out)
# Handy functions
def test_mixed(self):
c = np.array([True, True])
a = np.array([True, True])
assert_equal(np.choose(c, (a, 1)), np.array([1, 1]))
def test_choose(self):
x = 2*np.ones((3,), dtype=int)
y = 3*np.ones((3,), dtype=int)
x2 = 2*np.ones((2, 3), dtype=int)
y2 = 3*np.ones((2, 3), dtype=int)
ind = np.array([0, 0, 1])
A = ind.choose((x, y))
assert_equal(A, [2, 2, 3])
A = ind.choose((x2, y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
A = ind.choose((x, y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
def test_all(self):
a = np.random.normal(0, 1, (4, 5, 6, 7, 8))
for i in range(a.ndim):
amax = a.max(i)
aargmax = a.argmax(i)
axes = list(range(a.ndim))
axes.remove(i)
assert_(np.all(amax == aargmax.choose(*a.transpose(i,*axes))))
def test_basic(self):
A = np.choose(self.ind, (self.x, self.y))
assert_equal(A, [2, 2, 3])
def test_broadcast1(self):
A = np.choose(self.ind, (self.x2, self.y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
def test_broadcast2(self):
A = np.choose(self.ind, (self.x, self.y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
color_fade.py 文件源码
项目:house-of-enlightenment
作者: house-of-enlightenment
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def _next_frame(self):
sources = np.random.randint(0, 6, len(self.my_pixels))
colors = np.array([RED, BLUE, GREEN, BLACK, BLACK, BLACK])
for i in range(3):
c = np.choose(sources, colors[:, i])
self.my_pixels[:, i] = c
color_fade.py 文件源码
项目:house-of-enlightenment
作者: house-of-enlightenment
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def _next_frame(self):
sources = np.random.randint(0, 7, len(self.my_pixels))
colors = np.concatenate((self.colors, [BLACK, BLACK, BLACK]))
for i in range(3):
c = np.choose(sources, colors[:, i])
self.my_pixels[:, i] = c
color_fade.py 文件源码
项目:house-of-enlightenment
作者: house-of-enlightenment
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def _next_frame(self):
self.colors[:, 0] = self.colors[:, 0] + 119
self.sources = np.random.randint(0, 7, len(self.my_pixels))
colors = np.concatenate((self.colors, [BLACK, BLACK, BLACK]))
for i in range(3):
c = np.choose(self.sources, colors[:, i])
self.my_pixels[:, i] = c
def test_choose(self):
choices = [[0, 1, 2],
[3, 4, 5],
[5, 6, 7]]
tgt = [5, 1, 5]
a = [2, 0, 1]
out = np.choose(a, choices)
assert_equal(out, tgt)
def clip(self, a, m, M, out=None):
# use slow-clip
selector = np.less(a, m) + 2*np.greater(a, M)
return selector.choose((a, m, M), out=out)
# Handy functions
def test_mixed(self):
c = np.array([True, True])
a = np.array([True, True])
assert_equal(np.choose(c, (a, 1)), np.array([1, 1]))
def test_choose(self):
x = 2*np.ones((3,), dtype=int)
y = 3*np.ones((3,), dtype=int)
x2 = 2*np.ones((2, 3), dtype=int)
y2 = 3*np.ones((2, 3), dtype=int)
ind = np.array([0, 0, 1])
A = ind.choose((x, y))
assert_equal(A, [2, 2, 3])
A = ind.choose((x2, y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
A = ind.choose((x, y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
def test_all(self):
a = np.random.normal(0, 1, (4, 5, 6, 7, 8))
for i in range(a.ndim):
amax = a.max(i)
aargmax = a.argmax(i)
axes = list(range(a.ndim))
axes.remove(i)
assert_(np.all(amax == aargmax.choose(*a.transpose(i,*axes))))
def test_basic(self):
A = np.choose(self.ind, (self.x, self.y))
assert_equal(A, [2, 2, 3])
def test_broadcast1(self):
A = np.choose(self.ind, (self.x2, self.y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])