code
stringlengths
73
34.1k
label
stringclasses
1 value
public Vec feedfoward(Vec x) { Vec a_lprev = x; for (int l = 0; l < layersActivation.size(); l++) { Vec z_l = new DenseVector(layerSizes[l+1]); z_l.zeroOut(); W.get(l).multiply(a_lprev, 1.0, z_l); //add the bias term back in ...
java
private static void applyDropout(final Matrix X, final int randThresh, final Random rand, ExecutorService ex) { if (ex == null) { for (int i = 0; i < X.rows(); i++) for (int j = 0; j < X.cols(); j++) if (rand.nextInt() < randThresh) ...
java
private DataPoint getPredVecR(DataPoint data) { Vec w = new DenseVector(baseRegressors.size()); for (int i = 0; i < baseRegressors.size(); i++) w.set(i, baseRegressors.get(i).regress(data)); return new DataPoint(w); }
java
public static int getNextPow2TwinPrime(int m) { int pos = Arrays.binarySearch(twinPrimesP2, m+1); if(pos >= 0) return twinPrimesP2[pos]; else return twinPrimesP2[-pos - 1]; }
java
public void replaceNumericFeatures(List<Vec> newNumericFeatures) { if(this.size() != newNumericFeatures.size()) throw new RuntimeException("Input list does not have the same not of dataums as the dataset"); for(int i = 0; i < newNumericFeatures.size(); i++) { ...
java
protected void base_add(DataPoint dp, double weight) { datapoints.addDataPoint(dp); setWeight(size()-1, weight); }
java
public Iterator<DataPoint> getDataPointIterator() { Iterator<DataPoint> iteData = new Iterator<DataPoint>() { int cur = 0; int to = size(); @Override public boolean hasNext() { return cur < to; } ...
java
public Type getMissingDropped() { List<Integer> hasNoMissing = new IntList(); for (int i = 0; i < size(); i++) { DataPoint dp = getDataPoint(i); boolean missing = dp.getNumericalValues().countNaNs() > 0; for(int c : dp.getCategoricalValues()) ...
java
public List<Type> randomSplit(Random rand, double... splits) { if(splits.length < 1) throw new IllegalArgumentException("Input array of split fractions must be non-empty"); IntList randOrder = new IntList(size()); ListUtils.addRange(randOrder, 0, size(), 1); Collect...
java
public List<DataPoint> getDataPoints() { List<DataPoint> list = new ArrayList<>(size()); for(int i = 0; i < size(); i++) list.add(getDataPoint(i)); return list; }
java
public List<Vec> getDataVectors() { List<Vec> vecs = new ArrayList<>(size()); for(int i = 0; i < size(); i++) vecs.add(getDataPoint(i).getNumericalValues()); return vecs; }
java
public void setWeight(int i, double w) { if(i >= size() || i < 0) throw new IndexOutOfBoundsException("Dataset has only " + size() + " members, can't access index " + i ); else if(Double.isNaN(w) || Double.isInfinite(w) || w < 0) throw new ArithmeticException("Invalid we...
java
public double getWeight(int i) { if(i >= size() || i < 0) throw new IndexOutOfBoundsException("Dataset has only " + size() + " members, can't access index " + i ); if(weights == null) return 1; else if(weights.length <= i) return 1; ...
java
public Vec getDataWeights() { final int N = this.size(); if(N == 0) return new DenseVector(0); //assume everyone has the same weight until proven otherwise. double weight = getWeight(0); double[] weights_copy = null; for(int i = 1; i < N;...
java
public <Type extends DataSet> OnLineStatistics[] evaluateFeatureImportance(DataSet<Type> data, TreeFeatureImportanceInference imp) { OnLineStatistics[] importances = new OnLineStatistics[data.getNumFeatures()]; for(int i = 0; i < importances.length; i++) importances[i] = new OnLineStatis...
java
@WarmParameter(prefLowToHigh = true) public void setC(double C) { if(C <= 0 || Double.isInfinite(C) || Double.isNaN(C)) throw new IllegalArgumentException("Regularization term C must be a positive value, not " + C); this.C = C; }
java
private double getM_Bar_for_w0(int n, int l, List<Vec> columnsOfX, double[] col_neg_class_sum, double col_neg_class_sum_bias) { /** * if w=0, then D_part[i] = 0.5 for all i */ final double D_part_i = 0.5; //algo 3, Step 1. double M_bar = 0; ...
java
public void add(double x, double weight) { //See http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance if(weight < 0) throw new ArithmeticException("Can not add a negative weight"); else if(weight == 0) return; double n1 = n; n+=weig...
java
public void setBurnIn(double burnIn) { if(Double.isNaN(burnIn) || burnIn < 0 || burnIn >= 1) throw new IllegalArgumentException("BurnInFraction must be in [0, 1), not " + burnIn); this.burnIn = burnIn; }
java
public boolean add(int e) { if(e < 0 || e >= has.length) throw new IllegalArgumentException("Input must be in range [0, " + has.length + ") not " + e); else if(contains(e) ) return false; else { if (nnz == 0) { first = e...
java
public static List<Integer> unmodifiableView(int[] array, int length) { return Collections.unmodifiableList(view(array, length)); }
java
public static IntList view(int[] array, int length) { if(length > array.length || length < 0) throw new IllegalArgumentException("length must be non-negative and no more than the size of the array("+array.length+"), not " + length); return new IntList(array, length); }
java
public static IntList range(int start, int end, int step) { IntList l = new IntList((end-start)/step +1); for(int i = start; i < end; i++) l.add(i); return l; }
java
public int dataPointToCord(DataPointPair<Integer> dataPoint, int targetClass, int[] cord) { if(cord.length != getDimensionSize()) throw new ArithmeticException("Storage space and CPT dimension miss match"); DataPoint dp = dataPoint.getDataPoint(); int skipVal = -1; //Set ...
java
public double query(int targetClass, int targetValue, int[] cord) { double sumVal = 0; double targetVal = 0; int realTargetIndex = catIndexToRealIndex[targetClass]; CategoricalData queryData = valid.get(targetClass); //Now do all other target class posibilt...
java
public static Map<String, Parameter> toParameterMap(List<Parameter> params) { Map<String, Parameter> map = new HashMap<String, Parameter>(params.size()); for(Parameter param : params) { if(map.put(param.getASCIIName(), param) != null) throw new RuntimeException("N...
java
private static String spaceCamelCase(String in) { StringBuilder sb = new StringBuilder(in.length()+5); for(int i = 0; i < in.length(); i++) { char c = in.charAt(i); if(Character.isUpperCase(c)) sb.append(' '); sb.append(c); } ...
java
public static Distribution guessNumberOfBins(DataSet data) { if(data.size() < 20) return new UniformDiscrete(2, data.size()-1); else if(data.size() >= 1000000) return new LogUniform(50, 1000); int sqrt = (int) Math.sqrt(data.size()); return new UniformDiscrete...
java
private SingularValueDecomposition getSVD(DataSet dataSet) { Matrix cov = covarianceMatrix(meanVector(dataSet), dataSet); for(int i = 0; i < cov.rows(); i++)//force it to be symmetric for(int j = 0; j < i; j++) cov.set(j, i, cov.get(i, j)); EigenValueDecomposition...
java
public double backwardNaive(int n, double... args) { double term = getA(n, args)/getB(n,args); for(n = n-1; n >0; n--) { term = getA(n, args)/(getB(n,args)+term); } return term + getB(0, args); }
java
public double lentz(double... args) { double f_n = getB(0, args); if(f_n == 0.0) f_n = 1e-30; double c_n, c_0 = f_n; double d_n, d_0 = 0; double delta = 0; int j = 0; while(Math.abs(delta - 1) > 1e-15) { ...
java
public static List<List<DataPoint>> createClusterListFromAssignmentArray(int[] assignments, DataSet dataSet) { List<List<DataPoint>> clusterings = new ArrayList<>(); for(int i = 0; i < dataSet.size(); i++) { while(clusterings.size() <= assignments[i]) ...
java
public static List<DataPoint> getDatapointsFromCluster(int c, int[] assignments, DataSet dataSet, int[] indexFrom) { List<DataPoint> list = new ArrayList<>(); int pos = 0; for(int i = 0; i < dataSet.size(); i++) if(assignments[i] == c) { list.ad...
java
public Complex add(Complex c) { Complex ret = new Complex(real, imag); ret.mutableAdd(c); return ret; }
java
public Complex subtract(Complex c) { Complex ret = new Complex(real, imag); ret.mutableSubtract(c); return ret; }
java
public static void cMul(double a, double b, double c, double d, double[] results) { results[0] = a*c-b*d; results[1] = b*c+a*d; }
java
public void mutableMultiply(double c, double d) { double newR = this.real*c-this.imag*d; double newI = this.imag*c+this.real*d; this.real = newR; this.imag = newI; }
java
public Complex multiply(Complex c) { Complex ret = new Complex(real, imag); ret.mutableMultiply(c); return ret; }
java
public void mutableDivide(double c, double d) { final double[] r = new double[2]; cDiv(real, imag, c, d, r); this.real = r[0]; this.imag = r[1]; }
java
public Complex divide(Complex c) { Complex ret = new Complex(real, imag); ret.mutableDivide(c); return ret; }
java
public void setDelta(double delta) { if(delta <= 0 || delta >= 1 || Double.isNaN(delta)) throw new IllegalArgumentException("delta must be in (0,1), not " + delta); this.delta = delta; }
java
private void compress() { //compress ListIterator<OnLineStatistics> listIter = windows.listIterator(); double lastSizeSeen = -Double.MAX_VALUE; int lastSizeCount = 0; while(listIter.hasNext()) { OnLineStatistics window = listIter.next(); ...
java
private void computeSubClusterSplit(final int[][] subDesignation, int originalCluster, List<DataPoint> listOfDataPointsInCluster, DataSet fullDataSet, int[] fullDesignations, final int[][] originalPositions, final double[] splitEvaluation, PriorityQueue<Integer> cluste...
java
public static double sampleCorCoeff(Vec xData, Vec yData) { if(yData.length() != xData.length()) throw new ArithmeticException("X and Y data sets must have the same length"); double xMean = xData.mean(); double yMean = yData.mean(); double topSum = 0; for(int i...
java
public void setRange(double A, double B) { if(A == B) throw new RuntimeException("Values must be different"); else if(B > A) { double tmp = A; A = B; B = tmp; } this.A = A; this.B = B; }
java
private double queryWork(Vec x, Set<Integer> validIndecies, SparseVector logProd) { if(originalVecs == null) throw new UntrainedModelException("Model has not yet been created, queries can not be perfomed"); double logH = 0; for(int i = 0; i < sortedDimVals.length; i++) { ...
java
static private <T> void fillList(final int listsToAdd, Stack<List<T>> reusableLists, List<List<T>> aSplit) { for(int j = 0; j < listsToAdd; j++) if(reusableLists.isEmpty()) aSplit.add(new ArrayList<>()); else aSplit.add(reusableLists.pop()); }
java
private void batch_insert(Collection<Integer> set, boolean parallel) { for(int i : set) store[size++] = i; if(parallel) Arrays.parallelSort(store, 0, size); else Arrays.sort(store, 0, size); }
java
public void setMinMax(double min, double max) { if(min <= 0 || Double.isNaN(min) || Double.isInfinite(min)) throw new IllegalArgumentException("min value must be positive, not " + min); else if(min >= max || Double.isNaN(max) || Double.isInfinite(max)) throw new IllegalArgume...
java
public static void write(ClassificationDataSet data, OutputStream os) { PrintWriter writer = new PrintWriter(os); for(int i = 0; i < data.size(); i++) { int pred = data.getDataPointCategory(i); Vec vals = data.getDataPoint(i).getNumericalValues(); writer.w...
java
protected static double eq24(final double beta_i, final double gN, final double gP, final double U) { //6.2.2 double vi = 0;//Used as "other" value if(beta_i == 0)//if beta_i = 0 ... { //if beta_i = 0 and g'n(beta_i) >= 0 if(gN >= 0) ...
java
public int getSplittingAttribute() { //TODO refactor the splittingAttribute to just be in this order already if(splittingAttribute < catAttributes.length)//categorical feature return numNumericFeatures+splittingAttribute; //else, is Numerical attribute int numerAttribute ...
java
protected double getGain(ImpurityScore origScore, ClassificationDataSet source, List<IntList> aSplit) { ImpurityScore[] scores = getSplitScores(source, aSplit); return ImpurityScore.gain(origScore, scores); }
java
public int whichPath(DataPoint data) { int paths = getNumberOfPaths(); if(paths < 0) return paths;//Not trained else if(paths == 1)//ONLY one option, entropy was zero return 0; else if(splittingAttribute < catAttributes.length)//Same for classification and reg...
java
public CategoricalResults result(int i) { if(i < 0 || i >= getNumberOfPaths()) throw new IndexOutOfBoundsException("Invalid path, can to return a result for path " + i); return results[i]; }
java
public List<ClassificationDataSet> trainC(ClassificationDataSet dataPoints, Set<Integer> options) { return trainC(dataPoints, options, false); }
java
static protected <T> void distributMissing(List<ClassificationDataSet> splits, double[] fracs, ClassificationDataSet source, IntList hadMissing) { for (int i : hadMissing) { DataPoint dp = source.getDataPoint(i); for (int j = 0; j < fracs.length; j++) { double nw = fracs[j] * source.getWeight(i)...
java
public void setMaxTokenLength(int maxTokenLength) { if(maxTokenLength < 1) throw new IllegalArgumentException("Max token length must be positive, not " + maxTokenLength); if(maxTokenLength <= minTokenLength) throw new IllegalArgumentException("Max token length must be larger ...
java
public void setMinTokenLength(int minTokenLength) { if(minTokenLength < 0) throw new IllegalArgumentException("Minimum token length must be non negative, not " + minTokenLength); if(minTokenLength > maxTokenLength) throw new IllegalArgumentException("Minimum token length can ...
java
public void addNewKernelPoint() { KernelPoint source = points.get(0); KernelPoint toAdd = new KernelPoint(k, errorTolerance); toAdd.setMaxBudget(maxBudget); toAdd.setBudgetStrategy(budgetStrategy); standardMove(toAdd, source); toAdd.kernelAccel = source.kerne...
java
private void standardMove(KernelPoint destination, KernelPoint source) { destination.InvK = source.InvK; destination.InvKExpanded = source.InvKExpanded; destination.K = source.K; destination.KExpanded = source.KExpanded; }
java
public List<Vec> getRawBasisVecs() { List<Vec> vecs = new ArrayList<Vec>(getBasisSize()); vecs.addAll(this.points.get(0).vecs); return vecs; }
java
private void addMissingZeros() { //go back and add 0s for the onces we missed for (int i = 0; i < points.size(); i++) while(points.get(i).alpha.size() < this.points.get(0).vecs.size()) points.get(i).alpha.add(0.0); }
java
private void updateAverage() { if(t == last_t || t < burnIn) return; else if(last_t < burnIn)//first update since done burning { for(int i = 0; i < alphaAveraged.size(); i++) alphaAveraged.set(i, alphas.get(i)); } double w = t-last_t;/...
java
public void setSigma(double sigma) { if(sigma <= 0 || Double.isNaN(sigma) || Double.isInfinite(sigma)) throw new IllegalArgumentException("Sigma must be a positive constant, not " + sigma); this.sigma = sigma; this.sigmaSqrd2Inv = 0.5/(sigma*sigma); }
java
public void setMaxScaled(double maxFeature) { if(Double.isNaN(maxFeature)) throw new ArithmeticException("NaN is not a valid feature value"); else if(maxFeature > 1) throw new ArithmeticException("Maximum possible feature value is 1, can not use " + maxFeature); else ...
java
public void setMinScaled(double minFeature) { if(Double.isNaN(minFeature)) throw new ArithmeticException("NaN is not a valid feature value"); else if(minFeature < -1) throw new ArithmeticException("Minimum possible feature value is -1, can not use " + minFeature); els...
java
public void setOmega(double omega) { if(omega <= 0 || Double.isNaN(omega) || Double.isInfinite(omega)) throw new ArithmeticException("omega must be positive, not " + omega); this.omega = omega; this.cnst = Math.sqrt(Math.pow(2, 1/omega)-1); }
java
public void setSigma(double sigma) { if(sigma <= 0 || Double.isNaN(sigma) || Double.isInfinite(sigma)) throw new ArithmeticException("sigma must be positive, not " + sigma); this.sigma = sigma; }
java
private static Vec getColumn(Matrix x) { Vec t; for(int i = 0; i < x.cols(); i++) { t = x.getColumn(i); if(t.dot(t) > 0 ) return t; } throw new ArithmeticException("Matrix is essentially zero"); }
java
private void doWarmStartIfNotNull(Object warmSolution) throws FailedToFitException { if(warmSolution != null ) { if(warmSolution instanceof SimpleWeightVectorModel) { SimpleWeightVectorModel warm = (SimpleWeightVectorModel) warmSolution; if(war...
java
public static <T> List<T> mergedView(final List<T> left, final List<T> right) { List<T> merged = new AbstractList<T>() { @Override public T get(int index) { if(index < left.size()) return left.get(index); else ...
java
public static <T> List<T> collectFutures(Collection<Future<T>> futures) throws ExecutionException, InterruptedException { ArrayList<T> collected = new ArrayList<T>(futures.size()); for (Future<T> future : futures) collected.add(future.get()); return collected; }
java
public static IntList range(int start, int to, int step) { if(to < start) throw new RuntimeException("starting index " + start + " must be less than or equal to ending index" + to); else if(step < 1) throw new RuntimeException("Step size must be a positive integer, not " + st...
java
protected double invCdfRootFinding(double p, double tol) { if (p < 0 || p > 1) throw new ArithmeticException("Value of p must be in the range [0,1], not " + p); //two special case checks, as they can cause a failure to get a positive and negative value on the ends, which means we can...
java
public void setMomentum(double momentum) { if(momentum <= 0 || momentum >= 1 || Double.isNaN(momentum)) throw new IllegalArgumentException("Momentum must be in (0,1) not " + momentum); this.momentum = momentum; }
java
public static double logPdf(double x, double mu, double sigma) { return -0.5*log(2*PI) - log(sigma) + -pow(x-mu,2)/(2*sigma*sigma); }
java
public void setEta(double eta) { if(Double.isNaN(eta) || Double.isInfinite(eta) || eta <= 0) throw new ArithmeticException("convergence parameter must be a positive value"); this.eta = eta; }
java
public void setEpsilon(double eps) { if(eps < 0 || Double.isInfinite(eps) || Double.isNaN(eps)) throw new ArithmeticException("Regularization must be a positive value"); this.eps = eps; }
java
private int threshHoldExtractCluster(List<Integer> orderedFile, int[] designations) { int clustersFound = 0; OnLineStatistics stats = new OnLineStatistics(); for(double r : reach_d) if(!Double.isInfinite(r)) stats.add(r); double thresh = stats.get...
java
public void setK(final int K) { if(K < 2) throw new IllegalArgumentException("At least 2 topics must be learned"); this.K = K; gammaLocal = new ThreadLocal<Vec>() { @Override protected Vec initialValue() { return new Den...
java
public void setTau0(double tau0) { if(tau0 <= 0 || Double.isInfinite(tau0) || Double.isNaN(tau0)) throw new IllegalArgumentException("Eta must be a positive constant, not " + tau0); this.tau0 = tau0; }
java
public void setKappa(double kappa) { if(kappa < 0.5 || kappa > 1.0 || Double.isNaN(kappa)) throw new IllegalArgumentException("Kapp must be in [0.5, 1], not " + kappa); this.kappa = kappa; }
java
public Vec getTopicVec(int k) { return new ScaledVector(1.0/lambda.get(k).sum(), lambda.get(k)); }
java
public void model(DataSet dataSet, int topics, ExecutorService ex) { if(ex == null) ex = new FakeExecutor(); //Use notation same as original paper setK(topics); setD(dataSet.size()); setVocabSize(dataSet.getNumNumericalVars()); final List<Vec> doc...
java
private void prepareGammaTheta(Vec gamma_i, Vec eLogTheta_i, Vec expLogTheta_i, Random rand) { final double lambdaInv = (W * K) / (D * 100.0); for (int j = 0; j < gamma_i.length(); j++) gamma_i.set(j, sampleExpoDist(lambdaInv, rand.nextDouble()) + eta); expandPsiMinusPsiSum(gamm...
java
public void addNode(N node) { if(!nodes.containsKey(node)) nodes.put(node, new Pair<HashSet<N>, HashSet<N>>(new HashSet<N>(), new HashSet<N>())); }
java
public Set<N> getParents(N n) { Pair<HashSet<N>, HashSet<N>> p = nodes.get(n); if(p == null) return null; return p.getIncoming(); }
java
public Set<N> getChildren(N n) { Pair<HashSet<N>, HashSet<N>> p = nodes.get(n); if(p == null) return null; return p.getOutgoing(); }
java
public void removeNode(N node) { Pair<HashSet<N>, HashSet<N>> p = nodes.remove(node); if(p == null) return; //Outgoing edges we can ignore removint he node drops them. We need to avoid dangling incoming edges to this node we have removed HashSet<N> incomingNodes = p.getIn...
java
public void depends(int parent, int child) { dag.addNode(child); dag.addNode(parent); dag.addEdge(parent, child); }
java
public void setTau(double tau) { if(tau <= 0 || Double.isInfinite(tau) || Double.isNaN(tau)) throw new IllegalArgumentException("tau must be a positive constant, not " + tau); this.tau = tau; }
java
public double regress(DataPoint dp) { TreeNodeVisitor node = this; while(!node.isLeaf()) { int path = node.getPath(dp); if(path < 0 )//missing value case { double sum = 0; double resultSum = 0; for(int child ...
java
public final double updateAndGet(DoubleUnaryOperator updateFunction) { double prev, next; do { prev = get(); next = updateFunction.applyAsDouble(prev); } while (!compareAndSet(prev, next)); return next; }
java
public final double getAndAccumulate(double x, DoubleBinaryOperator accumulatorFunction) { double prev, next; do { prev = get(); next = accumulatorFunction.applyAsDouble(prev, x); } while (!compareAndSet(prev, next)); return prev; ...
java
public void applyTo(List<String> list) { for(int i = 0; i < list.size(); i++) list.set(i, stem(list.get(i))); }
java
public void applyTo(String[] arr) { for(int i = 0; i < arr.length; i++) arr[i] = stem(arr[i]); }
java
private void updateSetsLabeled(int i1, final double a1, final double C) { final double y_i = label[i1]; I1[i1] = a1 == 0 && y_i == 1; I2[i1] = a1 == C && y_i == -1; I3[i1] = a1 == C && y_i == 1; I4[i1] = a1 == 0 && y_i == -1; }
java
private void updateThreshold(int i) { double Fi = fcache[i]; double F_tilde_i = b_low; if (I0_b[i] || I2[i]) F_tilde_i = Fi + epsilon; else if (I0_a[i] || I1[i]) F_tilde_i = Fi - epsilon; double F_bar_i = b_up; if (I0_a[i] || ...
java
protected double decisionFunction(int v) { double sum = 0; for(int i = 0; i < vecs.size(); i++) if(alphas[i] > 0) sum += alphas[i] * label[i] * kEval(v, i); return sum; }
java