Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
S
seminar-breakout
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Analytics
Analytics
CI / CD
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Shashank Suhas
seminar-breakout
Commits
3465e1a5
Commit
3465e1a5
authored
Oct 15, 2017
by
Yuxin Wu
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
ProcessTensors and DumpTensors
parent
1d74ac21
Changes
5
Show whitespace changes
Inline
Side-by-side
Showing
5 changed files
with
81 additions
and
47 deletions
+81
-47
docs/conf.py
docs/conf.py
+2
-1
examples/mnist-convnet.py
examples/mnist-convnet.py
+7
-8
tensorpack/callbacks/graph.py
tensorpack/callbacks/graph.py
+67
-1
tensorpack/callbacks/inference.py
tensorpack/callbacks/inference.py
+3
-0
tensorpack/callbacks/stats.py
tensorpack/callbacks/stats.py
+2
-37
No files found.
docs/conf.py
View file @
3465e1a5
...
@@ -368,7 +368,8 @@ def autodoc_skip_member(app, what, name, obj, skip, options):
...
@@ -368,7 +368,8 @@ def autodoc_skip_member(app, what, name, obj, skip, options):
'GaussianDeform'
,
'GaussianDeform'
,
'dump_chkpt_vars'
,
'dump_chkpt_vars'
,
'VisualQA'
,
'VisualQA'
,
'huber_loss'
'huber_loss'
,
'DumpTensor'
]:
]:
return
True
return
True
if
name
in
[
'get_data'
,
'size'
,
'reset_state'
]:
if
name
in
[
'get_data'
,
'size'
,
'reset_state'
]:
...
...
examples/mnist-convnet.py
View file @
3465e1a5
...
@@ -16,7 +16,6 @@ about 0.6% validation error after 30 epochs.
...
@@ -16,7 +16,6 @@ about 0.6% validation error after 30 epochs.
from
tensorpack
import
*
from
tensorpack
import
*
from
tensorpack.tfutils
import
summary
from
tensorpack.tfutils
import
summary
from
tensorpack.dataflow
import
dataset
from
tensorpack.dataflow
import
dataset
import
tensorpack.tfutils.symbolic_functions
as
symbf
IMAGE_SIZE
=
28
IMAGE_SIZE
=
28
...
@@ -63,15 +62,15 @@ class Model(ModelDesc):
...
@@ -63,15 +62,15 @@ class Model(ModelDesc):
cost
=
tf
.
nn
.
sparse_softmax_cross_entropy_with_logits
(
logits
=
logits
,
labels
=
label
)
cost
=
tf
.
nn
.
sparse_softmax_cross_entropy_with_logits
(
logits
=
logits
,
labels
=
label
)
cost
=
tf
.
reduce_mean
(
cost
,
name
=
'cross_entropy_loss'
)
# the average cross-entropy loss
cost
=
tf
.
reduce_mean
(
cost
,
name
=
'cross_entropy_loss'
)
# the average cross-entropy loss
# compute the "
in
correct vector", for the callback ClassificationError to use at validation time
# compute the "correct vector", for the callback ClassificationError to use at validation time
wrong
=
symbf
.
prediction_incorrect
(
logits
,
label
,
name
=
'in
correct'
)
correct
=
tf
.
cast
(
tf
.
nn
.
in_top_k
(
logits
,
label
,
1
),
tf
.
float32
,
name
=
'
correct'
)
accuracy
=
symbf
.
accuracy
(
logits
,
label
,
name
=
'accuracy'
)
accuracy
=
tf
.
reduce_mean
(
correct
,
name
=
'accuracy'
)
# This will monitor training error (in a moving_average fashion):
# This will monitor training error (in a moving_average fashion):
# 1. write the value to tensosrboard
# 1. write the value to tensosrboard
# 2. write the value to stat.json
# 2. write the value to stat.json
# 3. print the value after each epoch
# 3. print the value after each epoch
train_error
=
tf
.
reduce_mean
(
wrong
,
name
=
'train_error'
)
train_error
=
tf
.
reduce_mean
(
1
-
correct
,
name
=
'train_error'
)
summary
.
add_moving_summary
(
train_error
,
accuracy
)
summary
.
add_moving_summary
(
train_error
,
accuracy
)
# Use a regex to find parameters to apply weight decay.
# Use a regex to find parameters to apply weight decay.
...
@@ -118,9 +117,9 @@ def get_config():
...
@@ -118,9 +117,9 @@ def get_config():
MaxSaver
(
'validation_accuracy'
),
# save the model with highest accuracy (prefix 'validation_')
MaxSaver
(
'validation_accuracy'
),
# save the model with highest accuracy (prefix 'validation_')
InferenceRunner
(
# run inference(for validation) after every epoch
InferenceRunner
(
# run inference(for validation) after every epoch
dataset_test
,
# the DataFlow instance used for validation
dataset_test
,
# the DataFlow instance used for validation
# Calculate both the cost and the
error
for this DataFlow
# Calculate both the cost and the
accuracy
for this DataFlow
[
ScalarStats
(
'cross_entropy_loss'
),
ScalarStats
(
'accuracy'
),
[
ScalarStats
(
'cross_entropy_loss'
),
ClassificationError
(
'
incorrect
'
)]),
ClassificationError
(
'
correct'
,
'validation_accuracy
'
)]),
],
],
steps_per_epoch
=
steps_per_epoch
,
steps_per_epoch
=
steps_per_epoch
,
max_epoch
=
100
,
max_epoch
=
100
,
...
...
tensorpack/callbacks/graph.py
View file @
3465e1a5
...
@@ -6,11 +6,15 @@
...
@@ -6,11 +6,15 @@
""" Graph related callbacks"""
""" Graph related callbacks"""
import
tensorflow
as
tf
import
tensorflow
as
tf
import
os
import
numpy
as
np
from
..utils
import
logger
from
..utils
import
logger
from
.base
import
Callback
from
.base
import
Callback
from
..tfutils.common
import
get_tensors_by_names
from
six.moves
import
zip
__all__
=
[
'RunOp'
,
'RunUpdateOps'
]
__all__
=
[
'RunOp'
,
'RunUpdateOps'
,
'ProcessTensors'
,
'DumpTensors'
,
'DumpTensor'
]
class
RunOp
(
Callback
):
class
RunOp
(
Callback
):
...
@@ -87,3 +91,65 @@ class RunUpdateOps(RunOp):
...
@@ -87,3 +91,65 @@ class RunUpdateOps(RunOp):
super
(
RunUpdateOps
,
self
)
.
__init__
(
super
(
RunUpdateOps
,
self
)
.
__init__
(
f
,
run_before
=
False
,
run_as_trigger
=
False
,
run_step
=
True
)
f
,
run_before
=
False
,
run_as_trigger
=
False
,
run_step
=
True
)
class
ProcessTensors
(
Callback
):
"""
Fetch extra tensors **along with** each training step,
and call some function over the values.
You can use it to print tensors, save tensors to file, etc.
Examples:
.. code-block:: python
ProcessTensors(['mycost1', 'mycost2'], lambda c1, c2: print(c1, c2, c1 + c2))
"""
def
__init__
(
self
,
names
,
fn
):
"""
Args:
names (list[str]): names of tensors
fn: a function taking all requested tensors as input
"""
assert
isinstance
(
names
,
(
list
,
tuple
)),
names
self
.
_names
=
names
self
.
_fn
=
fn
def
_setup_graph
(
self
):
tensors
=
get_tensors_by_names
(
self
.
_names
)
self
.
_fetch
=
tf
.
train
.
SessionRunArgs
(
fetches
=
tensors
)
def
_before_run
(
self
,
_
):
return
self
.
_fetch
def
_after_run
(
self
,
_
,
rv
):
results
=
rv
.
results
self
.
_fn
(
*
results
)
class
DumpTensors
(
ProcessTensors
):
"""
Dump some tensors to a file.
Every step this callback fetches tensors and write them to a npz file under ``logger.LOG_DIR``.
The dump can be loaded by ``dict(np.load(filename).items())``.
"""
def
__init__
(
self
,
names
):
"""
Args:
names (list[str]): names of tensors
"""
assert
isinstance
(
names
,
(
list
,
tuple
)),
names
self
.
_names
=
names
dir
=
logger
.
LOG_DIR
def
fn
(
*
args
):
dic
=
{}
for
name
,
val
in
zip
(
self
.
_names
,
args
):
dic
[
name
]
=
val
fname
=
os
.
path
.
join
(
dir
,
'DumpTensor-{}.npz'
.
format
(
self
.
global_step
))
np
.
savez
(
fname
,
**
dic
)
super
(
DumpTensors
,
self
)
.
__init__
(
names
,
fn
)
DumpTensor
=
DumpTensors
tensorpack/callbacks/inference.py
View file @
3465e1a5
...
@@ -143,6 +143,9 @@ class ClassificationError(Inferencer):
...
@@ -143,6 +143,9 @@ class ClassificationError(Inferencer):
taking account of the fact that batches might not have the same size in
taking account of the fact that batches might not have the same size in
testing (because the size of test set might not be a multiple of batch size).
testing (because the size of test set might not be a multiple of batch size).
Therefore the result can be different from averaging the error rate of each batch.
Therefore the result can be different from averaging the error rate of each batch.
You can also use the "correct prediction" tensor, so this inferencer will
give you "classification accuracy" instead of error.
"""
"""
def
__init__
(
self
,
wrong_tensor_name
=
'incorrect_vector'
,
summary_name
=
'validation_error'
):
def
__init__
(
self
,
wrong_tensor_name
=
'incorrect_vector'
,
summary_name
=
'validation_error'
):
...
...
tensorpack/callbacks/stats.py
View file @
3465e1a5
...
@@ -3,15 +3,13 @@
...
@@ -3,15 +3,13 @@
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
import
os
import
os
import
tensorflow
as
tf
import
numpy
as
np
import
numpy
as
np
from
six.moves
import
zip
from
.base
import
Callback
from
.base
import
Callback
from
..utils
import
logger
from
..utils
import
logger
from
..tfutils.common
import
get_op_tensor_name
,
get_tensors_by_names
from
..tfutils.common
import
get_op_tensor_name
__all__
=
[
'SendStat'
,
'DumpParamAsImage'
,
'InjectShell'
,
'DumpTensor'
]
__all__
=
[
'SendStat'
,
'DumpParamAsImage'
,
'InjectShell'
]
class
SendStat
(
Callback
):
class
SendStat
(
Callback
):
...
@@ -123,39 +121,6 @@ class DumpParamAsImage(Callback):
...
@@ -123,39 +121,6 @@ class DumpParamAsImage(Callback):
cv2
.
imwrite
(
fname
,
res
.
astype
(
'uint8'
))
cv2
.
imwrite
(
fname
,
res
.
astype
(
'uint8'
))
class
DumpTensor
(
Callback
):
"""
Dump some tensors to a file.
Every step this callback fetches tensors and write them to a npz file under ``logger.LOG_DIR``.
The dump can be loaded by ``dict(np.load(filename).items())``.
"""
# TODO run as trigger
def
__init__
(
self
,
names
):
"""
Args:
names (list[str]): names of tensors
"""
assert
isinstance
(
names
,
(
list
,
tuple
)),
names
self
.
_names
=
names
self
.
_dir
=
logger
.
LOG_DIR
def
_setup_graph
(
self
):
tensors
=
get_tensors_by_names
(
self
.
_names
)
self
.
_fetch
=
tf
.
train
.
SessionRunArgs
(
fetches
=
tensors
)
def
_before_run
(
self
,
_
):
return
self
.
_fetch
def
_after_run
(
self
,
_
,
rv
):
results
=
rv
.
results
dic
=
{}
for
name
,
val
in
zip
(
self
.
_names
,
results
):
dic
[
name
]
=
val
fname
=
os
.
path
.
join
(
self
.
_dir
,
'DumpTensor-{}.npz'
.
format
(
self
.
global_step
))
np
.
savez
(
fname
,
**
dic
)
try
:
try
:
import
cv2
import
cv2
except
ImportError
:
except
ImportError
:
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment