Python pylab.mean() Examples

The following are 6 code examples of pylab.mean(). 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 pylab , or try the search function .
Example #1
Source File: histfit.py    From fitter with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, data=None, X=None, Y=None, bins=None):
        """.. rubric:: **Constructor**

        One should provide either the parameter **data** alone, or the X and Y
        parameters, which are the histogram of some data sample.

        :param data: random data
        :param X: evenly spaced X data
        :param Y: probability density of the data
        :param bins: if data is providede, we will compute the probability using
            hist function and bins may be provided. 

        """

        self.data = data
        if data:
            Y, X, _ = pylab.hist(self.data, bins=bins, density=True)
            self.N = len(X) - 1
            self.X = [(X[i]+X[i+1])/2 for i in range(self.N)]
            self.Y = Y
            self.A = 1
            self.guess_std = pylab.std(self.data)
            self.guess_mean = pylab.mean(self.data)
            self.guess_amp = 1
        else:
            self.X = X
            self.Y = Y
            self.Y = self.Y / sum(self.Y)
            if len(self.X) == len(self.Y) + 1 :
                self.X = [(X[i]+X[i+1])/2 for i in range(len(X)-1)]

            self.N = len(self.X)
            self.guess_mean = self.X[int(self.N/2)]
            self.guess_std = sqrt(sum((self.X - mean(self.X))**2)/self.N)/(sqrt(2*3.14))
            self.guess_amp = 1.

        self.func = self._func_normal 
Example #2
Source File: subspace.py    From sysid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def nrms(data_fit, data_true):
    """
    Normalized root mean square error.
    """
    # root mean square error
    rms = pl.mean(np.linalg.norm(data_fit - data_true, axis=0))

    # normalization factor is the max - min magnitude, or 2 times max dist from mean
    norm_factor = 2 * \
        np.linalg.norm(data_true - pl.mean(data_true, axis=1), axis=0).max()
    return (norm_factor - rms)/norm_factor 
Example #3
Source File: ocrd_anybaseocr_deskew.py    From ocrd_anybaseocr with Apache License 2.0 5 votes vote down vote up
def estimate_skew_angle(self, image, angles):
        
        estimates = []
        
        for a in angles:
            v = mean(interpolation.rotate(
                image, a, order=0, mode='constant'), axis=1)
            v = var(v)
            estimates.append((v, a))
        if self.parameter['debug'] > 0:
            plot([y for x, y in estimates], [x for x, y in estimates])
            ginput(1, self.parameter['debug'])
        _, a = max(estimates)
        return a 
Example #4
Source File: ocrd_anybaseocr_binarize.py    From ocrd_anybaseocr with Apache License 2.0 5 votes vote down vote up
def check_page(self, image):
        if len(image.shape) == 3:
            return "input image is color image %s" % (image.shape,)
        if mean(image) < median(image):
            return "image may be inverted"
        h, w = image.shape
        if h < 600:
            return "image not tall enough for a page image %s" % (image.shape,)
        if h > 10000:
            return "image too tall for a page image %s" % (image.shape,)
        if w < 600:
            return "image too narrow for a page image %s" % (image.shape,)
        if w > 10000:
            return "line too wide for a page image %s" % (image.shape,)
        return None 
Example #5
Source File: histfit.py    From fitter with GNU General Public License v3.0 4 votes vote down vote up
def fit(self, error_rate=0.05, semilogy=False, Nfit=100,
            error_kwargs={"lw":1, "color":"black", "alpha":0.2},
            fit_kwargs={"lw":2, "color":"red"}):
        self.mus = []
        self.sigmas = []
        self.amplitudes = []
        self.fits = []

        pylab.figure(1)
        pylab.clf()
        pylab.bar(self.X, self.Y, width=0.85, ec="k")

        for x in range(Nfit):
            # 10% error on the data to add errors 
            self.E = [scipy.stats.norm.rvs(0, error_rate) for y in self.Y]
            #[scipy.stats.norm.rvs(0, self.std_data * error_rate) for x in range(self.N)]
            self.result = scipy.optimize.least_squares(self.func, 
                (self.guess_mean, self.guess_std, self.guess_amp))

            mu, sigma, amplitude = self.result['x']
            pylab.plot(self.X, amplitude * scipy.stats.norm.pdf(self.X, mu,sigma),
                **error_kwargs)
            self.sigmas.append(sigma)
            self.amplitudes.append(amplitude)
            self.mus.append(mu)


            self.fits.append(amplitude * scipy.stats.norm.pdf(self.X, mu,sigma))

        self.sigma = mean(self.sigmas)
        self.amplitude = mean(self.amplitudes)
        self.mu = mean(self.mus)


        pylab.plot(self.X, self.amplitude * scipy.stats.norm.pdf(self.X, self.mu, self.sigma), 
                   **fit_kwargs)
        if semilogy:
            pylab.semilogy() 
        pylab.grid()

        pylab.figure(2)
        pylab.clf()
        #pylab.bar(self.X, self.Y, width=0.85, ec="k", alpha=0.5)
        M = mean(self.fits, axis=0)
        S = pylab.std(self.fits, axis=0)
        pylab.fill_between(self.X, M-3*S, M+3*S, color="gray", alpha=0.5)
        pylab.fill_between(self.X, M-2*S, M+2*S, color="gray", alpha=0.5)
        pylab.fill_between(self.X, M-S, M+S, color="gray", alpha=0.5)
        #pylab.plot(self.X, M-S, color="k")
        #pylab.plot(self.X, M+S, color="k")
        pylab.plot(self.X, self.amplitude * scipy.stats.norm.pdf(self.X, self.mu, self.sigma), 
                   **fit_kwargs)
        pylab.grid()

        return self.mu, self.sigma, self.amplitude 
Example #6
Source File: dataset.py    From DEMUD with Apache License 2.0 4 votes vote down vote up
def plot_pcs(self, m, U, mu, k, S):
    """plot_pcs(m, U, mu, k, S)
    Plot the principal components in U, after DEMUD iteration m, 
        by adding back in the mean in mu.
    Ensure that there are k of them, 
        and list the corresponding singular values from S.
    """

    #assert (k == U.shape[1])
  
    colors = ['b','g','r','c','m','y','k','#666666','DarkGreen', 'Orange']
    while len(colors) < k: colors.extend(colors)
  
    pylab.clf()

    if m == 0:
      max_num_pcs = k
    else:
      cur_pcs = U.shape[1]
      max_num_pcs = min(min(cur_pcs,k), 4)
  
    umu = numpy.zeros_like(U)
    for i in range(max_num_pcs):
      umu[:,i] = U[:,i] + mu[:,0] #[i]
      
    for i in range(max_num_pcs):
      vector = umu[:,i]
      if i == 0 and m == 1:
        vector[0] -= 1
      label = 'PC %d, SV %.2e' % (i, S[i])
      pylab.plot(self.xvals, vector, color=colors[i], label=label)
      
    pylab.xlabel(self.xlabel)
    pylab.ylabel(self.ylabel)
    pylab.title('SVD of dataset ' + self.name + ' after selection ' + str(m))
    xvals = [self.xvals[z] for z in range(self.xvals.shape[0])]
    diff = pylab.mean([xvals[i] - xvals[i-1] for i in range(1, len(xvals))])
    pylab.xlim([float(xvals[0]) - diff / 6.0, float(xvals[-1]) + diff / 6.0])
    #pylab.xticks(xvals, self.features)
    pylab.legend()
    
    outdir = os.path.join('results', self.name)
    if not os.path.exists(outdir):
      os.mkdir(outdir)
    figfile = os.path.join(outdir, 'PCs-sel-%d-k-%d-(%s).pdf' % (m, k, label))
    pylab.savefig(figfile)
    print 'Wrote SVD to %s' % figfile
    pylab.close()


  # Write a list of the selections in CSV format