do linear regression [n_iter] times
    successive removing [outliers]
    return result of normal linregress
439418
def linregressIgnoringOutliers(x, y, n_iter=3, nstd=2):
    
    for _ in range(n_iter):
        m, n = linregress(x, y)[:2]
        y_fit = x * m + n
        dy = y - y_fit
        std = (dy**2).mean()**0.5
        inliers = abs(dy) < nstd * std
        if inliers.sum() > 2:
            x = x[inliers]
            y = y[inliers]
        else:
            break
    return linregress(x, y)
192527
def clean(self):
        
        if self.pst_arg is None:
            self.logger.statement("linear_analysis.clean(): not pst object")
            return
        if not self.pst.estimation and self.pst.nprior > 0:
            self.drop_prior_information()
59872
private double computeExplainedVariance(double[] eigenValues, int filteredEigenPairs) {
    double strongsum = 0., weaksum = 0.;
    for(int i = 0; i < filteredEigenPairs; i++) {
      strongsum += eigenValues[i];
    }
    for(int i = filteredEigenPairs; i < eigenValues.length; i++) {
      weaksum += eigenValues[i];
    }
    return strongsum / (strongsum + weaksum);
  }
372529
protected boolean linearEstimate(List<CalibrationObservation> observations  )
	{
		status("Estimating Homographies");
		List<DMatrixRMaj> homographies = new ArrayList<>();
		List<Se3_F64> motions = new ArrayList<>();

		for( CalibrationObservation obs : observations ) {
			if( !computeHomography.computeHomography(obs) )
				return false;

			DMatrixRMaj H = computeHomography.getHomography();

			homographies.add(H);
		}

		status("Estimating Calibration Matrix");
		computeK.process(homographies);

		DMatrixRMaj K = computeK.getCalibrationMatrix();

		decomposeH.setCalibrationMatrix(K);
		for( DMatrixRMaj H : homographies ) {
			motions.add(decomposeH.decompose(H));
		}

		status("Estimating Radial Distortion");
		computeRadial.process(K, homographies, observations);

		double distort[] = computeRadial.getParameters();

		convertIntoBundleStructure(motions, K,distort,observations);
		return true;
	}
1109592
def _log_linear_interpolation(predictions):
        
        log_probs = utils.average_arrays([p.log() for p in predictions])
        # pylint: disable=invalid-unary-operand-type
        return -log_probs.log_softmax()
820220
def calculate_linear_regressor_output_shapes(operator):
    '''
    
    '''
    check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)

    N = operator.inputs[0].type.shape[0]
    op = operator.raw_operator
    if hasattr(op, 'n_outputs_'):
        nout = op.n_outputs_
    else:
        nout = 1
    operator.outputs[0].type = FloatTensorType([N, nout])
105064
private void gaussNewton( double betas[] ) {

		A_temp.reshape(L_full.numRows, numControl);
		v_temp.reshape(L_full.numRows, 1);
		x.reshape(numControl,1,false);

		// don't check numControl inside in hope that the JVM can optimize the code better
		if( numControl == 4 ) {
			for( int i = 0; i < numIterations; i++ ) {
				UtilLepetitEPnP.jacobian_Control4(L_full,betas, A_temp);
				UtilLepetitEPnP.residuals_Control4(L_full,y,betas,v_temp.data);

				if( !solver.setA(A_temp) )
					return;

				solver.solve(v_temp,x);

				for( int j = 0; j < numControl; j++ ) {
					betas[j] -= x.data[j];
				}
			}
		} else {
			for( int i = 0; i < numIterations; i++ ) {
				UtilLepetitEPnP.jacobian_Control3(L_full,betas, A_temp);
				UtilLepetitEPnP.residuals_Control3(L_full,y,betas,v_temp.data);

				if( !solver.setA(A_temp) )
					return;

				solver.solve(v_temp,x);

				for( int j = 0; j < numControl; j++ ) {
					betas[j] -= x.data[j];
				}
			}
		}
	}
827941
public static LinearSolverDense<DMatrixRMaj> general(int numRows , int numCols ) {
        if( numRows == numCols )
            return linear(numRows);
        else
            return leastSquares(numRows,numCols);
    }
200404
private static double[] calcLinReg(double[] xData, double[] yData) {
        double sumX = 0;
        double sumY = 0;
        double prod = 0;
        int nstat = xData.length;
        double[] regCoef = new double[3]; //(intercept, gradient, r2)

        double meanYValue = mean(yData);
        double meanXValue = mean(xData);

        //calculating regression coefficients
        for (int i = 0; i < nstat; i++) {
            sumX += (xData[i] - meanXValue) * (xData[i] - meanXValue);
            sumY += (yData[i] - meanYValue) * (yData[i] - meanYValue);
            prod += (xData[i] - meanXValue) * (yData[i] - meanYValue);
        }
        if (sumX > 0 && sumY > 0) {
            regCoef[1] = prod / sumX;  //gradient
            regCoef[0] = meanYValue - regCoef[1] * meanXValue; //intercept
            regCoef[2] = Math.pow((prod / Math.sqrt(sumX * sumY)), 2); //r2
        }
        return regCoef;
    }
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])
98839
def obfn_reg(self):
        

        rl1 = np.linalg.norm((self.wl1 * self.obfn_gvar()).ravel(), 1)
        rl2 = 0.5*np.linalg.norm(self.obfn_gvar())**2
        return (self.lmbda*rl1 + self.mu*rl2, rl1, rl2)
910003
def _residual(x, in_filter, out_filter, stride,
              activate_before_residual=False):
  """"""
  if activate_before_residual:
    with tf.variable_scope('shared_activation'):
      x = _batch_norm('init_bn', x)
      x = _relu(x, 0.1)
      orig_x = x
  else:
    with tf.variable_scope('residual_only_activation'):
      orig_x = x
      x = _batch_norm('init_bn', x)
      x = _relu(x, 0.1)

  with tf.variable_scope('sub1'):
    x = _conv('conv1', x, 3, in_filter, out_filter, stride)

  with tf.variable_scope('sub2'):
    x = _batch_norm('bn2', x)
    x = _relu(x, 0.1)
    x = _conv('conv2', x, 3, out_filter, out_filter, [1, 1, 1, 1])

  with tf.variable_scope('sub_add'):
    if in_filter != out_filter:
      orig_x = tf.nn.avg_pool(orig_x, stride, stride, 'VALID')
      orig_x = tf.pad(
          orig_x, [[0, 0], [0, 0],
                   [0, 0], [(out_filter - in_filter) // 2,
                            (out_filter - in_filter) // 2]])
    x += orig_x

  tf.logging.debug('image after unit %s', x.get_shape())
  return x
430819
def _xval_model_error(self, fit_spectra, reject_outliers, fit_lb, fit_ub,
                           fitter, func):
        
        set1 = fit_spectra[::2]
        set2 = fit_spectra[1::2]
        errs = []
        signal_select = [] 
        models = []
        signals = []
        for this_set in [set1, set2]:
            choose_transients, model, signal, params, this_idx =\
                self._fit_helper(this_set, reject_outliers,
                                 fit_lb, fit_ub, fitter)
            models.append(np.nanmean(model[choose_transients], 0))
            signals.append(np.nanmean(signal[choose_transients], 0))

            signal_select.append(signal[choose_transients])
                
        #Cross-validation error estimation:
        model_err = np.mean([ut.rmse(models[0], signals[1]),
                              ut.rmse(models[1], signals[0])])
        # Also for the signal:
        signal_err = ut.rmse(np.nanmean(signal_select[0], 0),
                             np.nanmean(signal_select[1], 0))
        # Based on the errors, choose a function. Also report errors:
        return model_err, signal_err
304644
def _outlier_rejection(self, params, model, signal, ii):
        
        # Z score across repetitions:
        z_score = (params - np.mean(params, 0))/np.std(params, 0)
        # Silence warnings: 
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            outlier_idx = np.where(np.abs(z_score)>3.0)[0]
            nan_idx = np.where(np.isnan(params))[0]
            outlier_idx = np.unique(np.hstack([nan_idx, outlier_idx]))
            ii[outlier_idx] = 0
            model[outlier_idx] = np.nan
            signal[outlier_idx] = np.nan
            params[outlier_idx] = np.nan

        return model, signal, params, ii
92534
def _lmder1_linear_r1zcr(n, m, factor, target_fnorm1, target_fnorm2, target_params):
    """"""

    def func(params, vec):
        s = 0
        for j in range(1, n - 1):
            s += (j + 1) * params[j]
        for i in range(m):
            vec[i] = i * s - 1
        vec[m-1] = -1

    def jac(params, jac):
        jac.fill(0)

        for i in range(1, n - 1):
            for j in range(1, m - 1):
                jac[i,j] = j * (i + 1)

    guess = np.ones(n) * factor

    #_lmder1_test(m, func, jac, guess)
    _lmder1_driver(m, func, jac, guess,
                   target_fnorm1, target_fnorm2, None)
413876
def plot_series_residuals_internal(self, varied_data, varied_idx, **kwargs):
        
        nf = len(self.f_cb(*self.pre_process(
            self.internal_xout[0], self.internal_params_out[0])))
        xerr = np.empty((self.internal_xout.shape[0], nf))
        for idx, (res, params) in enumerate(zip(self.internal_xout, self.internal_params_out)):
            xerr[idx, :] = self.f_cb(res, params)
        return self.plot_series(xerr, varied_data, varied_idx, **kwargs)
1317416
def interpolate_linear(self, lons, lats, data):
        
        return self.interpolate(lons, lats, data, order=1)