Uses OLS to fit the regression.
337230
def fit_linear(X, y):
    
    model = linear_model.LinearRegression()
    model.fit(X, y)
    return model
1252798
def set_regression_mask(self, v):
        """"""
        base = self._base
        index = np.arange(v.size())
        np.random.shuffle(index)
        ones = np.ones(v.size())
        ones[index[int(base._tr_fraction * v.size()):]] = 0
        base._mask = SparseArray.fromlist(ones)
415143
def partial_fit(self, X):
        
        from pyemma.coordinates import source

        self._estimate(source(X), partial_fit=True)
        self._estimated = True

        return self
944544
def lnlike(x, star):
    """"""
    ll = lnprior(x)
    if np.isinf(ll):
        return ll, (np.nan, np.nan)
    per, t0, b = x
    model = TransitModel('b', per=per, t0=t0, b=b, rhos=10.)(star.time)
    like, d, vard = star.lnlike(model, full_output=True)
    ll += like
    return ll, (d,)
1275206
def lreg(self, xcol, ycol, name="Regression"):
        
        try:
            x = self.df[xcol].values.reshape(-1, 1)
            y = self.df[ycol]
            lm = linear_model.LinearRegression()
            lm.fit(x, y)
            predictions = lm.predict(x)
            self.df[name] = predictions
        except Exception as e:
            self.err(e, "Can not calculate linear regression")
937505
def fit_linear(xdata, ydata):
    
    x = _n.array(xdata)
    y = _n.array(ydata)

    ax  = _n.average(x)
    ay  = _n.average(y)
    axx = _n.average(x*x)
    ayx = _n.average(y*x)

    slope     = (ayx - ay*ax) / (axx - ax*ax)
    intercept = ay - slope*ax

    return slope, intercept
156180
def linear_regression(self):
        

        model = LinearRegression()
        scores = []

        kfold = KFold(n_splits=self.cv, shuffle=True, random_state=42)
        for i, (train, test) in enumerate(kfold.split(self.baseline_in, self.baseline_out)):
            model.fit(self.baseline_in.iloc[train], self.baseline_out.iloc[train])
            scores.append(model.score(self.baseline_in.iloc[test], self.baseline_out.iloc[test]))

        mean_score = sum(scores) / len(scores)
        
        self.models.append(model)
        self.model_names.append('Linear Regression')
        self.max_scores.append(mean_score)

        self.metrics['Linear Regression'] = {}
        self.metrics['Linear Regression']['R2'] = mean_score
        self.metrics['Linear Regression']['Adj R2'] = self.adj_r2(mean_score, self.baseline_in.shape[0], self.baseline_in.shape[1])
1320509
private function _power_regression($yValues, $xValues, $const) {
		foreach($xValues as &$value) {
			if ($value < 0.0) {
				$value = 0 - log(abs($value));
			} elseif ($value > 0.0) {
				$value = log($value);
			}
		}
		unset($value);
		foreach($yValues as &$value) {
			if ($value < 0.0) {
				$value = 0 - log(abs($value));
			} elseif ($value > 0.0) {
				$value = log($value);
			}
		}
		unset($value);

		$this->_leastSquareFit($yValues, $xValues, $const);
	}
384844
def fit(self, X):
        
        self.centers_, self.labels_, self.sse_arr_, self.n_iter_ = \
              _kmeans(X, self.n_clusters, self.max_iter, self.n_trials, self.tol)
884310
def _twofilter_smoothing_ON(self, t, ti, info, phi, lwinfo, return_ess,
                               modif_forward, modif_info):
        
        if modif_info is not None:
            lwinfo += modif_info
        Winfo = rs.exp_and_normalise(lwinfo)
        I = rs.multinomial(Winfo)
        if modif_forward is not None:
            lw = self.wgt[t].lw + modif_forward
            W = rs.exp_and_normalise(lw)
        else:
            W = self.wgt[t].W
        J = rs.multinomial(W)
        log_omega = self.model.logpt(t + 1, self.X[t][J], info.hist.X[ti][I])
        if modif_forward is not None:
            log_omega -= modif_forward[J]
        if modif_info is not None:
            log_omega -= modif_info[I]
        Om = rs.exp_and_normalise(log_omega)
        est = np.average(phi(self.X[t][J], info.hist.X[ti][I]), axis=0,
                         weights=Om)
        if return_ess:
            return (est, 1. / np.sum(Om**2))
        else:
            return est
1055297
def l1_regression(
    input_, target, name=PROVIDED, loss_weight=None,
    per_example_weights=None):
  """"""
  target = _convert_and_assert_tensors_compatible(input_, target)
  return apply_regression(input_,
                          functions.l1_regression_loss,
                          target,
                          [],
                          name='%s_loss' % name,
                          loss_weight=loss_weight,
                          per_example_weights=per_example_weights)
866953
def regressOut(Y, X, return_b=False):
    
    Xd = la.pinv(X)
    b = Xd.dot(Y)
    Y_out = Y-X.dot(b)
    if return_b:
        return Y_out, b
    else:
        return Y_out
315270
def fit(self, X, y=None):
        
        X = self._check_array(X)

        solver_kwargs = self._get_solver_kwargs()

        self._coef = algorithms._solvers[self.solver](X, y, **solver_kwargs)
        if self.fit_intercept:
            self.coef_ = self._coef[:-1]
            self.intercept_ = self._coef[-1]
        else:
            self.coef_ = self._coef
        return self
723250
def fit(self, x, y, *args, **kwargs):
        

        points = self._dimensionality_check(x)

        # if condition required to address backward compatibility
        if self.method in threed_krige:
            self.model = krige_methods[self.method](
                val=y,
                variogram_model=self.variogram_model,
                nlags=self.nlags,
                weight=self.weight,
                verbose=self.verbose,
                **points
            )
        else:
            self.model = krige_methods[self.method](
                z=y,
                variogram_model=self.variogram_model,
                nlags=self.nlags,
                weight=self.weight,
                verbose=self.verbose,
                **points
            )
1201929
def apply_fit(xy,coeffs):
    
    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]
    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]

    return x_new,y_new
769730
def fit(self, X, y):
    '''
    '''
    X, y = self._prepare_inputs(X, y, ensure_min_samples=2)
    unique_classes, y = np.unique(y, return_inverse=True)
    n, d = X.shape
    num_classes = len(unique_classes)

    if self.num_dims is None:
      dim = d
    else:
      if not 0 < self.num_dims <= d:
        raise ValueError('Invalid num_dims, must be in [1,%d]' % d)
      dim = self.num_dims

    if self.k is None:
      k = min(7, d - 1)
    elif self.k >= d:
      warnings.warn('Chosen k (%d) too large, using %d instead.' % (self.k,d-1))
      k = d - 1
    else:
      k = int(self.k)
    tSb = np.zeros((d,d))
    tSw = np.zeros((d,d))

    for c in xrange(num_classes):
      Xc = X[y==c]
      nc = Xc.shape[0]

      # classwise affinity matrix
      dist = pairwise_distances(Xc, metric='l2', squared=True)
      # distances to k-th nearest neighbor
      k = min(k, nc - 1)
      sigma = np.sqrt(np.partition(dist, k, axis=0)[:, k])

      local_scale = np.outer(sigma, sigma)
      with np.errstate(divide='ignore', invalid='ignore'):
        A = np.exp(-dist/local_scale)
        A[local_scale==0] = 0

      G = Xc.T.dot(A.sum(axis=0)[:,None] * Xc) - Xc.T.dot(A).dot(Xc)
      tSb += G/n + (1-nc/n)*Xc.T.dot(Xc) + _sum_outer(Xc)/n
      tSw += G/nc

    tSb -= _sum_outer(X)/n - tSw

    # symmetrize
    tSb = (tSb + tSb.T) / 2
    tSw = (tSw + tSw.T) / 2

    vals, vecs = _eigh(tSb, tSw, dim)
    order = np.argsort(-vals)[:dim]
    vals = vals[order].real
    vecs = vecs[:,order]

    if self.embedding_type == 'weighted':
       vecs *= np.sqrt(vals)
    elif self.embedding_type == 'orthonormalized':
       vecs, _ = np.linalg.qr(vecs)

    self.transformer_ = vecs.T
    return self
417822
def regression(fname="regression.png"):
    
    _, axes = plt.subplots(ncols=2, figsize=(18, 6))
    alphas = np.logspace(-10, 1, 300)
    data = load_concrete(split=True)

    # Plot prediction error in the middle
    oz = PredictionError(LassoCV(alphas=alphas), ax=axes[0])
    oz.fit(data.X.train, data.y.train)
    oz.score(data.X.test, data.y.test)
    oz.finalize()

    # Plot residuals on the right
    oz = ResidualsPlot(RidgeCV(alphas=alphas), ax=axes[1])
    oz.fit(data.X.train, data.y.train)
    oz.score(data.X.test, data.y.test)
    oz.finalize()

    # Save figure
    path = os.path.join(FIGURES, fname)
    plt.tight_layout()
    plt.savefig(path)