當前位置: 首頁>>代碼示例>>Python>>正文


Python numpy.ravel方法代碼示例

本文整理匯總了Python中numpy.ravel方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.ravel方法的具體用法?Python numpy.ravel怎麽用?Python numpy.ravel使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在numpy的用法示例。


在下文中一共展示了numpy.ravel方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: prediction

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def prediction(self, input_data='', mode='test_data'):

        prediction = {}
        vote = []

        for model in self.models:

            prediction = model.prediction(input_data, mode)
            vote.append(prediction['prediction'])

        prediction_return = max(set(vote), key=vote.count)

        if mode == 'future_data':
            data = input_data.split()
            input_data_x = [float(v) for v in data]
            input_data_x = np.ravel(input_data_x)
            return {"input_data_x": input_data_x, "input_data_y": None, "prediction": prediction_return}
        else:
            data = input_data.split()
            input_data_x = [float(v) for v in data[:-1]]
            input_data_x = np.ravel(input_data_x)
            input_data_y = float(data[-1])
            return {"input_data_x": input_data_x, "input_data_y": input_data_y, "prediction": prediction_return} 
開發者ID:fukuball,項目名稱:fuku-ml,代碼行數:25,代碼來源:Blending.py

示例2: test_knn

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def test_knn(datasets_dimred, genes, labels, idx, distr, xlabels):
    knns = [ 5, 10, 50, 100 ]
    len_distr = len(distr)
    for knn in knns:
        integrated = assemble(datasets_dimred[:], knn=knn, sigma=150)
        X = np.concatenate(integrated)
        distr.append(sil(X[idx, :], labels[idx]))
        for d in distr[:len_distr]:
            print(ttest_ind(np.ravel(X[idx, :]), np.ravel(d)))
        xlabels.append(str(knn))
    print('')
    
    plt.figure()
    plt.boxplot(distr, showmeans=True, whis='range')
    plt.xticks(range(1, len(xlabels) + 1), xlabels)
    plt.ylabel('Silhouette Coefficient')
    plt.ylim((-1, 1))
    plt.savefig('param_sensitivity_{}.svg'.format('knn')) 
開發者ID:brianhie,項目名稱:scanorama,代碼行數:20,代碼來源:param_sensitivity.py

示例3: test_sigma

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def test_sigma(datasets_dimred, genes, labels, idx, distr, xlabels):
    sigmas = [ 10, 50, 100, 200 ]
    len_distr = len(distr)
    for sigma in sigmas:
        integrated = assemble(datasets_dimred[:], sigma=sigma)
        X = np.concatenate(integrated)
        distr.append(sil(X[idx, :], labels[idx]))
        for d in distr[:len_distr]:
            print(ttest_ind(np.ravel(X[idx, :]), np.ravel(d)))
        xlabels.append(str(sigma))
    print('')
    
    plt.figure()
    plt.boxplot(distr, showmeans=True, whis='range')
    plt.xticks(range(1, len(xlabels) + 1), xlabels)
    plt.ylabel('Silhouette Coefficient')
    plt.ylim((-1, 1))
    plt.savefig('param_sensitivity_{}.svg'.format('sigma')) 
開發者ID:brianhie,項目名稱:scanorama,代碼行數:20,代碼來源:param_sensitivity.py

示例4: test_alpha

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def test_alpha(datasets_dimred, genes, labels, idx, distr, xlabels):
    alphas = [ 0, 0.05, 0.20, 0.50 ]
    len_distr = len(distr)
    for alpha in alphas:
        integrated = assemble(datasets_dimred[:], alpha=alpha, sigma=150)
        X = np.concatenate(integrated)
        distr.append(sil(X[idx, :], labels[idx]))
        for d in distr[:len_distr]:
            print(ttest_ind(np.ravel(X[idx, :]), np.ravel(d)))
        xlabels.append(str(alpha))
    print('')
    
    plt.figure()
    plt.boxplot(distr, showmeans=True, whis='range')
    plt.xticks(range(1, len(xlabels) + 1), xlabels)
    plt.ylabel('Silhouette Coefficient')
    plt.ylim((-1, 1))
    plt.savefig('param_sensitivity_{}.svg'.format('alpha')) 
開發者ID:brianhie,項目名稱:scanorama,代碼行數:20,代碼來源:param_sensitivity.py

示例5: test_approx

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def test_approx(datasets_dimred, genes, labels, idx, distr, xlabels):
    integrated = assemble(datasets_dimred[:], approx=False, sigma=150)
    X = np.concatenate(integrated)
    distr.append(sil(X[idx, :], labels[idx]))
    len_distr = len(distr)
    for d in distr[:len_distr]:
        print(ttest_ind(np.ravel(X[idx, :]), np.ravel(d)))
    xlabels.append('Exact NN')
    print('')
    
    plt.figure()
    plt.boxplot(distr, showmeans=True, whis='range')
    plt.xticks(range(1, len(xlabels) + 1), xlabels)
    plt.ylabel('Silhouette Coefficient')
    plt.ylim((-1, 1))
    plt.savefig('param_sensitivity_{}.svg'.format('approx')) 
開發者ID:brianhie,項目名稱:scanorama,代碼行數:18,代碼來源:param_sensitivity.py

示例6: test_perplexity

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def test_perplexity(datasets_dimred, genes, labels, idx,
                    distr, xlabels):
    X = np.concatenate(datasets_dimred)

    perplexities = [ 10, 100, 500, 2000 ]
    len_distr = len(distr)
    for perplexity in perplexities:
        embedding = fit_tsne(X, perplexity=perplexity)
        distr.append(sil(embedding[idx, :], labels[idx]))
        for d in distr[:len_distr]:
            print(ttest_ind(np.ravel(X[idx, :]), np.ravel(d)))
        xlabels.append(str(perplexity))
    print('')
    
    plt.figure()
    plt.boxplot(distr, showmeans=True, whis='range')
    plt.xticks(range(1, len(xlabels) + 1), xlabels)
    plt.ylabel('Silhouette Coefficient')
    plt.ylim((-1, 1))
    plt.savefig('param_sensitivity_{}.svg'.format('perplexity')) 
開發者ID:brianhie,項目名稱:scanorama,代碼行數:22,代碼來源:param_sensitivity.py

示例7: kernel_qchem_inter_rf_pos_neg

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def kernel_qchem_inter_rf_pos_neg(self, **kw):
    """ This is constructing the E_m-E_n and E_n-E_m matrices """
    h_rpa = diagflat(concatenate((ravel(self.FmE),-ravel(self.FmE))))
    print(h_rpa.shape)

    nf = self.nfermi[0]
    nv = self.norbs-self.vstart[0]
    vs = self.vstart[0]
    neh = nf*nv
    x = self.mo_coeff[0,0,:,:,0]
    pab2v = self.pb.get_ac_vertex_array()
    self.pmn2v = pmn2v = einsum('nb,pmb->pmn', x[:nf,:], einsum('ma,pab->pmb', x[vs:,:], pab2v))
    pmn2c = einsum('qp,pmn->qmn', self.hkernel_den, pmn2v)
    meri = einsum('pmn,pik->mnik', pmn2c, pmn2v).reshape((nf*nv,nf*nv))
    #print(meri.shape)
    #meri.fill(0.0)
    h_rpa[:neh, :neh] = h_rpa[:neh, :neh]+meri
    h_rpa[:neh, neh:] = h_rpa[:neh, neh:]+meri
    h_rpa[neh:, :neh] = h_rpa[neh:, :neh]-meri
    h_rpa[neh:, neh:] = h_rpa[neh:, neh:]-meri
    edif, s2z = np.linalg.eig(h_rpa)
    print(abs(h_rpa-h_rpa.transpose()).sum())
    print('edif', edif.real*27.2114)
    
    return 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:27,代碼來源:qchem_inter_rf.py

示例8: test_big_cell

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def test_big_cell():
    import time

    a = 1
    ncell = (2, 2, 2)
    Lvecs = np.diag(ncell) * a
    unit_cell = np.zeros((4, 3))
    unit_cell[1:] = (np.ones((3, 3)) - np.eye(3)) * a / 2

    grid = np.meshgrid(*map(np.arange, ncell), indexing="ij")
    shifts = np.stack(list(map(np.ravel, grid)), axis=1)
    supercell = (shifts[:, np.newaxis] + unit_cell[np.newaxis]).reshape(1, -1, 3)

    configs = supercell.repeat(1000, axis=0)
    configs += np.random.randn(*configs.shape) * 0.1

    df = run(Lvecs, configs, 8)
    df = df.groupby("qmag").mean().reset_index()

    large_q = df[-35:-10]["Sq"]
    mean = np.mean(large_q - 1)
    rms = np.sqrt(np.mean((large_q - 1) ** 2))
    assert np.abs(mean) < 0.01, mean
    assert rms < 0.1, rms 
開發者ID:WagnerGroup,項目名稱:pyqmc,代碼行數:26,代碼來源:test_sq.py

示例9: __init__

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def __init__(self, qlist=None, Lvecs=None, nq=4):
        """
        Inputs:
            qlist: (n, 3) array-like. If qlist is provided, Lvecs and nq are ignored
            Lvecs: (3, 3) array-like of lattice vectors. Required if qlist is None
            nq: int, if qlist is nonzero, use a uniform grid of shape (nq, nq, nq)
        """
        if qlist is not None:
            self.qlist = qlist
        else:
            assert (
                Lvecs is not None
            ), "need to provide either list of q vectors or lattice vectors"
            Gvecs = np.linalg.inv(Lvecs).T * 2 * np.pi
            qvecs = list(map(np.ravel, np.meshgrid(*[np.arange(nq)] * 3)))
            qvecs = np.stack(qvecs, axis=1)
            self.qlist = np.dot(qvecs, Gvecs) 
開發者ID:WagnerGroup,項目名稱:pyqmc,代碼行數:19,代碼來源:accumulators.py

示例10: __call__

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def __call__(self, transform_xy, x1, y1, x2, y2):
        x_, y_ = np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny)
        x, y = np.meshgrid(x_, y_)
        lon, lat = transform_xy(np.ravel(x), np.ravel(y))

        with np.errstate(invalid='ignore'):
            if self.lon_cycle is not None:
                lon0 = np.nanmin(lon)
                # Changed from 180 to 360 to be able to span only
                # 90-270 (left hand side)
                lon -= 360. * ((lon - lon0) > 360.)
            if self.lat_cycle is not None:
                lat0 = np.nanmin(lat)
                # Changed from 180 to 360 to be able to span only
                # 90-270 (left hand side)
                lat -= 360. * ((lat - lat0) > 360.)

        lon_min, lon_max = np.nanmin(lon), np.nanmax(lon)
        lat_min, lat_max = np.nanmin(lat), np.nanmax(lat)

        lon_min, lon_max, lat_min, lat_max = \
            self._adjust_extremes(lon_min, lon_max, lat_min, lat_max)

        return lon_min, lon_max, lat_min, lat_max 
開發者ID:python-control,項目名稱:python-control,代碼行數:26,代碼來源:grid.py

示例11: block2row

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def block2row(array, row, folder, block_id=None):
    if array.shape[0] == windowSize:
        # Parameters	
        name_string = str(block_id[0] + 1)
        m,n = array.shape
        u = m + 1 - windowSize
        v = n + 1 - windowSize

    	# Get Starting block indices
        start_idx = np.arange(u)[:,None]*n + np.arange(v)

    	# Get offsetted indices across the height and width of input array
        offset_idx = np.arange(windowSize)[:,None]*n + np.arange(windowSize)

    	# Get all actual indices & index into input array for final output
        flat_array = np.take(array,start_idx.ravel()[:,None] + offset_idx.ravel())

        # Save to (dask) array in .zarr format
        file_name = path + folder + name_string + 'r' + row + '.zarr'
        zarr.save(file_name, flat_array)
    
    return array


# Divide an image in overlapping blocks 
開發者ID:nmileva,項目名稱:starfm4py,代碼行數:27,代碼來源:starfm4py.py

示例12: test_minmax_func

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def test_minmax_func(self):
        # Tests minimum and maximum.
        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
        # max doesn't work if shaped
        xr = np.ravel(x)
        xmr = ravel(xm)
        # following are true because of careful selection of data
        assert_equal(max(xr), maximum.reduce(xmr))
        assert_equal(min(xr), minimum.reduce(xmr))

        assert_equal(minimum([1, 2, 3], [4, 0, 9]), [1, 0, 3])
        assert_equal(maximum([1, 2, 3], [4, 0, 9]), [4, 2, 9])
        x = arange(5)
        y = arange(5) - 2
        x[3] = masked
        y[0] = masked
        assert_equal(minimum(x, y), where(less(x, y), x, y))
        assert_equal(maximum(x, y), where(greater(x, y), x, y))
        assert_(minimum.reduce(x) == 0)
        assert_(maximum.reduce(x) == 4)

        x = arange(4).reshape(2, 2)
        x[-1, -1] = masked
        assert_equal(maximum.reduce(x, axis=None), 2) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:26,代碼來源:test_core.py

示例13: test_ravel

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def test_ravel(self):
        # Tests ravel
        a = array([[1, 2, 3, 4, 5]], mask=[[0, 1, 0, 0, 0]])
        aravel = a.ravel()
        assert_equal(aravel._mask.shape, aravel.shape)
        a = array([0, 0], mask=[1, 1])
        aravel = a.ravel()
        assert_equal(aravel._mask.shape, a.shape)
        # Checks that small_mask is preserved
        a = array([1, 2, 3, 4], mask=[0, 0, 0, 0], shrink=False)
        assert_equal(a.ravel()._mask, [0, 0, 0, 0])
        # Test that the fill_value is preserved
        a.fill_value = -99
        a.shape = (2, 2)
        ar = a.ravel()
        assert_equal(ar._mask, [0, 0, 0, 0])
        assert_equal(ar._data, [1, 2, 3, 4])
        assert_equal(ar.fill_value, -99)
        # Test index ordering
        assert_equal(a.ravel(order='C'), [1, 2, 3, 4])
        assert_equal(a.ravel(order='F'), [1, 3, 2, 4]) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:23,代碼來源:test_core.py

示例14: _update_diagnostics

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def _update_diagnostics(state, diagnostics):
    # Update logscore.
    cc_logscore = diagnostics.get('logscore', np.array([]))
    new_logscore = map(float, np.ravel(cc_logscore).tolist())
    state.diagnostics['logscore'].extend(new_logscore)

    # Update column_crp_alpha.
    cc_column_crp_alpha = diagnostics.get('column_crp_alpha', [])
    new_column_crp_alpha = map(float, np.ravel(cc_column_crp_alpha).tolist())
    state.diagnostics['column_crp_alpha'].extend(list(new_column_crp_alpha))

    # Update column_partition.
    def convert_column_partition(assignments):
        return [
            (col, int(assgn))
            for col, assgn in zip(state.outputs, assignments)
        ]
    new_column_partition = diagnostics.get('column_partition_assignments', [])
    if len(new_column_partition) > 0:
        assert len(new_column_partition) == len(state.outputs)
        trajectories = np.transpose(new_column_partition)[0].tolist()
        state.diagnostics['column_partition'].extend(
            map(convert_column_partition, trajectories)) 
開發者ID:probcomp,項目名稱:cgpm,代碼行數:25,代碼來源:lovecat.py

示例15: _check_transformer_output

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ravel [as 別名]
def _check_transformer_output(transformer, dataset, expected):
    """
    Given a transformer and a spark dataset, check if the transformer
    produces the expected results.
    """
    analyzed_df = tfs.analyze(dataset)
    out_df = transformer.transform(analyzed_df)

    # Collect transformed values
    out_colnames = list(_output_mapping.values())
    _results = []
    for row in out_df.select(out_colnames).collect():
        curr_res = [row[colname] for colname in out_colnames]
        _results.append(np.ravel(curr_res))
    out_tgt = np.hstack(_results)

    _err_msg = 'not close => shape {} != {}, max_diff {} > {}'
    max_diff = np.max(np.abs(expected - out_tgt))
    err_msg = _err_msg.format(expected.shape, out_tgt.shape,
                              max_diff, _all_close_tolerance)
    assert np.allclose(expected, out_tgt, atol=_all_close_tolerance), err_msg 
開發者ID:databricks,項目名稱:spark-deep-learning,代碼行數:23,代碼來源:tf_transformer_test.py


注:本文中的numpy.ravel方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。