-
Notifications
You must be signed in to change notification settings - Fork 214
Callbacks phase 1 #299
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JimClarke5
wants to merge
22
commits into
tensorflow:master
Choose a base branch
from
JimClarke5:Callbacks_Phase_1
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Callbacks phase 1 #299
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
c57a2e7
Merge pull request #3 from tensorflow/master
JimClarke5 09fc07e
Merge pull request #4 from tensorflow/master
JimClarke5 a99dcb4
Merge pull request #5 from tensorflow/master
JimClarke5 ba294ea
Merge pull request #6 from tensorflow/master
JimClarke5 04f419a
Merge pull request #7 from tensorflow/master
JimClarke5 02e7ebf
Merge pull request #8 from tensorflow/master
JimClarke5 e0c9ed8
Merge pull request #9 from tensorflow/master
JimClarke5 5b0374b
Merge pull request #10 from tensorflow/master
JimClarke5 e038bbd
Merge pull request #11 from tensorflow/master
JimClarke5 def3051
Merge pull request #13 from tensorflow/master
JimClarke5 11748ae
Merge pull request #15 from tensorflow/master
JimClarke5 a9412ea
Merge pull request #16 from tensorflow/master
JimClarke5 2ff8dfe
Merge pull request #17 from tensorflow/master
JimClarke5 df56f1d
Initial checkin
JimClarke5 ee5e38a
Merge pull request #18 from tensorflow/master
JimClarke5 26394d6
Merge pull request #19 from tensorflow/master
JimClarke5 9dcddcd
Initial checkin
JimClarke5 ab2e304
Merge remote-tracking branch 'origin/Callbacks_Phase_1' into Callback…
JimClarke5 9efff83
Added missing methods in Lambda Callback
JimClarke5 6aa84eb
Remove unused class, this is part of ProgressBar
JimClarke5 4b3bb7c
Fixes from PR Comments
JimClarke5 66a4bdd
Change tmoFile to deleteOnExit, remove finally block
JimClarke5 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
277 changes: 277 additions & 0 deletions
277
tensorflow-framework/src/main/java/org/tensorflow/framework/callbacks/CSVLogger.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,277 @@ | ||
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
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. | ||
=======================================================================*/ | ||
package org.tensorflow.framework.callbacks; | ||
|
||
import org.apache.commons.csv.CSVFormat; | ||
import org.apache.commons.csv.CSVPrinter; | ||
import org.tensorflow.ndarray.NdArray; | ||
import org.tensorflow.ndarray.Shape; | ||
import org.tensorflow.types.family.TNumber; | ||
|
||
import java.io.File; | ||
import java.io.FileWriter; | ||
import java.io.IOException; | ||
import java.util.ArrayList; | ||
import java.util.Collection; | ||
import java.util.Collections; | ||
import java.util.Iterator; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.StringJoiner; | ||
import java.util.logging.Level; | ||
import java.util.logging.Logger; | ||
import java.util.stream.Collectors; | ||
|
||
/** | ||
* Callback that streams epoch results to a CSV file. | ||
* | ||
* <p>Supports all values that can be represented as a string | ||
* | ||
* @param <T> the data type for the weights in the model | ||
*/ | ||
public class CSVLogger<T extends TNumber> extends Callback implements AutoCloseable { | ||
|
||
public static final char DEFAULT_SEPARATOR = ','; | ||
public static final boolean DEFAULT_APPEND = false; | ||
|
||
private final File file; | ||
private final char separator; | ||
private final boolean append; | ||
private List<String> keys; | ||
private boolean appendHeader = true; | ||
|
||
private CSVPrinter writer; | ||
|
||
/** | ||
* Creates a CSVLogger callback using {@link #DEFAULT_SEPARATOR} to separate elements in the csv | ||
* file, and {@link #DEFAULT_APPEND} for the append value. | ||
* | ||
* @param file the csv file | ||
*/ | ||
public CSVLogger(File file) { | ||
this(file, DEFAULT_SEPARATOR, DEFAULT_APPEND); | ||
} | ||
|
||
/** | ||
* Creates a CSVLogger callback using {@link #DEFAULT_SEPARATOR} to separate elements in the csv | ||
* file, and {@link #DEFAULT_APPEND} for the append value. | ||
* | ||
* @param filename filename of the csv file | ||
*/ | ||
public CSVLogger(String filename) { | ||
this(new File(filename), DEFAULT_SEPARATOR, DEFAULT_APPEND); | ||
} | ||
|
||
/** | ||
* Creates a CSVLogger callback using {@link #DEFAULT_APPEND} for the append value. | ||
* | ||
* @param file the csv file | ||
* @param separator string used to separate elements in the csv file. | ||
*/ | ||
public CSVLogger(File file, char separator) { | ||
this(file, separator, false); | ||
} | ||
|
||
/** | ||
* Creates a CSVLogger callback using {@link #DEFAULT_APPEND} for the append value. | ||
* | ||
* @param filename filename of the csv file | ||
* @param separator string used to separate elements in the csv file. | ||
*/ | ||
public CSVLogger(String filename, char separator) { | ||
this(new File(filename), separator, false); | ||
} | ||
|
||
/** | ||
* Creates a CSVLogger callback. | ||
* | ||
* @param filename filename of the csv file | ||
* @param separator the character used to separate elements in the csv file. | ||
* @param append if true, append if file exists (useful for continuing training). if false, | ||
* overwrite existing file. | ||
*/ | ||
public CSVLogger(String filename, char separator, boolean append) { | ||
this(new File(filename), separator, append); | ||
} | ||
|
||
/** | ||
* Creates a CSVLogger callback. | ||
* | ||
* @param file the csv file | ||
* @param separator the character used to separate elements in the csv file. | ||
* @param append if true, append if file exists (useful for continuing training). if false, | ||
* overwrite existing file. | ||
*/ | ||
public CSVLogger(File file, char separator, boolean append) { | ||
this.file = file; | ||
this.separator = separator; | ||
this.append = append; | ||
} | ||
|
||
/** {@inheritDoc} */ | ||
@Override | ||
public void onTrainBegin(Map<String, Number> logs) { | ||
appendHeader = !append || !file.exists(); | ||
} | ||
|
||
// TODO Should we handle Java arrays?? | ||
@SuppressWarnings("unchecked") | ||
private String handleValue(Object val) { | ||
|
||
if (val instanceof String) { | ||
return val.toString(); | ||
} else if (val instanceof NdArray) { // todo | ||
boolean isScalar = ((NdArray<?>) val).rank() == 0; | ||
if (isScalar) { | ||
return ((NdArray<?>) val).getObject().toString(); | ||
} else { | ||
NdArray<?> array = (NdArray<T>) val; | ||
return ndArrayToString(array); | ||
} | ||
} else if (val instanceof Collection) { | ||
return "[" | ||
+ ((Collection<T>) val).stream().map(Object::toString).collect(Collectors.joining(",")) | ||
+ "]"; | ||
} else { | ||
return val.toString(); | ||
} | ||
} | ||
|
||
/** | ||
* coverts an NdArray to a printable string | ||
* | ||
* @param ndArray the NdArray | ||
* @return the printable string | ||
*/ | ||
private String ndArrayToString(NdArray<?> ndArray) { | ||
Iterator<? extends NdArray<?>> iterator = ndArray.scalars().iterator(); | ||
Shape shape = ndArray.shape(); | ||
if (shape.numDimensions() == 0) { | ||
if (!iterator.hasNext()) { | ||
return ""; | ||
} | ||
return valToString(iterator.next().getObject()); | ||
} | ||
return ndArrayToString(iterator, shape, 0); | ||
} | ||
|
||
/** | ||
* coverts an NdArray iterator to a printable string | ||
* | ||
* @param iterator the NdArray iterator | ||
* @param shape the shape of the NdArray item | ||
* @param dimension the dimension within the overall NDArray tree | ||
* @return the printable string | ||
*/ | ||
private String ndArrayToString(Iterator<? extends NdArray<?>> iterator, Shape shape, int dimension) { | ||
if (dimension < shape.numDimensions() - 1) { | ||
StringJoiner joiner = new StringJoiner("", "[", "]"); | ||
for (long i = 0, size = shape.size(dimension); i < size; ++i) { | ||
String element = ndArrayToString(iterator, shape, dimension + 1); | ||
joiner.add(element); | ||
} | ||
return joiner.toString(); | ||
} else { | ||
StringJoiner joiner = new StringJoiner(", ", "[", "]"); | ||
for (long i = 0, size = shape.size(dimension); i < size; ++i) { | ||
Object element = iterator.next().getObject(); | ||
joiner.add(valToString(element)); | ||
} | ||
return joiner.toString(); | ||
} | ||
} | ||
|
||
/** | ||
* Converts a value to a printable string | ||
* | ||
* @param val the value | ||
* @return the printable string | ||
*/ | ||
private String valToString(Object val) { | ||
if (val instanceof Number) { | ||
Number nVal = (Number) val; | ||
if (nVal instanceof Float || nVal instanceof Double) { | ||
return String.format("%e", nVal.doubleValue()); | ||
} else if (nVal instanceof Byte) { | ||
return String.format("0x%2x", nVal.byteValue()); | ||
} else { | ||
return String.format("%d", nVal.longValue()); | ||
} | ||
} else { | ||
return val.toString(); | ||
} | ||
} | ||
|
||
/** {@inheritDoc} */ | ||
Craigacp marked this conversation as resolved.
Show resolved
Hide resolved
|
||
@Override | ||
@SuppressWarnings("unchecked") | ||
public void onEpochEnd(int epoch, Map<String, Number> logs) { | ||
logs = logs == null ? Collections.EMPTY_MAP : logs; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
||
if (keys == null) { | ||
keys = new ArrayList<>(logs.keySet()); | ||
Collections.sort(this.keys); | ||
} | ||
|
||
if (writer == null) { | ||
try { | ||
List<String> fieldNames = new ArrayList<>(); | ||
fieldNames.add("epoch"); | ||
fieldNames.addAll(this.keys); | ||
CSVFormat csvFormat = | ||
appendHeader | ||
? CSVFormat.EXCEL | ||
.withHeader(fieldNames.toArray(new String[0])) | ||
.withDelimiter(separator) | ||
: CSVFormat.EXCEL.withDelimiter(separator); | ||
writer = new CSVPrinter(new FileWriter(file, append), csvFormat); | ||
} catch (IOException ex) { | ||
Logger.getLogger(CSVLogger.class.getName()).log(Level.SEVERE, null, ex); | ||
return; | ||
} | ||
} | ||
|
||
/* TODO include when integrated with Model | ||
if (getModel().isStopTraining()) { | ||
final Map<String, Number> flogs = logs; | ||
keys.forEach( | ||
key -> { | ||
if (!flogs.containsKey(key)) { | ||
flogs.put(key, Double.NaN); | ||
} | ||
}); | ||
} | ||
*/ | ||
try { | ||
final List<String> values = new ArrayList<>(); | ||
final Map<String, Number> logsFinal = logs; | ||
values.add(String.valueOf(epoch)); | ||
keys.forEach(key -> values.add(handleValue(logsFinal.get(key)))); | ||
writer.printRecord(values); | ||
writer.flush(); | ||
} catch (IOException ex) { | ||
Logger.getLogger(CSVLogger.class.getName()).log(Level.SEVERE, null, ex); | ||
} | ||
} | ||
|
||
/** {@inheritDoc} */ | ||
@Override | ||
public void close() throws IOException { | ||
if (writer != null) { | ||
writer.close(); | ||
writer = null; | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.