code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_deleting_values_deletes_all_of_them(self) -> None:
"""
When we delete a key we lose all state about it.
"""
s = h2.settings.Settings(client=True)
s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] == 8000
del s[h2.settings.SettingCodes.HEADER_TABLE_SIZE]
wit... |
When we delete a key we lose all state about it.
| test_deleting_values_deletes_all_of_them | python | python-hyper/h2 | tests/test_settings.py | https://github.com/python-hyper/h2/blob/master/tests/test_settings.py | MIT |
def test_length_correctly_reported(self) -> None:
"""
Length is related only to the number of keys.
"""
s = h2.settings.Settings(client=True)
assert len(s) == 5
s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] == 8000
assert len(s) == 5
s.acknowledge()
... |
Length is related only to the number of keys.
| test_length_correctly_reported | python | python-hyper/h2 | tests/test_settings.py | https://github.com/python-hyper/h2/blob/master/tests/test_settings.py | MIT |
def test_new_values_follow_basic_acknowledgement_rules(self) -> None:
"""
A new value properly appears when acknowledged.
"""
s = h2.settings.Settings(client=True)
s[80] = 81
changed_settings = s.acknowledge()
assert s[80] == 81
assert len(changed_setting... |
A new value properly appears when acknowledged.
| test_new_values_follow_basic_acknowledgement_rules | python | python-hyper/h2 | tests/test_settings.py | https://github.com/python-hyper/h2/blob/master/tests/test_settings.py | MIT |
def test_single_values_arent_affected_by_acknowledgement(self) -> None:
"""
When acknowledged, unchanged settings remain unchanged.
"""
s = h2.settings.Settings(client=True)
assert s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] == 4096
s.acknowledge()
assert s[h2.... |
When acknowledged, unchanged settings remain unchanged.
| test_single_values_arent_affected_by_acknowledgement | python | python-hyper/h2 | tests/test_settings.py | https://github.com/python-hyper/h2/blob/master/tests/test_settings.py | MIT |
def test_settings_getters(self) -> None:
"""
Getters exist for well-known settings.
"""
s = h2.settings.Settings(client=True)
assert s.header_table_size == (
s[h2.settings.SettingCodes.HEADER_TABLE_SIZE]
)
assert s.enable_push == s[h2.settings.Setting... |
Getters exist for well-known settings.
| test_settings_getters | python | python-hyper/h2 | tests/test_settings.py | https://github.com/python-hyper/h2/blob/master/tests/test_settings.py | MIT |
def test_settings_setters(self) -> None:
"""
Setters exist for well-known settings.
"""
s = h2.settings.Settings(client=True)
s.header_table_size = 0
s.enable_push = 1
s.initial_window_size = 2
s.max_frame_size = 16385
s.max_concurrent_streams = 4... |
Setters exist for well-known settings.
| test_settings_setters | python | python-hyper/h2 | tests/test_settings.py | https://github.com/python-hyper/h2/blob/master/tests/test_settings.py | MIT |
def test_cannot_set_invalid_vals_for_initial_window_size(self, val) -> None:
"""
SETTINGS_INITIAL_WINDOW_SIZE only allows values between 0 and 2**32 - 1
inclusive.
"""
s = h2.settings.Settings()
if 0 <= val <= 2**31 - 1:
s.initial_window_size = val
... |
SETTINGS_INITIAL_WINDOW_SIZE only allows values between 0 and 2**32 - 1
inclusive.
| test_cannot_set_invalid_vals_for_initial_window_size | python | python-hyper/h2 | tests/test_settings.py | https://github.com/python-hyper/h2/blob/master/tests/test_settings.py | MIT |
def test_equality_reflexive(self, settings) -> None:
"""
An object compares equal to itself using the == operator and the !=
operator.
"""
assert (settings == settings)
assert settings == settings |
An object compares equal to itself using the == operator and the !=
operator.
| test_equality_reflexive | python | python-hyper/h2 | tests/test_settings.py | https://github.com/python-hyper/h2/blob/master/tests/test_settings.py | MIT |
def test_equality_multiple(self, settings, o_settings) -> None:
"""
Two objects compare themselves using the == operator and the !=
operator.
"""
if settings == o_settings:
assert settings == o_settings
assert settings == o_settings
else:
... |
Two objects compare themselves using the == operator and the !=
operator.
| test_equality_multiple | python | python-hyper/h2 | tests/test_settings.py | https://github.com/python-hyper/h2/blob/master/tests/test_settings.py | MIT |
def test_another_type_equality(self, settings) -> None:
"""
The object does not compare equal to an object of an unrelated type
(which does not implement the comparison) using the == operator.
"""
obj = object()
assert (settings != obj)
assert settings != obj |
The object does not compare equal to an object of an unrelated type
(which does not implement the comparison) using the == operator.
| test_another_type_equality | python | python-hyper/h2 | tests/test_settings.py | https://github.com/python-hyper/h2/blob/master/tests/test_settings.py | MIT |
def test_delegated_eq(self, settings) -> None:
"""
The result of comparison is delegated to the right-hand operand if
it is of an unrelated type.
"""
class Delegate:
def __eq__(self, other):
return [self]
def __ne__(self, other):
... |
The result of comparison is delegated to the right-hand operand if
it is of an unrelated type.
| test_delegated_eq | python | python-hyper/h2 | tests/test_settings.py | https://github.com/python-hyper/h2/blob/master/tests/test_settings.py | MIT |
def test_state_machine_only_allows_connection_states(self) -> None:
"""
The Connection state machine only allows ConnectionState inputs.
"""
c = h2.connection.H2ConnectionStateMachine()
with pytest.raises(ValueError):
c.process_input(1) |
The Connection state machine only allows ConnectionState inputs.
| test_state_machine_only_allows_connection_states | python | python-hyper/h2 | tests/test_state_machines.py | https://github.com/python-hyper/h2/blob/master/tests/test_state_machines.py | MIT |
def test_priority_frames_allowed_in_all_states(self, state, input_) -> None:
"""
Priority frames can be sent/received in all connection states except
closed.
"""
c = h2.connection.H2ConnectionStateMachine()
c.state = state
c.process_input(input_) |
Priority frames can be sent/received in all connection states except
closed.
| test_priority_frames_allowed_in_all_states | python | python-hyper/h2 | tests/test_state_machines.py | https://github.com/python-hyper/h2/blob/master/tests/test_state_machines.py | MIT |
def test_state_machine_only_allows_stream_states(self) -> None:
"""
The Stream state machine only allows StreamState inputs.
"""
s = h2.stream.H2StreamStateMachine(stream_id=1)
with pytest.raises(ValueError):
s.process_input(1) |
The Stream state machine only allows StreamState inputs.
| test_state_machine_only_allows_stream_states | python | python-hyper/h2 | tests/test_state_machines.py | https://github.com/python-hyper/h2/blob/master/tests/test_state_machines.py | MIT |
def test_stream_state_machine_forbids_pushes_on_server_streams(self) -> None:
"""
Streams where this peer is a server do not allow receiving pushed
frames.
"""
s = h2.stream.H2StreamStateMachine(stream_id=1)
s.process_input(h2.stream.StreamInputs.RECV_HEADERS)
wi... |
Streams where this peer is a server do not allow receiving pushed
frames.
| test_stream_state_machine_forbids_pushes_on_server_streams | python | python-hyper/h2 | tests/test_state_machines.py | https://github.com/python-hyper/h2/blob/master/tests/test_state_machines.py | MIT |
def test_stream_state_machine_forbids_sending_pushes_from_clients(self) -> None:
"""
Streams where this peer is a client do not allow sending pushed frames.
"""
s = h2.stream.H2StreamStateMachine(stream_id=1)
s.process_input(h2.stream.StreamInputs.SEND_HEADERS)
with pyte... |
Streams where this peer is a client do not allow sending pushed frames.
| test_stream_state_machine_forbids_sending_pushes_from_clients | python | python-hyper/h2 | tests/test_state_machines.py | https://github.com/python-hyper/h2/blob/master/tests/test_state_machines.py | MIT |
def test_cannot_send_on_closed_streams(self, input_) -> None:
"""
Sending anything but a PRIORITY frame is forbidden on closed streams.
"""
c = h2.stream.H2StreamStateMachine(stream_id=1)
c.state = h2.stream.StreamState.CLOSED
expected_error = (
h2.exceptions... |
Sending anything but a PRIORITY frame is forbidden on closed streams.
| test_cannot_send_on_closed_streams | python | python-hyper/h2 | tests/test_state_machines.py | https://github.com/python-hyper/h2/blob/master/tests/test_state_machines.py | MIT |
def test_reset_stream_keeps_header_state_correct(self, frame_factory) -> None:
"""
A stream that has been reset still affects the header decoder.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(stream_id=1, headers=self.example_request_headers)... |
A stream that has been reset still affects the header decoder.
| test_reset_stream_keeps_header_state_correct | python | python-hyper/h2 | tests/test_stream_reset.py | https://github.com/python-hyper/h2/blob/master/tests/test_stream_reset.py | MIT |
def test_reset_stream_keeps_flow_control_correct(self,
close_id,
other_id,
frame_factory) -> None:
"""
A stream that has been reset does not affe... |
A stream that has been reset does not affect the connection flow
control window.
| test_reset_stream_keeps_flow_control_correct | python | python-hyper/h2 | tests/test_stream_reset.py | https://github.com/python-hyper/h2/blob/master/tests/test_stream_reset.py | MIT |
def test_returns_correct_sequence_for_clients(self, frame_factory) -> None:
"""
For a client connection, the correct sequence of stream IDs is
returned.
"""
# Running the exhaustive version of this test (all 1 billion available
# stream IDs) is too painful. For that reaso... |
For a client connection, the correct sequence of stream IDs is
returned.
| test_returns_correct_sequence_for_clients | python | python-hyper/h2 | tests/test_utility_functions.py | https://github.com/python-hyper/h2/blob/master/tests/test_utility_functions.py | MIT |
def test_returns_correct_sequence_for_servers(self, frame_factory) -> None:
"""
For a server connection, the correct sequence of stream IDs is
returned.
"""
# Running the exhaustive version of this test (all 1 billion available
# stream IDs) is too painful. For that reaso... |
For a server connection, the correct sequence of stream IDs is
returned.
| test_returns_correct_sequence_for_servers | python | python-hyper/h2 | tests/test_utility_functions.py | https://github.com/python-hyper/h2/blob/master/tests/test_utility_functions.py | MIT |
def test_does_not_increment_without_stream_send(self) -> None:
"""
If a new stream isn't actually created, the next stream ID doesn't
change.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
first_stream_id = c.get_next_available_stream_id()
s... |
If a new stream isn't actually created, the next stream ID doesn't
change.
| test_does_not_increment_without_stream_send | python | python-hyper/h2 | tests/test_utility_functions.py | https://github.com/python-hyper/h2/blob/master/tests/test_utility_functions.py | MIT |
def element(name, *children, **attrs):
"""
Construct a string from the HTML element description.
"""
formatted_attributes = ' '.join(
'{}={}'.format(key, quote(str(value)))
for key, value in sorted(attrs.items())
)
formatted_children = ''.join(children)
return u'<{name} {attr... |
Construct a string from the HTML element description.
| element | python | python-hyper/h2 | visualizer/visualize.py | https://github.com/python-hyper/h2/blob/master/visualizer/visualize.py | MIT |
def row_for_output(event, side_effect):
"""
Given an output tuple (an event and its side effect), generates a table row
from it.
"""
point_size = {'point-size': '9'}
event_cell = element(
"td",
element("font", enum_member_name(event), **point_size)
)
side_effect_name = (
... |
Given an output tuple (an event and its side effect), generates a table row
from it.
| row_for_output | python | python-hyper/h2 | visualizer/visualize.py | https://github.com/python-hyper/h2/blob/master/visualizer/visualize.py | MIT |
def table_maker(initial_state, final_state, outputs, port):
"""
Construct an HTML table to label a state transition.
"""
header = "{} -> {}".format(
enum_member_name(initial_state), enum_member_name(final_state)
)
header_row = element(
"tr",
element(
"td",
... |
Construct an HTML table to label a state transition.
| table_maker | python | python-hyper/h2 | visualizer/visualize.py | https://github.com/python-hyper/h2/blob/master/visualizer/visualize.py | MIT |
def build_digraph(state_machine):
"""
Produce a L{graphviz.Digraph} object from a state machine.
"""
digraph = graphviz.Digraph(node_attr={'fontname': 'Menlo'},
edge_attr={'fontname': 'Menlo'},
graph_attr={'dpi': '200'})
# First, add the... |
Produce a L{graphviz.Digraph} object from a state machine.
| build_digraph | python | python-hyper/h2 | visualizer/visualize.py | https://github.com/python-hyper/h2/blob/master/visualizer/visualize.py | MIT |
def main():
"""
Renders all the state machines in h2 into images.
"""
program_name = sys.argv[0]
argv = sys.argv[1:]
description = """
Visualize h2 state machines as graphs.
"""
epilog = """
You must have the graphviz tool suite installed. Please visit
http://www.graphviz.o... |
Renders all the state machines in h2 into images.
| main | python | python-hyper/h2 | visualizer/visualize.py | https://github.com/python-hyper/h2/blob/master/visualizer/visualize.py | MIT |
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if pid == 0:
# According to "man 2 kill" PID 0 has a special meaning:
# it refers to <<every process in the process group of the
# calling process>> so we don't want to go any further.
# If we get h... | Check whether pid exists in the current process table. | pid_exists | python | amitt001/delegator.py | delegator.py | https://github.com/amitt001/delegator.py/blob/master/delegator.py | MIT |
def run(self, block=True, binary=False, cwd=None, env=None):
"""Runs the given command, with or without pexpect functionality enabled."""
self.blocking = block
# Use subprocess.
if self.blocking:
popen_kwargs = self._default_popen_kwargs.copy()
del popen_kwargs["... | Runs the given command, with or without pexpect functionality enabled. | run | python | amitt001/delegator.py | delegator.py | https://github.com/amitt001/delegator.py/blob/master/delegator.py | MIT |
def expect(self, pattern, timeout=-1):
"""Waits on the given pattern to appear in std_out"""
if self.blocking:
raise RuntimeError("expect can only be used on non-blocking commands.")
try:
self.subprocess.expect(pattern=pattern, timeout=timeout)
except pexpect.EO... | Waits on the given pattern to appear in std_out | expect | python | amitt001/delegator.py | delegator.py | https://github.com/amitt001/delegator.py/blob/master/delegator.py | MIT |
def send(self, s, end=os.linesep, signal=False):
"""Sends the given string or signal to std_in."""
if self.blocking:
raise RuntimeError("send can only be used on non-blocking commands.")
if not signal:
if self._uses_subprocess:
return self.subprocess.com... | Sends the given string or signal to std_in. | send | python | amitt001/delegator.py | delegator.py | https://github.com/amitt001/delegator.py/blob/master/delegator.py | MIT |
def pipe(self, command, timeout=None, cwd=None):
"""Runs the current command and passes its output to the next
given process.
"""
if not timeout:
timeout = self.timeout
if not self.was_run:
self.run(block=False, cwd=cwd)
data = self.out
... | Runs the current command and passes its output to the next
given process.
| pipe | python | amitt001/delegator.py | delegator.py | https://github.com/amitt001/delegator.py/blob/master/delegator.py | MIT |
def _expand_args(command):
"""Parses command strings and returns a Popen-ready list."""
# Prepare arguments.
if isinstance(command, STR_TYPES):
if sys.version_info[0] == 2:
splitter = shlex.shlex(command.encode("utf-8"))
elif sys.version_info[0] == 3:
splitter = shle... | Parses command strings and returns a Popen-ready list. | _expand_args | python | amitt001/delegator.py | delegator.py | https://github.com/amitt001/delegator.py/blob/master/delegator.py | MIT |
def __init__(self, env):
"""Implements the models and training of
Policy Gradient Methods
Argument:
env (Object): OpenAI gym environment
"""
self.env = env
# entropy loss weight
self.beta = 0.0
# value loss for all policy gradients except... | Implements the models and training of
Policy Gradient Methods
Argument:
env (Object): OpenAI gym environment
| __init__ | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def action(self, args):
"""Given mean and stddev, sample an action, clip
and return
We assume Gaussian distribution of probability
of selecting an action given a state
Argument:
args (list) : mean, stddev list
Return:
action (tensor):... | Given mean and stddev, sample an action, clip
and return
We assume Gaussian distribution of probability
of selecting an action given a state
Argument:
args (list) : mean, stddev list
Return:
action (tensor): policy action
| action | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def logp(self, args):
"""Given mean, stddev, and action compute
the log probability of the Gaussian distribution
Argument:
args (list) : mean, stddev action, list
Return:
logp (tensor): log of action
"""
mean, stddev, action = args
dist... | Given mean, stddev, and action compute
the log probability of the Gaussian distribution
Argument:
args (list) : mean, stddev action, list
Return:
logp (tensor): log of action
| logp | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def entropy(self, args):
"""Given the mean and stddev compute
the Gaussian dist entropy
Argument:
args (list) : mean, stddev list
Return:
entropy (tensor): action entropy
"""
mean, stddev = args
dist = tfp.distributions.Normal(loc=mean... | Given the mean and stddev compute
the Gaussian dist entropy
Argument:
args (list) : mean, stddev list
Return:
entropy (tensor): action entropy
| entropy | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def build_autoencoder(self):
"""Autoencoder to convert states into features
"""
# first build the encoder model
inputs = Input(shape=(self.state_dim, ), name='state')
feature_size = 32
x = Dense(256, activation='relu')(inputs)
x = Dense(128, activation='relu')(x)
... | Autoencoder to convert states into features
| build_autoencoder | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def train_autoencoder(self, x_train, x_test):
"""Training the autoencoder using randomly sampled
states from the environment
Arguments:
x_train (tensor): autoencoder train dataset
x_test (tensor): autoencoder test dataset
"""
# train the autoencoder
... | Training the autoencoder using randomly sampled
states from the environment
Arguments:
x_train (tensor): autoencoder train dataset
x_test (tensor): autoencoder test dataset
| train_autoencoder | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def build_actor_critic(self):
"""4 models are built but 3 models share the
same parameters. hence training one, trains the rest.
The 3 models that share the same parameters
are action, logp, and entropy models.
Entropy model is used by A2C only.
... | 4 models are built but 3 models share the
same parameters. hence training one, trains the rest.
The 3 models that share the same parameters
are action, logp, and entropy models.
Entropy model is used by A2C only.
Each model has the same MLP structure:
... | build_actor_critic | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def logp_loss(self, entropy, beta=0.0):
"""logp loss, the 3rd and 4th variables
(entropy and beta) are needed by A2C
so we have a different loss function structure
Arguments:
entropy (tensor): Entropy loss
beta (float): Entropy loss weight
Return... | logp loss, the 3rd and 4th variables
(entropy and beta) are needed by A2C
so we have a different loss function structure
Arguments:
entropy (tensor): Entropy loss
beta (float): Entropy loss weight
Return:
loss (tensor): computed loss
| logp_loss | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def save_weights(self,
actor_weights,
encoder_weights,
value_weights=None):
"""Save the actor, critic and encoder weights
useful for restoring the trained models
Arguments:
actor_weights (tensor): actor net paramet... | Save the actor, critic and encoder weights
useful for restoring the trained models
Arguments:
actor_weights (tensor): actor net parameters
encoder_weights (tensor): encoder weights
value_weights (tensor): value net parameters
| save_weights | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def load_weights(self,
actor_weights,
value_weights=None):
"""Load the trained weights
useful if we are interested in using
the network right away
Arguments:
actor_weights (string): filename containing actor net
... | Load the trained weights
useful if we are interested in using
the network right away
Arguments:
actor_weights (string): filename containing actor net
weights
value_weights (string): filename containing value net
weights
| load_weights | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def train_by_episode(self):
"""Train by episode
Prepare the dataset before the step by step training
"""
# only REINFORCE and REINFORCE with baseline
# use the ff code
# convert the rewards to returns
rewards = []
gamma = 0.99
for item in self.m... | Train by episode
Prepare the dataset before the step by step training
| train_by_episode | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def train(self, item, gamma=1.0):
"""Main routine for training
Arguments:
item (list) : one experience unit
gamma (float) : discount factor [0,1]
"""
[step, state, next_state, reward, done] = item
# must save state for entropy computation
self.st... | Main routine for training
Arguments:
item (list) : one experience unit
gamma (float) : discount factor [0,1]
| train | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def train(self, item, gamma=1.0):
"""Main routine for training
Arguments:
item (list) : one experience unit
gamma (float) : discount factor [0,1]
"""
[step, state, next_state, reward, done] = item
# must save state for entropy computation
self.st... | Main routine for training
Arguments:
item (list) : one experience unit
gamma (float) : discount factor [0,1]
| train | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def __init__(self, env):
"""Implements the models and training of
A2C policy gradient method
Arguments:
env (Object): OpenAI gym environment
"""
super().__init__(env)
# beta of entropy used in A2C
self.beta = 0.9
# loss function of A2C val... | Implements the models and training of
A2C policy gradient method
Arguments:
env (Object): OpenAI gym environment
| __init__ | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def train_by_episode(self, last_value=0):
"""Train by episode
Prepare the dataset before the step by step training
Arguments:
last_value (float): previous prediction of value net
"""
# implements A2C training from the last state
# to the first state
... | Train by episode
Prepare the dataset before the step by step training
Arguments:
last_value (float): previous prediction of value net
| train_by_episode | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def train(self, item, gamma=1.0):
"""Main routine for training
Arguments:
item (list) : one experience unit
gamma (float) : discount factor [0,1]
"""
[step, state, next_state, reward, done] = item
# must save state for entropy computation
self.st... | Main routine for training
Arguments:
item (list) : one experience unit
gamma (float) : discount factor [0,1]
| train | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def train(self, item, gamma=1.0):
"""Main routine for training
Arguments:
item (list) : one experience unit
gamma (float) : discount factor [0,1]
"""
[step, state, next_state, reward, done] = item
# must save state for entropy computation
self.sta... | Main routine for training
Arguments:
item (list) : one experience unit
gamma (float) : discount factor [0,1]
| train | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def setup_files(args):
"""Housekeeping to keep the output logs in separate folders
Arguments:
args: user-defined arguments
"""
postfix = 'reinforce'
has_value_model = False
if args.baseline:
postfix = "reinforce-baseline"
has_value_model = True
elif args.actor_critic:... | Housekeeping to keep the output logs in separate folders
Arguments:
args: user-defined arguments
| setup_files | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def setup_agent(env, args):
"""Agent initialization
Arguments:
env (Object): OpenAI environment
args : user-defined arguments
"""
# instantiate agent
if args.baseline:
agent = REINFORCEBaselineAgent(env)
elif args.a2c:
agent = A2CAgent(env)
elif args.actor_cri... | Agent initialization
Arguments:
env (Object): OpenAI environment
args : user-defined arguments
| setup_agent | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def setup_writer(fileid, postfix):
"""Use to prepare file and writer for data logging
Arguments:
fileid (string): unique file identfier
postfix (string): path
"""
# we dump episode num, step, total reward, and
# number of episodes solved in a csv file for analysis
csvfilename = ... | Use to prepare file and writer for data logging
Arguments:
fileid (string): unique file identfier
postfix (string): path
| setup_writer | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter10-policy/policygradient-car-10.1.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter10-policy/policygradient-car-10.1.1.py | MIT |
def nms(args, classes, offsets, anchors):
"""Perform NMS (Algorithm 11.12.1).
Arguments:
args : User-defined configurations
classes (tensor): Predicted classes
offsets (tensor): Predicted offsets
Returns:
objects (tensor): class predictions per anchor
indexe... | Perform NMS (Algorithm 11.12.1).
Arguments:
args : User-defined configurations
classes (tensor): Predicted classes
offsets (tensor): Predicted offsets
Returns:
objects (tensor): class predictions per anchor
indexes (tensor): indexes of detected objects
... | nms | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/boxes.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/boxes.py | MIT |
def show_boxes(args,
image,
classes,
offsets,
feature_shapes,
show=True):
"""Show detected objects on an image. Show bounding boxes
and class names.
Arguments:
image (tensor): Image to show detected objects (0.0 to 1.0)
... | Show detected objects on an image. Show bounding boxes
and class names.
Arguments:
image (tensor): Image to show detected objects (0.0 to 1.0)
classes (tensor): Predicted classes
offsets (tensor): Predicted offsets
feature_shapes (tensor): SSD head feature maps
show (boo... | show_boxes | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/boxes.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/boxes.py | MIT |
def show_anchors(image,
feature_shape,
anchors,
maxiou_indexes=None,
maxiou_per_gt=None,
labels=None,
show_grids=False):
"""Utility for showing anchor boxes for debugging purposes"""
image_height, image_width, ... | Utility for showing anchor boxes for debugging purposes | show_anchors | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/boxes.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/boxes.py | MIT |
def apply_random_noise(self, image, percent=30):
"""Apply random noise on an image (not used)"""
random = np.random.randint(0, 100)
if random < percent:
image = random_noise(image)
return image | Apply random noise on an image (not used) | apply_random_noise | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/data_generator.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/data_generator.py | MIT |
def apply_random_intensity_rescale(self, image, percent=30):
"""Apply random intensity rescale on an image (not used)"""
random = np.random.randint(0, 100)
if random < percent:
v_min, v_max = np.percentile(image, (0.2, 99.8))
image = exposure.rescale_intensity(image, in_r... | Apply random intensity rescale on an image (not used) | apply_random_intensity_rescale | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/data_generator.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/data_generator.py | MIT |
def apply_random_exposure_adjust(self, image, percent=30):
"""Apply random exposure adjustment on an image (not used)"""
random = np.random.randint(0, 100)
if random < percent:
image = exposure.adjust_gamma(image, gamma=0.4, gain=0.9)
# another exposure algo
#... | Apply random exposure adjustment on an image (not used) | apply_random_exposure_adjust | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/data_generator.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/data_generator.py | MIT |
def __data_generation(self, keys):
"""Generate train data: images and
object detection ground truth labels
Arguments:
keys (array): Randomly sampled keys
(key is image filename)
Returns:
x (tensor): Batch images
y (tensor): Batch cl... | Generate train data: images and
object detection ground truth labels
Arguments:
keys (array): Randomly sampled keys
(key is image filename)
Returns:
x (tensor): Batch images
y (tensor): Batch classes, offsets, and masks
| __data_generation | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/data_generator.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/data_generator.py | MIT |
def get_box_color(index=None):
"""Retrieve plt-compatible color string based on object index"""
colors = ['w', 'r', 'b', 'g', 'c', 'm', 'y', 'g', 'c', 'm', 'k']
if index is None:
return colors[randint(0, len(colors) - 1)]
return colors[index % len(colors)] | Retrieve plt-compatible color string based on object index | get_box_color | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/label_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/label_utils.py | MIT |
def get_box_rgbcolor(index=None):
"""Retrieve rgb color based on object index"""
colors = [(0, 0, 0), (255, 0, 0), (0, 0, 255), (0, 255, 0), (128, 128, 0)]
if index is None:
return colors[randint(0, len(colors) - 1)]
return colors[index % len(colors)] | Retrieve rgb color based on object index | get_box_rgbcolor | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/label_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/label_utils.py | MIT |
def load_csv(path):
"""Load a csv file into an np array"""
data = []
with open(path) as csv_file:
rows = csv.reader(csv_file, delimiter=',')
for row in rows:
data.append(row)
return np.array(data) | Load a csv file into an np array | load_csv | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/label_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/label_utils.py | MIT |
def get_label_dictionary(labels, keys):
"""Associate key (filename) to value (box coords, class)"""
dictionary = {}
for key in keys:
dictionary[key] = [] # empty boxes
for label in labels:
if len(label) != 6:
print("Incomplete label:", label[0])
continue
... | Associate key (filename) to value (box coords, class) | get_label_dictionary | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/label_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/label_utils.py | MIT |
def build_label_dictionary(path):
"""Build a dict with key=filename, value=[box coords, class]"""
labels = load_csv(path)
# skip the 1st line header
labels = labels[1:]
# keys are filenames
keys = np.unique(labels[:,0])
dictionary = get_label_dictionary(labels, keys)
classes = np.unique(... | Build a dict with key=filename, value=[box coords, class] | build_label_dictionary | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/label_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/label_utils.py | MIT |
def show_labels(image, labels, ax=None):
"""Draw bounding box on an object given box coords (labels[1:5])"""
if ax is None:
fig, ax = plt.subplots(1)
ax.imshow(image)
for label in labels:
# default label format is xmin, xmax, ymin, ymax
w = label[1] - label[0]
h = lab... | Draw bounding box on an object given box coords (labels[1:5]) | show_labels | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/label_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/label_utils.py | MIT |
def anchor_sizes(n_layers=4):
"""Generate linear distribution of sizes depending on
the number of ssd top layers
Arguments:
n_layers (int): Number of ssd head layers
Returns:
sizes (list): A list of anchor sizes
"""
s = np.linspace(0.2, 0.9, n_layers + 1)
sizes = []
fo... | Generate linear distribution of sizes depending on
the number of ssd top layers
Arguments:
n_layers (int): Number of ssd head layers
Returns:
sizes (list): A list of anchor sizes
| anchor_sizes | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/layer_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/layer_utils.py | MIT |
def anchor_boxes(feature_shape,
image_shape,
index=0,
n_layers=4,
aspect_ratios=(1, 2, 0.5)):
""" Compute the anchor boxes for a given feature map.
Anchor boxes are in minmax format
Arguments:
feature_shape (list): Feature map shap... | Compute the anchor boxes for a given feature map.
Anchor boxes are in minmax format
Arguments:
feature_shape (list): Feature map shape
image_shape (list): Image size shape
index (int): Indicates which of ssd head layers
are we referring to
n_layers (int): Number of ... | anchor_boxes | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/layer_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/layer_utils.py | MIT |
def centroid2minmax(boxes):
"""Centroid to minmax format
(cx, cy, w, h) to (xmin, xmax, ymin, ymax)
Arguments:
boxes (tensor): Batch of boxes in centroid format
Returns:
minmax (tensor): Batch of boxes in minmax format
"""
minmax= np.copy(boxes).astype(np.float)
minmax[...... | Centroid to minmax format
(cx, cy, w, h) to (xmin, xmax, ymin, ymax)
Arguments:
boxes (tensor): Batch of boxes in centroid format
Returns:
minmax (tensor): Batch of boxes in minmax format
| centroid2minmax | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/layer_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/layer_utils.py | MIT |
def minmax2centroid(boxes):
"""Minmax to centroid format
(xmin, xmax, ymin, ymax) to (cx, cy, w, h)
Arguments:
boxes (tensor): Batch of boxes in minmax format
Returns:
centroid (tensor): Batch of boxes in centroid format
"""
centroid = np.copy(boxes).astype(np.float)
centro... | Minmax to centroid format
(xmin, xmax, ymin, ymax) to (cx, cy, w, h)
Arguments:
boxes (tensor): Batch of boxes in minmax format
Returns:
centroid (tensor): Batch of boxes in centroid format
| minmax2centroid | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/layer_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/layer_utils.py | MIT |
def intersection(boxes1, boxes2):
"""Compute intersection of batch of boxes1 and boxes2
Arguments:
boxes1 (tensor): Boxes coordinates in pixels
boxes2 (tensor): Boxes coordinates in pixels
Returns:
intersection_areas (tensor): intersection of areas of
boxes1 and box... | Compute intersection of batch of boxes1 and boxes2
Arguments:
boxes1 (tensor): Boxes coordinates in pixels
boxes2 (tensor): Boxes coordinates in pixels
Returns:
intersection_areas (tensor): intersection of areas of
boxes1 and boxes2
| intersection | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/layer_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/layer_utils.py | MIT |
def union(boxes1, boxes2, intersection_areas):
"""Compute union of batch of boxes1 and boxes2
Arguments:
boxes1 (tensor): Boxes coordinates in pixels
boxes2 (tensor): Boxes coordinates in pixels
Returns:
union_areas (tensor): union of areas of
boxes1 and boxes2
"""
... | Compute union of batch of boxes1 and boxes2
Arguments:
boxes1 (tensor): Boxes coordinates in pixels
boxes2 (tensor): Boxes coordinates in pixels
Returns:
union_areas (tensor): union of areas of
boxes1 and boxes2
| union | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/layer_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/layer_utils.py | MIT |
def iou(boxes1, boxes2):
"""Compute IoU of batch boxes1 and boxes2
Arguments:
boxes1 (tensor): Boxes coordinates in pixels
boxes2 (tensor): Boxes coordinates in pixels
Returns:
iou (tensor): intersectiin of union of areas of
boxes1 and boxes2
"""
intersection_ar... | Compute IoU of batch boxes1 and boxes2
Arguments:
boxes1 (tensor): Boxes coordinates in pixels
boxes2 (tensor): Boxes coordinates in pixels
Returns:
iou (tensor): intersectiin of union of areas of
boxes1 and boxes2
| iou | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/layer_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/layer_utils.py | MIT |
def get_gt_data(iou,
n_classes=4,
anchors=None,
labels=None,
normalize=False,
threshold=0.6):
"""Retrieve ground truth class, bbox offset, and mask
Arguments:
iou (tensor): IoU of each bounding box wrt each anchor box
... | Retrieve ground truth class, bbox offset, and mask
Arguments:
iou (tensor): IoU of each bounding box wrt each anchor box
n_classes (int): Number of object classes
anchors (tensor): Anchor boxes per feature layer
labels (list): Ground truth labels
normalize (bool): If nor... | get_gt_data | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/layer_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/layer_utils.py | MIT |
def focal_loss_ce(y_true, y_pred):
"""Alternative CE focal loss (not used)
"""
# only missing in this FL is y_pred clipping
weight = (1 - y_pred)
weight *= weight
# alpha = 0.25
weight *= 0.25
return K.categorical_crossentropy(weight*y_true, y_pred) | Alternative CE focal loss (not used)
| focal_loss_ce | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/loss.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/loss.py | MIT |
def mask_offset(y_true, y_pred):
"""Pre-process ground truth and prediction data"""
# 1st 4 are offsets
offset = y_true[..., 0:4]
# last 4 are mask
mask = y_true[..., 4:8]
# pred is actually duplicated for alignment
# either we get the 1st or last 4 offset pred
# and apply the mask
... | Pre-process ground truth and prediction data | mask_offset | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/loss.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/loss.py | MIT |
def smooth_l1_loss(y_true, y_pred):
"""Smooth L1 loss using tensorflow Huber loss
"""
offset, pred = mask_offset(y_true, y_pred)
# Huber loss as approx of smooth L1
return Huber()(offset, pred) | Smooth L1 loss using tensorflow Huber loss
| smooth_l1_loss | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/loss.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/loss.py | MIT |
def build_ssd(input_shape,
backbone,
n_layers=4,
n_classes=4,
aspect_ratios=(1, 2, 0.5)):
"""Build SSD model given a backbone
Arguments:
input_shape (list): input image shape
backbone (model): Keras backbone model
n_layers (int): N... | Build SSD model given a backbone
Arguments:
input_shape (list): input image shape
backbone (model): Keras backbone model
n_layers (int): Number of layers of ssd head
n_classes (int): Number of obj classes
aspect_ratios (list): annchor box aspect ratios
Returns:
... | build_ssd | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/model.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/model.py | MIT |
def lr_scheduler(epoch):
"""Learning rate scheduler - called every epoch"""
lr = 1e-3
epoch_offset = config.params['epoch_offset']
if epoch > (200 - epoch_offset):
lr *= 1e-4
elif epoch > (180 - epoch_offset):
lr *= 5e-4
elif epoch > (160 - epoch_offset):
lr *= 1e-3
e... | Learning rate scheduler - called every epoch | lr_scheduler | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/model_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/model_utils.py | MIT |
def ssd_parser():
"""Instatiate a command line parser for ssd network model
building, training, and testing
"""
parser = argparse.ArgumentParser(description='SSD for object detection')
# arguments for model building and training
help_ = "Number of feature extraction layers of SSD head after back... | Instatiate a command line parser for ssd network model
building, training, and testing
| ssd_parser | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/model_utils.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/model_utils.py | MIT |
def resnet_layer(inputs,
num_filters=16,
kernel_size=3,
strides=1,
activation='relu',
batch_normalization=True,
conv_first=True):
"""2D Convolution-Batch Normalization-Activation stack builder
Arguments:
... | 2D Convolution-Batch Normalization-Activation stack builder
Arguments:
inputs (tensor): Input tensor from input image or previous layer
num_filters (int): Conv2D number of filters
kernel_size (int): Conv2D square kernel dimensions
strides (int): Conv2D square stride dimensions
... | resnet_layer | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/resnet.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/resnet.py | MIT |
def resnet_v1(input_shape, depth, num_classes=10):
"""ResNet Version 1 Model builder [a]
Stacks of 2 x (3 x 3) Conv2D-BN-ReLU
Last ReLU is after the shortcut connection.
At the beginning of each stage, the feature map size is halved (downsampled)
by a convolutional layer with strides=2, while the n... | ResNet Version 1 Model builder [a]
Stacks of 2 x (3 x 3) Conv2D-BN-ReLU
Last ReLU is after the shortcut connection.
At the beginning of each stage, the feature map size is halved (downsampled)
by a convolutional layer with strides=2, while the number of filters is
doubled. Within each stage, the la... | resnet_v1 | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/resnet.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/resnet.py | MIT |
def resnet_v2(input_shape, depth, n_layers=4):
"""ResNet Version 2 Model builder [b]
Stacks of (1 x 1)-(3 x 3)-(1 x 1) BN-ReLU-Conv2D or also known as
bottleneck layer
First shortcut connection per layer is 1 x 1 Conv2D.
Second and onwards shortcut connection is identity.
At the beginning of ea... | ResNet Version 2 Model builder [b]
Stacks of (1 x 1)-(3 x 3)-(1 x 1) BN-ReLU-Conv2D or also known as
bottleneck layer
First shortcut connection per layer is 1 x 1 Conv2D.
Second and onwards shortcut connection is identity.
At the beginning of each stage, the feature map size is halved (downsampled)... | resnet_v2 | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/resnet.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/resnet.py | MIT |
def build_resnet(input_shape,
n_layers=4,
version=2,
n=6):
"""Build a resnet as backbone of SSD
# Arguments:
input_shape (list): Input image size and channels
n_layers (int): Number of feature layers for SSD
version (int): Supports ResN... | Build a resnet as backbone of SSD
# Arguments:
input_shape (list): Input image size and channels
n_layers (int): Number of feature layers for SSD
version (int): Supports ResNetv1 and v2 but v2 by default
n (int): Determines number of ResNet layers
(Default is ResNet... | build_resnet | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/resnet.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/resnet.py | MIT |
def __init__(self, args):
"""Copy user-defined configs.
Build backbone and ssd network models.
"""
self.args = args
self.ssd = None
self.train_generator = None
self.build_model() | Copy user-defined configs.
Build backbone and ssd network models.
| __init__ | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/ssd-11.6.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/ssd-11.6.1.py | MIT |
def build_dictionary(self):
"""Read input image filenames and obj detection labels
from a csv file and store in a dictionary.
"""
# train dataset path
path = os.path.join(self.args.data_path,
self.args.train_labels)
# build dictionary:
... | Read input image filenames and obj detection labels
from a csv file and store in a dictionary.
| build_dictionary | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/ssd-11.6.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/ssd-11.6.1.py | MIT |
def build_generator(self):
"""Build a multi-thread train data generator."""
self.train_generator = \
DataGenerator(args=self.args,
dictionary=self.dictionary,
n_classes=self.n_classes,
feature_shap... | Build a multi-thread train data generator. | build_generator | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/ssd-11.6.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/ssd-11.6.1.py | MIT |
def evaluate(self, image_file=None, image=None):
"""Evaluate image based on image (np tensor) or filename"""
show = False
if image is None:
image = skimage.img_as_float(imread(image_file))
show = True
image, classes, offsets = self.detect_objects(image)
c... | Evaluate image based on image (np tensor) or filename | evaluate | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/ssd-11.6.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/ssd-11.6.1.py | MIT |
def print_summary(self):
"""Print network summary for debugging purposes."""
from tensorflow.keras.utils import plot_model
if self.args.summary:
self.backbone.summary()
self.ssd.summary()
plot_model(self.backbone,
to_file="backbone.png",... | Print network summary for debugging purposes. | print_summary | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter11-detection/ssd-11.6.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter11-detection/ssd-11.6.1.py | MIT |
def get_dictionary(self):
"""Load ground truth dictionary of
image filename : segmentation masks
"""
path = os.path.join(self.args.data_path,
self.args.train_labels)
self.dictionary = np.load(path,
allow_pickle=Tr... | Load ground truth dictionary of
image filename : segmentation masks
| get_dictionary | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter12-segmentation/data_generator.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter12-segmentation/data_generator.py | MIT |
def __data_generation(self, keys):
"""Generate train data: images and
segmentation ground truth labels
Arguments:
keys (array): Randomly sampled keys
(key is image filename)
Returns:
x (tensor): Batch of images
y (tensor): Batch of ... | Generate train data: images and
segmentation ground truth labels
Arguments:
keys (array): Randomly sampled keys
(key is image filename)
Returns:
x (tensor): Batch of images
y (tensor): Batch of pixel-wise categories
| __data_generation | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter12-segmentation/data_generator.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter12-segmentation/data_generator.py | MIT |
def __init__(self, args):
"""Copy user-defined configs.
Build backbone and fcn network models.
"""
self.args = args
self.fcn = None
self.train_generator = DataGenerator(args)
self.build_model()
self.eval_init() | Copy user-defined configs.
Build backbone and fcn network models.
| __init__ | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter12-segmentation/fcn-12.3.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter12-segmentation/fcn-12.3.1.py | MIT |
def build_model(self):
"""Build a backbone network and use it to
create a semantic segmentation
network based on FCN.
"""
# input shape is (480, 640, 3) by default
self.input_shape = (self.args.height,
self.args.width,
... | Build a backbone network and use it to
create a semantic segmentation
network based on FCN.
| build_model | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter12-segmentation/fcn-12.3.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter12-segmentation/fcn-12.3.1.py | MIT |
def preload_test(self):
"""Pre-load test dataset to save time """
path = os.path.join(self.args.data_path,
self.args.test_labels)
# ground truth data is stored in an npy file
self.test_dictionary = np.load(path,
allow_pi... | Pre-load test dataset to save time | preload_test | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter12-segmentation/fcn-12.3.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter12-segmentation/fcn-12.3.1.py | MIT |
def segment_objects(self, image, normalized=True):
"""Run segmentation prediction for a given image
Arguments:
image (tensor): Image loaded in a numpy tensor.
RGB components range is [0.0, 1.0]
normalized (Bool): Use normalized=True for
pixel... | Run segmentation prediction for a given image
Arguments:
image (tensor): Image loaded in a numpy tensor.
RGB components range is [0.0, 1.0]
normalized (Bool): Use normalized=True for
pixel-wise categorical prediction. False if
segmen... | segment_objects | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter12-segmentation/fcn-12.3.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter12-segmentation/fcn-12.3.1.py | MIT |
def evaluate(self, imagefile=None, image=None):
"""Perform segmentation on a given image filename
and display the results.
"""
import matplotlib.pyplot as plt
save_dir = "prediction"
if not os.path.isdir(save_dir):
os.makedirs(save_dir)
if image is... | Perform segmentation on a given image filename
and display the results.
| evaluate | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter12-segmentation/fcn-12.3.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter12-segmentation/fcn-12.3.1.py | MIT |
def eval(self):
"""Evaluate a trained FCN model using mean IoU
metric.
"""
s_iou = 0
s_pla = 0
# evaluate iou per test image
eps = np.finfo(float).eps
for key in self.test_keys:
# load a test image
image_path = os.path.join(self... | Evaluate a trained FCN model using mean IoU
metric.
| eval | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter12-segmentation/fcn-12.3.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter12-segmentation/fcn-12.3.1.py | MIT |
def print_summary(self):
"""Print network summary for debugging purposes."""
from tensorflow.keras.utils import plot_model
if self.args.summary:
self.backbone.summary()
self.fcn.summary()
plot_model(self.fcn,
to_file="fcn.png",
... | Print network summary for debugging purposes. | print_summary | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter12-segmentation/fcn-12.3.1.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter12-segmentation/fcn-12.3.1.py | MIT |
def conv_layer(inputs,
filters=32,
kernel_size=3,
strides=1,
use_maxpool=True,
postfix=None,
activation=None):
"""Helper function to build Conv2D-BN-ReLU layer
with optional MaxPooling2D.
"""
x = Conv2D(filter... | Helper function to build Conv2D-BN-ReLU layer
with optional MaxPooling2D.
| conv_layer | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter12-segmentation/model.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter12-segmentation/model.py | MIT |
def tconv_layer(inputs,
filters=32,
kernel_size=3,
strides=2,
postfix=None):
"""Helper function to build Conv2DTranspose-BN-ReLU
layer
"""
x = Conv2DTranspose(filters=filters,
kernel_size=kernel_size,
... | Helper function to build Conv2DTranspose-BN-ReLU
layer
| tconv_layer | python | PacktPublishing/Advanced-Deep-Learning-with-Keras | chapter12-segmentation/model.py | https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/master/chapter12-segmentation/model.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.