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 get_frequency_aware_conv2d(
data_format='default', freq_aware_name='frequency_aware_conv2d', *args, **kwargs
):
"""Returns a frequency-aware conv2d layer.
Args:
data_format (str): specifies the data format of batch input/output.
freq_aware_name (str): name of the returned layer
... | Returns a frequency-aware conv2d layer.
Args:
data_format (str): specifies the data format of batch input/output.
freq_aware_name (str): name of the returned layer
*args: position args for `keras.layers.Conv2D`.
**kwargs: keyword args for `keras.layers.Conv2D`.
Returns:
... | get_frequency_aware_conv2d | python | keunwoochoi/kapre | kapre/composed.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/composed.py | MIT |
def call(self, x):
"""
Args:
x (`Tensor`): batch audio signal in the specified 1D format in initiation.
Returns:
(`Tensor`): A framed tensor. The shape is (batch, time (frames), frame_length, channel) if `channels_last`,
or (batch, channel, time (frames), fra... |
Args:
x (`Tensor`): batch audio signal in the specified 1D format in initiation.
Returns:
(`Tensor`): A framed tensor. The shape is (batch, time (frames), frame_length, channel) if `channels_last`,
or (batch, channel, time (frames), frame_length) if `channels_first`... | call | python | keunwoochoi/kapre | kapre/signal.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/signal.py | MIT |
def call(self, x):
"""
Args:
x (`Tensor`): batch audio signal in the specified 1D format in initiation.
Returns:
(`Tensor`): A framed tensor. The shape is (batch, time (frames), channel) if `channels_last`, or
(batch, channel, time (frames)) if `channels_firs... |
Args:
x (`Tensor`): batch audio signal in the specified 1D format in initiation.
Returns:
(`Tensor`): A framed tensor. The shape is (batch, time (frames), channel) if `channels_last`, or
(batch, channel, time (frames)) if `channels_first`.
| call | python | keunwoochoi/kapre | kapre/signal.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/signal.py | MIT |
def call(self, log_melgrams):
"""
Args:
log_melgrams (float `Tensor`): a batch of log_melgrams. `(b, time, mel, ch)` if `channels_last`
and `(b, ch, time, mel)` if `channels_first`.
Returns:
(float `Tensor`):
MFCCs. `(batch, time, n_mfccs, ch... |
Args:
log_melgrams (float `Tensor`): a batch of log_melgrams. `(b, time, mel, ch)` if `channels_last`
and `(b, ch, time, mel)` if `channels_first`.
Returns:
(float `Tensor`):
MFCCs. `(batch, time, n_mfccs, ch)` if `channels_last`, `(batch, ch, time,... | call | python | keunwoochoi/kapre | kapre/signal.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/signal.py | MIT |
def _rdft(signal, dft_length):
"""DFT for real signals.
Calculates the onesided dft, assuming real signal implies complex conjugate symetry,
hence only onesided DFT is returned.
Args:
signal (tensor) signal to transform, assumes that the last dimension is the time dimension
signal c... | DFT for real signals.
Calculates the onesided dft, assuming real signal implies complex conjugate symetry,
hence only onesided DFT is returned.
Args:
signal (tensor) signal to transform, assumes that the last dimension is the time dimension
signal can be framed, e.g. (1, 40, 1024) for a... | _rdft | python | keunwoochoi/kapre | kapre/tflite_compatible_stft.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/tflite_compatible_stft.py | MIT |
def fixed_frame(signal, frame_length, frame_step):
"""tflite-compatible tf.signal.frame for fixed-size input.
Args:
signal: Tensor containing signal(s).
frame_length: Number of samples to put in each frame.
frame_step: Sample advance between successive frames.
Returns:
A ne... | tflite-compatible tf.signal.frame for fixed-size input.
Args:
signal: Tensor containing signal(s).
frame_length: Number of samples to put in each frame.
frame_step: Sample advance between successive frames.
Returns:
A new tensor where the last axis (or first, if first_axis) of ... | fixed_frame | python | keunwoochoi/kapre | kapre/tflite_compatible_stft.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/tflite_compatible_stft.py | MIT |
def stft_tflite(signal, frame_length, frame_step, fft_length, window_fn, pad_end):
"""tflite-compatible implementation of tf.signal.stft.
Compute the short-time Fourier transform of a 1D input while avoiding tf ops
that are not currently supported in tflite (Rfft, Range, SplitV).
fft_length must be fixe... | tflite-compatible implementation of tf.signal.stft.
Compute the short-time Fourier transform of a 1D input while avoiding tf ops
that are not currently supported in tflite (Rfft, Range, SplitV).
fft_length must be fixed. A Hann window is of frame_length is always
applied.
Since fixed (precomputed) f... | stft_tflite | python | keunwoochoi/kapre | kapre/tflite_compatible_stft.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/tflite_compatible_stft.py | MIT |
def continued_fraction_arctan(x, n=100, dtype=tf.float32):
"""Continued fraction Approximation to the arctan function
Approximate solution to arctan(x), atan is not a natively supported tflite
op (or a flex op). n is the number of iterations, the high the more accurate.
Accuracy is poor whe... | Continued fraction Approximation to the arctan function
Approximate solution to arctan(x), atan is not a natively supported tflite
op (or a flex op). n is the number of iterations, the high the more accurate.
Accuracy is poor when the argument is large.
https://functions.wolfram.com/Ele... | continued_fraction_arctan | python | keunwoochoi/kapre | kapre/tflite_compatible_stft.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/tflite_compatible_stft.py | MIT |
def atan2_tflite(y, x, n=100, dtype=tf.float32):
"""Approximation to the atan2 function
atan is not a tflite supported op or flex op, thus this uses an Approximation
Poor accuracy when either x is very small or y is very large.
https://en.wikipedia.org/wiki/Atan2
Args:
y (tenso... | Approximation to the atan2 function
atan is not a tflite supported op or flex op, thus this uses an Approximation
Poor accuracy when either x is very small or y is very large.
https://en.wikipedia.org/wiki/Atan2
Args:
y (tensor) - vertical component of tangent (or imaginary part of... | atan2_tflite | python | keunwoochoi/kapre | kapre/tflite_compatible_stft.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/tflite_compatible_stft.py | MIT |
def _shape_spectrum_output(spectrums, data_format):
"""Shape batch spectrograms into the right format.
Args:
spectrums (`Tensor`): result of tf.signal.stft or similar, i.e., (..., time, freq).
data_format (`str`): 'channels_first' or 'channels_last'
Returns:
spectrums (`Tensor`): a... | Shape batch spectrograms into the right format.
Args:
spectrums (`Tensor`): result of tf.signal.stft or similar, i.e., (..., time, freq).
data_format (`str`): 'channels_first' or 'channels_last'
Returns:
spectrums (`Tensor`): a transposed version of input `spectrums`
| _shape_spectrum_output | python | keunwoochoi/kapre | kapre/time_frequency.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py | MIT |
def call(self, x):
"""
Compute STFT of the input signal. If the `time` axis is not the last axis of `x`, it should be transposed first.
Args:
x (float `Tensor`): batch of audio signals, (batch, ch, time) or (batch, time, ch) based on input_data_format
Return:
(c... |
Compute STFT of the input signal. If the `time` axis is not the last axis of `x`, it should be transposed first.
Args:
x (float `Tensor`): batch of audio signals, (batch, ch, time) or (batch, time, ch) based on input_data_format
Return:
(complex `Tensor`): A STFT repre... | call | python | keunwoochoi/kapre | kapre/time_frequency.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py | MIT |
def call(self, x):
"""
Compute inverse STFT of the input STFT.
Args:
x (complex `Tensor`): batch of STFTs, (batch, ch, time, freq) or (batch, time, freq, ch) depending on `input_data_format`
Return:
(`float`): audio signals of x. Shape: 1D batch shape. I.e., (ba... |
Compute inverse STFT of the input STFT.
Args:
x (complex `Tensor`): batch of STFTs, (batch, ch, time, freq) or (batch, time, freq, ch) depending on `input_data_format`
Return:
(`float`): audio signals of x. Shape: 1D batch shape. I.e., (batch, time, ch) or (batch, ch, ... | call | python | keunwoochoi/kapre | kapre/time_frequency.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py | MIT |
def call(self, x):
"""
Args:
x (complex `Tensor`): input complex tensor
Returns:
(float `Tensor`): phase of `x` (Radian)
"""
if self.approx_atan_accuracy:
return atan2_tflite(tf.math.imag(x), tf.math.real(x), n=self.approx_atan_accuracy)
... |
Args:
x (complex `Tensor`): input complex tensor
Returns:
(float `Tensor`): phase of `x` (Radian)
| call | python | keunwoochoi/kapre | kapre/time_frequency.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py | MIT |
def call(self, x):
"""
Args:
x (`Tensor`): float tensor. Can be batch or not. Something like magnitude of STFT.
Returns:
(`Tensor`): decibel-scaled float tensor of `x`.
"""
return backend.magnitude_to_decibel(
x, ref_value=self.ref_value, amin... |
Args:
x (`Tensor`): float tensor. Can be batch or not. Something like magnitude of STFT.
Returns:
(`Tensor`): decibel-scaled float tensor of `x`.
| call | python | keunwoochoi/kapre | kapre/time_frequency.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py | MIT |
def call(self, x):
"""
Apply filterbank to `x`.
Args:
x (`Tensor`): float tensor in 2D batch shape.
"""
# x: 2d batch input. (b, t, fr, ch) or (b, ch, t, fr)
output = tf.tensordot(x, self.filterbank, axes=(self.freq_axis, 0))
# ch_last -> (b, t, ch, ... |
Apply filterbank to `x`.
Args:
x (`Tensor`): float tensor in 2D batch shape.
| call | python | keunwoochoi/kapre | kapre/time_frequency.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py | MIT |
def call(self, x):
"""
Args:
x (`Tensor`): a 2d batch (b, t, f, ch) or (b, ch, t, f)
Returns:
(`Tensor`): A tensor with the same shape as input data.
"""
if self.data_format == 'channels_first':
x = K.permute_dimensions(x, (0, 2, 3, 1))
... |
Args:
x (`Tensor`): a 2d batch (b, t, f, ch) or (b, ch, t, f)
Returns:
(`Tensor`): A tensor with the same shape as input data.
| call | python | keunwoochoi/kapre | kapre/time_frequency.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency.py | MIT |
def call(self, x):
"""
Compute STFT of the input signal. If the `time` axis is not the last axis of `x`, it should be transposed first.
Args:
x (float `Tensor`): batch of audio signals, (batch, ch, time) or (batch, time, ch) based on input_data_format
Return:
(r... |
Compute STFT of the input signal. If the `time` axis is not the last axis of `x`, it should be transposed first.
Args:
x (float `Tensor`): batch of audio signals, (batch, ch, time) or (batch, time, ch) based on input_data_format
Return:
(real `Tensor`): A STFT represen... | call | python | keunwoochoi/kapre | kapre/time_frequency_tflite.py | https://github.com/keunwoochoi/kapre/blob/master/kapre/time_frequency_tflite.py | MIT |
def test_spec_augment_apply_masks_to_axis(inputs):
"""
Tests the method _apply_masks_to_axis to see if shape is kept and
exceptions are caught
"""
data_format, axis, mask_param, n_masks = inputs
batch_src, input_shape = get_spectrogram(data_format)
spec_augment = SpecAugment(
input... |
Tests the method _apply_masks_to_axis to see if shape is kept and
exceptions are caught
| test_spec_augment_apply_masks_to_axis | python | keunwoochoi/kapre | tests/test_augmentation.py | https://github.com/keunwoochoi/kapre/blob/master/tests/test_augmentation.py | MIT |
def test_spec_augment_depth_exception():
"""
Checks that SpecAugments fails if Spectrogram has depth greater than 1.
"""
data_format = "default"
with pytest.raises(RuntimeError):
batch_src, input_shape = get_spectrogram(data_format=data_format, n_ch=4)
model = tf.keras.Sequential(... |
Checks that SpecAugments fails if Spectrogram has depth greater than 1.
| test_spec_augment_depth_exception | python | keunwoochoi/kapre | tests/test_augmentation.py | https://github.com/keunwoochoi/kapre/blob/master/tests/test_augmentation.py | MIT |
def test_spec_augment_layer(data_format, atol=1e-4):
"""
Tests the complete layer, checking if the parameter `training` has the expected behaviour.
"""
batch_src, input_shape = get_spectrogram(data_format)
model = tf.keras.Sequential()
spec_augment = SpecAugment(
input_shape=input_shap... |
Tests the complete layer, checking if the parameter `training` has the expected behaviour.
| test_spec_augment_layer | python | keunwoochoi/kapre | tests/test_augmentation.py | https://github.com/keunwoochoi/kapre/blob/master/tests/test_augmentation.py | MIT |
def test_filterbank_log(sample_rate, n_freq, n_bins, bins_per_octave, f_min, spread):
"""It only tests if the function is a valid wrapper"""
log_fb = KPB.filterbank_log(
sample_rate=sample_rate,
n_freq=n_freq,
n_bins=n_bins,
bins_per_octave=bins_per_octave,
f_min=f_min,
... | It only tests if the function is a valid wrapper | test_filterbank_log | python | keunwoochoi/kapre | tests/test_backend.py | https://github.com/keunwoochoi/kapre/blob/master/tests/test_backend.py | MIT |
def allclose_phase(a, b, atol=1e-3):
"""Testing phase.
Remember that a small error in complex value may lead to a large phase difference
if the norm is very small.
Therefore, it makes more sense to test it on the complex value itself rather than breaking it down to phase.
"""
np.testing.assert... | Testing phase.
Remember that a small error in complex value may lead to a large phase difference
if the norm is very small.
Therefore, it makes more sense to test it on the complex value itself rather than breaking it down to phase.
| allclose_phase | python | keunwoochoi/kapre | tests/test_time_frequency.py | https://github.com/keunwoochoi/kapre/blob/master/tests/test_time_frequency.py | MIT |
def assert_approx_phase(a, b, atol=1e-2, acceptable_fail_ratio=0.01):
"""Testing approximate phase.
Tflite phase is approximate, some values will always have a large error
So makes more sense to count the number that are within tolerance
"""
count_failed = np.sum(np.abs(a - b) > atol)
assert (
... | Testing approximate phase.
Tflite phase is approximate, some values will always have a large error
So makes more sense to count the number that are within tolerance
| assert_approx_phase | python | keunwoochoi/kapre | tests/test_time_frequency.py | https://github.com/keunwoochoi/kapre/blob/master/tests/test_time_frequency.py | MIT |
def test_melspectrogram_correctness(
n_fft, sr, hop_length, n_ch, data_format, amin, dynamic_range, n_mels, mel_f_min, mel_f_max
):
"""Test the correctness of melspectrogram.
Note that mel filterbank is tested separated
"""
def _get_melgram_model(return_decibel, amin, dynamic_range, input_shape=N... | Test the correctness of melspectrogram.
Note that mel filterbank is tested separated
| test_melspectrogram_correctness | python | keunwoochoi/kapre | tests/test_time_frequency.py | https://github.com/keunwoochoi/kapre/blob/master/tests/test_time_frequency.py | MIT |
def test_log_spectrogram_runnable(data_format):
"""test if log spectrogram layer works well"""
src_mono, batch_src, input_shape = get_audio(data_format=data_format, n_ch=1)
_ = get_log_frequency_spectrogram_layer(input_shape, return_decibel=True)
_ = get_log_frequency_spectrogram_layer(input_shape, retu... | test if log spectrogram layer works well | test_log_spectrogram_runnable | python | keunwoochoi/kapre | tests/test_time_frequency.py | https://github.com/keunwoochoi/kapre/blob/master/tests/test_time_frequency.py | MIT |
def test_save_load(save_format):
"""test saving/loading of models that has stft, melspectorgrma, and log frequency."""
src_mono, batch_src, input_shape = get_audio(data_format='channels_last', n_ch=1)
# test STFT save/load
save_load_compare(
STFT(input_shape=input_shape, pad_begin=True),
... | test saving/loading of models that has stft, melspectorgrma, and log frequency. | test_save_load | python | keunwoochoi/kapre | tests/test_time_frequency.py | https://github.com/keunwoochoi/kapre/blob/master/tests/test_time_frequency.py | MIT |
def save_load_compare(
layer, input_batch, allclose_func, save_format, layer_class=None, training=None, atol=1e-4
):
"""test a model with `layer` with the given `input_batch`.
The model prediction result is compared using `allclose_func` which may depend on the
data type of the model output (e.g., float... | test a model with `layer` with the given `input_batch`.
The model prediction result is compared using `allclose_func` which may depend on the
data type of the model output (e.g., float or complex).
| save_load_compare | python | keunwoochoi/kapre | tests/utils.py | https://github.com/keunwoochoi/kapre/blob/master/tests/utils.py | MIT |
def predict_using_tflite(model, batch_src):
"""Convert a keras model to tflite and infer on batch_src
Attempts to convert a keras model to a tflite model, load the tflite model,
then infer on the data in batch_src
Args:
model (keras model)
batch_src (numpy array) - audio to test model
... | Convert a keras model to tflite and infer on batch_src
Attempts to convert a keras model to a tflite model, load the tflite model,
then infer on the data in batch_src
Args:
model (keras model)
batch_src (numpy array) - audio to test model
Returns:
pred_tflite (numpy array) - arr... | predict_using_tflite | python | keunwoochoi/kapre | tests/utils.py | https://github.com/keunwoochoi/kapre/blob/master/tests/utils.py | MIT |
def add(ctx, task, priority, tags, extra, category, labels):
"""Add a new task to the to-do list.
Note:
Control the output of this using the verbosity option.
"""
if ctx.obj["verbose"] >= 2:
click.echo(f"Adding task: {task}")
click.echo(f"Priority: {priority}")
click.echo(f'T... | Add a new task to the to-do list.
Note:
Control the output of this using the verbosity option.
| add | python | Textualize/trogon | examples/demo.py | https://github.com/Textualize/trogon/blob/master/examples/demo.py | MIT |
def remove(ctx, task_id):
"""Remove a task from the to-do list by its ID."""
if ctx.obj["verbose"] >= 1:
click.echo(f"Removing task with ID: {task_id}")
# Implement the task removal functionality here | Remove a task from the to-do list by its ID. | remove | python | Textualize/trogon | examples/demo.py | https://github.com/Textualize/trogon/blob/master/examples/demo.py | MIT |
def list_tasks(ctx, all, completed):
"""List tasks from the to-do list."""
if ctx.obj["verbose"] >= 1:
click.echo(f"Listing tasks:")
# Implement the task listing functionality here | List tasks from the to-do list. | list_tasks | python | Textualize/trogon | examples/demo.py | https://github.com/Textualize/trogon/blob/master/examples/demo.py | MIT |
def add(verbose, task, priority, tags, extra, category, labels):
"""Add a new task to the to-do list."""
if verbose >= 2:
click.echo(f"Adding task: {task}")
click.echo(f"Priority: {priority}")
click.echo(f'Tags: {", ".join(tags)}')
click.echo(f"Extra data: {extra}")
click... | Add a new task to the to-do list. | add | python | Textualize/trogon | examples/nogroup_demo.py | https://github.com/Textualize/trogon/blob/master/examples/nogroup_demo.py | MIT |
def detect_run_string(_main: ModuleType = sys.modules["__main__"]) -> str:
"""This is a slightly modified version of a function from Click."""
path = sys.argv[0]
# The value of __package__ indicates how Python was called. It may
# not exist if a setuptools script is installed as an egg. It may be
#... | This is a slightly modified version of a function from Click. | detect_run_string | python | Textualize/trogon | trogon/detect_run_string.py | https://github.com/Textualize/trogon/blob/master/trogon/detect_run_string.py | MIT |
def introspect_click_app(app: BaseCommand) -> dict[CommandName, CommandSchema]:
"""
Introspect a Click application and build a data structure containing
information about all commands, options, arguments, and subcommands,
including the docstrings and command function references.
This function recur... |
Introspect a Click application and build a data structure containing
information about all commands, options, arguments, and subcommands,
including the docstrings and command function references.
This function recursively processes each command and its subcommands
(if any), creating a nested dicti... | introspect_click_app | python | Textualize/trogon | trogon/introspect.py | https://github.com/Textualize/trogon/blob/master/trogon/introspect.py | MIT |
def to_cli_args(self, include_root_command: bool = False) -> list[str]:
"""
Generates a list of strings representing the CLI invocation based on the user input data.
Returns:
A list of strings that can be passed to subprocess.run to execute the command.
"""
cli_args ... |
Generates a list of strings representing the CLI invocation based on the user input data.
Returns:
A list of strings that can be passed to subprocess.run to execute the command.
| to_cli_args | python | Textualize/trogon | trogon/run_command.py | https://github.com/Textualize/trogon/blob/master/trogon/run_command.py | MIT |
def to_cli_string(self, include_root_command: bool = False) -> Text:
"""
Generates a string representing the CLI invocation as if typed directly into the
command line.
Returns:
A string representing the command invocation.
"""
args = self.to_cli_args(include_... |
Generates a string representing the CLI invocation as if typed directly into the
command line.
Returns:
A string representing the command invocation.
| to_cli_string | python | Textualize/trogon | trogon/run_command.py | https://github.com/Textualize/trogon/blob/master/trogon/run_command.py | MIT |
async def selected_command_changed(
self, event: Tree.NodeHighlighted[CommandSchema]
) -> None:
"""When we highlight a node in the CommandTree, the main body of the home page updates
to display a form specific to the highlighted command."""
await self._refresh_command_form(event.node... | When we highlight a node in the CommandTree, the main body of the home page updates
to display a form specific to the highlighted command. | selected_command_changed | python | Textualize/trogon | trogon/trogon.py | https://github.com/Textualize/trogon/blob/master/trogon/trogon.py | MIT |
def _update_command_description(self, command: CommandSchema) -> None:
"""Update the description of the command at the bottom of the sidebar
based on the currently selected node in the command tree."""
description_box = self.query_one("#home-command-description", Static)
description_text... | Update the description of the command at the bottom of the sidebar
based on the currently selected node in the command tree. | _update_command_description | python | Textualize/trogon | trogon/trogon.py | https://github.com/Textualize/trogon/blob/master/trogon/trogon.py | MIT |
def _update_execution_string_preview(self) -> None:
"""Update the preview box showing the command string to be executed"""
command_name_syntax_style = self.get_component_rich_style("command-name-syntax")
prefix = Text(f"{self.click_app_name} ", command_name_syntax_style)
new_value = self... | Update the preview box showing the command string to be executed | _update_execution_string_preview | python | Textualize/trogon | trogon/trogon.py | https://github.com/Textualize/trogon/blob/master/trogon/trogon.py | MIT |
def __init__(self, title: TextType, message: TextType) -> None:
"""Initialise the dialog.
Args:
title: The title for the dialog.
message: The message to show.
"""
super().__init__()
self._title = title
self._message = message | Initialise the dialog.
Args:
title: The title for the dialog.
message: The message to show.
| __init__ | python | Textualize/trogon | trogon/widgets/about.py | https://github.com/Textualize/trogon/blob/master/trogon/widgets/about.py | MIT |
def compose(self) -> ComposeResult:
"""Compose the content of the modal dialog."""
with Vertical():
with Center():
yield Static(self._title, classes="spaced")
yield Static(self._message, id="message", classes="spaced")
with Center(classes="spaced"):
... | Compose the content of the modal dialog. | compose | python | Textualize/trogon | trogon/widgets/about.py | https://github.com/Textualize/trogon/blob/master/trogon/widgets/about.py | MIT |
def _form_changed(self) -> None:
"""Take the current state of the form and build a UserCommandData from it,
then post a FormChanged message"""
command_schema = self.command_schema
path_from_root = command_schema.path_from_root
# Sentinel root value to make constructing the tree... | Take the current state of the form and build a UserCommandData from it,
then post a FormChanged message | _form_changed | python | Textualize/trogon | trogon/widgets/form.py | https://github.com/Textualize/trogon/blob/master/trogon/widgets/form.py | MIT |
def apply_filter(self, filter_query: str) -> bool:
"""Show or hide this ParameterControls depending on whether it matches the filter query or not.
Args:
filter_query: The string to filter on.
Returns:
True if the filter matched (and the widget is visible).
"""
... | Show or hide this ParameterControls depending on whether it matches the filter query or not.
Args:
filter_query: The string to filter on.
Returns:
True if the filter matched (and the widget is visible).
| apply_filter | python | Textualize/trogon | trogon/widgets/parameter_controls.py | https://github.com/Textualize/trogon/blob/master/trogon/widgets/parameter_controls.py | MIT |
def compose(self) -> ComposeResult:
"""Takes the schemas for each parameter of the current command, and converts it into a
form consisting of Textual widgets."""
schema = self.schema
name = schema.name
argument_type = schema.type
default = schema.default
help_text... | Takes the schemas for each parameter of the current command, and converts it into a
form consisting of Textual widgets. | compose | python | Textualize/trogon | trogon/widgets/parameter_controls.py | https://github.com/Textualize/trogon/blob/master/trogon/widgets/parameter_controls.py | MIT |
def make_widget_group(self) -> Iterable[ControlWidgetType]:
"""For this option, yield a single set of widgets required to receive user input for it."""
schema = self.schema
default = schema.default
parameter_type = schema.type
name = schema.name
multiple = schema.multiple... | For this option, yield a single set of widgets required to receive user input for it. | make_widget_group | python | Textualize/trogon | trogon/widgets/parameter_controls.py | https://github.com/Textualize/trogon/blob/master/trogon/widgets/parameter_controls.py | MIT |
def _apply_default_value(
control_widget: ControlWidgetType, default_value: Any
) -> None:
"""Set the default value of a parameter-handling widget."""
if isinstance(control_widget, Input):
control_widget.value = str(default_value)
control_widget.placeholder = f"{defau... | Set the default value of a parameter-handling widget. | _apply_default_value | python | Textualize/trogon | trogon/widgets/parameter_controls.py | https://github.com/Textualize/trogon/blob/master/trogon/widgets/parameter_controls.py | MIT |
def actions(self, state):
'actions are index where we can make a move'
actions = []
for index, char in enumerate(state):
if char == '_':
actions.append(index)
return actions | actions are index where we can make a move | actions | python | simpleai-team/simpleai | samples/machine_learning/tic_tac_toe.py | https://github.com/simpleai-team/simpleai/blob/master/samples/machine_learning/tic_tac_toe.py | MIT |
def find_location(rows, element_to_find):
'''Find the location of a piece in the puzzle.
Returns a tuple: row, column'''
for ir, row in enumerate(rows):
for ic, element in enumerate(row):
if element == element_to_find:
return ir, ic | Find the location of a piece in the puzzle.
Returns a tuple: row, column | find_location | python | simpleai-team/simpleai | samples/search/eight_puzzle.py | https://github.com/simpleai-team/simpleai/blob/master/samples/search/eight_puzzle.py | MIT |
def actions(self, state):
'''Returns a list of the pieces we can move to the empty space.'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
actions = []
if row_e > 0:
actions.append(rows[row_e - 1][col_e])
if row_e < 2:
actio... | Returns a list of the pieces we can move to the empty space. | actions | python | simpleai-team/simpleai | samples/search/eight_puzzle.py | https://github.com/simpleai-team/simpleai/blob/master/samples/search/eight_puzzle.py | MIT |
def result(self, state, action):
'''Return the resulting state after moving a piece to the empty space.
(the "action" parameter contains the piece to move)
'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
row_n, col_n = find_location(rows, actio... | Return the resulting state after moving a piece to the empty space.
(the "action" parameter contains the piece to move)
| result | python | simpleai-team/simpleai | samples/search/eight_puzzle.py | https://github.com/simpleai-team/simpleai/blob/master/samples/search/eight_puzzle.py | MIT |
def heuristic(self, state):
'''Returns an *estimation* of the distance from a state to the goal.
We are using the manhattan distance.
'''
rows = string_to_list(state)
distance = 0
for number in '12345678e':
row_n, col_n = find_location(rows, number)
... | Returns an *estimation* of the distance from a state to the goal.
We are using the manhattan distance.
| heuristic | python | simpleai-team/simpleai | samples/search/eight_puzzle.py | https://github.com/simpleai-team/simpleai/blob/master/samples/search/eight_puzzle.py | MIT |
def result(self, s, a):
'''Result of applying an action to a state.'''
# result: boat on opposite side, and numbers of missioners and
# cannibals updated according to the move
if s[2] == 0:
return (s[0] - a[1][0], s[1] - a[1][1], 1)
else:
return (s[0] + a[... | Result of applying an action to a state. | result | python | simpleai-team/simpleai | samples/search/missioners.py | https://github.com/simpleai-team/simpleai/blob/master/samples/search/missioners.py | MIT |
def mkconstraints():
"""
Make constraint list for binary constraint problem.
"""
constraints = []
for j in range(1, 10):
vars = ["%s%d" % (i, j) for i in uppercase[:9]]
constraints.extend((c, const_different) for c in combinations(vars, 2))
for i in uppercase[:9]:
vars ... |
Make constraint list for binary constraint problem.
| mkconstraints | python | simpleai-team/simpleai | samples/search/sudoku.py | https://github.com/simpleai-team/simpleai/blob/master/samples/search/sudoku.py | MIT |
def step(self, viewer=None):
"This method evolves one step in time"
if not self.is_completed(self.state):
for agent in self.agents:
action = agent.program(self.percept(agent, self.state))
next_state = self.do_action(self.state, action, agent)
i... | This method evolves one step in time | step | python | simpleai-team/simpleai | simpleai/environments.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/environments.py | MIT |
def learn(self, examples, attributes, parent_examples):
"""
A decision tree learner that *strictly* follows the pseudocode given in
AIMA. In 3rd edition, see Figure 18.5, page 702.
"""
if not examples:
return self.plurality_value(parent_examples)
elif len(set(... |
A decision tree learner that *strictly* follows the pseudocode given in
AIMA. In 3rd edition, see Figure 18.5, page 702.
| learn | python | simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py | MIT |
def importance(self, attribute, examples):
"""
AIMA implies that importance should be information gain.
Since AIMA only defines it for binary features this implementation
was based on the wikipedia article:
http://en.wikipedia.org/wiki/Information_gain_in_decision_trees
"... |
AIMA implies that importance should be information gain.
Since AIMA only defines it for binary features this implementation
was based on the wikipedia article:
http://en.wikipedia.org/wiki/Information_gain_in_decision_trees
| importance | python | simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py | MIT |
def save(self, filepath):
"""
Saves the classifier to `filepath`.
Because this classifier needs to save the dataset, it must
be something that can be pickled and not something like an
iterator.
"""
if not filepath or not isinstance(filepath, str):
rai... |
Saves the classifier to `filepath`.
Because this classifier needs to save the dataset, it must
be something that can be pickled and not something like an
iterator.
| save | python | simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py | MIT |
def tree_to_str(root):
"""
Returns a string representation of a decision tree with
root node `root`.
"""
xs = []
for value, node, depth in iter_tree(root):
template = "{indent}"
if node is not root:
template += "case={value}\t"
if node.attribute is None:
... |
Returns a string representation of a decision tree with
root node `root`.
| tree_to_str | python | simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py | MIT |
def take_branch(self, example):
"""
Returns a `DecisionTreeNode` instance that can better classify
`example` based on the selectors value.
If there are no more branches (ie, this node is a leaf) or the
attribute gives a value for an unexistent branch then this method
retu... |
Returns a `DecisionTreeNode` instance that can better classify
`example` based on the selectors value.
If there are no more branches (ie, this node is a leaf) or the
attribute gives a value for an unexistent branch then this method
returns None.
| take_branch | python | simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py | MIT |
def _max_gain_split(self, examples):
"""
Returns an OnlineInformationGain of the attribute with
max gain based on `examples`.
"""
gains = self._new_set_of_gain_counters()
for example in examples:
for gain in gains:
gain.add(example)
win... |
Returns an OnlineInformationGain of the attribute with
max gain based on `examples`.
| _max_gain_split | python | simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py | MIT |
def _new_set_of_gain_counters(self):
"""
Creates a new set of OnlineInformationGain objects
for each attribute.
"""
return [OnlineInformationGain(attribute, self.target)
for attribute in self.attributes] |
Creates a new set of OnlineInformationGain objects
for each attribute.
| _new_set_of_gain_counters | python | simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/classifiers.py | MIT |
def precision(classifier, testset):
"""
Runs the classifier for each example in `testset`
and verifies that the classification is correct
using the `target`.
Returns a number between 0.0 and 1.0 with the
precision of classification for this test set.
"""
hit = 0
total = 0
for e... |
Runs the classifier for each example in `testset`
and verifies that the classification is correct
using the `target`.
Returns a number between 0.0 and 1.0 with the
precision of classification for this test set.
| precision | python | simpleai-team/simpleai | simpleai/machine_learning/evaluation.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/evaluation.py | MIT |
def kfold(dataset, problem, method, k=10):
"""
Does a k-fold on `dataset` with `method`.
This is, it randomly creates k-partitions of the dataset, and k-times
trains the method with k-1 parts and runs it with the partition left.
After all this, returns the overall success ratio.
"""
if k <=... |
Does a k-fold on `dataset` with `method`.
This is, it randomly creates k-partitions of the dataset, and k-times
trains the method with k-1 parts and runs it with the partition left.
After all this, returns the overall success ratio.
| kfold | python | simpleai-team/simpleai | simpleai/machine_learning/evaluation.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/evaluation.py | MIT |
def save(self, filepath):
"""
Pickles the tree and saves it into `filepath`
"""
if not filepath or not isinstance(filepath, str):
raise ValueError("Invalid filepath")
# Removes dataset so is not saved in the pickle
self.dataset = None
with open(filep... |
Pickles the tree and saves it into `filepath`
| save | python | simpleai-team/simpleai | simpleai/machine_learning/models.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/models.py | MIT |
def load(cls, filepath):
"""
Loads a pickled version of the classifier saved in `filepath`
"""
with open(filepath, "rb") as filehandler:
classifier = pickle.load(filehandler)
if not isinstance(classifier, Classifier):
raise ValueError("Pickled object is n... |
Loads a pickled version of the classifier saved in `filepath`
| load | python | simpleai-team/simpleai | simpleai/machine_learning/models.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/models.py | MIT |
def __init__(self, dataset, target_index):
"""
`dataset` should be an iterable, *not* an iterator.
`target_index` is the index in the vector where the classification
of an example is defined.
"""
super(VectorDataClassificationProblem, self).__init__()
try:
... |
`dataset` should be an iterable, *not* an iterator.
`target_index` is the index in the vector where the classification
of an example is defined.
| __init__ | python | simpleai-team/simpleai | simpleai/machine_learning/models.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/models.py | MIT |
def __init__(self, function=None, name=None, description=None):
"""
Creates an attribute with `function`.
Adds a name and a description if it's specified.
"""
self.name = name
self.function = function
self.description = description |
Creates an attribute with `function`.
Adds a name and a description if it's specified.
| __init__ | python | simpleai-team/simpleai | simpleai/machine_learning/models.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/models.py | MIT |
def is_attribute(method, name=None):
"""
Decorator for methods that are attributes.
"""
if name is None:
name = method.__name__
method.is_attribute = True
method.name = name
return method |
Decorator for methods that are attributes.
| is_attribute | python | simpleai-team/simpleai | simpleai/machine_learning/models.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/models.py | MIT |
def boltzmann_exploration(actions, utilities, temperature, action_counter):
'''returns an action with a probability depending on utilities and temperature'''
utilities = [utilities[x] for x in actions]
temperature = max(temperature, 0.01)
_max = max(utilities)
_min = min(utilities)
if _max == _m... | returns an action with a probability depending on utilities and temperature | boltzmann_exploration | python | simpleai-team/simpleai | simpleai/machine_learning/reinforcement_learning.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/reinforcement_learning.py | MIT |
def make_exponential_temperature(initial_temperature, alpha):
'''returns a function like initial / exp(n * alpha)'''
def _function(n):
try:
return initial_temperature / math.exp(n * alpha)
except OverflowError:
return 0.01
return _function | returns a function like initial / exp(n * alpha) | make_exponential_temperature | python | simpleai-team/simpleai | simpleai/machine_learning/reinforcement_learning.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/reinforcement_learning.py | MIT |
def revise(domains, arc, constraints):
"""
Given the arc X, Y (variables), removes the values from X's domain that
do not meet the constraint between X and Y.
That is, given x1 in X's domain, x1 will be removed from the domain, if
there is no value y in Y's domain that makes constraint(X,Y) True, f... |
Given the arc X, Y (variables), removes the values from X's domain that
do not meet the constraint between X and Y.
That is, given x1 in X's domain, x1 will be removed from the domain, if
there is no value y in Y's domain that makes constraint(X,Y) True, for
those constraints affecting X and Y.
... | revise | python | simpleai-team/simpleai | simpleai/search/arc.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/arc.py | MIT |
def all_arcs(constraints):
"""
For each constraint ((X, Y), const) adds:
((X, Y), const)
((Y, X), const)
"""
arcs = set()
for neighbors, constraint in constraints:
if len(neighbors) == 2:
x, y = neighbors
list(map(arcs.add, ((x, y), (y, x))))
ret... |
For each constraint ((X, Y), const) adds:
((X, Y), const)
((Y, X), const)
| all_arcs | python | simpleai-team/simpleai | simpleai/search/arc.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/arc.py | MIT |
def arc_consistency_3(domains, constraints):
"""
Makes a CSP problem arc consistent.
Ignores any constraint that is not binary.
"""
arcs = list(all_arcs(constraints))
pending_arcs = set(arcs)
while pending_arcs:
x, y = pending_arcs.pop()
if revise(domains, (x, y), constrain... |
Makes a CSP problem arc consistent.
Ignores any constraint that is not binary.
| arc_consistency_3 | python | simpleai-team/simpleai | simpleai/search/arc.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/arc.py | MIT |
def backtrack(problem, variable_heuristic='', value_heuristic='', inference=True):
'''
Backtracking search.
variable_heuristic is the heuristic for variable choosing, can be
MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE, or blank for simple
ordered choosing.
value_heuristic is the heuristi... |
Backtracking search.
variable_heuristic is the heuristic for variable choosing, can be
MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE, or blank for simple
ordered choosing.
value_heuristic is the heuristic for value choosing, can be
LEAST_CONSTRAINING_VALUE or blank for simple ordered choo... | backtrack | python | simpleai-team/simpleai | simpleai/search/csp.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/csp.py | MIT |
def _most_constrained_variable_chooser(problem, variables, domains):
'''
Choose the variable that has less available values.
'''
# the variable with fewer values available
return sorted(variables, key=lambda v: len(domains[v]))[0] |
Choose the variable that has less available values.
| _most_constrained_variable_chooser | python | simpleai-team/simpleai | simpleai/search/csp.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/csp.py | MIT |
def _highest_degree_variable_chooser(problem, variables, domains):
'''
Choose the variable that is involved on more constraints.
'''
# the variable involved in more constraints
return sorted(variables, key=lambda v: problem.var_degrees[v], reverse=True)[0] |
Choose the variable that is involved on more constraints.
| _highest_degree_variable_chooser | python | simpleai-team/simpleai | simpleai/search/csp.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/csp.py | MIT |
def _find_conflicts(problem, assignment, variable=None, value=None):
'''
Find violated constraints on a given assignment, with the possibility
of specifying a new variable and value to add to the assignment before
checking.
'''
if variable is not None and value is not None:
assignment = ... |
Find violated constraints on a given assignment, with the possibility
of specifying a new variable and value to add to the assignment before
checking.
| _find_conflicts | python | simpleai-team/simpleai | simpleai/search/csp.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/csp.py | MIT |
def _least_constraining_values_sorter(problem, assignment, variable, domains):
'''
Sort values based on how many conflicts they generate if assigned.
'''
# the value that generates less conflicts
def update_assignment(value):
new_assignment = deepcopy(assignment)
new_assignment[varia... |
Sort values based on how many conflicts they generate if assigned.
| _least_constraining_values_sorter | python | simpleai-team/simpleai | simpleai/search/csp.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/csp.py | MIT |
def convert_to_binary(variables, domains, constraints):
"""
Returns new constraint list, all binary, using hidden variables.
You can use it as previous step when creating a problem.
"""
def wdiff(vars_):
def diff(variables, values):
hidden, other = variables
if hidd... |
Returns new constraint list, all binary, using hidden variables.
You can use it as previous step when creating a problem.
| convert_to_binary | python | simpleai-team/simpleai | simpleai/search/csp.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/csp.py | MIT |
def _all_expander(fringe, iteration, viewer):
'''
Expander that expands all nodes on the fringe.
'''
expanded_neighbors = [node.expand(local_search=True)
for node in fringe]
if viewer:
viewer.event('expanded', list(fringe), expanded_neighbors)
list(map(fringe.... |
Expander that expands all nodes on the fringe.
| _all_expander | python | simpleai-team/simpleai | simpleai/search/local.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/local.py | MIT |
def _first_expander(fringe, iteration, viewer):
'''
Expander that expands only the first node on the fringe.
'''
current = fringe[0]
neighbors = current.expand(local_search=True)
if viewer:
viewer.event('expanded', [current], [neighbors])
fringe.extend(neighbors) |
Expander that expands only the first node on the fringe.
| _first_expander | python | simpleai-team/simpleai | simpleai/search/local.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/local.py | MIT |
def _random_best_expander(fringe, iteration, viewer):
'''
Expander that expands one randomly chosen nodes on the fringe that
is better than the current (first) node.
'''
current = fringe[0]
neighbors = current.expand(local_search=True)
if viewer:
viewer.event('expanded', [current], [... |
Expander that expands one randomly chosen nodes on the fringe that
is better than the current (first) node.
| _random_best_expander | python | simpleai-team/simpleai | simpleai/search/local.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/local.py | MIT |
def _create_simulated_annealing_expander(schedule):
'''
Creates an expander that has a random chance to choose a node that is worse
than the current (first) node, but that chance decreases with time.
'''
def _expander(fringe, iteration, viewer):
T = schedule(iteration)
current = frin... |
Creates an expander that has a random chance to choose a node that is worse
than the current (first) node, but that chance decreases with time.
| _create_simulated_annealing_expander | python | simpleai-team/simpleai | simpleai/search/local.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/local.py | MIT |
def _create_genetic_expander(problem, mutation_chance):
'''
Creates an expander that expands the bests nodes of the population,
crossing over them.
'''
def _expander(fringe, iteration, viewer):
fitness = [x.value for x in fringe]
sampler = InverseTransformSampler(fitness, fringe)
... |
Creates an expander that expands the bests nodes of the population,
crossing over them.
| _create_genetic_expander | python | simpleai-team/simpleai | simpleai/search/local.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/local.py | MIT |
def _local_search(problem, fringe_expander, iterations_limit=0, fringe_size=1,
random_initial_states=False, stop_when_no_better=True,
viewer=None):
'''
Basic algorithm for all local search algorithms.
'''
if viewer:
viewer.event('started')
fringe = Bounde... |
Basic algorithm for all local search algorithms.
| _local_search | python | simpleai-team/simpleai | simpleai/search/local.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/local.py | MIT |
def path(self):
'''Path (list of nodes and actions) from root to this node.'''
node = self
path = []
while node:
path.append((node.action, node.state))
node = node.parent
return list(reversed(path)) | Path (list of nodes and actions) from root to this node. | path | python | simpleai-team/simpleai | simpleai/search/models.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/models.py | MIT |
def breadth_first(problem, graph_search=False, viewer=None):
'''
Breadth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
return _search(problem,
FifoList(),
... |
Breadth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
| breadth_first | python | simpleai-team/simpleai | simpleai/search/traditional.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/traditional.py | MIT |
def depth_first(problem, graph_search=False, viewer=None):
'''
Depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
return _search(problem,
LifoList(),
... |
Depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
| depth_first | python | simpleai-team/simpleai | simpleai/search/traditional.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/traditional.py | MIT |
def uniform_cost(problem, graph_search=False, viewer=None):
'''
Uniform cost search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, and SearchProblem.cost.
'''
return _search(problem,
... |
Uniform cost search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, and SearchProblem.cost.
| uniform_cost | python | simpleai-team/simpleai | simpleai/search/traditional.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/traditional.py | MIT |
def greedy(problem, graph_search=False, viewer=None):
'''
Greedy search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
'''
return _search(problem,
... |
Greedy search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
| greedy | python | simpleai-team/simpleai | simpleai/search/traditional.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/traditional.py | MIT |
def astar(problem, graph_search=False, viewer=None):
'''
A* search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
'''
return _search(problem,
... |
A* search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
| astar | python | simpleai-team/simpleai | simpleai/search/traditional.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/traditional.py | MIT |
def _search(problem, fringe, graph_search=False, depth_limit=None,
node_factory=SearchNode, graph_replace_when_better=False,
viewer=None):
'''
Basic search algorithm, base of all the other search algorithms.
'''
if viewer:
viewer.event('started')
memory = set()
i... |
Basic search algorithm, base of all the other search algorithms.
| _search | python | simpleai-team/simpleai | simpleai/search/traditional.py | https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/traditional.py | MIT |
def test_target_in_attributes(self):
"""
If target in attributes precision is 1.0.
"""
self.problem.attributes = [self.target]
self.this = self.classifier(self.corpus, self.problem)
prec = evaluation.precision(self.this, self.test_set)
self.assertEqual(prec, 1.0) |
If target in attributes precision is 1.0.
| test_target_in_attributes | python | simpleai-team/simpleai | tests/machine_learning/test_classifiers.py | https://github.com/simpleai-team/simpleai/blob/master/tests/machine_learning/test_classifiers.py | MIT |
def test_equal_classification(self):
"""
This checks that the three tree learning methods are equal.
"""
pseudo = DecisionTreeLearner(self.corpus, self.problem)
for test in self.test_set:
self.assertEqual(pseudo.classify(test), self.this.classify(test)) |
This checks that the three tree learning methods are equal.
| test_equal_classification | python | simpleai-team/simpleai | tests/machine_learning/test_classifiers.py | https://github.com/simpleai-team/simpleai/blob/master/tests/machine_learning/test_classifiers.py | MIT |
def setup_dataset(self):
"""
Creates a corpus with the iris dataset. Returns the dataset,
the attributes getter and the target getter.
"""
dataset = []
with open(self.IRIS_PATH) as filehandler:
file_data = filehandler.read()
for line in file_data.spl... |
Creates a corpus with the iris dataset. Returns the dataset,
the attributes getter and the target getter.
| setup_dataset | python | simpleai-team/simpleai | tests/machine_learning/test_classifiers.py | https://github.com/simpleai-team/simpleai/blob/master/tests/machine_learning/test_classifiers.py | MIT |
def setup_dataset(self):
"""
Creates a corpus with n k-bit examples of the parity problem:
k random bits followed by a 1 if an odd number of bits are 1, else 0
"""
k = 2
n = 100
dataset = []
for i in range(n):
# Pseudo random generation of bi... |
Creates a corpus with n k-bit examples of the parity problem:
k random bits followed by a 1 if an odd number of bits are 1, else 0
| setup_dataset | python | simpleai-team/simpleai | tests/machine_learning/test_classifiers.py | https://github.com/simpleai-team/simpleai/blob/master/tests/machine_learning/test_classifiers.py | MIT |
def setup_dataset(self):
"""
Creates a corpus of primes. Returns the dataset,
the attributes getter and the target getter.
"""
size = 105 # Magic number, chosen to avoid an "error" that cannot be
# patched in Dtree Pseudo (with modifing the pseudocode).
... |
Creates a corpus of primes. Returns the dataset,
the attributes getter and the target getter.
| setup_dataset | python | simpleai-team/simpleai | tests/machine_learning/test_classifiers.py | https://github.com/simpleai-team/simpleai/blob/master/tests/machine_learning/test_classifiers.py | MIT |
def isprime(self, number):
"""
Returns if a number is prime testing if
is divisible by any number from 0 to sqrt(number)
"""
if number < 2:
return False
if number == 2:
return True
if not number & 1:
return False
for i... |
Returns if a number is prime testing if
is divisible by any number from 0 to sqrt(number)
| isprime | python | simpleai-team/simpleai | tests/machine_learning/test_classifiers.py | https://github.com/simpleai-team/simpleai/blob/master/tests/machine_learning/test_classifiers.py | MIT |
def get_ray_directions(
H: int,
W: int,
focal: Union[float, Tuple[float, float]],
principal: Optional[Tuple[float, float]] = None,
use_pixel_centers: bool = True,
normalize: bool = True,
) -> torch.FloatTensor:
"""
Get ray directions for all pixels in camera coordinate.
Reference: ht... |
Get ray directions for all pixels in camera coordinate.
Reference: https://www.scratchapixel.com/lessons/3d-basic-rendering/
ray-tracing-generating-camera-rays/standard-coordinate-systems
Inputs:
H, W, focal, principal, use_pixel_centers: image height, width, focal length, principal... | get_ray_directions | python | VAST-AI-Research/TripoSR | tsr/utils.py | https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/utils.py | MIT |
def forward(
self,
hidden_states: torch.FloatTensor,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
**cross_attention_kwargs,
) -> torch.Tensor:
r"""
The forward method of the `Attention` class.
... |
The forward method of the `Attention` class.
Args:
hidden_states (`torch.Tensor`):
The hidden states of the query.
encoder_hidden_states (`torch.Tensor`, *optional*):
The hidden states of the encoder.
attention_mask (`torch.Tensor`, *... | forward | python | VAST-AI-Research/TripoSR | tsr/models/transformer/attention.py | https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/attention.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.