Python numpy.vstack() Examples

The following are 30 code examples of numpy.vstack(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: BDA.py    From transferlearning with MIT License 7 votes vote down vote up
def proxy_a_distance(source_X, target_X):
    """
    Compute the Proxy-A-Distance of a source/target representation
    """
    nb_source = np.shape(source_X)[0]
    nb_target = np.shape(target_X)[0]

    train_X = np.vstack((source_X, target_X))
    train_Y = np.hstack((np.zeros(nb_source, dtype=int),
                         np.ones(nb_target, dtype=int)))

    clf = svm.LinearSVC(random_state=0)
    clf.fit(train_X, train_Y)
    y_pred = clf.predict(train_X)
    error = metrics.mean_absolute_error(train_Y, y_pred)
    dist = 2 * (1 - 2 * error)
    return dist 
Example #2
Source File: snippets.py    From Collaborative-Learning-for-Weakly-Supervised-Object-Detection with MIT License 6 votes vote down vote up
def generate_anchors_pre(height, width, feat_stride, anchor_scales=(8,16,32), anchor_ratios=(0.5,1,2)):
  """ A wrapper function to generate anchors given different scales
    Also return the number of anchors in variable 'length'
  """
  anchors = generate_anchors(ratios=np.array(anchor_ratios), scales=np.array(anchor_scales))
  A = anchors.shape[0]
  shift_x = np.arange(0, width) * feat_stride
  shift_y = np.arange(0, height) * feat_stride
  shift_x, shift_y = np.meshgrid(shift_x, shift_y)
  shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose()
  K = shifts.shape[0]
  # width changes faster, so here it is H, W, C
  anchors = anchors.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2))
  anchors = anchors.reshape((K * A, 4)).astype(np.float32, copy=False)
  length = np.int32(anchors.shape[0])

  return anchors, length 
Example #3
Source File: tools_fri_doa_plane.py    From FRIDA with MIT License 6 votes vote down vote up
def mtx_updated_G(phi_recon, M, mtx_amp2visi_ri, mtx_fri2visi_ri):
    """
    Update the linear transformation matrix that links the FRI sequence to the
    visibilities by using the reconstructed Dirac locations.
    :param phi_recon: the reconstructed Dirac locations (azimuths)
    :param M: the Fourier series expansion is between -M to M
    :param p_mic_x: a vector that contains microphones' x-coordinates
    :param p_mic_y: a vector that contains microphones' y-coordinates
    :param mtx_freq2visi: the linear mapping from Fourier series to visibilities
    :return:
    """
    L = 2 * M + 1
    ms_half = np.reshape(np.arange(-M, 1, step=1), (-1, 1), order='F')
    phi_recon = np.reshape(phi_recon, (1, -1), order='F')
    mtx_amp2freq = np.exp(-1j * ms_half * phi_recon)  # size: (M + 1) x K
    mtx_amp2freq_ri = np.vstack((mtx_amp2freq.real, mtx_amp2freq.imag[:-1, :]))  # size: (2M + 1) x K
    mtx_fri2amp_ri = linalg.lstsq(mtx_amp2freq_ri, np.eye(L))[0]
    # projection mtx_freq2visi to the null space of mtx_fri2amp
    mtx_null_proj = np.eye(L) - np.dot(mtx_fri2amp_ri.T,
                                       linalg.lstsq(mtx_fri2amp_ri.T, np.eye(L))[0])
    G_updated = np.dot(mtx_amp2visi_ri, mtx_fri2amp_ri) + \
                np.dot(mtx_fri2visi_ri, mtx_null_proj)
    return G_updated 
Example #4
Source File: images.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def image_reslice(image, spec, method=None, fill=0, dtype=None, weights=None, image_type=None):
    '''
    image_reslice(image, spec) yields a duplicate of the given image resliced to have the voxels
      indicated by the given image spec. Note that spec may be an image itself.

    Optional arguments that can be passed to image_interpolate() (asside from affine) are allowed
    here and are passed through.
    '''
    if image_type is None and is_image(image): image_type = to_image_type(image)
    spec = to_image_spec(spec)
    image = to_image(image)
    # we make a big mesh and interpolate at these points...
    imsh = spec['image_shape']
    (args, kw) = ([np.arange(n) for n in imsh[:3]], {'indexing': 'ij'})
    ijk = np.asarray([u.flatten() for u in np.meshgrid(*args, **kw)])
    ijk = np.dot(spec['affine'], np.vstack([ijk, np.ones([1,ijk.shape[1]])]))[:3]
    # interpolate here...
    u = image_interpolate(image, ijk, method=method, fill=fill, dtype=dtype, weights=weights)
    return to_image((np.reshape(u, imsh), spec), image_type=image_type) 
Example #5
Source File: core.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def apply_affine(aff, coords):
    '''
    apply_affine(affine, coords) yields the result of applying the given affine transformation to
      the given coordinate or coordinates.

    This function expects coords to be a (dims X n) matrix but if the first dimension is neither 2
    nor 3, coords.T is used; i.e.:
      apply_affine(affine3x3, coords2xN) ==> newcoords2xN
      apply_affine(affine4x4, coords3xN) ==> newcoords3xN
      apply_affine(affine3x3, coordsNx2) ==> newcoordsNx2 (for N != 2)
      apply_affine(affine4x4, coordsNx3) ==> newcoordsNx3 (for N != 3)
    '''
    if aff is None: return coords
    (coords,tr) = (np.asanyarray(coords), False)
    if len(coords.shape) == 1: return np.squeeze(apply_affine(np.reshape(coords, (-1,1)), aff))
    elif len(coords.shape) > 2: raise ValueError('cannot apply affine to ND-array for N > 2')
    if   len(coords) == 2: aff = to_affine(aff, 2)
    elif len(coords) == 3: aff = to_affine(aff, 3)
    else: (coords,aff,tr) = (coords.T, to_affine(aff, coords.shape[1]), True)
    r = np.dot(aff, np.vstack([coords, np.ones([1,coords.shape[1]])]))[:-1]
    return r.T if tr else r 
Example #6
Source File: core.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def subcurve(self, t0, t1):
        '''
        curve.subcurve(t0, t1) yields a curve-spline object that is equivalent to the given
          curve but that extends from curve(t0) to curve(t1) only.
        '''
        # if t1 is less than t0, then we want to actually do this in reverse...
        if t1 == t0: raise ValueError('Cannot take subcurve of a point')
        if t1 < t0:
            tt = self.curve_length()
            return self.reverse().subcurve(tt - t0, tt - t1)
        idx = [ii for (ii,t) in enumerate(self.t) if t0 < t and t < t1]
        pt0 = self(t0)
        pt1 = self(t1)
        coords = np.vstack([[pt0], self.coordinates.T[idx], [pt1]])
        ts = np.concatenate([[t0], self.t[idx], [t1]])
        dists  = None if self.distances is None else np.diff(ts)
        return CurveSpline(
            coords.T,
            order=self.order,
            smoothing=self.smoothing,
            periodic=False,
            distances=dists,
            meta_data=self.meta_data) 
Example #7
Source File: datasets.py    From discomll with Apache License 2.0 6 votes vote down vote up
def breastcancer_cont(replication=2):
    f = open(path + "breast_cancer_wisconsin_cont.txt", "r")
    data = np.loadtxt(f, delimiter=",", dtype=np.string0)
    x_train = np.array(data[:, range(0, 9)])
    y_train = np.array(data[:, 9])
    for j in range(replication - 1):
        x_train = np.vstack([x_train, data[:, range(0, 9)]])
        y_train = np.hstack([y_train, data[:, 9]])
    x_train = np.array(x_train, dtype=np.float)

    f = open(path + "breast_cancer_wisconsin_cont_test.txt")
    data = np.loadtxt(f, delimiter=",", dtype=np.string0)
    x_test = np.array(data[:, range(0, 9)])
    y_test = np.array(data[:, 9])
    for j in range(replication - 1):
        x_test = np.vstack([x_test, data[:, range(0, 9)]])
        y_test = np.hstack([y_test, data[:, 9]])
    x_test = np.array(x_test, dtype=np.float)

    return x_train, y_train, x_test, y_test 
Example #8
Source File: datasets.py    From discomll with Apache License 2.0 6 votes vote down vote up
def breastcancer_disc(replication=2):
    f = open(path + "breast_cancer_wisconsin_disc.txt")
    data = np.loadtxt(f, delimiter=",")
    x_train = data[:, range(1, 10)]
    y_train = data[:, 10]
    for j in range(replication - 1):
        x_train = np.vstack([x_train, data[:, range(1, 10)]])
        y_train = np.hstack([y_train, data[:, 10]])

    f = open(path + "breast_cancer_wisconsin_disc_test.txt")
    data = np.loadtxt(f, delimiter=",")
    x_test = data[:, range(1, 10)]
    y_test = data[:, 10]
    for j in range(replication - 1):
        x_test = np.vstack([x_test, data[:, range(1, 10)]])
        y_test = np.hstack([y_test, data[:, 10]])

    return x_train, y_train, x_test, y_test 
Example #9
Source File: datasets.py    From discomll with Apache License 2.0 6 votes vote down vote up
def iris(replication=2):
    f = open(path + "iris.txt")
    data = np.loadtxt(f, delimiter=",", dtype=np.string0)
    x_train = np.array(data[:, range(0, 4)], dtype=np.float)
    y_train = data[:, 4]

    for j in range(replication - 1):
        x_train = np.vstack([x_train, data[:, range(0, 4)]])
        y_train = np.hstack([y_train, data[:, 4]])
    x_train = np.array(x_train, dtype=np.float)

    f = open(path + "iris_test.txt")
    data = np.loadtxt(f, delimiter=",", dtype=np.string0)
    x_test = np.array(data[:, range(0, 4)], dtype=np.float)
    y_test = data[:, 4]

    for j in range(replication - 1):
        x_test = np.vstack([x_test, data[:, range(0, 4)]])
        y_test = np.hstack([y_test, data[:, 4]])
    x_test = np.array(x_test, dtype=np.float)

    return x_train, y_train, x_test, y_test 
Example #10
Source File: datasets.py    From discomll with Apache License 2.0 6 votes vote down vote up
def regression_data():
    f = open(path + "regression_data1.txt")
    data = np.loadtxt(f, delimiter=",")
    x1 = np.insert(data[:, 0].reshape(len(data), 1), 0, np.ones(len(data)), axis=1)
    y1 = data[:, 1]
    f = open(path + "regression_data2.txt")
    data = np.loadtxt(f, delimiter=",")
    x2 = np.insert(data[:, 0].reshape(len(data), 1), 0, np.ones(len(data)), axis=1)
    y2 = data[:, 1]
    x1 = np.vstack((x1, x2))
    y1 = np.hstack((y1, y2))

    f = open(path + "regression_data_test1.txt")
    data = np.loadtxt(f, delimiter=",")
    x1_test = np.insert(data[:, 0].reshape(len(data), 1), 0, np.ones(len(data)), axis=1)
    y1_test = data[:, 1]
    f = open(path + "regression_data_test2.txt")
    data = np.loadtxt(f, delimiter=",")
    x2_test = np.insert(data[:, 0].reshape(len(data), 1), 0, np.ones(len(data)), axis=1)
    y2_test = data[:, 1]
    x1_test = np.vstack((x1_test, x2_test))
    y1_test = np.hstack((y1_test, y2_test))
    return x1, y1, x1_test, y1_test 
Example #11
Source File: datasets.py    From discomll with Apache License 2.0 6 votes vote down vote up
def ex3(replication=2):
    f = open(path + "ex3.txt")
    train_data = np.loadtxt(f, delimiter=",")
    f = open(path + "ex3_test.txt")
    test_data = np.loadtxt(f, delimiter=",")

    x_train = np.insert(train_data[:, (0, 1)], 0, np.ones(len(train_data)), axis=1)
    y_train = train_data[:, 2]
    x_test = np.insert(test_data[:, (0, 1)], 0, np.ones(len(test_data)), axis=1)
    y_test = test_data[:, 2]

    for i in range(replication - 1):
        x_train = np.vstack((x_train, np.insert(train_data[:, (0, 1)], 0, np.ones(len(train_data)), axis=1)))
        y_train = np.hstack((y_train, train_data[:, 2]))

        x_test = np.vstack((x_test, np.insert(test_data[:, (0, 1)], 0, np.ones(len(test_data)), axis=1)))
        y_test = np.hstack((y_test, test_data[:, 2]))

    return x_train, y_train, x_test, y_test 
Example #12
Source File: TCA.py    From transferlearning with MIT License 6 votes vote down vote up
def fit(self, Xs, Xt):
        '''
        Transform Xs and Xt
        :param Xs: ns * n_feature, source feature
        :param Xt: nt * n_feature, target feature
        :return: Xs_new and Xt_new after TCA
        '''
        X = np.hstack((Xs.T, Xt.T))
        X /= np.linalg.norm(X, axis=0)
        m, n = X.shape
        ns, nt = len(Xs), len(Xt)
        e = np.vstack((1 / ns * np.ones((ns, 1)), -1 / nt * np.ones((nt, 1))))
        M = e * e.T
        M = M / np.linalg.norm(M, 'fro')
        H = np.eye(n) - 1 / n * np.ones((n, n))
        K = kernel(self.kernel_type, X, None, gamma=self.gamma)
        n_eye = m if self.kernel_type == 'primal' else n
        a, b = np.linalg.multi_dot([K, M, K.T]) + self.lamb * np.eye(n_eye), np.linalg.multi_dot([K, H, K.T])
        w, V = scipy.linalg.eig(a, b)
        ind = np.argsort(w)
        A = V[:, ind[:self.dim]]
        Z = np.dot(A.T, K)
        Z /= np.linalg.norm(Z, axis=0)
        Xs_new, Xt_new = Z[:, :ns].T, Z[:, ns:].T
        return Xs_new, Xt_new 
Example #13
Source File: coroOnlyScheduler.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def scheduleRevisit(self, sInd, smin, det, pInds):
        """A Helper Method for scheduling revisits after observation detection
        Args:
            sInd - sInd of the star just detected
            smin - minimum separation of the planet to star of planet just detected
            det - 
            pInds - Indices of planets around target star
        Return:
            updates self.starRevisit attribute
        """

        TK = self.TimeKeeping

        t_rev = TK.currentTimeNorm.copy() + self.revisit_wait[sInd]
        # finally, populate the revisit list (NOTE: sInd becomes a float)
        revisit = np.array([sInd, t_rev.to('day').value])
        if self.starRevisit.size == 0:#If starRevisit has nothing in it
            self.starRevisit = np.array([revisit])#initialize sterRevisit
        else:
            revInd = np.where(self.starRevisit[:,0] == sInd)[0]#indices of the first column of the starRevisit list containing sInd 
            if revInd.size == 0:
                self.starRevisit = np.vstack((self.starRevisit, revisit))
            else:
                self.starRevisit[revInd,1] = revisit[1]#over 
Example #14
Source File: test_tcpr.py    From libTLDA with MIT License 5 votes vote down vote up
def test_fit():
    """Test for fitting the model."""
    X = np.vstack((rnd.randn(5, 2), rnd.randn(5, 2)+1))
    y = np.hstack((np.zeros((5,)), np.ones((5,))))
    Z = np.vstack((rnd.randn(5, 2)-1, rnd.randn(5, 2)+2))
    clf = TargetContrastivePessimisticClassifier(l2=0.1)
    clf.fit(X, y, Z)
    assert clf.is_trained 
Example #15
Source File: test_tcpr.py    From libTLDA with MIT License 5 votes vote down vote up
def test_predict():
    """Test for making predictions."""
    X = np.vstack((rnd.randn(5, 2), rnd.randn(5, 2)+1))
    y = np.hstack((np.zeros((5,)), np.ones((5,))))
    Z = np.vstack((rnd.randn(5, 2)-1, rnd.randn(5, 2)+2))
    clf = TargetContrastivePessimisticClassifier(l2=0.1)
    clf.fit(X, y, Z)
    u_pred = clf.predict(Z)
    labels = np.unique(y)
    assert len(np.setdiff1d(np.unique(u_pred), labels)) == 0 
Example #16
Source File: test_scl.py    From libTLDA with MIT License 5 votes vote down vote up
def test_init():
    """Test for object type."""
    clf = StructuralCorrespondenceClassifier()
    assert type(clf) == StructuralCorrespondenceClassifier
    assert not clf.is_trained


# def test_fit():
#     """Test for fitting the model."""
#     X = np.vstack((rnd.randn(5, 2), rnd.randn(5, 2)+1))
#     y = np.hstack((np.zeros((5,)), np.ones((5,))))
#     Z = np.vstack((rnd.randn(5, 2)-1, rnd.randn(5, 2)+2))
#     clf = StructuralCorrespondenceClassifier(l2=1.0)
#     clf.fit(X, y, Z)
#     assert clf.is_trained


# def test_predict():
#     """Test for making predictions."""
#     X = np.vstack((rnd.randn(5, 2), rnd.randn(5, 2)+1))
#     y = np.hstack((np.zeros((5,)), np.ones((5,))))
#     Z = np.vstack((rnd.randn(5, 2)-1, rnd.randn(5, 2)+2))
#     clf = StructuralCorrespondenceClassifier(l2=1.0)
#     clf.fit(X, y, Z)
#     u_pred = clf.predict(Z)
#     labels = np.unique(y)
#     assert len(np.setdiff1d(np.unique(u_pred), labels)) == 0 
Example #17
Source File: viz.py    From libTLDA with MIT License 5 votes vote down vote up
def plotc(parameters, ax=[], color='k', gridsize=(101, 101)):
    """
    Plot a linear classifier in a 2D scatterplot.

    INPUT   (1) tuple 'parameters': consists of a list of class proportions
                (1 by K classes), an array of class means (K classes by
                D features), an array of class-covariance matrices (D features
                by D features by K classes)
            (2) object 'ax': axes of a pyplot figure or subject (def: empty)
            (3) str 'colors': colors of the contours in the plot (def: 'k')
            (4) tuple 'gridsize': number of points in the grid
                (def: (101, 101))
    OUTPUT  None
    """
    # Check for figure object
    if fig:
        ax = fig.gca()
    else:
        fig, ax = plt.subplots()

    # Get axes limits
    xl = ax.get_xlim()
    yl = ax.get_ylim()

    # Define grid
    gx = np.linspace(xl[0], xl[1], gridsize[0])
    gy = np.linspace(yl[0], yl[1], gridsize[1])
    x, y = np.meshgrid(gx, gy)
    xy = np.vstack((x.ravel(), y.ravel())).T

    # Values of grid
    z = np.dot(xy, parameters[:-1, :]) + parameters[-1, :]
    z = np.reshape(z[:, 0] - z[:, 1], gridsize)

    # Plot grid
    ax.contour(x, y, z, levels=0, colors=colors) 
Example #18
Source File: L_bracket.py    From fenics-topopt with MIT License 5 votes vote down vote up
def get_passive_elements(self):
        X, Y = np.mgrid[self.passive_min_x:self.passive_max_x + 1,
            self.passive_min_y:self.passive_max_y]
        pairs = np.vstack([X.ravel(), Y.ravel()]).T
        passive_to_ids = np.vectorize(lambda pair: xy_to_id(*pair,
            nelx=self.nelx - 1, nely=self.nely - 1), signature="(m)->()")
        return passive_to_ids(pairs) 
Example #19
Source File: imdb.py    From Collaborative-Learning-for-Weakly-Supervised-Object-Detection with MIT License 5 votes vote down vote up
def merge_roidbs(a, b):
    assert len(a) == len(b)
    for i in range(len(a)):
      a[i]['boxes'] = np.vstack((a[i]['boxes'], b[i]['boxes']))
      a[i]['gt_classes'] = np.hstack((a[i]['gt_classes'],
                                      b[i]['gt_classes']))
      a[i]['gt_overlaps'] = scipy.sparse.vstack([a[i]['gt_overlaps'],
                                                 b[i]['gt_overlaps']])
      a[i]['seg_areas'] = np.hstack((a[i]['seg_areas'],
                                     b[i]['seg_areas']))
    return a 
Example #20
Source File: generate_anchors.py    From Collaborative-Learning-for-Weakly-Supervised-Object-Detection with MIT License 5 votes vote down vote up
def generate_anchors(base_size=16, ratios=[0.5, 1, 2],
                     scales=2 ** np.arange(3, 6)):
  """
  Generate anchor (reference) windows by enumerating aspect ratios X
  scales wrt a reference (0, 0, 15, 15) window.
  """

  base_anchor = np.array([1, 1, base_size, base_size]) - 1
  ratio_anchors = _ratio_enum(base_anchor, ratios)
  anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales)
                       for i in range(ratio_anchors.shape[0])])
  return anchors 
Example #21
Source File: tools_fri_doa_plane.py    From FRIDA with MIT License 5 votes vote down vote up
def cpx_mtx2real(mtx):
    """
    extend complex valued matrix to an extended matrix of real values only
    :param mtx: input complex valued matrix
    :return:
    """
    return np.vstack((np.hstack((mtx.real, -mtx.imag)), np.hstack((mtx.imag, mtx.real)))) 
Example #22
Source File: tools_fri_doa_plane.py    From FRIDA with MIT License 5 votes vote down vote up
def hermitian_expan(half_vec_len):
    """
    expand a real-valued vector to a Hermitian symmetric vector.
    The input vector is a concatenation of the real parts with NON-POSITIVE indices and
    the imaginary parts with STRICTLY-NEGATIVE indices.
    :param half_vec_len: length of the first half vector
    :return:
    """
    D0 = np.eye(half_vec_len)
    D1 = np.vstack((D0, D0[1:, ::-1]))
    D2 = np.vstack((D0, -D0[1:, ::-1]))
    D2 = D2[:, :-1]
    return D1, D2 
Example #23
Source File: tools_fri_doa_plane.py    From FRIDA with MIT License 5 votes vote down vote up
def coef_expan_mtx(K):
    """
    expansion matrix for an annihilating filter of size K + 1
    :param K: number of Dirac. The filter size is K + 1
    :return:
    """
    if K % 2 == 0:
        D0 = np.eye(np.int(K / 2. + 1))
        D1 = np.vstack((D0, D0[1:, ::-1]))
        D2 = np.vstack((D0, -D0[1:, ::-1]))[:, :-1]
    else:
        D0 = np.eye(np.int((K + 1) / 2.))
        D1 = np.vstack((D0, D0[:, ::-1]))
        D2 = np.vstack((D0, -D0[:, ::-1]))
    return D1, D2 
Example #24
Source File: tools_fri_doa_plane.py    From FRIDA with MIT License 5 votes vote down vote up
def Tmtx_ri(b_ri, K, D, L):
    """
    build convolution matrix associated with b_ri
    :param b_ri: a real-valued vector
    :param K: number of Diracs
    :param D1: expansion matrix for the real-part
    :param D2: expansion matrix for the imaginary-part
    :return:
    """
    b_ri = np.dot(D, b_ri)
    b_r = b_ri[:L]
    b_i = b_ri[L:]
    Tb_r = linalg.toeplitz(b_r[K:], b_r[K::-1])
    Tb_i = linalg.toeplitz(b_i[K:], b_i[K::-1])
    return np.vstack((np.hstack((Tb_r, -Tb_i)), np.hstack((Tb_i, Tb_r)))) 
Example #25
Source File: tools_fri_doa_plane.py    From FRIDA with MIT License 5 votes vote down vote up
def Rmtx_ri(coef_ri, K, D, L):
    coef_ri = np.squeeze(coef_ri)
    coef_r = coef_ri[:K + 1]
    coef_i = coef_ri[K + 1:]
    R_r = linalg.toeplitz(np.concatenate((np.array([coef_r[-1]]),
                                          np.zeros(L - K - 1))),
                          np.concatenate((coef_r[::-1],
                                          np.zeros(L - K - 1)))
                          )
    R_i = linalg.toeplitz(np.concatenate((np.array([coef_i[-1]]),
                                          np.zeros(L - K - 1))),
                          np.concatenate((coef_i[::-1],
                                          np.zeros(L - K - 1)))
                          )
    return np.dot(np.vstack((np.hstack((R_r, -R_i)), np.hstack((R_i, R_r)))), D) 
Example #26
Source File: tools_fri_doa_plane.py    From FRIDA with MIT License 5 votes vote down vote up
def mtx_updated_G_multiband(phi_recon, M, mtx_amp2visi_ri,
                            mtx_fri2visi_ri, num_bands):
    """
    Update the linear transformation matrix that links the FRI sequence to the
    visibilities by using the reconstructed Dirac locations.
    :param phi_recon: the reconstructed Dirac locations (azimuths)
    :param M: the Fourier series expansion is between -M to M
    :param p_mic_x: a vector that contains microphones' x-coordinates
    :param p_mic_y: a vector that contains microphones' y-coordinates
    :param mtx_freq2visi: the linear mapping from Fourier series to visibilities
    :return:
    """
    L = 2 * M + 1
    ms_half = np.reshape(np.arange(-M, 1, step=1), (-1, 1), order='F')
    phi_recon = np.reshape(phi_recon, (1, -1), order='F')
    mtx_amp2freq = np.exp(-1j * ms_half * phi_recon)  # size: (M + 1) x K
    mtx_amp2freq_ri = np.vstack((mtx_amp2freq.real, mtx_amp2freq.imag[:-1, :]))  # size: (2M + 1) x K
    mtx_fri2amp_ri = linalg.lstsq(mtx_amp2freq_ri, np.eye(L))[0]
    # projection mtx_freq2visi to the null space of mtx_fri2amp
    mtx_null_proj = np.eye(L) - np.dot(mtx_fri2amp_ri.T,
                                       linalg.lstsq(mtx_fri2amp_ri.T, np.eye(L))[0])
    G_updated = np.dot(mtx_amp2visi_ri,
                       linalg.block_diag(*([mtx_fri2amp_ri] * num_bands))
                       ) + \
                np.dot(mtx_fri2visi_ri,
                       linalg.block_diag(*([mtx_null_proj] * num_bands))
                       )
    return G_updated 
Example #27
Source File: __init__.py    From StructEngPy with MIT License 5 votes vote down vote up
def resolve_beam_force(self,beam_id):
        if not self.is_solved:
            raise Exception('The model has to be solved first.')
        if beam_id in self.__beams.keys():
            beam=self.__beams[beam_id]
            i=beam.nodes[0].hid
            j=beam.nodes[1].hid
            T=beam.transform_matrix
            ue=np.vstack([
                        self.d_[i*6:i*6+6],
                        self.d_[j*6:j*6+6]
                        ])   
            return (beam.Ke_.dot(T.dot(ue))+beam.re_).reshape(12)
        else:
            raise Exception("The element doesn't exists.") 
Example #28
Source File: coco_error_analysis.py    From mmdetection with Apache License 2.0 5 votes vote down vote up
def makeplot(rs, ps, outDir, class_name, iou_type):
    cs = np.vstack([
        np.ones((2, 3)),
        np.array([.31, .51, .74]),
        np.array([.75, .31, .30]),
        np.array([.36, .90, .38]),
        np.array([.50, .39, .64]),
        np.array([1, .6, 0])
    ])
    areaNames = ['allarea', 'small', 'medium', 'large']
    types = ['C75', 'C50', 'Loc', 'Sim', 'Oth', 'BG', 'FN']
    for i in range(len(areaNames)):
        area_ps = ps[..., i, 0]
        figure_tile = iou_type + '-' + class_name + '-' + areaNames[i]
        aps = [ps_.mean() for ps_ in area_ps]
        ps_curve = [
            ps_.mean(axis=1) if ps_.ndim > 1 else ps_ for ps_ in area_ps
        ]
        ps_curve.insert(0, np.zeros(ps_curve[0].shape))
        fig = plt.figure()
        ax = plt.subplot(111)
        for k in range(len(types)):
            ax.plot(rs, ps_curve[k + 1], color=[0, 0, 0], linewidth=0.5)
            ax.fill_between(
                rs,
                ps_curve[k],
                ps_curve[k + 1],
                color=cs[k],
                label=str(f'[{aps[k]:.3f}]' + types[k]))
        plt.xlabel('recall')
        plt.ylabel('precision')
        plt.xlim(0, 1.)
        plt.ylim(0, 1.)
        plt.title(figure_tile)
        plt.legend()
        # plt.show()
        fig.savefig(outDir + f'/{figure_tile}.png')
        plt.close(fig) 
Example #29
Source File: test_attacks.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_attack_strength(self):
        # This uses the existing input structure for SPSA. Tom tried for ~40
        # minutes to get generate_np to work correctly but could not.

        n_samples = 10
        x_val = np.random.rand(n_samples, 2)
        x_val = np.array(x_val, dtype=np.float32)

        # The SPSA attack currently uses non-one-hot labels
        # TODO: change this to use standard cleverhans label conventions
        feed_labs = np.random.randint(0, 2, n_samples)

        x_input = tf.placeholder(tf.float32, shape=(1,2))
        y_label = tf.placeholder(tf.int32, shape=(1,))

        x_adv_op = self.attack.generate(
            x_input, y=y_label,
            epsilon=.5, num_steps=100, batch_size=64, spsa_iters=1,
        )

        all_x_adv = []
        for i in range(n_samples):
            x_adv_np = self.sess.run(x_adv_op, feed_dict={
                            x_input: np.expand_dims(x_val[i], axis=0),
                             y_label: np.expand_dims(feed_labs[i], axis=0),
            })
            all_x_adv.append(x_adv_np[0])

        x_adv = np.vstack(all_x_adv)
        new_labs = np.argmax(self.sess.run(self.model(x_adv)), axis=1)
        self.assertTrue(np.mean(feed_labs == new_labs) < 0.1) 
Example #30
Source File: gtf_utils.py    From models with MIT License 5 votes vote down vote up
def get_all_exons(self):
        exons = np.vstack([i.exons for i in self.trans])
        exons = np.unique(exons, axis=0)
        ind = np.lexsort((exons[:,1],exons[:,0]))
        if self.strand == '-':
            ind = ind[::-1]
        exons = exons[ind]
        return exons