python类ones()的实例源码

cvglmnetPlot.py 文件源码 项目:glmnet_py 作者: hanfang 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def cvglmnetPlot(cvobject, sign_lambda = 1.0, **options):

    sloglam = sign_lambda*scipy.log(cvobject['lambdau'])

    fig = plt.gcf()
    ax1 = plt.gca()
    #fig, ax1 = plt.subplots()    

    plt.errorbar(sloglam, cvobject['cvm'], cvobject['cvsd'], \
                 ecolor = (0.5, 0.5, 0.5), \
                 **options
                 )
    plt.hold(True)         
    plt.plot(sloglam, cvobject['cvm'], linestyle = 'dashed',\
             marker = 'o', markerfacecolor = 'r')             

    xlim1 = ax1.get_xlim()
    ylim1 = ax1.get_ylim()

    xval = sign_lambda*scipy.log(scipy.array([cvobject['lambda_min'], cvobject['lambda_min']]))
    plt.plot(xval, ylim1, color = 'b', linestyle = 'dashed', \
             linewidth = 1)

    if cvobject['lambda_min'] != cvobject['lambda_1se']:
        xval = sign_lambda*scipy.log([cvobject['lambda_1se'], cvobject['lambda_1se']])
        plt.plot(xval, ylim1, color = 'b', linestyle = 'dashed', \
             linewidth = 1)

    ax2 = ax1.twiny()
    ax2.xaxis.tick_top()

    atdf = ax1.get_xticks()
    indat = scipy.ones(atdf.shape, dtype = scipy.integer)
    if sloglam[-1] >= sloglam[1]:
        for j in range(len(sloglam)-1, -1, -1):
            indat[atdf <= sloglam[j]] = j
    else:
        for j in range(len(sloglam)):
            indat[atdf <= sloglam[j]] = j

    prettydf = cvobject['nzero'][indat]

    ax2.set(XLim=xlim1, XTicks = atdf, XTickLabels = prettydf)
    ax2.grid()
    ax1.yaxis.grid()

    ax2.set_xlabel('Degrees of Freedom')

  #  plt.plot(xlim1, [ylim1[1], ylim1[1]], 'b')
  #  plt.plot([xlim1[1], xlim1[1]], ylim1, 'b')

    if sign_lambda < 0:
        ax1.set_xlabel('-log(Lambda)')
    else:
        ax1.set_xlabel('log(Lambda)')

    ax1.set_ylabel(cvobject['name'])

    #plt.show()
cvglmnetPlot.py 文件源码 项目:glmnet_py 作者: hanfang 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def cvglmnetPlot(cvobject, sign_lambda = 1.0, **options):

    sloglam = sign_lambda*scipy.log(cvobject['lambdau'])

    fig = plt.gcf()
    ax1 = plt.gca()
    #fig, ax1 = plt.subplots()    

    plt.errorbar(sloglam, cvobject['cvm'], cvobject['cvsd'], \
                 ecolor = (0.5, 0.5, 0.5), \
                 **options
                 )
    plt.hold(True)         
    plt.plot(sloglam, cvobject['cvm'], linestyle = 'dashed',\
             marker = 'o', markerfacecolor = 'r')             

    xlim1 = ax1.get_xlim()
    ylim1 = ax1.get_ylim()

    xval = sign_lambda*scipy.log(scipy.array([cvobject['lambda_min'], cvobject['lambda_min']]))
    plt.plot(xval, ylim1, color = 'b', linestyle = 'dashed', \
             linewidth = 1)

    if cvobject['lambda_min'] != cvobject['lambda_1se']:
        xval = sign_lambda*scipy.log([cvobject['lambda_1se'], cvobject['lambda_1se']])
        plt.plot(xval, ylim1, color = 'b', linestyle = 'dashed', \
             linewidth = 1)

    ax2 = ax1.twiny()
    ax2.xaxis.tick_top()

    atdf = ax1.get_xticks()
    indat = scipy.ones(atdf.shape, dtype = scipy.integer)
    if sloglam[-1] >= sloglam[1]:
        for j in range(len(sloglam)-1, -1, -1):
            indat[atdf <= sloglam[j]] = j
    else:
        for j in range(len(sloglam)):
            indat[atdf <= sloglam[j]] = j

    prettydf = cvobject['nzero'][indat]

    ax2.set(XLim=xlim1, XTicks = atdf, XTickLabels = prettydf)
    ax2.grid()
    ax1.yaxis.grid()

    ax2.set_xlabel('Degrees of Freedom')

  #  plt.plot(xlim1, [ylim1[1], ylim1[1]], 'b')
  #  plt.plot([xlim1[1], xlim1[1]], ylim1, 'b')

    if sign_lambda < 0:
        ax1.set_xlabel('-log(Lambda)')
    else:
        ax1.set_xlabel('log(Lambda)')

    ax1.set_ylabel(cvobject['name'])

    #plt.show()
datasets.py 文件源码 项目:Cascade-CNN-Face-Detection 作者: gogolgrind 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_fddb_face_data(k = 12, on_drive = False):
        root = 'F:\\datasets\\image_data_sets\\faces\\FDDB\\'
        iroot = os.path.join(root,'originalPics')
        eroot = os.path.join(root,'FDDB-folds')
        pattern = '-ellipseList.txt'
        c = 0
        X,y = [],[]
        for path, subdirs, files in os.walk(eroot):
            for fname in files:
                if fname.find(pattern) > 0:
                    fpath = os.path.join(path,fname)
                    print(fpath)
                    with open(fpath) as f:
                        lines = sp.array(f.readlines())
                        paths_indx = sp.where([line.find('/') > 0 for line in lines])[0]
                        counts_indx = paths_indx + 1

                        paths = sp.array([e.strip() for e in lines[paths_indx]])
                        ellipces = []
                        for i in counts_indx:
                            cnt = int(lines[i])
                            ellipces.append(lines[i+1:i+cnt+1])
                        ellipces = [ [ [float(num) for num in line.split()[:-1]] for line in e] for e in ellipces]
                        ellipces = sp.array(ellipces)
                        for iname,ells in zip(paths[:],ellipces[:]):
                            ppath = os.path.join(iroot,iname.replace('/','\\')) + '.jpg'
                            file_id = iname.split('/')[-1]

                            frame = fr.get_frame(ppath)
                            for item in ells:
                                ra,rb,theta,x,y = item
                                x1,y1,x2,y2 = util.ellipse2bbox(a = ra, b = rb, angle = theta, cx = x, cy = y)
                                x = x1
                                y = y1
                                h = abs(y2-y1)
                                w = abs(x2-x1)
                                print(file_id,(y,x,h,w))

                                non_neg = x > 0 and y > 0
                                if not non_neg:
                                    continue
                                if on_drive:   
                                    for item in Datasets.data_augmentation(frame,y,x,w,h):
                                        fr.write_frame('F:\\train_data\\pos\\' + str(c) + '_' + str(file_id) + '_pos',item)
                                        c +=1
                                else:
                                    pass
        X = sp.array(X)
        y = sp.ones(len(X))
        return X,y
rvm.py 文件源码 项目:prml 作者: Yevgnen 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def fit(self, X, T, max_iter=int(1e2), tol=1e-3, bound=1e10):
        """Fit a RVM model with the training data ``(X, T)``."""
        # Initialize the hyperparameters
        self._init_hyperparameters(X, T)

        # Compute design matrix
        n_samples = X.shape[0]
        phi = sp.c_[sp.ones(n_samples), self._compute_design_matrix(X)]  # Add x0

        alpha = self.cov
        beta = self.beta

        log_evidence = -1e10
        for iter in range(max_iter):
            alpha[alpha >= bound] = bound
            rv_indices = sp.nonzero(alpha < bound)[0]
            rv_phi = phi[:, rv_indices]
            rv_alpha = alpha[rv_indices]

            # Compute the posterior distribution
            post_cov = spla.inv(sp.diag(rv_alpha) + beta * sp.dot(rv_phi.T, rv_phi))
            post_mean = beta * sp.dot(post_cov, sp.dot(rv_phi.T, T))

            # Re-estimate the hyperparameters
            gamma = 1 - rv_alpha * post_cov.diagonal()
            rv_alpha = gamma / (post_mean * post_mean)
            beta = (n_samples + 1 - gamma.sum()) / spla.norm(T - sp.dot(rv_phi, post_mean))**2

            # Evalueate the log evidence and test the relative change
            C = sp.eye(rv_phi.shape[0]) / beta + rv_phi.dot(sp.diag(1.0 / rv_alpha)).dot(rv_phi.T)
            log_evidence_new = -0.5 * (sp.log(spla.det(C)) + T.dot(spla.inv(C)).dot((T)))
            diff = spla.norm(log_evidence_new - log_evidence)
            if (diff < tol * spla.norm(log_evidence)):
                break

            log_evidence = log_evidence_new
            alpha[rv_indices] = rv_alpha

        # Should re-compute the posterior distribution
        self.rv_indices = rv_indices
        self.cov = post_cov
        self.mean = post_mean
        self.beta = beta

        return self


问题


面经


文章

微信
公众号

扫码关注公众号