code
stringlengths
11
173k
docstring
stringlengths
2
593k
func_name
stringlengths
2
189
language
stringclasses
1 value
repo
stringclasses
833 values
path
stringlengths
11
294
url
stringlengths
60
339
license
stringclasses
4 values
public double matthewsCorrelation(int classIdx) { Preconditions.checkState(numRowCounter > 0, "Cannot get Matthews correlation: no evaluation has been performed"); return EvaluationUtils.matthewsCorrelation((long) truePositives.getCount(classIdx), (long) falsePositives.getCount(classIdx), (long) falseNegatives.getCount(classIdx), (long) trueNegatives.getCount(classIdx)); }
Calculate the binary Mathews correlation coefficient, for the specified class.<br> MCC = (TP*TN - FP*FN) / sqrt((TP+FP)(TP+FN)(TN+FP)(TN+FN))<br> @param classIdx Class index to calculate Matthews correlation coefficient for
JsonDeserialize::matthewsCorrelation
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public double matthewsCorrelation(EvaluationAveraging averaging) { Preconditions.checkState(numRowCounter > 0, "Cannot get Matthews correlation: no evaluation has been performed"); int nClasses = confusion().getClasses().size(); if (averaging == EvaluationAveraging.Macro) { double macroMatthewsCorrelation = 0.0; for (int i = 0; i < nClasses; i++) { macroMatthewsCorrelation += matthewsCorrelation(i); } macroMatthewsCorrelation /= nClasses; return macroMatthewsCorrelation; } else if (averaging == EvaluationAveraging.Micro) { long tpCount = 0; long fpCount = 0; long fnCount = 0; long tnCount = 0; for (int i = 0; i < nClasses; i++) { tpCount += truePositives.getCount(i); fpCount += falsePositives.getCount(i); fnCount += falseNegatives.getCount(i); tnCount += trueNegatives.getCount(i); } return EvaluationUtils.matthewsCorrelation(tpCount, fpCount, fnCount, tnCount); } else { throw new UnsupportedOperationException("Unknown averaging approach: " + averaging); } }
Calculate the average binary Mathews correlation coefficient, using macro or micro averaging.<br> MCC = (TP*TN - FP*FN) / sqrt((TP+FP)(TP+FN)(TN+FP)(TN+FN))<br> Note: This is NOT the same as the multi-class Matthews correlation coefficient @param averaging Averaging approach @return Average
JsonDeserialize::matthewsCorrelation
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public Map<Integer, Integer> truePositives() { return convertToMap(truePositives, confusion().getClasses().size()); }
True positives: correctly rejected @return the total true positives so far
JsonDeserialize::truePositives
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public Map<Integer, Integer> trueNegatives() { return convertToMap(trueNegatives, confusion().getClasses().size()); }
True negatives: correctly rejected @return the total true negatives so far
JsonDeserialize::trueNegatives
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public Map<Integer, Integer> falsePositives() { return convertToMap(falsePositives, confusion().getClasses().size()); }
False positive: wrong guess @return the count of the false positives
JsonDeserialize::falsePositives
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public Map<Integer, Integer> falseNegatives() { return convertToMap(falseNegatives, confusion().getClasses().size()); }
False negatives: correctly rejected @return the total false negatives so far
JsonDeserialize::falseNegatives
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public Map<Integer, Integer> negative() { return addMapsByKey(trueNegatives(), falsePositives()); }
Total negatives true negatives + false negatives @return the overall negative count
JsonDeserialize::negative
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public Map<Integer, Integer> positive() { return addMapsByKey(truePositives(), falseNegatives()); }
Returns all of the positive guesses: true positive + false negative
JsonDeserialize::positive
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public void addToConfusion(Integer real, Integer guess) { confusion().add(real, guess); }
Adds to the confusion matrix @param real the actual guess @param guess the system guess
JsonDeserialize::addToConfusion
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public int classCount(Integer clazz) { return confusion().getActualTotal(clazz); }
Returns the number of times the given label has actually occurred @param clazz the label @return the number of times the label actually occurred
JsonDeserialize::classCount
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public int getTopNCorrectCount() { if (confusion == null) return 0; if (topN <= 1) { int nClasses = confusion().getClasses().size(); int countCorrect = 0; for (int i = 0; i < nClasses; i++) { countCorrect += confusion().getCount(i, i); } return countCorrect; } return topNCorrectCount; }
Return the number of correct predictions according to top N value. For top N = 1 (default) this is equivalent to the number of correct predictions @return Number of correct top N predictions
JsonDeserialize::getTopNCorrectCount
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public int getTopNTotalCount() { if (topN <= 1) { return getNumRowCounter(); } return topNTotalCount; }
Return the total number of top N evaluations. Most of the time, this is exactly equal to {@link #getNumRowCounter()}, but may differ in the case of using {@link #eval(int, int)} as top N accuracy cannot be calculated in that case (i.e., requires the full probability distribution, not just predicted/actual indices) @return Total number of top N predictions
JsonDeserialize::getTopNTotalCount
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public ConfusionMatrix<Integer> getConfusionMatrix() { return confusion; }
Returns the confusion matrix variable @return confusion matrix variable for this evaluation
JsonDeserialize::getConfusionMatrix
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public String confusionToString() { int nClasses = confusion().getClasses().size(); //First: work out the longest label size int maxLabelSize = 0; for (String s : labelsList) { maxLabelSize = Math.max(maxLabelSize, s.length()); } //Build the formatting for the rows: int labelSize = Math.max(maxLabelSize + 5, 10); StringBuilder sb = new StringBuilder(); sb.append("%-3d"); sb.append("%-"); sb.append(labelSize); sb.append("s | "); StringBuilder headerFormat = new StringBuilder(); headerFormat.append(" %-").append(labelSize).append("s "); for (int i = 0; i < nClasses; i++) { sb.append("%7d"); headerFormat.append("%7d"); } String rowFormat = sb.toString(); StringBuilder out = new StringBuilder(); //First: header row Object[] headerArgs = new Object[nClasses + 1]; headerArgs[0] = "Predicted:"; for (int i = 0; i < nClasses; i++) headerArgs[i + 1] = i; out.append(String.format(headerFormat.toString(), headerArgs)).append("\n"); //Second: divider rows out.append(" Actual:\n"); //Finally: data rows for (int i = 0; i < nClasses; i++) { Object[] args = new Object[nClasses + 2]; args[0] = i; args[1] = labelsList.get(i); for (int j = 0; j < nClasses; j++) { args[j + 2] = confusion().getCount(i, j); } out.append(String.format(rowFormat, args)); out.append("\n"); } return out.toString(); }
Get a String representation of the confusion matrix
JsonDeserialize::confusionToString
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public List<Prediction> getPredictionErrors() { if (this.confusionMatrixMetaData == null) return null; List<Prediction> list = new ArrayList<>(); List<Map.Entry<Pair<Integer, Integer>, List<Object>>> sorted = new ArrayList<>(confusionMatrixMetaData.entrySet()); Collections.sort(sorted, new Comparator<Map.Entry<Pair<Integer, Integer>, List<Object>>>() { @Override public int compare(Map.Entry<Pair<Integer, Integer>, List<Object>> o1, Map.Entry<Pair<Integer, Integer>, List<Object>> o2) { Pair<Integer, Integer> p1 = o1.getKey(); Pair<Integer, Integer> p2 = o2.getKey(); int order = Integer.compare(p1.getFirst(), p2.getFirst()); if (order != 0) return order; order = Integer.compare(p1.getSecond(), p2.getSecond()); return order; } }); for (Map.Entry<Pair<Integer, Integer>, List<Object>> entry : sorted) { Pair<Integer, Integer> p = entry.getKey(); if (p.getFirst().equals(p.getSecond())) { //predicted = actual -> not an error -> skip continue; } for (Object m : entry.getValue()) { list.add(new Prediction(p.getFirst(), p.getSecond(), m)); } } return list; }
Get a list of prediction errors, on a per-record basis<br> <p> <b>Note</b>: Prediction errors are ONLY available if the "evaluate with metadata" method is used: {@link #eval(INDArray, INDArray, List)} Otherwise (if the metadata hasn't been recorded via that previously mentioned eval method), there is no value in splitting each prediction out into a separate Prediction object - instead, use the confusion matrix to get the counts, via {@link #getConfusionMatrix()} @return A list of prediction errors, or null if no metadata has been recorded
JsonDeserialize::getPredictionErrors
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public List<Prediction> getPredictionsByActualClass(int actualClass) { if (confusionMatrixMetaData == null) return null; List<Prediction> out = new ArrayList<>(); for (Map.Entry<Pair<Integer, Integer>, List<Object>> entry : confusionMatrixMetaData.entrySet()) { //Entry Pair: (Actual,Predicted) if (entry.getKey().getFirst() == actualClass) { int actual = entry.getKey().getFirst(); int predicted = entry.getKey().getSecond(); for (Object m : entry.getValue()) { out.add(new Prediction(actual, predicted, m)); } } } return out; }
Get a list of predictions, for all data with the specified <i>actual</i> class, regardless of the predicted class. <p> <b>Note</b>: Prediction errors are ONLY available if the "evaluate with metadata" method is used: {@link #eval(INDArray, INDArray, List)} Otherwise (if the metadata hasn't been recorded via that previously mentioned eval method), there is no value in splitting each prediction out into a separate Prediction object - instead, use the confusion matrix to get the counts, via {@link #getConfusionMatrix()} @param actualClass Actual class to get predictions for @return List of predictions, or null if the "evaluate with metadata" method was not used
JsonDeserialize::getPredictionsByActualClass
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public List<Prediction> getPredictionByPredictedClass(int predictedClass) { if (confusionMatrixMetaData == null) return null; List<Prediction> out = new ArrayList<>(); for (Map.Entry<Pair<Integer, Integer>, List<Object>> entry : confusionMatrixMetaData.entrySet()) { //Entry Pair: (Actual,Predicted) if (entry.getKey().getSecond() == predictedClass) { int actual = entry.getKey().getFirst(); int predicted = entry.getKey().getSecond(); for (Object m : entry.getValue()) { out.add(new Prediction(actual, predicted, m)); } } } return out; }
Get a list of predictions, for all data with the specified <i>predicted</i> class, regardless of the actual data class. <p> <b>Note</b>: Prediction errors are ONLY available if the "evaluate with metadata" method is used: {@link #eval(INDArray, INDArray, List)} Otherwise (if the metadata hasn't been recorded via that previously mentioned eval method), there is no value in splitting each prediction out into a separate Prediction object - instead, use the confusion matrix to get the counts, via {@link #getConfusionMatrix()} @param predictedClass Actual class to get predictions for @return List of predictions, or null if the "evaluate with metadata" method was not used
JsonDeserialize::getPredictionByPredictedClass
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public List<Prediction> getPredictions(int actualClass, int predictedClass) { if (confusionMatrixMetaData == null) return null; List<Prediction> out = new ArrayList<>(); List<Object> list = confusionMatrixMetaData.get(new Pair<>(actualClass, predictedClass)); if (list == null) return out; for (Object meta : list) { out.add(new Prediction(actualClass, predictedClass, meta)); } return out; }
Get a list of predictions in the specified confusion matrix entry (i.e., for the given actua/predicted class pair) @param actualClass Actual class @param predictedClass Predicted class @return List of predictions that match the specified actual/predicted classes, or null if the "evaluate with metadata" method was not used
JsonDeserialize::getPredictions
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Apache-2.0
public static <R> MergeLambda<R> mergeConcatenate(){ return new MergeLambda<R>() { @Override public List<R> merge(List<R> a, List<R> b) { List<R> res = Lists.newArrayList(a); res.addAll(b); return res; } }; }
A MergeLambda that merges by concatenating the two lists
Metric::mergeConcatenate
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/custom/CustomEvaluation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/custom/CustomEvaluation.java
Apache-2.0
public void updateProperties(InputStream inputStream) { try { conf.load(inputStream); conf.putAll(System.getProperties()); } catch (IOException e) { log.warn("Error loading system properties from input stream", e); } }
Load the additional properties from an input stream and load all system properties @param inputStream
Nd4jContext::updateProperties
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/context/Nd4jContext.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/context/Nd4jContext.java
Apache-2.0
public Properties getConf() { return conf; }
Get the configuration for nd4j @return
Nd4jContext::getConf
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/context/Nd4jContext.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/context/Nd4jContext.java
Apache-2.0
public OpaqueNDArray(Pointer p) { super(p); }
Constructs an OpaqueNDArray from a given Pointer. @param p The Pointer object representing the native memory address.
OpaqueNDArray::OpaqueNDArray
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public static OpaqueNDArray create( OpaqueDataBuffer shapeInfo, OpaqueDataBuffer buffer, OpaqueDataBuffer specialBuffer, long offset) { return Nd4j.getNativeOps().create(shapeInfo, buffer, specialBuffer, offset); }
Creates an OpaqueNDArray with given buffers and offset. This method delegates the creation to {@link Nd4j#getNativeOps()}. @param shapeInfo The shape information buffer. @param buffer The primary data buffer. @param specialBuffer The special buffer (e.g., for GPU data). @param offset The offset in the buffer. @return A new OpaqueNDArray.
OpaqueNDArray::create
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public DataType dataType() { return ArrayOptionsHelper.dataType(extras()); }
Gets the data type of the OpaqueNDArray. This method uses {@link Nd4j#getNativeOps()} to retrieve the data type. @return The DataType of the array.
OpaqueNDArray::dataType
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public long extras() { return Shape.extras(shapeInfo()); }
Gets the extra information of the OpaqueNDArray. This method uses {@link Nd4j#getNativeOps()} to retrieve the extra information. @return A long value representing the extra information.
OpaqueNDArray::extras
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public static long getOpaqueNDArrayOffset(OpaqueNDArray array) { return Nd4j.getNativeOps().getOpaqueNDArrayOffset(array); }
Retrieves the offset of an OpaqueNDArray. This method uses {@link Nd4j#getNativeOps()} to retrieve the offset. @param array The OpaqueNDArray whose offset is to be retrieved. @return The offset value.
OpaqueNDArray::getOpaqueNDArrayOffset
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public static long[] getOpaqueNDArrayShapeInfo(OpaqueNDArray array) { LongPointer ret = Nd4j.getNativeOps().getOpaqueNDArrayShapeInfo(array); long len = Nd4j.getNativeOps().getShapeInfoLength(array); ret.capacity(len); long[] retArr = new long[(int) len]; ret.get(retArr); return retArr; }
Retrieves the shape information of an OpaqueNDArray. This method uses {@link Nd4j#getNativeOps()} to retrieve the shape information. @param array The OpaqueNDArray whose shape information is to be retrieved. @return An array of long values representing the shape information.
OpaqueNDArray::getOpaqueNDArrayShapeInfo
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public static Pointer getOpaqueNDArrayBuffer(OpaqueNDArray array) { return Nd4j.getNativeOps().getOpaqueNDArrayBuffer(array); }
Retrieves the primary buffer of an OpaqueNDArray. This method uses {@link Nd4j#getNativeOps()} to retrieve the buffer. @param array The OpaqueNDArray whose buffer is to be retrieved. @return A Pointer to the buffer.
OpaqueNDArray::getOpaqueNDArrayBuffer
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public static Pointer getOpaqueNDArraySpecialBuffer(OpaqueNDArray array) { return Nd4j.getNativeOps().getOpaqueNDArraySpecialBuffer(array); }
Retrieves the special buffer of an OpaqueNDArray. This method uses {@link Nd4j#getNativeOps()} to retrieve the special buffer. @param array The OpaqueNDArray whose special buffer is to be retrieved. @return A Pointer to the special buffer.
OpaqueNDArray::getOpaqueNDArraySpecialBuffer
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public static long getOpaqueNDArrayLength(OpaqueNDArray array) { return Nd4j.getNativeOps().getOpaqueNDArrayLength(array); }
Gets the length of the OpaqueNDArray. This method uses {@link Nd4j#getNativeOps()} to retrieve the length. @param array The OpaqueNDArray whose length is to be retrieved. @return The length of the array.
OpaqueNDArray::getOpaqueNDArrayLength
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public static void deleteNDArray(OpaqueNDArray array) { Nd4j.getNativeOps().deleteNDArray(array); }
Deletes an OpaqueNDArray. This method uses {@link Nd4j#getNativeOps()} to delete the array. @param array The OpaqueNDArray to delete.
OpaqueNDArray::deleteNDArray
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public static void delete(OpaqueNDArray array) { if (array != null && !array.isNull()) { deleteNDArray(array); array.setNull(); } }
Deletes and nullifies an OpaqueNDArray. This method uses {@link Nd4j#getNativeOps()} to delete the array. @param array The OpaqueNDArray to delete.
OpaqueNDArray::delete
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public static OpaqueNDArray fromINDArrayUncached(INDArray array) { if (array == null) { return null; } DataBuffer buffer = array.data(); DataBuffer shapeInfo = array.shapeInfoDataBuffer(); return create( shapeInfo.opaqueBuffer(), array.isEmpty() ? null : buffer.opaqueBuffer(), array.isEmpty() ? null :buffer.opaqueBuffer(), array.offset() ); }
Converts an INDArray to an OpaqueNDArray. This method uses {@link Nd4j#getNativeOps()} to create the OpaqueNDArray. @param array The INDArray to convert. @return The corresponding OpaqueNDArray.
OpaqueNDArray::fromINDArrayUncached
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public static INDArray toINDArray(OpaqueNDArray opaqueArray) { if (opaqueArray == null || opaqueArray.isNull()) { return null; } long offset = opaqueArray.getOffset(); long[] shapeInfoPtr = opaqueArray.shapeInfo(); Pointer bufferPtr = opaqueArray.buffer(); Pointer specialBufferPtr = opaqueArray.specialBuffer(); long length = opaqueArray.length(); // Extract shape information long[] shape = Shape.shape(shapeInfoPtr); long[] stride = Shape.stride(shapeInfoPtr); char order = Shape.order(shapeInfoPtr); long ews = Shape.elementWiseStride(shapeInfoPtr); long extras = Shape.extras(shapeInfoPtr); // Create LongShapeDescriptor LongShapeDescriptor descriptor = LongShapeDescriptor.builder() .shape(shape) .stride(stride) .offset(offset) .ews(ews) .order(order) .extras(extras) .build(); // Create DataBuffer from the OpaqueNDArray's buffer DataType dataType = ArrayOptionsHelper.dataType(extras); DataBuffer buffer = Nd4j.createBuffer(bufferPtr,specialBufferPtr,length,dataType); // Create INDArray using the descriptor and buffer return Nd4j.create(buffer, descriptor); }
Converts an OpaqueNDArray to an INDArray. This method uses the data and shape information from {@link Nd4j#getNativeOps()} to create the INDArray. @param opaqueArray The OpaqueNDArray to convert. @return The corresponding INDArray.
OpaqueNDArray::toINDArray
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public long getOffset() { return getOpaqueNDArrayOffset(this); }
Gets the offset of the current OpaqueNDArray. @return The offset of the array.
OpaqueNDArray::getOffset
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public long[] shapeInfo() { return getOpaqueNDArrayShapeInfo(this); }
Gets the shape information of the current OpaqueNDArray. @return An array of long values representing the shape information.
OpaqueNDArray::shapeInfo
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public Pointer buffer() { return getOpaqueNDArrayBuffer(this); }
Gets the primary buffer of the current OpaqueNDArray. @return A Pointer to the buffer.
OpaqueNDArray::buffer
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public Pointer specialBuffer() { return getOpaqueNDArraySpecialBuffer(this); }
Gets the special buffer of the current OpaqueNDArray. @return A Pointer to the special buffer.
OpaqueNDArray::specialBuffer
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public long length() { return getOpaqueNDArrayLength(this); }
Gets the length of the current OpaqueNDArray. @return The length of the array.
OpaqueNDArray::length
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArray.java
Apache-2.0
public StringVector(Pointer p) { super(p); }
/* ****************************************************************************** * * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ***************************************************************************** package org.nd4j.nativeblas; import org.bytedeco.javacpp.BytePointer; import org.bytedeco.javacpp.Loader; import org.bytedeco.javacpp.Pointer; import org.bytedeco.javacpp.annotation.*; @Name("std::vector<std::string>") public class StringVector extends Pointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}.
StringVector::StringVector
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/StringVector.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/StringVector.java
Apache-2.0
public static OpaqueDataBuffer allocateDataBuffer(long numElements, @NonNull DataType dataType, boolean allocateBoth) { OpaqueDataBuffer buffer = null; int ec = 0; String em = null; for (int t = 0; t < MAX_TRIES; t++) { try { // try to allocate data buffer buffer = Nd4j.getNativeOps().allocateDataBuffer(numElements, dataType.toInt(), allocateBoth); //when using func trace we want to print allocation traces when deallocation is called. this is used to debug //potential race condition and crashes. c++ prints the equivalent stack trace when func trace is enabled. //This allows us to check where a deallocated buffer that caused an issue was allocated. if(buffer != null && Nd4j.getNativeOps().isFuncTrace()) buffer.captureTrace(); // check error code ec = Nd4j.getNativeOps().lastErrorCode(); if (ec != 0) { em = Nd4j.getNativeOps().lastErrorMessage(); // if allocation failed it might be caused by casual OOM, so we'll try GC System.gc(); // sleeping for 50ms Thread.sleep(50); } else { // just return the buffer return buffer; } } catch (Exception e) { throw new RuntimeException(e); } } // if MAX_TRIES is over, we'll just throw an exception throw new RuntimeException("Allocation failed: [" + em + "] for amount of memory " + numElements * dataType.width() + " bytes"); }
This method allocates new InteropDataBuffer and returns pointer to it @param numElements @param dataType @param allocateBoth @return
OpaqueDataBuffer::allocateDataBuffer
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
Apache-2.0
public void expand(long numElements) { int ec = 0; String em = null; for (int t = 0; t < MAX_TRIES; t++) { try { // try to expand the buffer Nd4j.getNativeOps().dbExpand(this, numElements); // check error code ec =Nd4j.getNativeOps().lastErrorCode(); if (ec != 0) { em =Nd4j.getNativeOps().lastErrorMessage(); // if expansion failed it might be caused by casual OOM, so we'll try GC System.gc(); Thread.sleep(50); } else { // just return return; } } catch (Exception e) { throw new RuntimeException(e); } } // if MAX_TRIES is over, we'll just throw an exception throw new RuntimeException("DataBuffer expansion failed: [" + em + "]"); }
This method expands buffer, and copies content to the new buffer PLEASE NOTE: if InteropDataBuffer doesn't own actual buffers - original pointers won't be released @param numElements
OpaqueDataBuffer::expand
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
Apache-2.0
public OpaqueDataBuffer createView(long bytesLength) { OpaqueDataBuffer buffer = null; int ec = 0; String em = null; for (int t = 0; t < MAX_TRIES; t++) { try { buffer =Nd4j.getNativeOps().dbCreateView(this, bytesLength); if(NativeOpsHolder.getInstance().getDeviceNativeOps().isFuncTrace()) buffer.captureTrace(); // check error code ec =Nd4j.getNativeOps().lastErrorCode(); if (ec != 0) { em =Nd4j.getNativeOps().lastErrorMessage(); // if view creation failed it might be caused by casual OOM, so we'll try GC System.gc(); // sleeping to let gc kick in Thread.sleep(50); } else { // just return return buffer; } } catch (Exception e) { throw new RuntimeException(e); } } // if MAX_TRIES is over, we'll just throw an exception throw new RuntimeException("DataBuffer expansion failed: [" + em + "]"); }
This method creates a view out of this InteropDataBuffer @param bytesLength @return
OpaqueDataBuffer::createView
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
Apache-2.0
public Pointer primaryBuffer() { return Nd4j.getNativeOps().dbPrimaryBuffer(this); }
This method returns pointer to linear buffer, primary one. @return
OpaqueDataBuffer::primaryBuffer
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
Apache-2.0
public Pointer specialBuffer() { return Nd4j.getNativeOps(). dbSpecialBuffer(this); }
This method returns pointer to special buffer, device one, if any. @return
OpaqueDataBuffer::specialBuffer
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
Apache-2.0
public int deviceId() { return Nd4j.getNativeOps().dbDeviceId(this); }
This method returns deviceId of this DataBuffer @return
OpaqueDataBuffer::deviceId
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
Apache-2.0
public void setPrimaryBuffer(Pointer ptr, long numElements) { //note we call print here because dbSetSpecialBuffer can deallocate on the c++ side printAllocationTraceIfNeeded(); Nd4j.getNativeOps().dbSetPrimaryBuffer(this, ptr, numElements); }
This method allows to set external pointer as primary buffer. PLEASE NOTE: if InteropDataBuffer owns current memory buffer, it will be released @param ptr @param numElements
OpaqueDataBuffer::setPrimaryBuffer
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
Apache-2.0
public void syncToSpecial() { Nd4j.getNativeOps().dbSyncToSpecial(this); }
This method synchronizes device memory
OpaqueDataBuffer::syncToSpecial
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
Apache-2.0
public void syncToPrimary() { Nd4j.getNativeOps().dbSyncToPrimary(this); }
This method synchronizes host memory
OpaqueDataBuffer::syncToPrimary
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
Apache-2.0
public void closeBuffer() { printAllocationTraceIfNeeded(); if(Nd4j.getEnvironment().isFuncTracePrintDeallocate()) { System.out.println("Java side deallocation current trace: \n " + currentTrace()); } Nd4j.getNativeOps().dbClose(this); }
This method releases underlying buffer
OpaqueDataBuffer::closeBuffer
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueDataBuffer.java
Apache-2.0
public OpExecTrace(Pointer p) { super(p); }
/* ****************************************************************************** * * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ***************************************************************************** package org.nd4j.nativeblas; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import java.nio.DoubleBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; @Namespace("sd::ops") @NoOffset public class OpExecTrace extends Pointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}.
OpExecTrace::OpExecTrace
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpExecTrace.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpExecTrace.java
Apache-2.0
public OpExecTrace(long size) { super((Pointer)null); allocateArray(size); }
/* ****************************************************************************** * * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ***************************************************************************** package org.nd4j.nativeblas; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import java.nio.DoubleBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; @Namespace("sd::ops") @NoOffset public class OpExecTrace extends Pointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. public OpExecTrace(Pointer p) { super(p); } /** Native array allocator. Access with {@link Pointer#position(long)}.
OpExecTrace::OpExecTrace
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpExecTrace.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpExecTrace.java
Apache-2.0
public static OpaqueNDArrayArr createFrom(List<INDArray> array) { OpaqueNDArray[] inputs = array.stream() .map(OpaqueNDArray::fromINDArray).toArray(OpaqueNDArray[]::new); OpaqueNDArrayArr inputsOpaque = (OpaqueNDArrayArr) new OpaqueNDArrayArr().capacity(inputs.length); inputsOpaque.put(inputs); return inputsOpaque; }
@see {@link #createFrom(INDArray...)} @param array @return
OpaqueNDArrayArr::createFrom
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArrayArr.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/nativeblas/OpaqueNDArrayArr.java
Apache-2.0
public static String validate(TestCase testCase) { return validate(testCase, false); }
Run test case @param testCase Test case to run @return NULL if test passes, or error message otherwise
OpValidation::validate
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/OpValidation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/OpValidation.java
Apache-2.0
public static String validate(OpTestCase testCase) { collectCoverageInformation(testCase); //Check shape function: List<LongShapeDescriptor> outShapes; try { outShapes = Nd4j.getExecutioner().calculateOutputShape(testCase.op()); } catch (Throwable t) { throw new IllegalStateException("Error calculating output shapes during op validation", t); } if (outShapes.size() != testCase.testFns().size()) { return "Expected number of output shapes and number of outputs differ. " + outShapes.size() + " output shapes," + " but OpTestCase specifies " + testCase.testFns().size() + " outputs expected"; } for (int i = 0; i < outShapes.size(); i++) { val act = outShapes.get(i); val exp = testCase.expShapes().get(i); if(!Objects.equals(exp.dataType(), act.dataType())) { return "Shape function check failed for output " + i + ": expected shape " + exp + ", actual shape " + act; } if(!Arrays.equals(act.getShape(), exp.getShape())){ return "Shape function check failed for output " + i + ": expected shape " + exp + ", actual shape " + act; } } //Check the outputs: try { Nd4j.getExecutioner().execAndReturn(testCase.op()); } catch (Throwable t) { throw new IllegalStateException("Error during op execution", t); } for (int i = 0; i < testCase.testFns().size(); i++) { String error; try { error = testCase.testFns().get(i).apply(testCase.op().outputArguments().get(i)); } catch (Throwable t) { throw new IllegalStateException("Exception thrown during op output validation for output " + i, t); } if (error != null) { return "Output " + i + " failed: " + error; } } return null; //OK }
Validate the outputs of a single op @param testCase Op test case to run @return NULL if test is OK, or an error message otherwise
OpValidation::validate
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/OpValidation.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/OpValidation.java
Apache-2.0
public OpTestCase expectedOutput(int outputNum, INDArray expected) { return expectedOutput(outputNum,expected,1e-3); }
Validate the op output using INDArray.equals(INDArray) @param outputNum Number of the output @param expected Expected INDArray
OpTestCase::expectedOutput
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/OpTestCase.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/OpTestCase.java
Apache-2.0
public OpTestCase expectedOutputRelError(int outputNum, @NonNull INDArray expected, double maxRelError, double minAbsError) { testFns.put(outputNum, new RelErrorFn(expected, maxRelError, minAbsError)); expShapes.put(outputNum, expected.shapeDescriptor()); return this; }
Validate the output for a single variable using element-wise relative error: relError = abs(x-y)/(abs(x)+abs(y)), with x=y=0 case defined to be 0.0. Also has a minimum absolute error condition, which must be satisfied for the relative error failure to be considered legitimate @param outputNum output number @param expected Expected INDArray @param maxRelError Maximum allowable relative error @param minAbsError Minimum absolute error for a failure to be considered legitimate
OpTestCase::expectedOutputRelError
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/OpTestCase.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/OpTestCase.java
Apache-2.0
public OpTestCase expectedOutput(int outputNum, @NonNull LongShapeDescriptor expShape, @NonNull Function<INDArray, String> validationFn) { testFns.put(outputNum, validationFn); expShapes.put(outputNum, expShape); return this; }
@param outputNum Output number to check @param expShape Expected shape for the output @param validationFn Function to use to validate the correctness of the specific Op. Should return null if validation passes, or an error message if the op validation fails
OpTestCase::expectedOutput
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/OpTestCase.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/OpTestCase.java
Apache-2.0
public static boolean checkActivationGradients(ActGradConfig config){ SameDiff sd = config.getSd(); List<String> actGrads = config.getActivationGradsToCheck(); double maxRelError = config.getMaxRelError(); double minAbsError = config.getMinAbsError(); Preconditions.checkState(sd != null, "SameDiff instance was not set in configuration"); Preconditions.checkState(actGrads != null && !actGrads.isEmpty(), "No activation gradients were specified to gradient check"); Preconditions.checkState(config.getEps() > 0.0, "Epsilon has not been set"); Preconditions.checkState(maxRelError > 0.0, "Max relative error must be set (is 0.0)"); for(String s : actGrads){ SDVariable v = sd.getVariables().get(s).getVariable(); Preconditions.checkState(v != null, "No variable with name \"%s\" was found", s); Preconditions.checkState(v.getVariableType() == VariableType.ARRAY, "Only variables with type ARRAY may be " + "gradient checked using this method. Variable \"%s\" has type %s", s, v.getVariableType()); Preconditions.checkState(v.dataType().isFPType(), "Cannot gradient check activation variable \"%s\": must be floating point type. Is type: %s", s, v.dataType()); if(v.dataType() != DataType.DOUBLE){ log.warn("Floating point variable {} is not double precision - this may result in spurious failures due to limited precision. Variable is type: {}", s, v.dataType()); } } boolean debugBefore = sd.isDebugMode(); if(config.isDebugMode()){ sd.enableDebugMode(); } //Validation sanity checks: if(!config.isSkipValidation()){ validateInternalState(sd, true); } //Loss function variables List<String> lossFnVariables = sd.getLossVariables(); Preconditions.checkState(lossFnVariables != null && !lossFnVariables.isEmpty(), "Expected 1 or more loss function variables for gradient check, got %s", lossFnVariables); //TODO also check that all inputs are non-zero (otherwise: consider out = sum(x * y) with all x and y being 0 // in this case, gradients of x and y are all 0 too //Collect names of variables to get gradients for - i.e., the names of the GRADIENT variables for the specified activations sd.createGradFunction(); Set<String> varsRequiringGrads = new HashSet<>(); for(String s : actGrads){ SDVariable grad = sd.getVariable(s).gradient(); Preconditions.checkState( grad != null,"Could not get gradient for activation \"%s\": gradient variable is null", s); varsRequiringGrads.add(s); } //Calculate analytical gradients Map<String,INDArray> grads = sd.calculateGradients(config.getPlaceholderValues(), new ArrayList<>(varsRequiringGrads)); Map<String,INDArray> gradientsForAct = new HashMap<>(); for(String s : actGrads){ INDArray arr = grads.get(s); Preconditions.checkState(arr != null, "No activation gradient array for variable \"%s\"", s); gradientsForAct.put(s, arr.dup()); } //Now, check gradients int totalNFailures = 0; int totalCount = 0; double maxError = 0.0; ActivationGradientCheckListener listener = new ActivationGradientCheckListener(); sd.setListeners(listener); Random r = new Random(12345); int maxPerParam = config.getMaxPerParam(); for(String s : actGrads){ long n = gradientsForAct.get(s).length(); if(config.isPrint()){ log.info("Starting test for variable \"{}\" with {} values", s, n); } Iterator<long[]> iter; if(maxPerParam > 0 && config.getSubset() != null && maxPerParam < n){ //Subset case long[] shape = gradientsForAct.get(s).shape(); List<long[]> l = new ArrayList<>(); if(config.getSubset() == Subset.RANDOM){ Set<Integer> set = new HashSet<>(); while(set.size() < maxPerParam){ int next = r.nextInt((int)n); set.add(next); } List<Integer> sorted = new ArrayList<>(set); Collections.sort(sorted); for(Integer i : sorted){ long[] pos = Shape.ind2subC(shape, i); l.add(pos); } } else { //Every N long everyN = n / maxPerParam; long curr = 0; while(curr < n){ long[] pos = Shape.ind2subC(shape, curr); l.add(pos); curr += everyN; } } iter = l.iterator(); } else { //Standard case: do all parameters iter = new NdIndexIterator('c',gradientsForAct.get(s).shape()); } INDArray varMask = (config.getGradCheckMask() == null ? null : config.getGradCheckMask().get(s)); listener.setVariableName(s); int i=0; while(iter.hasNext()){ long[] idx = iter.next(); String strIdx = null; if(config.isPrint()){ strIdx = Arrays.toString(idx).replaceAll(" ",""); } boolean maskValue = (varMask == null || (varMask.getDouble(idx) != 0)); if(!maskValue){ //Skip this specific entry (masked out) continue; } //Set listener to apply eps, then do forward pass: listener.setIdx(idx); listener.setEps(config.getEps()); double scorePlus = 0.0; Map<String,INDArray> m = sd.output(config.getPlaceholderValues(), lossFnVariables); for(INDArray arr : m.values()){ scorePlus += arr.sumNumber().doubleValue(); } listener.setEps(-config.getEps()); m = sd.output(config.getPlaceholderValues(), lossFnVariables); double scoreMinus = 0.0; for(INDArray arr : m.values()){ scoreMinus += arr.sumNumber().doubleValue(); } double numericalGrad = (scorePlus - scoreMinus) / (2 * config.getEps()); double analyticGrad = gradientsForAct.get(s).getDouble(idx); if (Double.isInfinite(numericalGrad) || Double.isNaN(numericalGrad)) { throw new IllegalStateException("Numerical gradient was " + numericalGrad + " for variable \"" + s + "\", parameter " + i + " of " + n + " (position: " + strIdx + ")"); } if (Double.isInfinite(analyticGrad) || Double.isNaN(analyticGrad)) { throw new IllegalStateException("Analytic (SameDiff) gradient was " + analyticGrad + " for variable \"" + s + "\", parameter " + i + " of " + n + " (position: " + strIdx + ")"); } double relError; if(numericalGrad == 0.0 && analyticGrad == 0.0){ relError = 0.0; } else { relError = Math.abs(analyticGrad - numericalGrad) / (Math.abs(Math.abs(analyticGrad) + Math.abs(numericalGrad))); } if (relError > maxError) maxError = relError; if (relError > maxRelError || Double.isNaN(relError)) { double absError = Math.abs(analyticGrad - numericalGrad); if (absError < minAbsError) { if(config.isPrint()) { log.info("Param " + i + " (" + s + strIdx + ") passed: grad= " + analyticGrad + ", numericalGrad= " + numericalGrad + ", relError= " + relError + "; absolute error = " + absError + " < minAbsoluteError = " + minAbsError); } } else { if (config.isPrint()) log.info("Param " + i + " (" + s + strIdx + ") FAILED: grad= " + analyticGrad + ", numericalGrad= " + numericalGrad + ", relError= " + relError + ", absError=" + absError + ", scorePlus=" + scorePlus + ", scoreMinus= " + scoreMinus); if (config.isExitOnFirstFailure()) return false; totalNFailures++; } } else if (config.isPrint()) { log.info("Param " + i + " (" + s + strIdx + ") passed: grad= " + analyticGrad + ", numericalGrad= " + numericalGrad + ", relError= " + relError); } i++; } } return totalNFailures == 0; }
Gradient check the ACTIVATIONS (i.e., ARRAY type SDVariables) as opposed to the parameters of a network (as are tested in {@link #checkGradients(SameDiff, Map, double, double, double, boolean, boolean, boolean, boolean, Set, Map, int, Subset)} @param config Configuration for gradient check @return True if gradient checks pass
Subset::checkActivationGradients
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/GradCheckUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/GradCheckUtil.java
Apache-2.0
public TestCase(SameDiff sameDiff) { this.sameDiff = sameDiff; }
@param sameDiff SameDiff instance to test. Note: All of the required inputs should already be set
TestSerialization::TestCase
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
Apache-2.0
public TestCase expectedOutput(@NonNull String name, @NonNull INDArray expected,double eps) { return expected(name, new EqualityFn(expected,eps)); }
Validate the output (forward pass) for a single variable using INDArray.equals(INDArray) @param name Name of the variable to check @param expected Expected INDArray @param eps the expected epsilon, defaults to 1e-3
TestSerialization::expectedOutput
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
Apache-2.0
public TestCase expectedOutput(@NonNull String name, @NonNull INDArray expected) { return expectedOutput(name,expected,1e-3); }
Validate the output (forward pass) for a single variable using INDArray.equals(INDArray) @param name Name of the variable to check @param expected Expected INDArray
TestSerialization::expectedOutput
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
Apache-2.0
public TestCase expectedOutputRelError(@NonNull String name, @NonNull INDArray expected, double maxRelError, double minAbsError) { return expected(name, new RelErrorFn(expected, maxRelError, minAbsError)); }
Validate the output (forward pass) for a single variable using element-wise relative error: relError = abs(x-y)/(abs(x)+abs(y)), with x=y=0 case defined to be 0.0. Also has a minimum absolute error condition, which must be satisfied for the relative error failure to be considered legitimate @param name Name of the variable to check @param expected Expected INDArray @param maxRelError Maximum allowable relative error @param minAbsError Minimum absolute error for a failure to be considered legitimate
TestSerialization::expectedOutputRelError
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
Apache-2.0
public TestCase expected(@NonNull SDVariable var, @NonNull INDArray output) { return expected(var.name(), output); }
Validate the output (forward pass) for a single variable using INDArray.equals(INDArray) @param var Variable to check @param output Expected INDArray
TestSerialization::expected
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
Apache-2.0
public TestCase expected(@NonNull String name, @NonNull INDArray output) { return expectedOutput(name, output); }
Validate the output (forward pass) for a single variable using INDArray.equals(INDArray) @param name Name of the variable to check @param output Expected INDArray
TestSerialization::expected
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
Apache-2.0
public TestCase expected(String name, Function<INDArray, String> validationFn) { if (fwdTestFns == null) fwdTestFns = new LinkedHashMap<>(); fwdTestFns.put(name, validationFn); return this; }
@param name The name of the variable to check @param validationFn Function to use to validate the correctness of the specific Op. Should return null if validation passes, or an error message if the op validation fails
TestSerialization::expected
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
Apache-2.0
public TestCase gradCheckSkipVariables(String... toSkip) { if (gradCheckSkipVariables == null) gradCheckSkipVariables = new LinkedHashSet<>(); Collections.addAll(gradCheckSkipVariables, toSkip); return this; }
Specify the input variables that should NOT be gradient checked. For example, if an input is an integer index (not real valued) it should be skipped as such an input cannot be gradient checked @param toSkip Name of the input variables to skip gradient check for
TestSerialization::gradCheckSkipVariables
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/TestCase.java
Apache-2.0
public static Map<String, INDArray> stackOutputs(List<Map<String, INDArray>> outputs){ Map<String, List<INDArray>> outs = new HashMap<>(); for(Map<String, INDArray> batch : outputs){ for(String k : batch.keySet()){ if(!outs.containsKey(k)) outs.put(k, new ArrayList<INDArray>()); outs.get(k).add(batch.get(k)); } } Map<String, INDArray> ret = new HashMap<>(); for(String k : outs.keySet()){ try { ret.put(k, Nd4j.concat(0, outs.get(k).toArray(new INDArray[0]))); } catch(Exception e){ throw new ND4JException("Error concatenating batch outputs", e); } } return ret; }
Stack batch outputs, like an output from {@link org.nd4j.autodiff.samediff.SameDiff#output(MultiDataSetIterator, String...)}
TrainingUtils::stackOutputs
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/util/TrainingUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/util/TrainingUtils.java
Apache-2.0
public static List<INDArray> getSingleOutput(List<Map<String, INDArray>> outputs, String output){ List<INDArray> batches = new ArrayList<>(); for(Map<String, INDArray> batch : outputs) batches.add(batch.get(output)); return batches; }
Get a list of batch outputs for a single variable from a list of batch outputs for all variables
TrainingUtils::getSingleOutput
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/util/TrainingUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/util/TrainingUtils.java
Apache-2.0
public static boolean executedOn(String className,int lineNumber,DifferentialFunction funcToTest) { if(funcToTest.getCreationLocation() != null) { return funcToTest.getCreationLocation().getLineNumber() == lineNumber && funcToTest.getCreationLocation().getClassName().equals(className); } return false; }
Tests whether the given function was executed on the given line number and class name. Note: In order for this function to work correctly, ensure that {@link Environment#isVerbose()}} or {@link Environment#isDebug()} is true set via {@link Environment#setDebug(boolean)} or {@link Environment#setVerbose(boolean)} or {@link org.nd4j.linalg.api.ops.executioner.OpExecutioner#enableDebugMode(boolean)} or {@link org.nd4j.linalg.api.ops.executioner.OpExecutioner#enableVerboseMode(boolean)} @param className class name to test @param lineNumber line number to test @param funcToTest function to test @return
SameDiffUtils::executedOn
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/util/SameDiffUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/util/SameDiffUtils.java
Apache-2.0
public static Map<String, INDArray> stackOutputs(List<ExecutionResult> outputs){ Map<String, List<INDArray>> outs = new HashMap<>(); for(ExecutionResult batch : outputs) { if(batch.getOutputs() != null) { for(String k : batch.getOutputs().keySet()) { if(!outs.containsKey(k)) outs.put(k, new ArrayList<>()); outs.get(k).add(batch.getOutputs().get(k).get()); } } else if(batch.getValueOutputs() != null) { for(String k : batch.getValueOutputs().keySet()) { if(!outs.containsKey(k)) outs.put(k, new ArrayList<>()); outs.get(k).add(batch.getValueOutputs().get(k).getTensorValue()); } } } Map<String, INDArray> ret = new HashMap<>(); for(String k : outs.keySet()) { try { ret.put(k, Nd4j.concat(0, outs.get(k).toArray(new INDArray[0]))); } catch(Exception e){ throw new ND4JException("Error concatenating batch outputs", e); } } return ret; }
Stack batch outputs, like an output from {@link SameDiff#output(MultiDataSetIterator, String...)}
SameDiffUtils::stackOutputs
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/util/SameDiffUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/util/SameDiffUtils.java
Apache-2.0
public static SDVariable reductionBroadcastableWithOrigShape(int origRank, int[] reduceDims, SDVariable toExpand) { if (Shape.isWholeArray(origRank, reduceDims)) { //Output is [1,1] which is already broadcastable return toExpand; } else if (origRank == 2 && reduceDims.length == 1) { //In this case: [a,b] -> [1,b] or [a,b] -> [a,1] //both are already broadcastable return toExpand; } else { //Example: [a,b,c].sum(1) -> [a,c]... want [a,1,c] for (int d : reduceDims) { toExpand = toExpand.getSameDiff().expandDims(toExpand, d); } return toExpand; } }
Add 1s as required to the array make an array possible to be broadcast with the original (pre-reduce) array. <p> Example: if doing [a,b,c].sum(1), result is [a,c]. To 'undo' this in a way that can be auto-broadcast, we want to expand as required - i.e., [a,c] -> [a,1,c] which can be auto-broadcast with the original [a,b,c]. This is typically only used with reduction operations backprop. @param origRank Rank of the original array, before the reduction was executed @param reduceDims Dimensions that the original array was reduced from @param toExpand Array to add 1s to the shape to (such that it can be @return Reshaped array.
SameDiffUtils::reductionBroadcastableWithOrigShape
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/util/SameDiffUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/util/SameDiffUtils.java
Apache-2.0
public Operands addArgument(@NonNull String id, @NonNull INDArray array) { map.put(NodeDescriptor.builder().name(id).build(), array); return this; }
This method allows to pass array to the node identified by its name @param id @param array @return
Operands::addArgument
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
Apache-2.0
public Operands addArgument(int id, @NonNull INDArray array) { map.put(NodeDescriptor.builder().id(id).build(), array); return this; }
This method allows to pass array to the node identified by numeric id @param id @param array @return
Operands::addArgument
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
Apache-2.0
public Operands addArgument( int id, int index, @NonNull INDArray array) { map.put(NodeDescriptor.builder().id(id).index(index).build(), array); return this; }
This method allows to pass array to multi-output node in the graph @param id @param index @param array @return
Operands::addArgument
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
Apache-2.0
public INDArray getById(@NonNull String name) { return map.get(NodeDescriptor.builder().name(name).build()); }
This method returns array identified its name @param name @return
Operands::getById
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
Apache-2.0
public INDArray getById(int id) { return map.get(NodeDescriptor.builder().id(id).build()); }
This method returns array identified its numeric id @param name @return
Operands::getById
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
Apache-2.0
public INDArray getById(int id, int index) { return map.get(NodeDescriptor.builder().id(id).index(index).build()); }
This method returns array identified its numeric id and index @param name @return
Operands::getById
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
Apache-2.0
public INDArray[] asArray() { val val = map.values(); val res = new INDArray[val.size()]; int cnt = 0; for (val v: val) res[cnt++] = v; return res; }
This method return operands as array, in order of addition @return
Operands::asArray
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
Apache-2.0
public Collection<Pair<NodeDescriptor, INDArray>> asCollection() { val c = new HashSet<Pair<NodeDescriptor, INDArray>>(); for (val k: map.keySet()) c.add(Pair.makePair(k, map.get(k))); return c; }
This method returns contents of this entity as collection of key->value pairs @return
Operands::asCollection
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/input/Operands.java
Apache-2.0
public int getFlatConfiguration(FlatBufferBuilder builder) { byte prof = profilingMode == OpExecutioner.ProfilingMode.INF_PANIC ? ProfilingMode.INF_PANIC : profilingMode == OpExecutioner.ProfilingMode.NAN_PANIC ? ProfilingMode.NAN_PANIC : profilingMode == OpExecutioner.ProfilingMode.ANY_PANIC ? ProfilingMode.ANY_PANIC : ProfilingMode.NONE; byte exec = executionMode == ExecutionMode.SEQUENTIAL ? org.nd4j.graph.ExecutionMode.SEQUENTIAL : executionMode == ExecutionMode.AUTO ? org.nd4j.graph.ExecutionMode.AUTO : executionMode == ExecutionMode.STRICT ? org.nd4j.graph.ExecutionMode.STRICT : -1; byte outp = outputMode == OutputMode.IMPLICIT ? org.nd4j.graph.OutputMode.IMPLICIT : outputMode == OutputMode.EXPLICIT ? org.nd4j.graph.OutputMode.EXPLICIT : outputMode == OutputMode.EXPLICIT_AND_IMPLICIT ? org.nd4j.graph.OutputMode.EXPLICIT_AND_IMPLICIT : outputMode == OutputMode.VARIABLE_SPACE ? org.nd4j.graph.OutputMode.VARIABLE_SPACE : -1; if (exec == -1) throw new UnsupportedOperationException("Unknown values were passed into configuration as ExecutionMode: [" + executionMode + "]"); if (outp == -1) throw new UnsupportedOperationException("Unknown values were passed into configuration as OutputMode: [" + outputMode + "]"); return FlatConfiguration.createFlatConfiguration(builder, -1, prof, exec, outp, gatherTimings, footprintForward, footprintBackward, Direction.FORWARD_ONLY); }
This method @param builder @return
ExecutorConfiguration::getFlatConfiguration
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/conf/ExecutorConfiguration.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/execution/conf/ExecutorConfiguration.java
Apache-2.0
public ListenerVariables otherRequiredVariables(SameDiff sd){ return ListenerVariables.empty(); }
Return any requested variables that are not part of the evaluations
BaseEvaluationListener::otherRequiredVariables
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/BaseEvaluationListener.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/BaseEvaluationListener.java
Apache-2.0
public void epochStartEvaluations(SameDiff sd, At at){ //No op }
See {@link Listener#epochStart(SameDiff, At)}
BaseEvaluationListener::epochStartEvaluations
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/BaseEvaluationListener.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/BaseEvaluationListener.java
Apache-2.0
public ListenerResponse epochEndEvaluations(SameDiff sd, At at, LossCurve lossCurve, long epochTimeMillis, EvaluationRecord evaluations) { //No op return ListenerResponse.CONTINUE; }
See {@link Listener#epochEnd(SameDiff, At, LossCurve, long)}, also provided the requested evaluations
BaseEvaluationListener::epochEndEvaluations
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/BaseEvaluationListener.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/BaseEvaluationListener.java
Apache-2.0
public ListenerResponse validationDoneEvaluations(SameDiff sd, At at, long validationTimeMillis, EvaluationRecord evaluations) { //No op return ListenerResponse.CONTINUE; }
See {@link Listener#validationDone(SameDiff, At, long)}, also provided the requested evaluations
BaseEvaluationListener::validationDoneEvaluations
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/BaseEvaluationListener.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/BaseEvaluationListener.java
Apache-2.0
public void activationAvailableEvaluations(SameDiff sd, At at, MultiDataSet batch, SameDiffOp op, String varName, INDArray activation){ //No op }
See {@link Listener#activationAvailable(SameDiff, At, MultiDataSet, SameDiffOp, String, INDArray)}
BaseEvaluationListener::activationAvailableEvaluations
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/BaseEvaluationListener.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/BaseEvaluationListener.java
Apache-2.0
public Map<String, List<IEvaluation>> trainEvaluations() { return trainEvaluations; }
Get the requested training evaluations
ListenerEvaluations::trainEvaluations
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
Apache-2.0
public Map<String, Integer> trainEvaluationLabels() { return trainEvaluationLabels; }
Get the label indices for the requested training evaluations
ListenerEvaluations::trainEvaluationLabels
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
Apache-2.0
public Map<String, List<IEvaluation>> validationEvaluations() { return validationEvaluations; }
Get the requested validation evaluations
ListenerEvaluations::validationEvaluations
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
Apache-2.0
public Map<String, Integer> validationEvaluationLabels() { return validationEvaluationLabels; }
Get the label indices for the requested validation evaluations
ListenerEvaluations::validationEvaluationLabels
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
Apache-2.0
public ListenerVariables requiredVariables() { return new ListenerVariables(trainEvaluations.keySet(), validationEvaluations.keySet(), new HashSet<String>(), new HashSet<String>()); }
Get the required variables for these evaluations
ListenerEvaluations::requiredVariables
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
Apache-2.0
public boolean isEmpty() { return trainEvaluations.isEmpty() && validationEvaluations.isEmpty(); }
@return true if there are no requested evaluations
ListenerEvaluations::isEmpty
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
Apache-2.0
public Builder trainEvaluation(@NonNull String variableName, int labelIndex, @NonNull IEvaluation... evaluations) { addEvaluations(false, this.trainEvaluations, this.trainEvaluationLabels, variableName, labelIndex, evaluations); return this; }
Add requested training evaluations for a parm/variable @param variableName The variable to evaluate @param labelIndex The index of the label to evaluate against @param evaluations The evaluations to run
Builder::trainEvaluation
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
Apache-2.0
public Builder trainEvaluation(@NonNull SDVariable variable, int labelIndex, @NonNull IEvaluation... evaluations) { return trainEvaluation(variable.name(), labelIndex, evaluations); }
Add requested training evaluations for a parm/variable @param variable The variable to evaluate @param labelIndex The index of the label to evaluate against @param evaluations The evaluations to run
Builder::trainEvaluation
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
Apache-2.0
public Builder validationEvaluation(@NonNull String variableName, int labelIndex, @NonNull IEvaluation... evaluations) { addEvaluations(true, this.validationEvaluations, this.validationEvaluationLabels, variableName, labelIndex, evaluations); return this; }
Add requested validation evaluations for a parm/variable @param variableName The variable to evaluate @param labelIndex The index of the label to evaluate against @param evaluations The evaluations to run
Builder::validationEvaluation
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
Apache-2.0
public Builder validationEvaluation(@NonNull SDVariable variable, int labelIndex, @NonNull IEvaluation... evaluations) { return validationEvaluation(variable.name(), labelIndex, evaluations); }
Add requested validation evaluations for a parm/variable @param variable The variable to evaluate @param labelIndex The index of the label to evaluate against @param evaluations The evaluations to run
Builder::validationEvaluation
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
Apache-2.0
public Builder addEvaluations(boolean validation, @NonNull String variableName, int labelIndex, @NonNull IEvaluation... evaluations) { if (validation) { return validationEvaluation(variableName, labelIndex, evaluations); } else { return trainEvaluation(variableName, labelIndex, evaluations); } }
Add requested evaluations for a parm/variable, for either training or validation @param validation Whether to add these evaluations as validation or training @param variableName The variable to evaluate @param labelIndex The index of the label to evaluate against @param evaluations The evaluations to run
Builder::addEvaluations
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerEvaluations.java
Apache-2.0
public Set<String> trainingVariables() { return trainingVariables; }
Get required training variables
ListenerVariables::trainingVariables
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerVariables.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerVariables.java
Apache-2.0
public Set<String> validationVariables() { return validationVariables; }
Get required validation variables
ListenerVariables::validationVariables
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerVariables.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerVariables.java
Apache-2.0
public Set<String> evaluationVariables() { return evaluationVariables; }
Get required evaluation variables
ListenerVariables::evaluationVariables
java
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerVariables.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/listeners/ListenerVariables.java
Apache-2.0