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
async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode of the fan.""" _LOGGER.debug("Setting the preset mode to: %s", preset_mode) await self._try_command( "Setting preset mode of the miio device failed.", self._device.set_mode, ...
Set the preset mode of the fan.
async_set_preset_mode
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode of the fan.""" _LOGGER.debug("Setting the preset mode to: %s", preset_mode) await self._try_command( "Setting preset mode of the miio device failed.", self._device.set_mode, ...
Set the preset mode of the fan.
async_set_preset_mode
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode of the fan.""" _LOGGER.debug("Setting the preset mode to: %s", preset_mode) await self._try_command( "Setting preset mode of the miio device failed.", self._device.set_mode, ...
Set the preset mode of the fan.
async_set_preset_mode
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode of the fan.""" _LOGGER.debug("Setting the preset mode to: %s", preset_mode) await self._try_command( "Setting preset mode of the miio device failed.", self._device.set_mode, ...
Set the preset mode of the fan.
async_set_preset_mode
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_reset_filter(self): """Reset the filter lifetime and usage.""" if self._device_features & FEATURE_RESET_FILTER == 0: return await self._try_command( "Resetting the filter lifetime of the miio device failed.", self._device.reset_filter, ...
Reset the filter lifetime and usage.
async_reset_filter
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode of the fan.""" _LOGGER.debug("Setting the preset mode to: %s", preset_mode) await self._try_command( "Setting preset mode of the miio device failed.", self._device.set_mode, ...
Set the preset mode of the fan.
async_set_preset_mode
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_reset_filter(self): """Reset the filter lifetime and usage.""" if self._device_features & FEATURE_RESET_FILTER == 0: return await self._try_command( "Resetting the upper filter lifetime of the miio device failed.", self._device.reset_upper_fil...
Reset the filter lifetime and usage.
async_reset_filter
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_reset_filter(self): """Reset the filter lifetime and usage.""" if self._device_features & FEATURE_RESET_FILTER == 0: return await self._try_command( "Resetting filter lifetime of the miio device failed.", self._device.reset_filter, )
Reset the filter lifetime and usage.
async_reset_filter
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode of the fan.""" _LOGGER.debug("Setting the preset mode to: %s", preset_mode) if preset_mode == SPEED_OFF: await self.async_turn_off() return if self._natural_mode: ...
Set the preset mode of the fan.
async_set_preset_mode
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_percentage(self, percentage: int) -> None: """Set the speed percentage of the fan.""" _LOGGER.debug("Setting the fan speed percentage to: %s", percentage) if percentage == 0: await self.async_turn_off() return if self._natural_mode: ...
Set the speed percentage of the fan.
async_set_percentage
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_direction(self, direction: str) -> None: """Set the direction of the fan.""" if direction == "forward": direction = "right" if direction == "reverse": direction = "left" if self._oscillate: await self._try_command( ...
Set the direction of the fan.
async_set_direction
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_delay_off(self, delay_off_countdown: int) -> None: """Set scheduled off timer in minutes.""" await self._try_command( "Setting delay off miio device failed.", self._device.delay_off, delay_off_countdown * 60, )
Set scheduled off timer in minutes.
async_set_delay_off
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode of the fan.""" _LOGGER.debug("Setting the preset mode to: %s", preset_mode) if preset_mode == SPEED_OFF: await self.async_turn_off() return await self._try_command( ...
Set the preset mode of the fan.
async_set_preset_mode
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_percentage(self, percentage: int) -> None: """Set the speed percentage of the fan.""" _LOGGER.debug("Setting the fan speed percentage to: %s", percentage) if percentage == 0: await self.async_turn_off() return await self._try_command( ...
Set the speed percentage of the fan.
async_set_percentage
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_delay_off(self, delay_off_countdown: int) -> None: """Set scheduled off timer in minutes.""" await self._try_command( "Setting delay off miio device failed.", self._device.delay_off, delay_off_countdown, )
Set scheduled off timer in minutes.
async_set_delay_off
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode of the fan.""" _LOGGER.debug("Setting the preset mode to: %s", preset_mode) await self._try_command( "Setting preset mode of the miio device failed.", self._device.set_mode, ...
Set the preset mode of the fan.
async_set_preset_mode
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_percentage(self, percentage: int) -> None: """Set the speed percentage of the fan.""" _LOGGER.debug("Setting the fan speed percentage to: %s", percentage) if percentage == 0: await self.async_turn_off() return await self._try_command( ...
Set the speed percentage of the fan.
async_set_percentage
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_delay_off(self, delay_off_countdown: int) -> None: """Set scheduled off timer in minutes.""" await self._try_command( "Setting delay off miio device failed.", self._device.delay_off, delay_off_countdown, )
Set scheduled off timer in minutes.
async_set_delay_off
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode of the fan.""" _LOGGER.debug("Setting the preset mode to: %s", preset_mode) if not self._state: await self._try_command( "Turning the miio device on failed.", self._device.on ...
Set the preset mode of the fan.
async_set_preset_mode
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_percentage(self, percentage: int) -> None: """Set the speed percentage of the fan.""" _LOGGER.debug("Setting the fan speed percentage to: %s", percentage) if percentage == 0: await self.async_turn_off() return if not self._state: ...
Set the speed percentage of the fan.
async_set_percentage
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_delay_off(self, delay_off_countdown: int) -> None: """Set scheduled off timer in minutes.""" await self._try_command( "Setting delay off miio device failed.", self._device.delay_off, delay_off_countdown, )
Set scheduled off timer in minutes.
async_set_delay_off
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode of the fan.""" _LOGGER.debug("Setting the preset mode to: %s", preset_mode) _LOGGER.debug( "Calling set_mode_and_speed with parameters: %s", self._preset_modes_to_mode_speed[preset_mod...
Set the preset mode of the fan.
async_set_preset_mode
python
syssi/xiaomi_airpurifier
custom_components/xiaomi_miio_airpurifier/fan.py
https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py
Apache-2.0
def get_from_config(): """Get benchmarks configuration from the config.json file""" current_path = Path(__file__).resolve().parent config_path = current_path / "config.json" with open(config_path, "r") as config_file: config_file = "".join(line for line in config_file if line and "//" not in li...
Get benchmarks configuration from the config.json file
get_from_config
python
scikit-learn/scikit-learn
asv_benchmarks/benchmarks/common.py
https://github.com/scikit-learn/scikit-learn/blob/master/asv_benchmarks/benchmarks/common.py
BSD-3-Clause
def get_estimator_path(benchmark, directory, params, save=False): """Get path of pickled fitted estimator""" path = Path(__file__).resolve().parent / "cache" path = (path / "estimators" / directory) if save else (path / "tmp") filename = ( benchmark.__class__.__name__ + "_estimator_" ...
Get path of pickled fitted estimator
get_estimator_path
python
scikit-learn/scikit-learn
asv_benchmarks/benchmarks/common.py
https://github.com/scikit-learn/scikit-learn/blob/master/asv_benchmarks/benchmarks/common.py
BSD-3-Clause
def make_data(self, params): """Return the dataset for a combination of parameters""" # The datasets are cached using joblib.Memory so it's fast and can be # called for each repeat pass
Return the dataset for a combination of parameters
make_data
python
scikit-learn/scikit-learn
asv_benchmarks/benchmarks/common.py
https://github.com/scikit-learn/scikit-learn/blob/master/asv_benchmarks/benchmarks/common.py
BSD-3-Clause
def setup_cache(self): """Pickle a fitted estimator for all combinations of parameters""" # This is run once per benchmark class. clear_tmp() param_grid = list(itertools.product(*self.params)) for params in param_grid: if self.skip(params): continue...
Pickle a fitted estimator for all combinations of parameters
setup_cache
python
scikit-learn/scikit-learn
asv_benchmarks/benchmarks/common.py
https://github.com/scikit-learn/scikit-learn/blob/master/asv_benchmarks/benchmarks/common.py
BSD-3-Clause
def setup(self, *params): """Generate dataset and load the fitted estimator""" # This is run once per combination of parameters and per repeat so we # need to avoid doing expensive operations there. if self.skip(params): raise NotImplementedError self.X, self.X_val,...
Generate dataset and load the fitted estimator
setup
python
scikit-learn/scikit-learn
asv_benchmarks/benchmarks/common.py
https://github.com/scikit-learn/scikit-learn/blob/master/asv_benchmarks/benchmarks/common.py
BSD-3-Clause
def load_data(dtype=np.float32, order="C", random_state=13): """Load the data, then cache and memmap the train/test split""" ###################################################################### # Load dataset print("Loading dataset...") data = fetch_covtype( download_if_missing=True, shuff...
Load the data, then cache and memmap the train/test split
load_data
python
scikit-learn/scikit-learn
benchmarks/bench_covertype.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_covertype.py
BSD-3-Clause
def print_outlier_ratio(y): """ Helper function to show the distinct value count of element in the target. Useful indicator for the datasets used in bench_isolation_forest.py. """ uniq, cnt = np.unique(y, return_counts=True) print("----- Target count values: ") for u, c in zip(uniq, cnt): ...
Helper function to show the distinct value count of element in the target. Useful indicator for the datasets used in bench_isolation_forest.py.
print_outlier_ratio
python
scikit-learn/scikit-learn
benchmarks/bench_isolation_forest.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_isolation_forest.py
BSD-3-Clause
def get_data( n_samples_train, n_samples_test, n_features, contamination=0.1, random_state=0 ): """Function based on code from: https://scikit-learn.org/stable/ auto_examples/ensemble/plot_isolation_forest.html#sphx-glr-auto- examples-ensemble-plot-isolation-forest-py """ rng = np.random.RandomS...
Function based on code from: https://scikit-learn.org/stable/ auto_examples/ensemble/plot_isolation_forest.html#sphx-glr-auto- examples-ensemble-plot-isolation-forest-py
get_data
python
scikit-learn/scikit-learn
benchmarks/bench_isolation_forest_predict.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_isolation_forest_predict.py
BSD-3-Clause
def bench_isotonic_regression(Y): """ Runs a single iteration of isotonic regression on the input data, and reports the total time taken (in seconds). """ gc.collect() tstart = default_timer() isotonic_regression(Y) return default_timer() - tstart
Runs a single iteration of isotonic regression on the input data, and reports the total time taken (in seconds).
bench_isotonic_regression
python
scikit-learn/scikit-learn
benchmarks/bench_isotonic.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_isotonic.py
BSD-3-Clause
def load_data(dtype=np.float32, order="F"): """Load the data, then cache and memmap the train/test split""" ###################################################################### # Load dataset print("Loading dataset...") data = fetch_openml("mnist_784", as_frame=True) X = check_array(data["data...
Load the data, then cache and memmap the train/test split
load_data
python
scikit-learn/scikit-learn
benchmarks/bench_mnist.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_mnist.py
BSD-3-Clause
def benchmark( metrics=tuple(v for k, v in sorted(METRICS.items())), formats=tuple(v for k, v in sorted(FORMATS.items())), samples=1000, classes=4, density=0.2, n_times=5, ): """Times metric calculations for a number of inputs Parameters ---------- metrics : array-like of callab...
Times metric calculations for a number of inputs Parameters ---------- metrics : array-like of callables (1d or 0d) The metric functions to time. formats : array-like of callables (1d or 0d) These may transform a dense indicator matrix into multilabel representation. sampl...
benchmark
python
scikit-learn/scikit-learn
benchmarks/bench_multilabel_metrics.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_multilabel_metrics.py
BSD-3-Clause
def _tabulate(results, metrics, formats): """Prints results by metric and format Uses the last ([-1]) value of other fields """ column_width = max(max(len(k) for k in formats) + 1, 8) first_width = max(len(k) for k in metrics) head_fmt = "{:<{fw}s}" + "{:>{cw}s}" * len(formats) row_fmt = "{...
Prints results by metric and format Uses the last ([-1]) value of other fields
_tabulate
python
scikit-learn/scikit-learn
benchmarks/bench_multilabel_metrics.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_multilabel_metrics.py
BSD-3-Clause
def _plot( results, metrics, formats, title, x_ticks, x_label, format_markers=("x", "|", "o", "+"), metric_colors=("c", "m", "y", "k", "g", "r", "b"), ): """ Plot the results by metric, format and some other variable given by x_label """ fig = plt.figure("scikit-learn...
Plot the results by metric, format and some other variable given by x_label
_plot
python
scikit-learn/scikit-learn
benchmarks/bench_multilabel_metrics.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_multilabel_metrics.py
BSD-3-Clause
def print_outlier_ratio(y): """ Helper function to show the distinct value count of element in the target. Useful indicator for the datasets used in bench_isolation_forest.py. """ uniq, cnt = np.unique(y, return_counts=True) print("----- Target count values: ") for u, c in zip(uniq, cnt): ...
Helper function to show the distinct value count of element in the target. Useful indicator for the datasets used in bench_isolation_forest.py.
print_outlier_ratio
python
scikit-learn/scikit-learn
benchmarks/bench_online_ocsvm.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_online_ocsvm.py
BSD-3-Clause
def autolabel_auc(rects, ax): """Attach a text label above each bar displaying its height.""" for rect in rects: height = rect.get_height() ax.text( rect.get_x() + rect.get_width() / 2.0, 1.05 * height, "%.3f" % height, ha="center", va=...
Attach a text label above each bar displaying its height.
autolabel_auc
python
scikit-learn/scikit-learn
benchmarks/bench_online_ocsvm.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_online_ocsvm.py
BSD-3-Clause
def autolabel_time(rects, ax): """Attach a text label above each bar displaying its height.""" for rect in rects: height = rect.get_height() ax.text( rect.get_x() + rect.get_width() / 2.0, 1.05 * height, "%.1f" % height, ha="center", va...
Attach a text label above each bar displaying its height.
autolabel_time
python
scikit-learn/scikit-learn
benchmarks/bench_online_ocsvm.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_online_ocsvm.py
BSD-3-Clause
def _nls_subproblem( X, W, H, tol, max_iter, alpha=0.0, l1_ratio=0.0, sigma=0.01, beta=0.1 ): """Non-negative least square solver Solves a non-negative least squares subproblem using the projected gradient descent algorithm. Parameters ---------- X : array-like, shape (n_samples, n_features)...
Non-negative least square solver Solves a non-negative least squares subproblem using the projected gradient descent algorithm. Parameters ---------- X : array-like, shape (n_samples, n_features) Constant matrix. W : array-like, shape (n_samples, n_components) Constant matrix. ...
_nls_subproblem
python
scikit-learn/scikit-learn
benchmarks/bench_plot_nmf.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_plot_nmf.py
BSD-3-Clause
def norm_diff(A, norm=2, msg=True, random_state=None): """ Compute the norm diff with the original matrix, when randomized SVD is called with *params. norm: 2 => spectral; 'fro' => Frobenius """ if msg: print("... computing %s norm ..." % norm) if norm == 2: # s = sp.linalg...
Compute the norm diff with the original matrix, when randomized SVD is called with *params. norm: 2 => spectral; 'fro' => Frobenius
norm_diff
python
scikit-learn/scikit-learn
benchmarks/bench_plot_randomized_svd.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_plot_randomized_svd.py
BSD-3-Clause
def bench_scikit_tree_classifier(X, Y): """Benchmark with scikit-learn decision tree classifier""" from sklearn.tree import DecisionTreeClassifier gc.collect() # start time tstart = datetime.now() clf = DecisionTreeClassifier() clf.fit(X, Y).predict(X) delta = datetime.now() - tstart ...
Benchmark with scikit-learn decision tree classifier
bench_scikit_tree_classifier
python
scikit-learn/scikit-learn
benchmarks/bench_tree.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_tree.py
BSD-3-Clause
def bench_scikit_tree_regressor(X, Y): """Benchmark with scikit-learn decision tree regressor""" from sklearn.tree import DecisionTreeRegressor gc.collect() # start time tstart = datetime.now() clf = DecisionTreeRegressor() clf.fit(X, Y).predict(X) delta = datetime.now() - tstart ...
Benchmark with scikit-learn decision tree regressor
bench_scikit_tree_regressor
python
scikit-learn/scikit-learn
benchmarks/bench_tree.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_tree.py
BSD-3-Clause
def load_data(dtype=np.float32, order="C", shuffle=True, seed=0): """Load the data, then cache and memmap the train/test split""" print("Loading dataset...") data = fetch_openml("mnist_784", as_frame=True) X = check_array(data["data"], dtype=dtype, order=order) y = data["target"] if shuffle: ...
Load the data, then cache and memmap the train/test split
load_data
python
scikit-learn/scikit-learn
benchmarks/bench_tsne_mnist.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_tsne_mnist.py
BSD-3-Clause
def nn_accuracy(X, X_embedded, k=1): """Accuracy of the first nearest neighbor""" knn = NearestNeighbors(n_neighbors=1, n_jobs=-1) _, neighbors_X = knn.fit(X).kneighbors() _, neighbors_X_embedded = knn.fit(X_embedded).kneighbors() return np.mean(neighbors_X == neighbors_X_embedded)
Accuracy of the first nearest neighbor
nn_accuracy
python
scikit-learn/scikit-learn
benchmarks/bench_tsne_mnist.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_tsne_mnist.py
BSD-3-Clause
def bhtsne(X): """Wrapper for the reference lvdmaaten/bhtsne implementation.""" # PCA preprocessing is done elsewhere in the benchmark script n_iter = -1 # TODO find a way to report the number of iterations return ( run_bh_tsne( X, ...
Wrapper for the reference lvdmaaten/bhtsne implementation.
bhtsne
python
scikit-learn/scikit-learn
benchmarks/bench_tsne_mnist.py
https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_tsne_mnist.py
BSD-3-Clause
def has_openmp_flags(target): """Return whether target sources use OpenMP flags. Make sure that both compiler and linker source use OpenMP. Look at `get_meson_info` docstring to see what `target` looks like. """ target_sources = target["target_sources"] target_use_openmp_flags = any( h...
Return whether target sources use OpenMP flags. Make sure that both compiler and linker source use OpenMP. Look at `get_meson_info` docstring to see what `target` looks like.
has_openmp_flags
python
scikit-learn/scikit-learn
build_tools/check-meson-openmp-dependencies.py
https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/check-meson-openmp-dependencies.py
BSD-3-Clause
def get_canonical_name_meson(target, build_path): """Return a name based on generated shared library. The goal is to return a name that can be easily matched with the output from `git_grep_info`. Look at `get_meson_info` docstring to see what `target` looks like. """ # Expect a list with one e...
Return a name based on generated shared library. The goal is to return a name that can be easily matched with the output from `git_grep_info`. Look at `get_meson_info` docstring to see what `target` looks like.
get_canonical_name_meson
python
scikit-learn/scikit-learn
build_tools/check-meson-openmp-dependencies.py
https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/check-meson-openmp-dependencies.py
BSD-3-Clause
def get_meson_info(): """Return names of extension that use OpenMP based on meson introspect output. The meson introspect json info is a list of targets where a target is a dict that looks like this (parts not used in this script are not shown for simplicity): { 'name': '_k_means_elkan.cpython-31...
Return names of extension that use OpenMP based on meson introspect output. The meson introspect json info is a list of targets where a target is a dict that looks like this (parts not used in this script are not shown for simplicity): { 'name': '_k_means_elkan.cpython-312-x86_64-linux-gnu', 'f...
get_meson_info
python
scikit-learn/scikit-learn
build_tools/check-meson-openmp-dependencies.py
https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/check-meson-openmp-dependencies.py
BSD-3-Clause
def get_git_grep_info(): """Return names of extensions that use OpenMP based on git grep regex.""" git_grep_filenames = subprocess.check_output( ["git", "grep", "-lP", "cython.*parallel|_openmp_helpers"], text=True ).splitlines() git_grep_filenames = [f for f in git_grep_filenames if ".pyx" in f...
Return names of extensions that use OpenMP based on git grep regex.
get_git_grep_info
python
scikit-learn/scikit-learn
build_tools/check-meson-openmp-dependencies.py
https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/check-meson-openmp-dependencies.py
BSD-3-Clause
def get_contributors(): """Get the list of contributor profiles. Require admin rights.""" # get core devs and contributor experience team core_devs = [] documentation_team = [] contributor_experience_team = [] comm_team = [] core_devs_slug = "core-devs" contributor_experience_team_slug =...
Get the list of contributor profiles. Require admin rights.
get_contributors
python
scikit-learn/scikit-learn
build_tools/generate_authors_table.py
https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/generate_authors_table.py
BSD-3-Clause
def get_profile(login): """Get the GitHub profile from login""" print("get profile for %s" % (login,)) try: profile = get("https://api.github.com/users/%s" % login).json() except requests.exceptions.HTTPError: return dict(name=login, avatar_url=LOGO_URL, html_url="") if profile["nam...
Get the GitHub profile from login
get_profile
python
scikit-learn/scikit-learn
build_tools/generate_authors_table.py
https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/generate_authors_table.py
BSD-3-Clause
def key(profile): """Get a sorting key based on the lower case last name, then firstname""" components = profile["name"].lower().split(" ") return " ".join([components[-1]] + components[:-1])
Get a sorting key based on the lower case last name, then firstname
key
python
scikit-learn/scikit-learn
build_tools/generate_authors_table.py
https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/generate_authors_table.py
BSD-3-Clause
def get_versions(versions_file): """Get the versions of the packages used in the linter job. Parameters ---------- versions_file : str The path to the file that contains the versions of the packages. Returns ------- versions : dict A dictionary with the versions of the pack...
Get the versions of the packages used in the linter job. Parameters ---------- versions_file : str The path to the file that contains the versions of the packages. Returns ------- versions : dict A dictionary with the versions of the packages.
get_versions
python
scikit-learn/scikit-learn
build_tools/get_comment.py
https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/get_comment.py
BSD-3-Clause
def get_step_message(log, start, end, title, message, details): """Get the message for a specific test. Parameters ---------- log : str The log of the linting job. start : str The string that marks the start of the test. end : str The string that marks the end of the t...
Get the message for a specific test. Parameters ---------- log : str The log of the linting job. start : str The string that marks the start of the test. end : str The string that marks the end of the test. title : str The title for this section. message ...
get_step_message
python
scikit-learn/scikit-learn
build_tools/get_comment.py
https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/get_comment.py
BSD-3-Clause
def get_headers(token): """Get the headers for the GitHub API.""" return { "Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}", "X-GitHub-Api-Version": "2022-11-28", }
Get the headers for the GitHub API.
get_headers
python
scikit-learn/scikit-learn
build_tools/get_comment.py
https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/get_comment.py
BSD-3-Clause
def create_or_update_comment(comment, message, repo, pr_number, token): """Create a new comment or update existing one.""" # repo is in the form of "org/repo" if comment is not None: print("updating existing comment") # API doc: https://docs.github.com/en/rest/issues/comments?apiVersion=2022...
Create a new comment or update existing one.
create_or_update_comment
python
scikit-learn/scikit-learn
build_tools/get_comment.py
https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/get_comment.py
BSD-3-Clause
def make_distributor_init_64_bits( distributor_init, vcomp140_dll_filename, msvcp140_dll_filename, ): """Create a _distributor_init.py file for 64-bit architectures. This file is imported first when importing the sklearn package so as to pre-load the vendored vcomp140.dll and msvcp140.dll. ...
Create a _distributor_init.py file for 64-bit architectures. This file is imported first when importing the sklearn package so as to pre-load the vendored vcomp140.dll and msvcp140.dll.
make_distributor_init_64_bits
python
scikit-learn/scikit-learn
build_tools/github/vendor.py
https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/github/vendor.py
BSD-3-Clause
def _get_guide(*refs, is_developer=False): """Get the rst to refer to user/developer guide. `refs` is several references that can be used in the :ref:`...` directive. """ if len(refs) == 1: ref_desc = f":ref:`{refs[0]}` section" elif len(refs) == 2: ref_desc = f":ref:`{refs[0]}` and...
Get the rst to refer to user/developer guide. `refs` is several references that can be used in the :ref:`...` directive.
_get_guide
python
scikit-learn/scikit-learn
doc/api_reference.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/api_reference.py
BSD-3-Clause
def _get_submodule(module_name, submodule_name): """Get the submodule docstring and automatically add the hook. `module_name` is e.g. `sklearn.feature_extraction`, and `submodule_name` is e.g. `image`, so we get the docstring and hook for `sklearn.feature_extraction.image` submodule. `module_name` is u...
Get the submodule docstring and automatically add the hook. `module_name` is e.g. `sklearn.feature_extraction`, and `submodule_name` is e.g. `image`, so we get the docstring and hook for `sklearn.feature_extraction.image` submodule. `module_name` is used to reset the current module because autosummary ...
_get_submodule
python
scikit-learn/scikit-learn
doc/api_reference.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/api_reference.py
BSD-3-Clause
def add_js_css_files(app, pagename, templatename, context, doctree): """Load additional JS and CSS files only for certain pages. Note that `html_js_files` and `html_css_files` are included in all pages and should be used for the ones that are used by multiple pages. All page-specific JS and CSS files s...
Load additional JS and CSS files only for certain pages. Note that `html_js_files` and `html_css_files` are included in all pages and should be used for the ones that are used by multiple pages. All page-specific JS and CSS files should be added here instead.
add_js_css_files
python
scikit-learn/scikit-learn
doc/conf.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/conf.py
BSD-3-Clause
def make_carousel_thumbs(app, exception): """produces the final resized carousel images""" if exception is not None: return print("Preparing carousel images") image_dir = os.path.join(app.builder.outdir, "_images") for glr_plot, max_width in carousel_thumbs.items(): image = os.path....
produces the final resized carousel images
make_carousel_thumbs
python
scikit-learn/scikit-learn
doc/conf.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/conf.py
BSD-3-Clause
def skip_properties(app, what, name, obj, skip, options): """Skip properties that are fitted attributes""" if isinstance(obj, property): if name.endswith("_") and not name.startswith("_"): return True return skip
Skip properties that are fitted attributes
skip_properties
python
scikit-learn/scikit-learn
doc/conf.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/conf.py
BSD-3-Clause
def infer_next_release_versions(): """Infer the most likely next release versions to make.""" all_version_full = {"rc": "0.99.0rc1", "final": "0.99.0", "bf": "0.98.1"} all_version_short = {"rc": "0.99", "final": "0.99", "bf": "0.98"} all_previous_tag = {"rc": "unused", "final": "0.98.33", "bf": "0.97.22...
Infer the most likely next release versions to make.
infer_next_release_versions
python
scikit-learn/scikit-learn
doc/conf.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/conf.py
BSD-3-Clause
def pytest_collection_modifyitems(config, items): """Called after collect is completed. Parameters ---------- config : pytest config items : list of collected items """ skip_doctests = False if np_base_version < parse_version("2"): # TODO: configure numpy to output scalar arrays...
Called after collect is completed. Parameters ---------- config : pytest config items : list of collected items
pytest_collection_modifyitems
python
scikit-learn/scikit-learn
doc/conftest.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/conftest.py
BSD-3-Clause
def add_content(self, more_content): """Override default behavior to add only the first line of the docstring. Modified based on the part of processing docstrings in the original implementation of this method. https://github.com/sphinx-doc/sphinx/blob/faa33a53a389f6f8bc1f6ae97d6015fa92...
Override default behavior to add only the first line of the docstring. Modified based on the part of processing docstrings in the original implementation of this method. https://github.com/sphinx-doc/sphinx/blob/faa33a53a389f6f8bc1f6ae97d6015fa92393c4a/sphinx/ext/autodoc/__init__.py#L609-L622 ...
add_content
python
scikit-learn/scikit-learn
doc/sphinxext/autoshortsummary.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/sphinxext/autoshortsummary.py
BSD-3-Clause
def _linkcode_resolve(domain, info, package, url_fmt, revision): """Determine a link to online source for a class/method/function This is called by sphinx.ext.linkcode An example with a long-untouched module that everyone has >>> _linkcode_resolve('py', {'module': 'tty', ... ...
Determine a link to online source for a class/method/function This is called by sphinx.ext.linkcode An example with a long-untouched module that everyone has >>> _linkcode_resolve('py', {'module': 'tty', ... 'fullname': 'setraw'}, ... package='tty', ....
_linkcode_resolve
python
scikit-learn/scikit-learn
doc/sphinxext/github_link.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/sphinxext/github_link.py
BSD-3-Clause
def override_pst_pagetoc(app, pagename, templatename, context, doctree): """Overrides the `generate_toc_html` function of pydata-sphinx-theme for API.""" @cache def generate_api_toc_html(kind="html"): """Generate the in-page toc for an API page. This relies on the `generate_toc_html` funct...
Overrides the `generate_toc_html` function of pydata-sphinx-theme for API.
override_pst_pagetoc
python
scikit-learn/scikit-learn
doc/sphinxext/override_pst_pagetoc.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/sphinxext/override_pst_pagetoc.py
BSD-3-Clause
def generate_api_toc_html(kind="html"): """Generate the in-page toc for an API page. This relies on the `generate_toc_html` function added by pydata-sphinx-theme into the context. We save the original function into `pst_generate_toc_html` and override `generate_toc_html` with this funct...
Generate the in-page toc for an API page. This relies on the `generate_toc_html` function added by pydata-sphinx-theme into the context. We save the original function into `pst_generate_toc_html` and override `generate_toc_html` with this function for generated API pages. The pagetoc o...
generate_api_toc_html
python
scikit-learn/scikit-learn
doc/sphinxext/override_pst_pagetoc.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/sphinxext/override_pst_pagetoc.py
BSD-3-Clause
def user_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Sphinx role for linking to a user profile. Defaults to linking to Github profiles, but the profile URIS can be configured via the ``issues_user_uri`` config value. Examples: :: :user:`sloria` Anchor text also...
Sphinx role for linking to a user profile. Defaults to linking to Github profiles, but the profile URIS can be configured via the ``issues_user_uri`` config value. Examples: :: :user:`sloria` Anchor text also works: :: :user:`Steven Loria <sloria>`
user_role
python
scikit-learn/scikit-learn
doc/sphinxext/sphinx_issues.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/sphinxext/sphinx_issues.py
BSD-3-Clause
def plot_digits(X, title): """Small helper function to plot 100 digits.""" fig, axs = plt.subplots(nrows=10, ncols=10, figsize=(8, 8)) for img, ax in zip(X, axs.ravel()): ax.imshow(img.reshape((16, 16)), cmap="Greys") ax.axis("off") fig.suptitle(title, fontsize=24)
Small helper function to plot 100 digits.
plot_digits
python
scikit-learn/scikit-learn
examples/applications/plot_digits_denoising.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_digits_denoising.py
BSD-3-Clause
def plot_gallery(images, titles, h, w, n_row=3, n_col=4): """Helper function to plot a gallery of portraits""" plt.figure(figsize=(1.8 * n_col, 2.4 * n_row)) plt.subplots_adjust(bottom=0, left=0.01, right=0.99, top=0.90, hspace=0.35) for i in range(n_row * n_col): plt.subplot(n_row, n_col, i + 1...
Helper function to plot a gallery of portraits
plot_gallery
python
scikit-learn/scikit-learn
examples/applications/plot_face_recognition.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_face_recognition.py
BSD-3-Clause
def benchmark_influence(conf): """ Benchmark influence of `changing_param` on both MSE and latency. """ prediction_times = [] prediction_powers = [] complexities = [] for param_value in conf["changing_param_values"]: conf["tuned_params"][conf["changing_param"]] = param_value ...
Benchmark influence of `changing_param` on both MSE and latency.
benchmark_influence
python
scikit-learn/scikit-learn
examples/applications/plot_model_complexity_influence.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_model_complexity_influence.py
BSD-3-Clause
def plot_influence(conf, mse_values, prediction_times, complexities): """ Plot influence of model complexity on both accuracy and latency. """ fig = plt.figure() fig.subplots_adjust(right=0.75) # first axes (prediction error) ax1 = fig.add_subplot(111) line1 = ax1.plot(complexities, ms...
Plot influence of model complexity on both accuracy and latency.
plot_influence
python
scikit-learn/scikit-learn
examples/applications/plot_model_complexity_influence.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_model_complexity_influence.py
BSD-3-Clause
def stream_reuters_documents(data_path=None): """Iterate over documents of the Reuters dataset. The Reuters archive will automatically be downloaded and uncompressed if the `data_path` directory does not exist. Documents are represented as dictionaries with 'body' (str), 'title' (str), 'topics' (l...
Iterate over documents of the Reuters dataset. The Reuters archive will automatically be downloaded and uncompressed if the `data_path` directory does not exist. Documents are represented as dictionaries with 'body' (str), 'title' (str), 'topics' (list(str)) keys.
stream_reuters_documents
python
scikit-learn/scikit-learn
examples/applications/plot_out_of_core_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_out_of_core_classification.py
BSD-3-Clause
def get_minibatch(doc_iter, size, pos_class=positive_class): """Extract a minibatch of examples, return a tuple X_text, y. Note: size is before excluding invalid docs with no topics assigned. """ data = [ ("{title}\n\n{body}".format(**doc), pos_class in doc["topics"]) for doc in iterto...
Extract a minibatch of examples, return a tuple X_text, y. Note: size is before excluding invalid docs with no topics assigned.
get_minibatch
python
scikit-learn/scikit-learn
examples/applications/plot_out_of_core_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_out_of_core_classification.py
BSD-3-Clause
def autolabel(rectangles): """attach some text vi autolabel on rectangles.""" for rect in rectangles: height = rect.get_height() ax.text( rect.get_x() + rect.get_width() / 2.0, 1.05 * height, "%.4f" % height, ha="center", va="bottom", ...
attach some text vi autolabel on rectangles.
autolabel
python
scikit-learn/scikit-learn
examples/applications/plot_out_of_core_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_out_of_core_classification.py
BSD-3-Clause
def atomic_benchmark_estimator(estimator, X_test, verbose=False): """Measure runtime prediction of each instance.""" n_instances = X_test.shape[0] runtimes = np.zeros(n_instances, dtype=float) for i in range(n_instances): instance = X_test[[i], :] start = time.time() estimator.pr...
Measure runtime prediction of each instance.
atomic_benchmark_estimator
python
scikit-learn/scikit-learn
examples/applications/plot_prediction_latency.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_prediction_latency.py
BSD-3-Clause
def bulk_benchmark_estimator(estimator, X_test, n_bulk_repeats, verbose): """Measure runtime prediction of the whole input.""" n_instances = X_test.shape[0] runtimes = np.zeros(n_bulk_repeats, dtype=float) for i in range(n_bulk_repeats): start = time.time() estimator.predict(X_test) ...
Measure runtime prediction of the whole input.
bulk_benchmark_estimator
python
scikit-learn/scikit-learn
examples/applications/plot_prediction_latency.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_prediction_latency.py
BSD-3-Clause
def benchmark_estimator(estimator, X_test, n_bulk_repeats=30, verbose=False): """ Measure runtimes of prediction in both atomic and bulk mode. Parameters ---------- estimator : already trained estimator supporting `predict()` X_test : test input n_bulk_repeats : how many times to repeat whe...
Measure runtimes of prediction in both atomic and bulk mode. Parameters ---------- estimator : already trained estimator supporting `predict()` X_test : test input n_bulk_repeats : how many times to repeat when evaluating bulk mode Returns ------- atomic_runtimes, bulk_runtimes : ...
benchmark_estimator
python
scikit-learn/scikit-learn
examples/applications/plot_prediction_latency.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_prediction_latency.py
BSD-3-Clause
def generate_dataset(n_train, n_test, n_features, noise=0.1, verbose=False): """Generate a regression dataset with the given parameters.""" if verbose: print("generating dataset...") X, y, coef = make_regression( n_samples=n_train + n_test, n_features=n_features, noise=noise, coef=True ...
Generate a regression dataset with the given parameters.
generate_dataset
python
scikit-learn/scikit-learn
examples/applications/plot_prediction_latency.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_prediction_latency.py
BSD-3-Clause
def boxplot_runtimes(runtimes, pred_type, configuration): """ Plot a new `Figure` with boxplots of prediction runtimes. Parameters ---------- runtimes : list of `np.array` of latencies in micro-seconds cls_names : list of estimator class names that generated the runtimes pred_type : 'bulk' ...
Plot a new `Figure` with boxplots of prediction runtimes. Parameters ---------- runtimes : list of `np.array` of latencies in micro-seconds cls_names : list of estimator class names that generated the runtimes pred_type : 'bulk' or 'atomic'
boxplot_runtimes
python
scikit-learn/scikit-learn
examples/applications/plot_prediction_latency.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_prediction_latency.py
BSD-3-Clause
def n_feature_influence(estimators, n_train, n_test, n_features, percentile): """ Estimate influence of the number of features on prediction time. Parameters ---------- estimators : dict of (name (str), estimator) to benchmark n_train : nber of training instances (int) n_test : nber of tes...
Estimate influence of the number of features on prediction time. Parameters ---------- estimators : dict of (name (str), estimator) to benchmark n_train : nber of training instances (int) n_test : nber of testing instances (int) n_features : list of feature-space dimensionality to test (i...
n_feature_influence
python
scikit-learn/scikit-learn
examples/applications/plot_prediction_latency.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_prediction_latency.py
BSD-3-Clause
def construct_grids(batch): """Construct the map grid from the batch object Parameters ---------- batch : Batch object The object returned by :func:`fetch_species_distributions` Returns ------- (xgrid, ygrid) : 1-D arrays The grid corresponding to the values in batch.covera...
Construct the map grid from the batch object Parameters ---------- batch : Batch object The object returned by :func:`fetch_species_distributions` Returns ------- (xgrid, ygrid) : 1-D arrays The grid corresponding to the values in batch.coverages
construct_grids
python
scikit-learn/scikit-learn
examples/applications/plot_species_distribution_modeling.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_species_distribution_modeling.py
BSD-3-Clause
def create_species_bunch(species_name, train, test, coverages, xgrid, ygrid): """Create a bunch with information about a particular organism This will use the test/train record arrays to extract the data specific to the given species name. """ bunch = Bunch(name=" ".join(species_name.split("_")[:2]...
Create a bunch with information about a particular organism This will use the test/train record arrays to extract the data specific to the given species name.
create_species_bunch
python
scikit-learn/scikit-learn
examples/applications/plot_species_distribution_modeling.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_species_distribution_modeling.py
BSD-3-Clause
def build_projection_operator(l_x, n_dir): """Compute the tomography design matrix. Parameters ---------- l_x : int linear size of image array n_dir : int number of angles at which projections are acquired. Returns ------- p : sparse matrix of shape (n_dir l_x, l_x**2...
Compute the tomography design matrix. Parameters ---------- l_x : int linear size of image array n_dir : int number of angles at which projections are acquired. Returns ------- p : sparse matrix of shape (n_dir l_x, l_x**2)
build_projection_operator
python
scikit-learn/scikit-learn
examples/applications/plot_tomography_l1_reconstruction.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_tomography_l1_reconstruction.py
BSD-3-Clause
def index(redirects, index_map, k): """Find the index of an article name after redirect resolution""" k = redirects.get(k, k) return index_map.setdefault(k, len(index_map))
Find the index of an article name after redirect resolution
index
python
scikit-learn/scikit-learn
examples/applications/wikipedia_principal_eigenvector.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/wikipedia_principal_eigenvector.py
BSD-3-Clause
def get_redirects(redirects_filename): """Parse the redirections and build a transitively closed map out of it""" redirects = {} print("Parsing the NT redirect file") for l, line in enumerate(BZ2File(redirects_filename)): split = line.split() if len(split) != 4: print("ignori...
Parse the redirections and build a transitively closed map out of it
get_redirects
python
scikit-learn/scikit-learn
examples/applications/wikipedia_principal_eigenvector.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/wikipedia_principal_eigenvector.py
BSD-3-Clause
def get_adjacency_matrix(redirects_filename, page_links_filename, limit=None): """Extract the adjacency graph as a scipy sparse matrix Redirects are resolved first. Returns X, the scipy sparse adjacency matrix, redirects as python dict from article names to article names and index_map a python dict ...
Extract the adjacency graph as a scipy sparse matrix Redirects are resolved first. Returns X, the scipy sparse adjacency matrix, redirects as python dict from article names to article names and index_map a python dict from article names to python int (article indexes).
get_adjacency_matrix
python
scikit-learn/scikit-learn
examples/applications/wikipedia_principal_eigenvector.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/wikipedia_principal_eigenvector.py
BSD-3-Clause
def predict_proba(self, X): """Min-max scale output of `decision_function` to [0, 1].""" df = self.decision_function(X) calibrated_df = (df - self.df_min_) / (self.df_max_ - self.df_min_) proba_pos_class = np.clip(calibrated_df, 0, 1) proba_neg_class = 1 - proba_pos_class ...
Min-max scale output of `decision_function` to [0, 1].
predict_proba
python
scikit-learn/scikit-learn
examples/calibration/plot_calibration_curve.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/calibration/plot_calibration_curve.py
BSD-3-Clause
def predict_proba(self, X): """Min-max scale output of `decision_function` to [0,1].""" df = self.decision_function(X) calibrated_df = (df - self.df_min_) / (self.df_max_ - self.df_min_) proba_pos_class = np.clip(calibrated_df, 0, 1) proba_neg_class = 1 - proba_pos_class ...
Min-max scale output of `decision_function` to [0,1].
predict_proba
python
scikit-learn/scikit-learn
examples/calibration/plot_compare_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/calibration/plot_compare_calibration.py
BSD-3-Clause
def generate_data(n_samples, n_features): """Generate random blob-ish data with noisy features. This returns an array of input data with shape `(n_samples, n_features)` and an array of `n_samples` target labels. Only one feature contains discriminative information, the other features contain only ...
Generate random blob-ish data with noisy features. This returns an array of input data with shape `(n_samples, n_features)` and an array of `n_samples` target labels. Only one feature contains discriminative information, the other features contain only noise.
generate_data
python
scikit-learn/scikit-learn
examples/classification/plot_lda.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/classification/plot_lda.py
BSD-3-Clause
def _classifier_has(attr): """Check if we can delegate a method to the underlying classifier. First, we check the first fitted classifier if available, otherwise we check the unfitted classifier. """ return lambda estimator: ( hasattr(estimator.classifier_, attr) if hasattr(estimato...
Check if we can delegate a method to the underlying classifier. First, we check the first fitted classifier if available, otherwise we check the unfitted classifier.
_classifier_has
python
scikit-learn/scikit-learn
examples/cluster/plot_inductive_clustering.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/cluster/plot_inductive_clustering.py
BSD-3-Clause
def bench_k_means(kmeans, name, data, labels): """Benchmark to evaluate the KMeans initialization methods. Parameters ---------- kmeans : KMeans instance A :class:`~sklearn.cluster.KMeans` instance with the initialization already set. name : str Name given to the strategy. I...
Benchmark to evaluate the KMeans initialization methods. Parameters ---------- kmeans : KMeans instance A :class:`~sklearn.cluster.KMeans` instance with the initialization already set. name : str Name given to the strategy. It will be used to show the results in a table....
bench_k_means
python
scikit-learn/scikit-learn
examples/cluster/plot_kmeans_digits.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/cluster/plot_kmeans_digits.py
BSD-3-Clause
def ricker_function(resolution, center, width): """Discrete sub-sampled Ricker (Mexican hat) wavelet""" x = np.linspace(0, resolution - 1, resolution) x = ( (2 / (np.sqrt(3 * width) * np.pi**0.25)) * (1 - (x - center) ** 2 / width**2) * np.exp(-((x - center) ** 2) / (2 * width**2)) ...
Discrete sub-sampled Ricker (Mexican hat) wavelet
ricker_function
python
scikit-learn/scikit-learn
examples/decomposition/plot_sparse_coding.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/decomposition/plot_sparse_coding.py
BSD-3-Clause
def ricker_matrix(width, resolution, n_components): """Dictionary of Ricker (Mexican hat) wavelets""" centers = np.linspace(0, resolution - 1, n_components) D = np.empty((n_components, resolution)) for i, center in enumerate(centers): D[i] = ricker_function(resolution, center, width) D /= np...
Dictionary of Ricker (Mexican hat) wavelets
ricker_matrix
python
scikit-learn/scikit-learn
examples/decomposition/plot_sparse_coding.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/decomposition/plot_sparse_coding.py
BSD-3-Clause
def fit(self, X, y): """ Fit the estimator to the training data. """ self.classes_ = sorted(set(y)) # Custom attribute to track if the estimator is fitted self._is_fitted = True return self
Fit the estimator to the training data.
fit
python
scikit-learn/scikit-learn
examples/developing_estimators/sklearn_is_fitted.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/developing_estimators/sklearn_is_fitted.py
BSD-3-Clause
def predict(self, X): """ Perform Predictions If the estimator is not fitted, then raise NotFittedError """ check_is_fitted(self) # Perform prediction logic predictions = [self.classes_[0]] * len(X) return predictions
Perform Predictions If the estimator is not fitted, then raise NotFittedError
predict
python
scikit-learn/scikit-learn
examples/developing_estimators/sklearn_is_fitted.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/developing_estimators/sklearn_is_fitted.py
BSD-3-Clause
def score(self, X, y): """ Calculate Score If the estimator is not fitted, then raise NotFittedError """ check_is_fitted(self) # Perform scoring logic return 0.5
Calculate Score If the estimator is not fitted, then raise NotFittedError
score
python
scikit-learn/scikit-learn
examples/developing_estimators/sklearn_is_fitted.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/developing_estimators/sklearn_is_fitted.py
BSD-3-Clause
def _f(self, s1, s2): """ kernel value between a pair of sequences """ return sum( [1.0 if c1 == c2 else self.baseline_similarity for c1 in s1 for c2 in s2] )
kernel value between a pair of sequences
_f
python
scikit-learn/scikit-learn
examples/gaussian_process/plot_gpr_on_structured_data.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/gaussian_process/plot_gpr_on_structured_data.py
BSD-3-Clause
def plot_gpr_samples(gpr_model, n_samples, ax): """Plot samples drawn from the Gaussian process model. If the Gaussian process model is not trained then the drawn samples are drawn from the prior distribution. Otherwise, the samples are drawn from the posterior distribution. Be aware that a sample here...
Plot samples drawn from the Gaussian process model. If the Gaussian process model is not trained then the drawn samples are drawn from the prior distribution. Otherwise, the samples are drawn from the posterior distribution. Be aware that a sample here corresponds to a function. Parameters ---...
plot_gpr_samples
python
scikit-learn/scikit-learn
examples/gaussian_process/plot_gpr_prior_posterior.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/gaussian_process/plot_gpr_prior_posterior.py
BSD-3-Clause