Makes a predictive distribution.

        xs: values to go into the Pmf

        Returns: Pmf that maps from x to the mean prevalence of x
15816
def PredictivePmf(self, xs, name=''):
        
        alpha0 = self.params.sum()
        ps = self.params / alpha0
        return MakePmfFromItems(zip(xs, ps), name=name)
402390
def predict(self, x):
        
        if isinstance(x, RDD):
            return x.map(lambda v: self.predict(v))

        x = _convert_to_vector(x)
        margin = self.weights.dot(x) + self.intercept
        if self._threshold is None:
            return margin
        else:
            return 1 if margin > self._threshold else 0
475070
def get_std_xy_dataset_statistics(x_values, y_values, expect_negative_correlation = False, STDev_cutoff = 1.0):
    ''''''
    assert(len(x_values) == len(y_values))
    csv_lines = ['ID,X,Y'] + [','.join(map(str, [c + 1, x_values[c], y_values[c]])) for c in xrange(len(x_values))]
    data = parse_csv(csv_lines, expect_negative_correlation = expect_negative_correlation, STDev_cutoff = STDev_cutoff)

    assert(len(data['predictions']) == 1)
    assert(1 in data['predictions'])
    assert(data['predictions'][1]['name'] == 'Y')
    summary_data = data['predictions'][1]

    stats = {}
    for spair in field_name_mapper:
        stats[spair[1]] = summary_data[spair[0]]
    if stats['std_warnings']:
        stats['std_warnings'] = '\n'.join(stats['std_warnings'])
    else:
        stats['std_warnings'] = None
    return stats
740078
def cumulative_distribution(self, X):
        
        self.check_fit()
        return norm.cdf(X, loc=self.mean, scale=self.std)
128305
def predict(self, X):
        
        check_is_fitted(self, 'estimators_')

        X = check_array(X, dtype=DTYPE, order="C")
        score = self._decision_function(X)
        if score.shape[1] == 1:
            score = score.ravel()

        return score
341650
def _maximization(self, X):
        """"""

        # Iterate through clusters and recalculate mean and covariance
        for i in range(self.k):
            resp = np.expand_dims(self.responsibility[:, i], axis=1)
            mean = (resp * X).sum(axis=0) / resp.sum()
            covariance = (X - mean).T.dot((X - mean) * resp) / resp.sum()
            self.parameters[i]["mean"], self.parameters[i]["cov"] = mean, covariance

        # Update weights
        n_samples = np.shape(X)[0]
        self.priors = self.responsibility.sum(axis=0) / n_samples
1214683
def Mean(self):
        
        mu = 0.0
        for x, p in self.d.iteritems():
            mu += p * x
        return mu
784740
def cdf(self, x):
        
        t = 0
        N = float(self.n)

        if len(self) == 1:  # only one centroid
            return int(x >= self.C.min_key())

        for i, key in enumerate(self.C.keys()):
            c_i = self.C[key]
            if i == len(self) - 1:
                delta = (c_i.mean - self.C.prev_item(key)[1].mean) / 2.
            else:
                delta = (self.C.succ_item(key)[1].mean - c_i.mean) / 2.
            z = max(-1, (x - c_i.mean) / delta)

            if z < 1:
                return t / N + c_i.count / N * (z + 1) / 2

            t += c_i.count
        return 1
1000356
def randomise_proposed_value(self):
        
        if self.parameter_type is MMCParameterType.UNIFORM_DIST:
            (a, b) = self.static_dist_or_list
            self.proposed_value = random.uniform(a, b)
        elif self.parameter_type is MMCParameterType.NORMAL_DIST:
            (mu, sigma) = self.static_dist_or_list
            self.proposed_value = random.normalvariate(mu, sigma)
        elif self.parameter_type is MMCParameterType.DISCRETE_RANGE:
            (min_v, max_v, step) = self.static_dist_or_list
            self.proposed_value = random.choice(
                numpy.arange(min_v, max_v, step))
        elif self.parameter_type is MMCParameterType.LIST:
            self.proposed_value = random.choice(self.static_dist_or_list)
        elif self.parameter_type is MMCParameterType.STATIC_VALUE:
            raise TypeError('This value is static, it cannot be mutated.')
        else:
            raise TypeError(
                'Cannot randomise this parameter, unknown parameter type.')
        return
782708
@Override
    public int predict(T x) {
        double minDist = Double.MAX_VALUE;
        int bestCluster = 0;

        for (int i = 0; i < k; i++) {
            double dist = distance.d(x, medoids[i]);
            if (dist < minDist) {
                minDist = dist;
                bestCluster = i;
            }
        }

        return bestCluster;
    }
75055
def pdf(self, x_test):
		
		N,D = self.data.shape
		x_test = np.asfortranarray(x_test)
		x_test = x_test.reshape([-1, D])
		
		pdfs = self._individual_pdfs(x_test)
		#import pdb; pdb.set_trace()
		# combine values based on fully_dimensional!
		if self.fully_dimensional:
			# first the product of the individual pdfs for each point in the data across dimensions and then the average (factorized kernel)
			pdfs = np.sum(np.prod(pdfs, axis=-1)*self.weights[None, :], axis=-1)
		else:
			# first the average over the 1d pdfs and the the product over dimensions (TPE like factorization of the pdf)
			pdfs = np.prod(np.sum(pdfs*self.weights[None,:,None], axis=-2), axis=-1)
		return(pdfs)
843724
def predict(self, X):
        
        X = np.atleast_2d(X)
        m = np.empty(shape=(0,1))
        s = np.empty(shape=(0,1))

        for k in range(X.shape[0]):
            preds = []
            for pred in self.model.estimators_:
                preds.append(pred.predict(X[k,:])[0])
            m = np.vstack((m ,np.array(preds).mean()))
            s = np.vstack((s ,np.array(preds).std()))
        return m, s
949899
def count_above_mean(x):
    
    m = np.mean(x)
    return np.where(x > m)[0].size
33316
def predict(self, x):
        
        if self._is_leaf():
            d1 = self.predict_initialize['count_dict']
            d2 = count_dict(self.Y)
            for key, value in d1.iteritems():
                if key in d2:
                    d2[key] += value
                else:
                    d2[key] = value
            return argmax(d2)
        else:
            if self.criterion(x):
                return self.right.predict(x)
            else:
                return self.left.predict(x)
496612
def root_mean_square(X):
    '''  '''
    segment_width = X.shape[1]
    return np.sqrt(np.sum(X * X, axis=1) / segment_width)
1262917
def get_tau_at_quantile(mean, stddev, quantile):
    
    tau_model = {}
    for imt in mean:
        tau_model[imt] = {}
        for key in mean[imt]:
            if quantile is None:
                tau_model[imt][key] = mean[imt][key]
            else:
                tau_model[imt][key] = _at_percentile(mean[imt][key],
                                                     stddev[imt][key],
                                                     quantile)
    return tau_model
790638
def _crps_cdf_single(x, cdf_or_dist, xmin=None, xmax=None, tol=1e-6):
    
    # TODO: this function is pretty slow.  Look for clever ways to speed it up.

    # allow for directly passing in scipy.stats distribution objects.
    cdf = getattr(cdf_or_dist, 'cdf', cdf_or_dist)
    assert callable(cdf)

    # if bounds aren't given, discover them
    if xmin is None or xmax is None:
        # Note that infinite values for xmin and xmax are valid, but
        # it slows down the resulting quadrature significantly.
        xmin, xmax = _discover_bounds(cdf)

    # make sure the bounds haven't clipped the cdf.
    if (tol is not None) and (cdf(xmin) >= tol) or (cdf(xmax) <= (1. - tol)):
        raise ValueError('CDF does not meet tolerance requirements at %s '
                         'extreme(s)! Consider using function defaults '
                         'or using infinities at the bounds. '
                         % ('lower' if cdf(xmin) >= tol else 'upper'))

    # CRPS = int_-inf^inf (F(y) - H(x))**2 dy
    #      = int_-inf^x F(y)**2 dy + int_x^inf (1 - F(y))**2 dy
    def lhs(y):
        # left hand side of CRPS integral
        return np.square(cdf(y))
    # use quadrature to integrate the lhs
    lhs_int, lhs_tol = integrate.quad(lhs, xmin, x)
    # make sure the resulting CRPS will be with tolerance
    if (tol is not None) and (lhs_tol >= 0.5 * tol):
        raise ValueError('Lower integral did not evaluate to within tolerance! '
                         'Tolerance achieved: %f , Value of integral: %f \n'
                         'Consider setting the lower bound to -np.inf.' %
                         (lhs_tol, lhs_int))

    def rhs(y):
        # right hand side of CRPS integral
        return np.square(1. - cdf(y))
    rhs_int, rhs_tol = integrate.quad(rhs, x, xmax)
    # make sure the resulting CRPS will be with tolerance
    if (tol is not None) and (rhs_tol >= 0.5 * tol):
        raise ValueError('Upper integral did not evaluate to within tolerance! \n'
                         'Tolerance achieved: %f , Value of integral: %f \n'
                         'Consider setting the upper bound to np.inf or if '
                         'you already have, set warn_level to `ignore`.' %
                         (rhs_tol, rhs_int))

    return lhs_int + rhs_int