Returns the errors between the observed values and the one step
 ahead forecasts.
320169
def errors
      @errors ||= @time_series.zip(one_step_ahead_forecasts).map do |(observation, forecast)|
        forecast - observation if forecast && observation
      end
    end
1171054
private Metric predictAnomalies() {
        Metric predictions = new Metric(getResultScopeName(), getResultMetricName());
        Map<Long, Double> predictionDatapoints = new HashMap<>();

        double[][] noiseMatrix = rpca.getE().getData();
        double[] noiseVector = matrixToVector(noiseMatrix);

        for (int i = 0; i < noiseVector.length; i++) {
            Long timestamp = timestamps[i];
            double noiseValue = noiseVector[i];
            double anomalyScore = calculateAnomalyScore(noiseValue);
            predictionDatapoints.put(timestamp, anomalyScore);
        }

        predictions.setDatapoints(predictionDatapoints);
        return predictions;
    }
175567
def predict_proba(self, dataframe):
        
        ret = numpy.ones((dataframe.shape[0], 2))
        ret[:, 0] = (1 - self.mean)
        ret[:, 1] = self.mean
        return ret
156391
def map_forecast_estimate(self):
        
        assert self.forecasts is not None
        islog = self.pst.parameter_data.partrans == "log"
        par_map = self.map_parameter_estimate
        par_map.loc[islog,:] = np.log10(par_map.loc[islog,:])
        par_map = Matrix.from_dataframe(par_map.loc[:,["post_expt"]])
        posts,priors = [],[]
        post_expt = (self.predictions.T * par_map).to_dataframe()
        for fname in self.forecast_names:
            #fname = forecast.col_names[0]
            pr = self.pst.res.loc[fname,"modelled"]
            priors.append(pr)
            posts.append(pr + post_expt.loc[fname,"post_expt"])
        return pd.DataFrame(data=np.array([priors,posts]).transpose(),
                            columns=["prior_expt","post_expt"],
                            index=self.forecast_names)
880242
def _std_err(self):
        
        return np.sqrt(np.sum(np.square(self._resids), axis=1) / self._df_err)
579729
def _check_time_series(self, other):
        
        if not isinstance(other, TimeSeries):
            msg = "unsupported operand types(s) for +: %s and %s" % \
                  (type(self), type(other))
            raise TypeError(msg)
1152209
def mean_squared_error(true, pred):
  
  result = tf.reduce_sum(
      tf.squared_difference(true, pred)) / tf.to_float(tf.size(pred))
  return result
957755
def _handle_outliers(self, p_o):
        
        if self.ignore_outliers:
            outliers = np.where(p_o.sum(axis=1)==0)[0]
            if outliers.size > 0:
                p_o[outliers, :] = 1.0
                self.found_outliers = True
        return p_o
571905
def get_anomalies(smoothed_errors, y_true, z, window, all_anomalies, error_buffer):
    

    mu = np.mean(smoothed_errors)
    sigma = np.std(smoothed_errors)

    epsilon = mu + (z * sigma)

    # compare to epsilon
    errors_seq, anomaly_indices, max_error_below_e = group_consecutive_anomalies(
        smoothed_errors,
        epsilon,
        y_true,
        error_buffer,
        window,
        all_anomalies
    )

    if len(errors_seq) > 0:
        anomaly_indices = prune_anomalies(
            errors_seq,
            smoothed_errors,
            max_error_below_e,
            anomaly_indices
        )

    return anomaly_indices
331303
def compute_absolute_error(self, predicted_data, record, dataframe_record):
        ''''''
        absolute_error = abs(record['DDG'] - predicted_data[self.ddg_analysis_type])
        dataframe_record['AbsoluteError'] = absolute_error
450563
def on_backward_end(self, **kwargs):
        ""
        if (self.acc_batches % self.n_step) == 0:
            for p in (self.learn.model.parameters()):
                if p.requires_grad: p.grad.div_(self.acc_samples)
            self.acc_samples = 0
        else: return {'skip_step':True, 'skip_zero':True}
682447
def trend_coefficients(self, order=LINEAR):
        ''''''
        if not len(self.points):
            raise ArithmeticError('Cannot calculate the trend of an empty series')
        return LazyImport.numpy().polyfit(self.timestamps, self.values, order)
314435
public static double rootMeansSquaredError(double[] real, double[] predicted) {
        double ret = 0.0;
        for (int i = 0; i < real.length; i++) {
            ret += Math.pow((real[i] - predicted[i]), 2);
        }
        return Math.sqrt(ret / real.length);
    }
513167
private int getMinErrorRateWindowSizeIncremental() {
		int numSamples = this.stm.numInstances();
		if (numSamples < 2 * this.minSTMSizeOption.getValue()) {
			return numSamples;
		} else {
			List<Integer> numSamplesRange = new ArrayList<>();
			numSamplesRange.add(numSamples);
			while (numSamplesRange.get(numSamplesRange.size() - 1) >= 2 * this.minSTMSizeOption.getValue())
				numSamplesRange.add(numSamplesRange.get(numSamplesRange.size() - 1) / 2);
			List<Double> errorRates = new ArrayList<>();
			for (Integer numSamplesIt : numSamplesRange) {
				int idx = numSamples - numSamplesIt;
				List<Integer> predHistory;
				if (this.predictionHistories.containsKey(idx)) {
					predHistory = this.getIncrementalTestTrainPredHistory(this.stm, idx, this.predictionHistories.get(idx));
				} else if (this.predictionHistories.containsKey(idx-1)){
					predHistory = this.predictionHistories.remove(idx-1);
					predHistory.remove(0);
					predHistory = this.getIncrementalTestTrainPredHistory(this.stm, idx, predHistory);
					this.predictionHistories.put(idx, predHistory);
				} else {
					predHistory = this.getTestTrainPredHistory(this.stm, idx);
					this.predictionHistories.put(idx, predHistory);
				}
				errorRates.add(this.getHistoryErrorRate(predHistory));
			}
			int minErrorRateIdx = errorRates.indexOf(Collections.min(errorRates));
			if (minErrorRateIdx > 0) {
				for (int i = 1; i < errorRates.size(); i++){
					if (errorRates.get(i) < errorRates.get(0)){
						int idx = numSamples - numSamplesRange.get(i);
						List<Integer> predHistory = this.getTestTrainPredHistory(this.stm, idx);
						errorRates.set(i, this.getHistoryErrorRate(predHistory));
						this.predictionHistories.remove(idx);
						this.predictionHistories.put(idx, predHistory);
					}
				}
				minErrorRateIdx = errorRates.indexOf(Collections.min(errorRates));
			}
			int windowSize = numSamplesRange.get(minErrorRateIdx);
			if (windowSize < numSamples) {
				this.adaptHistories(minErrorRateIdx);
			}
			return windowSize;
		}
	}
82923
def isValidationInProgress(self):
        
        today = DateTime()
        down_from = self.getDownFrom()
        down_to = self.getDownTo()

        return down_from <= today <= down_to
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
81144
def click_estimate_difference():
    

    c1 = _pylab.ginput()
    if len(c1)==0:
        return None

    c2 = _pylab.ginput()
    if len(c2)==0:
        return None

    return [c2[0][0]-c1[0][0], c2[0][1]-c1[0][1]]