我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.random.randn()。
def __init__(self): super(TestWindow, self).__init__() # generate random data points cc = 0.2*2 self.data = np.array(.1*rdn.randn(1000,2),dtype=np.float32) # initialize the GL widget self.widget = GLPlotWidget() self.widget.set_data(self.data) # put the window at the screen position (100, 100) self.setGeometry(100, 100, self.widget.width, self.widget.height) self.setCentralWidget(self.widget) self.show() # create the Qt App and window
def initialize_vectors(self): self.vec2e = np.zeros(len(self.vocab_e), dtype=np.int) for i in range(len(self.vocab_e)): w = self.vocab_e[i] self.e2vec[w] = i self.vec2e[i] = i #randomize and normalize the initial vector self.vec_e = RD.randn(len(self.vocab_e), self.dim) for i in range(len(self.vec_e)): self.vec_e[i] /= LA.norm(self.vec_e[i]) self.vec2r = np.zeros(len(self.vocab_r), dtype=np.int) for i in range(len(self.vocab_r)): w = self.vocab_r[i] #randomize and normalize the initial vector self.r2vec[w] = i self.vec2r[i] = i self.vec_r = RD.randn(len(self.vocab_r), self.dim) for i in range(len(self.vec_r)): self.vec_r[i] /= LA.norm(self.vec_r[i]) print "Initialized vectors for all entities and relations." #GD of h + r - t
def test_errors(self): x = np.random.randn(1, 2, 3) assert_raises_regex(ValueError, 'invalid axis .* `source`', np.moveaxis, x, 3, 0) assert_raises_regex(ValueError, 'invalid axis .* `source`', np.moveaxis, x, -4, 0) assert_raises_regex(ValueError, 'invalid axis .* `destination`', np.moveaxis, x, 0, 5) assert_raises_regex(ValueError, 'repeated axis in `source`', np.moveaxis, x, [0, 0], [0, 1]) assert_raises_regex(ValueError, 'repeated axis in `destination`', np.moveaxis, x, [0, 1], [1, 1]) assert_raises_regex(ValueError, 'must have the same number', np.moveaxis, x, 0, [0, 1]) assert_raises_regex(ValueError, 'must have the same number', np.moveaxis, x, [0, 1], [0])
def test_returns(self, seed_value, window_length): returns = Returns(window_length=window_length) today = datetime64(1, 'ns') assets = arange(3) out = empty((3,), dtype=float) seed(seed_value) # Seed so we get deterministic results. test_data = abs(randn(window_length, 3)) # Calculate the expected returns expected = (test_data[-1] - test_data[0]) / test_data[0] out = empty((3,), dtype=float) returns.compute(today, assets, out, test_data) check_allclose(expected, out)
def test_identity_module(self): """ identity module should preserve input """ with IsolatedSession() as issn: pred_input = tf.placeholder(tf.float32, [None, None]) final_output = tf.identity(pred_input, name='output') gfn = issn.asGraphFunction([pred_input], [final_output]) for _ in range(10): m, n = prng.randint(10, 1000, size=2) mat = prng.randn(m, n).astype(np.float32) with IsolatedSession() as issn: feeds, fetches = issn.importGraphFunction(gfn) mat_out = issn.run(fetches[0], {feeds[0]: mat}) self.assertTrue(np.all(mat_out == mat))
def test_predictor_output_transform(): predictor = Predictor( inputs=[NumericInput(dim=30, name="x")], outputs=[ Output( name="y", dim=1, activation="sigmoid", transform=log, inverse_transform=exp)], dense_layer_sizes=[30], dense_activation="relu") y = predictor.predict({"x": randn(10, 30)})["y"] eq_(len(y), 10) # make sure transformed outputs are within given bounds assert exp(0.0) <= y.min() <= exp(1.0) assert exp(0.0) <= y.max() <= exp(1.0)
def test_getter(): def fun(input_dict): A = np.sum(input_dict['item_1']) B = np.sum(input_dict['item_2']) C = np.sum(input_dict['item_2']) return A + B + C d_fun = grad(fun) input_dict = {'item_1' : npr.randn(5, 6), 'item_2' : npr.randn(4, 3), 'item_X' : npr.randn(2, 4)} result = d_fun(input_dict) assert np.allclose(result['item_1'], np.ones((5, 6))) assert np.allclose(result['item_2'], 2 * np.ones((4, 3))) assert np.allclose(result['item_X'], np.zeros((2, 4)))
def test_grads(): def fun(input_dict): A = np.sum(np.sin(input_dict['item_1'])) B = np.sum(np.cos(input_dict['item_2'])) return A + B def d_fun(input_dict): g = grad(fun)(input_dict) A = np.sum(g['item_1']) B = np.sum(np.sin(g['item_1'])) C = np.sum(np.sin(g['item_2'])) return A + B + C input_dict = {'item_1' : npr.randn(5, 6), 'item_2' : npr.randn(4, 3), 'item_X' : npr.randn(2, 4)} check_grads(fun, input_dict) check_grads(d_fun, input_dict)
def test_getter(): def fun(input_list): A = np.sum(input_list[0]) B = np.sum(input_list[1]) C = np.sum(input_list[1]) return A + B + C d_fun = grad(fun) input_list = [npr.randn(5, 6), npr.randn(4, 3), npr.randn(2, 4)] result = d_fun(input_list) assert np.allclose(result[0], np.ones((5, 6))) assert np.allclose(result[1], 2 * np.ones((4, 3))) assert np.allclose(result[2], np.zeros((2, 4)))
def test_grads(): def fun(input_list): A = np.sum(np.sin(input_list[0])) B = np.sum(np.cos(input_list[1])) return A + B def d_fun(input_list): g = grad(fun)(input_list) A = np.sum(g[0]) B = np.sum(np.sin(g[0])) C = np.sum(np.sin(g[1])) return A + B + C input_list = [npr.randn(5, 6), npr.randn(4, 3), npr.randn(2, 4)] check_grads(fun, input_list) check_grads(d_fun, input_list)
def addOUNoise(a, epsilon): """Adds noise from an Ornstein Uhlenbeck process to the actions""" def ou_func(x, mu, theta, sigma): return theta * (mu - x) + sigma * randn(1) a_new = np.zeros(np.shape(a)) noise = np.zeros(np.shape(a)) noise[0] = (max(epsilon, 0) * ou_func(a[0], 0.0, 0.60, 0.30)) noise[1] = (max(epsilon, 0) * ou_func(a[1], 0.5, 1.00, 0.10)) noise[2] = (max(epsilon, 0) * ou_func(a[2], -0.1, 1.00, 0.10)) a_new[0] = a[0] + noise[0] a_new[1] = a[1] + noise[1] a_new[2] = a[2] + noise[2] return a_new
def GetRadar(dt): """ Simulate radar range to object at 1K altidue and moving at 100m/s. Adds about 5% measurement noise. Returns slant range to the object. Call once for each new measurement at dt time from last call. """ if not hasattr (GetRadar, "posp"): GetRadar.posp = 0 if GetRadar.posp > 10: vel = 0; else: vel = 100 + .5 * randn() alt = 1000 + 10 * randn() pos = GetRadar.posp + vel*dt v = 0 + pos* 0.05*randn() slant_range = math.sqrt (pos**2 + alt**2) + v GetRadar.posp = pos return slant_range
def gen(self, n_samples=1, u=None): """ Generate samples. :param n_samples: number of samples :param u: random numbers to use in generating samples; if None, new random numbers are drawn :return: samples """ x = rng.randn(n_samples, self.n_inputs).astype(dtype) if u is None else u if getattr(self, 'batch_norm', False): for layer, bn in izip(self.layers[::-1], self.bns[::-1]): x = bn.eval_inv(x) x = layer.eval_forward(x) else: for layer in self.layers[::-1]: x = layer.eval_forward(x) return x
def gen(self, x, n_samples=1, u=None): """ Generate samples conditioned on x. :param x: numpy vector to condition on :param n_samples: number of samples :param u: random numbers to use in generating samples; if None, new random numbers are drawn :return: samples """ xx = np.tile(x, [n_samples, 1]) y = rng.randn(n_samples, self.n_outputs).astype(dtype) if u is None else u if getattr(self, 'batch_norm', False): for layer, bn in izip(self.layers[::-1], self.bns[::-1]): y = bn.eval_inv(y) y = layer.eval_forward(xx, y) else: for layer in self.layers[::-1]: y = layer.eval_forward(xx, y) return y
def gen(self, n_samples=1, u=None): """ Generate samples from made. Requires as many evaluations as number of inputs. :param n_samples: number of samples :param u: random numbers to use in generating samples; if None, new random numbers are drawn :return: samples """ x = np.zeros([n_samples, self.n_inputs], dtype=dtype) u = rng.randn(n_samples, self.n_inputs).astype(dtype) if u is None else u for i in xrange(1, self.n_inputs + 1): m, logp = self.eval_comps(x) idx = np.argwhere(self.input_order == i)[0, 0] x[:, idx] = m[:, idx] + np.exp(np.minimum(-0.5 * logp[:, idx], 10.0)) * u[:, idx] return x
def gen(self, n_samples=1, u=None): """ Generate samples from made. Requires as many evaluations as number of inputs. :param n_samples: number of samples :param u: random numbers to use in generating samples; if None, new random numbers are drawn :return: samples """ x = np.zeros([n_samples, self.n_inputs], dtype=dtype) u = rng.randn(n_samples, self.n_inputs).astype(dtype) if u is None else u for i in xrange(1, self.n_inputs + 1): m, logp, loga = self.eval_comps(x) idx = np.argwhere(self.input_order == i)[0, 0] for n in xrange(n_samples): z = util.discrete_sample(np.exp(loga[n, idx]))[0] x[n, idx] = m[n, idx, z] + np.exp(np.minimum(-0.5 * logp[n, idx, z], 10.0)) * u[n, idx] return x
def gen(self, x, n_samples=1, u=None): """ Generate samples from made conditioned on x. Requires as many evaluations as number of outputs. :param x: input vector :param n_samples: number of samples :param u: random numbers to use in generating samples; if None, new random numbers are drawn :return: samples """ y = np.zeros([n_samples, self.n_outputs], dtype=dtype) u = rng.randn(n_samples, self.n_outputs).astype(dtype) if u is None else u xy = (np.tile(x, [n_samples, 1]), y) for i in xrange(1, self.n_outputs + 1): m, logp = self.eval_comps(xy) idx = np.argwhere(self.output_order == i)[0, 0] y[:, idx] = m[:, idx] + np.exp(np.minimum(-0.5 * logp[:, idx], 10.0)) * u[:, idx] return y
def gen(self, x, n_samples=1, u=None): """ Generate samples from made conditioned on x. Requires as many evaluations as number of outputs. :param x: input vector :param n_samples: number of samples :param u: random numbers to use in generating samples; if None, new random numbers are drawn :return: samples """ y = np.zeros([n_samples, self.n_outputs], dtype=dtype) u = rng.randn(n_samples, self.n_outputs).astype(dtype) if u is None else u xy = (np.tile(x, [n_samples, 1]), y) for i in xrange(1, self.n_outputs + 1): m, logp, loga = self.eval_comps(xy) idx = np.argwhere(self.output_order == i)[0, 0] for n in xrange(n_samples): z = util.discrete_sample(np.exp(loga[n, idx]))[0] y[n, idx] = m[n, idx, z] + np.exp(np.minimum(-0.5 * logp[n, idx, z], 10.0)) * u[n, idx] return y
def gen(self, x, n_samples=1, u=None): """ Generate samples, by propagating random numbers through each made, after conditioning on input x. :param x: input vector :param n_samples: number of samples :param u: random numbers to use in generating samples; if None, new random numbers are drawn :return: samples """ y = rng.randn(n_samples, self.n_outputs).astype(dtype) if u is None else u if getattr(self, 'batch_norm', False): for made, bn in izip(self.mades[::-1], self.bns[::-1]): y = bn.eval_inv(y) y = made.gen(x, n_samples, y) else: for made in self.mades[::-1]: y = made.gen(x, n_samples, y) return y
def test_np(): npr.seed(0) nx, nineq, neq = 4, 6, 7 Q = npr.randn(nx, nx) G = npr.randn(nineq, nx) A = npr.randn(neq, nx) D = np.diag(npr.rand(nineq)) K_ = np.bmat(( (Q, np.zeros((nx, nineq)), G.T, A.T), (np.zeros((nineq, nx)), D, np.eye(nineq), np.zeros((nineq, neq))), (G, np.eye(nineq), np.zeros((nineq, nineq + neq))), (A, np.zeros((neq, nineq + nineq + neq))) )) K = block(( (Q, 0, G.T, A.T), (0, D, 'I', 0), (G, 'I', 0, 0), (A, 0, 0, 0) )) assert np.allclose(K_, K)
def test_series_negate(self): expr = self.ex('-') # float lhs = Series(randn(5)) expect = -lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) assert_series_equal(expect, result) # int lhs = Series(randint(5, size=5)) expect = -lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) assert_series_equal(expect, result) # bool doesn't work with numexpr but works elsewhere lhs = Series(rand(5) > 0.5) if self.engine == 'numexpr': with tm.assertRaises(NotImplementedError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: expect = -lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) assert_series_equal(expect, result)
def test_index_duplicate_periods(self): # monotonic idx = PeriodIndex([2000, 2007, 2007, 2009, 2009], freq='A-JUN') ts = Series(np.random.randn(len(idx)), index=idx) result = ts[2007] expected = ts[1:3] assert_series_equal(result, expected) result[:] = 1 self.assertTrue((ts[1:3] == 1).all()) # not monotonic idx = PeriodIndex([2000, 2007, 2007, 2009, 2007], freq='A-JUN') ts = Series(np.random.randn(len(idx)), index=idx) result = ts[2007] expected = ts[idx == 2007] assert_series_equal(result, expected)
def test_align_series(self): rng = period_range('1/1/2000', '1/1/2010', freq='A') ts = Series(np.random.randn(len(rng)), index=rng) result = ts + ts[::2] expected = ts + ts expected[1::2] = np.nan assert_series_equal(result, expected) result = ts + _permute(ts[::2]) assert_series_equal(result, expected) # it works! for kind in ['inner', 'outer', 'left', 'right']: ts.align(ts[::2], join=kind) msg = "Input has different freq=D from PeriodIndex\\(freq=A-DEC\\)" with assertRaisesRegexp(ValueError, msg): ts + ts.asfreq('D', how="end")
def test_repr_truncation(self): max_len = 20 with option_context("display.max_colwidth", max_len): df = DataFrame({'A': np.random.randn(10), 'B': [tm.rands(np.random.randint( max_len - 1, max_len + 1)) for i in range(10) ]}) r = repr(df) r = r[r.find('\n') + 1:] adj = fmt._get_adjustment() for line, value in lzip(r.split('\n'), df['B']): if adj.len(value) + 1 > max_len: self.assertIn('...', line) else: self.assertNotIn('...', line) with option_context("display.max_colwidth", 999999): self.assertNotIn('...', repr(df)) with option_context("display.max_colwidth", max_len + 2): self.assertNotIn('...', repr(df))
def test_repr_html_long_multiindex(self): max_rows = get_option('display.max_rows') max_L1 = max_rows // 2 tuples = list(itertools.product(np.arange(max_L1), ['foo', 'bar'])) idx = MultiIndex.from_tuples(tuples, names=['first', 'second']) df = DataFrame(np.random.randn(max_L1 * 2, 2), index=idx, columns=['A', 'B']) reg_repr = df._repr_html_() assert '...' not in reg_repr tuples = list(itertools.product(np.arange(max_L1 + 1), ['foo', 'bar'])) idx = MultiIndex.from_tuples(tuples, names=['first', 'second']) df = DataFrame(np.random.randn((max_L1 + 1) * 2, 2), index=idx, columns=['A', 'B']) long_repr = df._repr_html_() assert '...' in long_repr
def test_scatter_plot_legacy(self): tm._skip_if_no_scipy() df = DataFrame(randn(100, 2)) def scat(**kwds): return plotting.scatter_matrix(df, **kwds) _check_plot_works(scat) _check_plot_works(scat, marker='+') _check_plot_works(scat, vmin=0) if _ok_for_gaussian_kde('kde'): _check_plot_works(scat, diagonal='kde') if _ok_for_gaussian_kde('density'): _check_plot_works(scat, diagonal='density') _check_plot_works(scat, diagonal='hist') _check_plot_works(scat, range_padding=.1) def scat2(x, y, by=None, ax=None, figsize=None): return plotting.scatter_plot(df, x, y, by, ax, figsize=None) _check_plot_works(scat2, x=0, y=1) grouper = Series(np.repeat([1, 2, 3, 4, 5], 20), df.index) _check_plot_works(scat2, x=0, y=1, by=grouper)
def test_getitem(self): # slicing sl = self.frame[:20] self.assertEqual(20, len(sl.index)) # column access for _, series in compat.iteritems(sl): self.assertEqual(20, len(series.index)) self.assertTrue(tm.equalContents(series.index, sl.index)) for key, _ in compat.iteritems(self.frame._series): self.assertIsNotNone(self.frame[key]) self.assertNotIn('random', self.frame) with assertRaisesRegexp(KeyError, 'random'): self.frame['random'] df = self.frame.copy() df['$10'] = randn(len(df)) ad = randn(len(df)) df['@awesome_domain'] = ad self.assertRaises(KeyError, df.__getitem__, 'df["$10"]') res = df['@awesome_domain'] assert_numpy_array_equal(ad, res.values)
def test_getitem_ix_mixed_integer(self): df = DataFrame(np.random.randn(4, 3), index=[1, 10, 'C', 'E'], columns=[1, 2, 3]) result = df.ix[:-1] expected = df.ix[df.index[:-1]] assert_frame_equal(result, expected) result = df.ix[[1, 10]] expected = df.ix[Index([1, 10], dtype=object)] assert_frame_equal(result, expected) # 11320 df = pd.DataFrame({"rna": (1.5, 2.2, 3.2, 4.5), -1000: [11, 21, 36, 40], 0: [10, 22, 43, 34], 1000: [0, 10, 20, 30]}, columns=['rna', -1000, 0, 1000]) result = df[[1000]] expected = df.iloc[:, [3]] assert_frame_equal(result, expected) result = df[[-1000]] expected = df.iloc[:, [1]] assert_frame_equal(result, expected)
def test_getitem_setitem_ix_negative_integers(self): result = self.frame.ix[:, -1] assert_series_equal(result, self.frame['D']) result = self.frame.ix[:, [-1]] assert_frame_equal(result, self.frame[['D']]) result = self.frame.ix[:, [-1, -2]] assert_frame_equal(result, self.frame[['D', 'C']]) self.frame.ix[:, [-1]] = 0 self.assertTrue((self.frame['D'] == 0).all()) df = DataFrame(np.random.randn(8, 4)) self.assertTrue(isnull(df.ix[:, [-1]].values).all()) # #1942 a = DataFrame(randn(20, 2), index=[chr(x + 65) for x in range(20)]) a.ix[-1] = a.ix[-2] assert_series_equal(a.ix[-1], a.ix[-2], check_names=False) self.assertEqual(a.ix[-1].name, 'T') self.assertEqual(a.ix[-2].name, 'S')
def test_getitem_setitem_integer_slice_keyerrors(self): df = DataFrame(np.random.randn(10, 5), index=lrange(0, 20, 2)) # this is OK cp = df.copy() cp.ix[4:10] = 0 self.assertTrue((cp.ix[4:10] == 0).values.all()) # so is this cp = df.copy() cp.ix[3:11] = 0 self.assertTrue((cp.ix[3:11] == 0).values.all()) result = df.ix[4:10] result2 = df.ix[3:11] expected = df.reindex([4, 6, 8, 10]) assert_frame_equal(result, expected) assert_frame_equal(result2, expected) # non-monotonic, raise KeyError df2 = df.iloc[lrange(5) + lrange(5, 10)[::-1]] self.assertRaises(KeyError, df2.ix.__getitem__, slice(3, 11)) self.assertRaises(KeyError, df2.ix.__setitem__, slice(3, 11), 0)
def test_fancy_setitem_int_labels(self): # integer index defers to label-based indexing df = DataFrame(np.random.randn(10, 5), index=np.arange(0, 20, 2)) tmp = df.copy() exp = df.copy() tmp.ix[[0, 2, 4]] = 5 exp.values[:3] = 5 assert_frame_equal(tmp, exp) tmp = df.copy() exp = df.copy() tmp.ix[6] = 5 exp.values[3] = 5 assert_frame_equal(tmp, exp) tmp = df.copy() exp = df.copy() tmp.ix[:, 2] = 5 # tmp correctly sets the dtype # so match the exp way exp[2] = 5 assert_frame_equal(tmp, exp)
def test_fancy_getitem_int_labels(self): df = DataFrame(np.random.randn(10, 5), index=np.arange(0, 20, 2)) result = df.ix[[4, 2, 0], [2, 0]] expected = df.reindex(index=[4, 2, 0], columns=[2, 0]) assert_frame_equal(result, expected) result = df.ix[[4, 2, 0]] expected = df.reindex(index=[4, 2, 0]) assert_frame_equal(result, expected) result = df.ix[4] expected = df.xs(4) assert_series_equal(result, expected) result = df.ix[:, 3] expected = df[3] assert_series_equal(result, expected)
def test_fancy_index_int_labels_exceptions(self): df = DataFrame(np.random.randn(10, 5), index=np.arange(0, 20, 2)) # labels that aren't contained self.assertRaises(KeyError, df.ix.__setitem__, ([0, 1, 2], [2, 3, 4]), 5) # try to set indices not contained in frame self.assertRaises(KeyError, self.frame.ix.__setitem__, ['foo', 'bar', 'baz'], 1) self.assertRaises(KeyError, self.frame.ix.__setitem__, (slice(None, None), ['E']), 1) # partial setting now allows this GH2578 # self.assertRaises(KeyError, # self.frame.ix.__setitem__, # (slice(None, None), 'E'), 1)
def test_ix_frame_align(self): b = DataFrame(np.random.randn(3, 4)) df_orig = DataFrame(randn(10, 4)) df = df_orig.copy() df.ix[:3] = b out = b.ix[:3] assert_frame_equal(out, b) b.sort_index(inplace=True) df = df_orig.copy() df.ix[[0, 1, 2]] = b out = df.ix[[0, 1, 2]].reindex(b.index) assert_frame_equal(out, b) df = df_orig.copy() df.ix[:3] = b out = df.ix[:3] assert_frame_equal(out, b.reindex(out.index))
def test_theta_0(): rng.seed(0) n_samples = 100 Y = rng.randn(n_samples, 5) X = rng.randn(n_samples, 5) sgcrf = SparseGaussianCRF(lamL=0.01, lamT=0.01) sgcrf.fit(X, Y) assert np.allclose(sgcrf.Lam, np.eye(5), .1, .2)
def test_rsi(self, seed_value, expected): rsi = RSI() today = datetime64(1, 'ns') assets = arange(3) out = empty((3,), dtype=float) seed(seed_value) # Seed so we get deterministic results. test_data = abs(randn(15, 3)) out = empty((3,), dtype=float) rsi.compute(today, assets, out, test_data) check_allclose(expected, out)
def test_masked_rankdata_2d(self, seed_value, method, use_mask, set_missing, ascending): eyemask = ~eye(5, dtype=bool) nomask = ones((5, 5), dtype=bool) seed(seed_value) asfloat = (randn(5, 5) * seed_value) asdatetime = (asfloat).copy().view('datetime64[ns]') mask = eyemask if use_mask else nomask if set_missing: asfloat[:, 2] = nan asdatetime[:, 2] = NaTns float_result = masked_rankdata_2d( data=asfloat, mask=mask, missing_value=nan, method=method, ascending=True, ) datetime_result = masked_rankdata_2d( data=asdatetime, mask=mask, missing_value=NaTns, method=method, ascending=True, ) check_arrays(float_result, datetime_result)
def randn_data(self, seed, shape): """ Build a block of testing data from numpy.random.randn. """ random_seed(seed) return randn(*shape)
def sample_v_given_h(self, h, eps=1e-5): mean_v = self.mean_v.eval(feed_dict={self.hidden: h}) if not self.beta_sampling: rnds = np.random.randn(mean_v.shape[0], mean_v.shape[1]).astype(h.dtype) return np.clip(mean_v + rnds * self.sigma, eps, 1. - eps) mvvm = mean_v * (1 - mean_v) var_v = np.fmin(mvvm, self.sigma**2) operand = (mvvm + 1.5 * eps) / (var_v + eps) - 1 alpha = mean_v * operand + eps beta = (1 - mean_v) * operand + eps return np.random.beta(alpha, beta).astype(h.dtype)
def sample_h_given_v(self, v, eps=1e-5): mean_h = self.mean_h.eval(feed_dict={self.visible: v}) if not self.beta_sampling: rnds = np.random.randn(mean_h.shape[0], mean_h.shape[1]).astype(v.dtype) return np.clip(mean_h + rnds * self.sigma, eps, 1. - eps) mhhm = mean_h * (1 - mean_h) # Handle the cases where h is close to 0.0 or 1.0 # Normally beta distribution will give a sample close to 0.0 or 1.0, # breaking requirement that there be some variation (sample dispersion # close to 0.0 when it ought to be close to self.sigma). small_h = self.sigma**2 > mhhm small_count = np.sum(small_h) if small_count: # We randomize these cases with probability self.sigma. switch = np.random.rand(small_count) < self.sigma if np.sum(switch): mean_h[small_h][switch] = np.random.rand(np.sum(switch)) mhhm = mean_h * (1 - mean_h) var_h = np.fmin(mhhm, self.sigma**2) operand = (mhhm + 1.5 * eps) / (var_h + eps) - 1 alpha = mean_h * operand + eps beta = (1 - mean_h) * operand + eps return np.random.beta(alpha, beta).astype(v.dtype)
def train_feed(self, data): """Return feed_dict based on data to be used for training.""" return {self.train_args[0]: data, self.train_args[1]: randn(data.shape[0], self.n_z)}
def cost_args(self, data): """Return args to self.cost() for given dataset.""" return [data, randn(data.shape[0], self.n_z)]
def noise(self): x = self.state dx = self.theta * (self.mu - x) + self.sigma * nr.randn(len(x)) self.state = x + dx return self.state
def _generate_data(self, n, m): return randn(n, m)
def _generate_data_complex(self, n, m): return randn(n, m) + 1.j * rand(n, m)
def _generate_flt_data(self, n, m): return (randn(n, m)).astype(np.float32)
def _generate_non_native_data(self, n, m): data = randn(n, m) data = self._neg_byteorder(data) assert_(not data.dtype.isnative) return data
def test_move_to_end(self): x = np.random.randn(5, 6, 7) for source, expected in [(0, (6, 7, 5)), (1, (5, 7, 6)), (2, (5, 6, 7)), (-1, (5, 6, 7))]: actual = np.moveaxis(x, source, -1).shape assert_(actual, expected)