Here are the examples of the python api numpy.random.random_integers taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
79 Examples
3
Example 1
def next(self):
if self.batch_count >= self.num_batches:
raise StopIteration()
else:
self.last = np.random.random_integers(low=0,
high=self.num_samples - 1,
size=(self.batch_size,))
self.batch_count += 1
return self.X[self.last, :, :, :]
3
Example 2
def randombox(shape):
"""
Generate a random box, returning the box and the edge lengths
"""
edges = [np.random.random_integers(0, shape[j], size=(2,))
for j in range(len(shape))]
for j in range(len(shape)):
edges[j].sort()
if edges[j][0] == edges[j][1]:
edges[j][0] = 0; edges[j][1] = shape[j]/2+1
return edges, box(shape, edges)
3
Example 3
Project: attention-lvcsr Source File: test_basic.py
def random_lil(shape, dtype, nnz):
rval = sp.lil_matrix(shape, dtype=dtype)
huge = 2 ** 30
for k in range(nnz):
# set non-zeros in random locations (row x, col y)
idx = numpy.random.random_integers(huge, size=2) % shape
value = numpy.random.rand()
# if dtype *int*, value will always be zeros!
if "int" in dtype:
value = int(value * 100)
# The call to tuple is needed as scipy 0.13.1 do not support
# ndarray with lenght 2 as idx tuple.
rval.__setitem__(
tuple(idx),
value)
return rval
3
Example 4
Project: Outsmart Source File: outsmart.py
def random_terrain():
"""Return a randomized terrain"""
answer = np.ones((I_MAX+1, J_MAX+1))*100
for i, j in zip(nprand.random_integers(0, I_MAX, 8),
nprand.random_integers(0, J_MAX, 8)):
answer[i, j] = nprand.random_integers(2, 4)*100
answer[0, 0] += 1
return answer
3
Example 5
Project: scikit-beam Source File: test_fit2d_save.py
def test_save_output_fit2d():
filename = "function_values"
msk = np.random.random_integers(
0, 1, (np.random.random_integers(0, 200),
np.random.random_integers(0, 200))).astype(bool)
fit2d_save(msk, filename, dir_path=None)
msk2 = read_fit2d_msk(filename)
assert_array_equal(msk2, msk)
os.remove("function_values.msk")
3
Example 6
Project: bdot Source File: test_carray.py
@raises(ValueError)
def test_dot_incompatible_dtype():
matrix = np.random.random_integers(0, 12000, size=(10000, 100))
bcarray = bdot.carray(matrix, chunklen=2**13, cparams=bdot.cparams(clevel=2))
v = bcarray[0].astype('int32')
result = bcarray.dot(v)
3
Example 7
Project: msmtools Source File: test_bootstrapping.py
def validate_counts(self, ntraj, length, n, tau):
dtrajs = []
for i in range(ntraj):
dtrajs.append(np.random.random_integers(0, n-1, size=length))
for i in range(10):
C = msmest.bootstrap_counts(dtrajs, tau).toarray()
assert(np.shape(C) == (n, n))
assert(np.sum(C) == (ntraj*length) / tau)
3
Example 8
Project: python-matlab-bridge Source File: test_set_variable.py
def test_array_content(self):
test_array = np.random.random_integers(2, 20, (5, 10))
self.mlab.set_variable('test', test_array)
npt.assert_equal(self.mlab.get_variable('test'), test_array)
test_array = np.asfortranarray(test_array)
self.mlab.set_variable('test', test_array)
npt.assert_equal(self.mlab.get_variable('test'), test_array)
# force non-contiguous
test_array = test_array[::-1]
self.mlab.set_variable('test', test_array)
npt.assert_equal(self.mlab.get_variable('test'), test_array)
3
Example 9
Project: pandas-ml Source File: test_manifold.py
def test_spectral_embedding(self):
N = 10
m = np.random.random_integers(50, 200, size=(N, N))
m = (m + m.T) / 2
df = pdml.ModelFrame(m)
self.assert_numpy_array_almost_equal(df.data.values, m)
result = df.manifold.spectral_embedding(random_state=self.random_state)
expected = manifold.spectral_embedding(m, random_state=self.random_state)
self.assertIsInstance(result, pdml.ModelFrame)
self.assert_index_equal(result.index, df.index)
# signs can be inversed
self.assert_numpy_array_almost_equal(np.abs(result.data.values),
np.abs(expected))
3
Example 10
def create_random(self, size, range, symmetric=False):
"""Creates a random terrain map"""
ret = numpy.random.random_integers(0, range, size)
if symmetric:
ret = self.make_symmetric(ret)
return ret
3
Example 11
Project: dask Source File: test_linalg.py
def test_lu_errors():
A = np.random.random_integers(0, 10, (10, 10, 10))
dA = da.from_array(A, chunks=(5, 5, 5))
pytest.raises(ValueError, lambda: da.linalg.lu(dA))
A = np.random.random_integers(0, 10, (10, 8))
dA = da.from_array(A, chunks=(5, 4))
pytest.raises(ValueError, lambda: da.linalg.lu(dA))
A = np.random.random_integers(0, 10, (20, 20))
dA = da.from_array(A, chunks=(5, 4))
pytest.raises(ValueError, lambda: da.linalg.lu(dA))
3
Example 12
Project: eps-moea Source File: eps_moea.py
def archive_select(archive_marker):
"""Selects for breeding an individual from the archive. Currently selects
randomly.
Arguments:
archive_marker - a length-p boolean vector stating which of the population
is in the archive.
Returns:
the index in the population of the selected archive member.
"""
return N.where(archive_marker)[0][\
N.random.random_integers(0, archive_marker.sum() - 1)]
3
Example 13
Project: bdot Source File: test_carray.py
def test_dot_matrix_int64_unequal_chunklen():
matrix1 = np.random.random_integers(0, 120, size=(1000, 100))
bcarray1 = bdot.carray(matrix1, chunklen=2**9, cparams=bdot.cparams(clevel=2))
matrix2 = np.random.random_integers(0, 120, size=(1000, 100))
bcarray2 = bdot.carray(matrix2, chunklen=2**8, cparams=bdot.cparams(clevel=2))
result = bcarray1.dot(bcarray2)
expected = matrix1.dot(matrix2.T)
assert_array_equal(expected, result)
3
Example 14
Project: trees Source File: malware.py
def get_random_feature(self):
'Select a random feature and a random threshold'
rec_num, f_num = self.features.shape
fID = np.random.random_integers(0, f_num-1)
record = np.random.random_integers(0, rec_num-1)
value = self.features[record, fID]
return (fID, value)
3
Example 15
def test_perform(self):
x = tensor.lscalar()
f = function([x], self.op(x))
M = numpy.random.random_integers(3, 50, size=())
assert numpy.allclose(f(M), numpy.bartlett(M))
assert numpy.allclose(f(0), numpy.bartlett(0))
assert numpy.allclose(f(-1), numpy.bartlett(-1))
b = numpy.array([17], dtype='uint8')
assert numpy.allclose(f(b[0]), numpy.bartlett(b[0]))
3
Example 16
def setUp(self):
self.dim = 100
C = np.random.random_integers(0, 50, size=(self.dim, self.dim))
C = 0.5 * (C + np.transpose(C))
self.T = C / np.sum(C, axis=1)[:, np.newaxis]
"""Eigenvalues and left eigenvectors, sorted"""
v, L = eig(np.transpose(self.T))
ind = np.argsort(np.abs(v))[::-1]
v = v[ind]
L = L[:, ind]
"""Compute stationary distribution"""
self.mu = L[:, 0] / np.sum(L[:, 0])
pass
3
Example 17
Project: bdot Source File: benchmarks.py
def mem_matrix_2_18_vector_32(self):
matrix = np.random.random_integers(0, 120, size=(2 ** 18, 32))
bcarray = bdot.carray(matrix, chunklen=2**14, cparams=bdot.cparams(clevel=2))
v = bcarray[0]
output = bcarray.empty_like_dot(v)
result = bcarray.dot(v, out=output)
return result
3
Example 18
def generate_data(max_seq_length, batch_size, num_batches):
x = []
y = []
for i in range(num_batches):
# it's important to include sequences of different length in
# the training data in order the model was able to learn something
seq_length = random.randint(1, max_seq_length)
# each batch consists of sequences of equal length
# x_batch has shape (T, B, F=1)
x_batch = np.random.random_integers(0, 1, (seq_length, batch_size, 1))
# y_batch has shape (B, F=1)
y_batch = x_batch.sum(axis=(0,)) % 2
x.append(x_batch.astype(theano.config.floatX))
y.append(y_batch.astype(theano.config.floatX))
return {'x': x, 'y': y}
3
Example 19
Project: keras-rl Source File: memory.py
def sample_batch_indexes(low, high, size):
if high - low >= size:
# We have enough data. Draw without replacement, that is each index is unique in the
# batch. We cannot use `np.random.choice` here because it is horribly inefficient as
# the memory grows. See https://github.com/numpy/numpy/issues/2764 for a discussion.
# `random.sample` does the same thing (drawing without replacement) and is way faster.
try:
r = xrange(low, high)
except NameError:
r = range(low, high)
batch_idxs = random.sample(r, size)
else:
# Not enough data. Help ourselves with sampling from the range, but the same index
# can occur multiple times. This is not good and should be avoided by picking a
# large enough warm-up phase.
warnings.warn('Not enough entries to sample without replacement. Consider increasing your warm-up phase to avoid oversampling!')
batch_idxs = np.random.random_integers(low, high - 1, size=size)
assert len(batch_idxs) == size
return batch_idxs
3
Example 20
def test_spectral_clustering(self):
N = 50
m = np.random.random_integers(1, 200, size=(N, N))
m = (m + m.T) / 2
df = pdml.ModelFrame(m)
result = df.cluster.spectral_clustering(random_state=self.random_state)
expected = cluster.spectral_clustering(m, random_state=self.random_state)
self.assertIsInstance(result, pdml.ModelSeries)
self.assert_index_equal(result.index, df.index)
self.assert_numpy_array_equal(result.values, expected)
3
Example 21
Project: pele Source File: bhpt.py
def tryExchange(self):
k = np.random.random_integers( 0, self.nreplicas - 2)
print "trying exchange", k, k+1
deltaE = self.replicas[k].markovE - self.replicas[k+1].markovE
deltabeta = 1./self.replicas[k].temperature - 1./self.replicas[k+1].temperature
w = min( 1. , np.exp( deltaE * deltabeta ) )
rand = np.random.rand()
if w > rand:
#accept step
print "accepting exchange ", k, k+1, w, rand
E1 = self.replicas[k].markovE
coords1 = copy.copy( self.replicas[k].coords )
self.replicas[k].markovE = self.replicas[k+1].markovE
self.replicas[k].coords = copy.copy( self.replicas[k+1].coords )
self.replicas[k+1].markovE = E1
self.replicas[k+1].coords = coords1
else:
print "rejecting exchange ", k, k+1, w, rand
3
Example 22
Project: deep_recommend_system Source File: generate_testdata.py
def WriteImageSeries(writer, tag, n_images=1):
"""Write a few dummy images to writer."""
step = 0
session = tf.Session()
p = tf.placeholder("uint8", (1, 4, 4, 3))
s = tf.image_summary(tag, p)
for _ in xrange(n_images):
im = np.random.random_integers(0, 255, (1, 4, 4, 3))
summ = session.run(s, feed_dict={p: im})
writer.add_summary(summ, step)
step += 20
session.close()
3
Example 23
Project: nupic Source File: sp_plotter.py
def getRandomWithMods(inputSpace, maxChanges):
""" Returns a random selection from the inputSpace with randomly modified
up to maxChanges number of bits.
"""
size = len(inputSpace)
ind = np.random.random_integers(0, size-1, 1)[0]
value = copy.deepcopy(inputSpace[ind])
if maxChanges == 0:
return value
return modifyBits(value, maxChanges)
3
Example 24
Project: bdot Source File: test_carray.py
def test_dot_int64():
matrix = np.random.random_integers(0, 12000, size=(10000, 100))
bcarray = bdot.carray(matrix, chunklen=2**13, cparams=bdot.cparams(clevel=2))
v = bcarray[0]
result = bcarray.dot(v)
expected = matrix.dot(v)
assert_array_equal(expected, result)
3
Example 25
Project: lstm-anomaly-detect Source File: lstm-synthetic-wave-anomaly-detect.py
def dropin(X, y):
""" The name suggests the inverse of dropout, i.e. adding more samples. See Data Augmentation section at
http://simaaron.github.io/Estimating-rainfall-from-weather-radar-readings-using-recurrent-neural-networks/
:param X: Each row is a training sequence
:param y: Tne target we train and will later predict
:return: new augmented X, y
"""
print("X shape:", X.shape)
print("y shape:", y.shape)
X_hat = []
y_hat = []
for i in range(0, len(X)):
for j in range(0, np.random.random_integers(0, random_data_dup)):
X_hat.append(X[i, :])
y_hat.append(y[i])
return np.asarray(X_hat), np.asarray(y_hat)
3
Example 26
Project: APGL Source File: SparseGraphProfile.py
def profileSparseMatrices(self):
A = numpy.random.random_integers(0, 1, (1000, 1000))
#W = scipy.sparse.csr_matrix(A)
W = scipy.sparse.coo_matrix(A)
#W.sort_indices()
#Results: lil_matrix has the fastest row operations but very slow column ones
#csr_matrix has fast-ish row operations and slightly slower column ones
#csc_matrix is the opposite
def getRows():
for i in range(W.shape[0]):
W.getrow(i).getnnz()
#W.tocsc()
#for i in range(W.shape[0]):
# W.getcol(i).getnnz()
ProfileUtils.profile('getRows()', globals(), locals())
3
Example 27
Project: kaggle-cifar Source File: data.py
def get_next_batch(self):
epoch, batchnum = self.curr_epoch, self.curr_batchnum
self.advance_batch()
data = rand(self.num_cases, self.get_data_dims()).astype(n.single) # <--changed to rand
labels = n.require(n.c_[random_integers(0,self.num_classes-1,self.num_cases)], requirements='C', dtype=n.single)
return self.curr_epoch, self.curr_batchnum, {'data':data, 'labels':labels}
3
Example 28
Project: bdot Source File: test_carray.py
def test_dot_matrix_int64():
matrix = np.random.random_integers(0, 120, size=(1000, 100))
bcarray1 = bdot.carray(matrix, chunklen=2**9, cparams=bdot.cparams(clevel=2))
bcarray2 = bdot.carray(matrix, chunklen=2**9, cparams=bdot.cparams(clevel=2))
result = bcarray1.dot(bcarray2)
expected = matrix.dot(matrix.T)
assert_array_equal(expected, result)
3
Example 29
Project: dask Source File: test_linalg.py
def test_solve_triangular_errors():
A = np.random.random_integers(0, 10, (10, 10, 10))
b = np.random.random_integers(1, 10, 10)
dA = da.from_array(A, chunks=(5, 5, 5))
db = da.from_array(b, chunks=5)
pytest.raises(ValueError, lambda: da.linalg.solve_triangular(dA, db))
A = np.random.random_integers(0, 10, (10, 10))
b = np.random.random_integers(1, 10, 10)
dA = da.from_array(A, chunks=(3, 3))
db = da.from_array(b, chunks=5)
pytest.raises(ValueError, lambda: da.linalg.solve_triangular(dA, db))
3
Example 30
def getPair(self):
i=0
j=i
while i == j:
i,j = np.random.random_integers(0,self.nreps-1,2)
return i,j
3
Example 31
Project: mayavi Source File: test_mlab_integration.py
def test_imshow_colormap(self):
# Check if the pipeline is refreshed when we change colormap.
# See issue #262
a = np.random.random_integers(0, 10, (100, 100))
actor = mlab.imshow(a, colormap="cool")
with self.assertTraitChanges(actor, 'pipeline_changed'):
actor.module_manager.scalar_lut_manager.lut_mode = 'jet'
3
Example 32
Project: bdot Source File: test_carray.py
def test_dot_matrix_int64_unequal_length():
matrix1 = np.random.random_integers(0, 120, size=(1000, 100))
bcarray1 = bdot.carray(matrix1, chunklen=2**9, cparams=bdot.cparams(clevel=2))
matrix2 = np.random.random_integers(0, 120, size=(10000, 100))
bcarray2 = bdot.carray(matrix2, chunklen=2**10, cparams=bdot.cparams(clevel=2))
result = bcarray1.dot(bcarray2)
expected = matrix1.dot(matrix2.T)
assert_array_equal(expected, result)
3
Example 33
def next(self):
if self.batch_count >= self.num_batches:
raise StopIteration()
else:
self.last = np.random.random_integers(low=0,
high=self.num_samples - 1,
size=(self.batch_size,))
self.batch_count += 1
return self.X[self.last, :, :, :], self.y[self.last]
3
Example 34
Project: chainer Source File: test_array.py
def _convert_array(xs, array_module):
if array_module == 'all_numpy':
return xs
elif array_module == 'all_cupy':
return cupy.asarray(xs)
else:
return [cupy.asarray(x) if numpy.random.random_integers(0, 1)
else x for x in xs]
3
Example 35
def setUp(self):
self.dim = 100
C = np.random.random_integers(0, 50, size=(self.dim, self.dim))
C = 0.5 * (C + np.transpose(C))
self.T = C / np.sum(C, axis=1)[:, np.newaxis]
"""Eigenvalues and left eigenvectors, sorted"""
v, L = eig(np.transpose(self.T))
ind = np.argsort(np.abs(v))[::-1]
v = v[ind]
L = L[:, ind]
"""Compute stationary distribution"""
self.mu = L[:, 0] / np.sum(L[:, 0])
3
Example 36
Project: bdot Source File: benchmarks.py
def time_matrix_2_18_vector_32(self):
matrix = np.random.random_integers(0, 120, size=(2 ** 18, 32))
bcarray = bdot.carray(matrix, chunklen=2**14, cparams=bdot.cparams(clevel=2))
v = bcarray[0]
output = bcarray.empty_like_dot(v)
result = bcarray.dot(v, out=output)
3
Example 37
Project: msmtools Source File: bootstrapping.py
def bootstrap_counts_singletraj(dtraj, lagtime, n):
"""
Samples n counts at the given lagtime from the given trajectory
"""
# check if length is sufficient
L = len(dtraj)
if (lagtime > L):
raise ValueError(
'Cannot sample counts with lagtime ' + str(lagtime) + ' from a trajectory with length ' + str(L))
# sample
I = np.random.random_integers(0, L - lagtime - 1, size=n)
J = I + lagtime
# return state pairs
return (dtraj[I], dtraj[J])
3
Example 38
def test_infer_shape(self):
x = tensor.lscalar()
self._compile_and_check([x], [self.op(x)],
[numpy.random.random_integers(3, 50, size=())],
self.op_class)
self._compile_and_check([x], [self.op(x)], [0], self.op_class)
self._compile_and_check([x], [self.op(x)], [1], self.op_class)
3
Example 39
Project: pele Source File: ptmc.py
def tryExchangePar(self):
#choose which pair to try and exchange
k = np.random.random_integers( 0, self.nreplicas - 2)
#print "trying exchange", k, k+1
#determine if the exchange will be accepted
E1, T1 = self.getRepEnergyT(k)
E2, T2 = self.getRepEnergyT(k+1)
deltaE = E1 - E2
deltabeta = 1./T1 - 1./T2
w = min( 1. , np.exp( deltaE * deltabeta ) )
rand = np.random.rand()
if w > rand:
#accept exchange
self.ex_outstream.write("accepting exchange %d %d %g %g %g %g %d\n" % (k, k+1, E1, E2, T1, T2, self.step_num) )
self.doExchangePar(k, k+1)
3
Example 40
Project: pele Source File: ptmc.py
def tryExchangeNoParallel(self):
#choose which pair to try and exchange
k = np.random.random_integers( 0, self.nreplicas - 2)
#print "trying exchange", k, k+1
#determine if the exchange will be accepted
deltaE = self.replicas[k].markovE - self.replicas[k+1].markovE
deltabeta = 1./self.replicas[k].temperature - 1./self.replicas[k+1].temperature
w = min( 1. , np.exp( deltaE * deltabeta ) )
rand = np.random.rand()
if w > rand:
#accept step
self.ex_outstream.write("accepting exchange %d %d %g %g\n" % (k, k+1, w, rand) )
self.doExchangePar(k, k+1)
3
Example 41
Project: bdot Source File: test_carray.py
def test_dot_matrix_1_int64():
matrix = np.random.random_integers(0, 120, size=(10000, 100))
bcarray = bdot.carray(matrix, chunklen=2**13, cparams=bdot.cparams(clevel=2))
v = bcarray[0]
output = bcarray.empty_like_dot(v)
result = bcarray.dot(v, out=output)
expected = matrix.dot(v)
assert_array_equal(expected, result)
3
Example 42
Project: BitcoinTradingAlgorithmToolkit Source File: genetic.py
def rand_gene():
ri = np.random.random_integers
g = gene_type()
ind = [0]*len(g)
for i in xrange( len(g)):
if g[i] == bool:
ind[i] = ri(0,1)
elif g[i] == int:
ind[i] = ri(1,50)
return ind
0
Example 43
Project: qutip Source File: mcsolve_f90.py
def run(self):
if debug:
print(inspect.stack()[0][3])
from numpy.random import random_integers
if (config.c_num == 0):
# force one trajectory if no collapse operators
config.ntraj = 1
self.ntraj = 1
# Set unravel_type to 1 to integrate without collapses
self.unravel_type = 1
if (config.e_num == 0):
# If we are returning states, and there are no
# collapse operators, set average_states to False to return
# ket vectors instead of density matrices
config.options.average_states = False
# generate a random seed, useful if e.g. running with MPI
self.seed = random_integers(1e8)
if (self.serial_run):
# run in serial
sols = self.serial()
else:
# run in paralell
sols = self.parallel()
# gather data
self.sol = _gather(sols)
0
Example 44
Project: pebl Source File: base.py
def _alter_network_randomly_and_score(self):
net = self.evaluator.network
n_nodes = self.data.variables.size
max_attempts = n_nodes**2
# continue making changes and undoing them till we get an acyclic network
for i in xrange(max_attempts):
node1, node2 = N.random.random_integers(0, n_nodes-1, 2)
if (node1, node2) in net.edges:
# node1 -> node2 exists, so reverse it.
add,remove = [(node2, node1)], [(node1, node2)]
elif (node2, node1) in net.edges:
# node2 -> node1 exists, so remove it
add,remove = [], [(node2, node1)]
else:
# node1 and node2 unconnected, so connect them
add,remove = [(node1, node2)], []
try:
score = self.evaluator.alter_network(add=add, remove=remove)
except evaluator.CyclicNetworkError:
continue # let's try again!
else:
if add and remove:
self.reverse += 1
elif add:
self.add += 1
else:
self.remove += 1
return score
# Could not find a valid network
raise CannotAlterNetworkException()
0
Example 45
Project: pytango Source File: PowerSupplyDS.py
@DebugIt()
def read_noise(self):
return numpy.random.random_integers(1000, size=(100, 100))
0
Example 46
Project: deep_recommend_system Source File: gmm_ops_test.py
@staticmethod
def make_data_from_centers(num_vectors, centers):
"""Generates 2-dimensional data with random centers.
Args:
num_vectors: number of training examples.
centers: a list of random 2-dimensional centers.
Returns:
A tuple containing the data as a numpy array and the cluster ids.
"""
vectors = []
classes = []
for _ in xrange(num_vectors):
current_class = np.random.random_integers(0, len(centers) - 1)
vectors.append([np.random.normal(centers[current_class][0],
np.random.random_sample()),
np.random.normal(centers[current_class][1],
np.random.random_sample())])
classes.append(current_class)
return np.asarray(vectors), len(centers)
0
Example 47
Project: rootpy Source File: test_plot_contour_matrix.py
def random_symm(n):
a = np.random.random_integers(-10, 10, size=(n, n))
return (a + a.T) / 2
0
Example 48
def generate_image(image_shape, image_format='jpeg', label=0):
"""Generates an image and an example containing the encoded image.
GenerateImage must be called within an active session.
Args:
image_shape: the shape of the image to generate.
image_format: the encoding format of the image.
label: the int64 labels for the image.
Returns:
image: the generated image.
example: a TF-example with a feature key 'image/encoded' set to the
serialized image and a feature key 'image/format' set to the image
encoding format ['jpeg', 'png'].
"""
image = np.random.random_integers(0, 255, size=image_shape)
tf_encoded = _encoder(image, image_format)
example = tf.train.Example(features=tf.train.Features(feature={
'image/encoded': _encoded_bytes_feature(tf_encoded),
'image/format': _string_feature(image_format),
'image/class/label': _encoded_int64_feature(np.array(label)),
}))
return image, example.SerializeToString()
0
Example 49
Project: deep_recommend_system Source File: generate_testdata.py
def WriteAudioSeries(writer, tag, n_audio=1):
"""Write a few dummy audio clips to writer."""
step = 0
session = tf.Session()
min_frequency_hz = 440
max_frequency_hz = 880
sample_rate = 4000
duration_frames = sample_rate * 0.5 # 0.5 seconds.
frequencies_per_run = 1
num_channels = 2
p = tf.placeholder("float32", (frequencies_per_run, duration_frames,
num_channels))
s = tf.audio_summary(tag, p, sample_rate)
for _ in xrange(n_audio):
# Generate a different frequency for each channel to show stereo works.
frequencies = np.random.random_integers(
min_frequency_hz, max_frequency_hz,
size=(frequencies_per_run, num_channels))
tiled_frequencies = np.tile(frequencies, (1, duration_frames))
tiled_increments = np.tile(
np.arange(0, duration_frames), (num_channels, 1)).T.reshape(
1, duration_frames * num_channels)
tones = np.sin(2.0 * np.pi * tiled_frequencies * tiled_increments /
sample_rate)
tones = tones.reshape(frequencies_per_run, duration_frames, num_channels)
summ = session.run(s, feed_dict={p: tones})
writer.add_summary(summ, step)
step += 20
session.close()
0
Example 50
Project: mnist-helper Source File: mnist_helpers.py
def elastic_transform(image, kernel_dim=13, sigma=6, alpha=36, negated=False):
"""
This method performs elastic transformations on an image by convolving
with a gaussian kernel.
NOTE: Image dimensions should be a sqaure image
:param image: the input image
:type image: a numpy nd array
:param kernel_dim: dimension(1-D) of the gaussian kernel
:type kernel_dim: int
:param sigma: standard deviation of the kernel
:type sigma: float
:param alpha: a multiplicative factor for image after convolution
:type alpha: float
:param negated: a flag indicating whether the image is negated or not
:type negated: boolean
:returns: a nd array transformed image
"""
# convert the image to single channel if it is multi channel one
if image.ndim == 3:
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# check if the image is a negated one
if not negated:
image = 255-image
# check if the image is a square one
if image.shape[0] != image.shape[1]:
raise ValueError("Image should be of sqaure form")
# check if kernel dimesnion is odd
if kernel_dim % 2 == 0:
raise ValueError("Kernel dimension should be odd")
# create an empty image
result = numpy.zeros(image.shape)
# create random displacement fields
displacement_field_x = numpy.array([[random_integers(-1, 1) for x in xrange(image.shape[0])] \
for y in xrange(image.shape[1])]) * alpha
displacement_field_y = numpy.array([[random_integers(-1, 1) for x in xrange(image.shape[0])] \
for y in xrange(image.shape[1])]) * alpha
# create the gaussian kernel
kernel = create_2d_gaussian(kernel_dim, sigma)
# convolve the fields with the gaussian kernel
displacement_field_x = convolve2d(displacement_field_x, kernel)
displacement_field_y = convolve2d(displacement_field_y, kernel)
# make the distortrd image by averaging each pixel value to the neighbouring
# four pixels based on displacement fields
for row in xrange(image.shape[1]):
for col in xrange(image.shape[0]):
low_ii = row + int(math.floor(displacement_field_x[row, col]))
high_ii = row + int(math.ceil(displacement_field_x[row, col]))
low_jj = col + int(math.floor(displacement_field_y[row, col]))
high_jj = col + int(math.ceil(displacement_field_y[row, col]))
if low_ii < 0 or low_jj < 0 or high_ii >= image.shape[1] -1 \
or high_jj >= image.shape[0] - 1:
continue
res = image[low_ii, low_jj]/4 + image[low_ii, high_jj]/4 + \
image[high_ii, low_jj]/4 + image[high_ii, high_jj]/4
result[row, col] = res
# if the input image was not negated, make the output image also a non
# negated one
if not negated:
result = 255-result
return result