text stringlengths 81 112k |
|---|
Visualize the computational graph.
:param filename: Filename of the output image together with file extension. Supported formats: `png`, `jpg`,
`pdf`, ... . Check `graphviz` Python package for more options
:type filename: str
:return: The DOT representation of the computational... |
If some tasks of the workflow are the same they are deep copied.
def _make_tasks_unique(tasks):
"""If some tasks of the workflow are the same they are deep copied."""
unique_tasks = []
prev_tasks = set()
for task in tasks:
if task in prev_tasks:
task ... |
Returns dictionary items
def items(self):
""" Returns dictionary items """
return {dep.task: value for dep, value in self._result.items()}.items() |
Dictionary get method
def get(self, key, default=None):
""" Dictionary get method """
if isinstance(key, EOTask):
key = self._uuid_dict[key.private_task_config.uuid]
return self._result.get(key, default) |
Maps morphological operation type to function
:param morph_type: Morphological operation type
:type morph_type: MorphologicalOperations
:return: function
def get_operation(cls, morph_type):
""" Maps morphological operation type to function
:param morph_type: Morphologic... |
Execute method takes EOPatch and changes the specified feature
def execute(self, eopatch):
""" Execute method takes EOPatch and changes the specified feature
"""
feature_type, feature_name = next(self.feature(eopatch))
eopatch[feature_type][feature_name] = self.process(eopatch[fea... |
Applies the morphological operation to the mask object
def process(self, raster):
""" Applies the morphological operation to the mask object
"""
dim = len(raster.shape)
if dim == 3:
for dim in range(raster.shape[2]):
raster[:, :, dim] = self.morph_opera... |
:return: dictionary of out-degrees, see get_outdegree
def get_outdegrees(self):
"""
:return: dictionary of out-degrees, see get_outdegree
"""
return {vertex: len(self.adj_dict[vertex]) for vertex in self.adj_dict} |
Adds the edge ``u_vertex -> v_vertex`` to the graph if the edge is not already present.
:param u_vertex: Vertex
:param v_vertex: Vertex
:return: ``True`` if a new edge was added. ``False`` otherwise.
def add_edge(self, u_vertex, v_vertex):
"""Adds the edge ``u_vertex -> v_vertex``... |
Removes the edge ``u_vertex -> v_vertex`` from the graph if the edge is present.
:param u_vertex: Vertex
:param v_vertex: Vertex
:return: ``True`` if the existing edge was removed. ``False`` otherwise.
def del_edge(self, u_vertex, v_vertex):
"""Removes the edge ``u_vertex -> v_ver... |
Adds a new vertex to the graph if not present.
:param vertex: Vertex
:return: ``True`` if ``vertex`` added and not yet present. ``False`` otherwise.
def add_vertex(self, vertex):
"""Adds a new vertex to the graph if not present.
:param vertex: Vertex
:return: ``True`` i... |
Removes the vertex ``vertex`` and all incident edges from the graph.
**Note** that this is an expensive operation that should be avoided!
Running time is O(V+E)
:param vertex: Vertex
:return: ``True`` if ``vertex`` was removed from the graph. ``False`` otherwise.
def del_verte... |
Return DirectedGraph created from edges
:param edges:
:return: DirectedGraph
def from_edges(edges):
""" Return DirectedGraph created from edges
:param edges:
:return: DirectedGraph
"""
dag = DirectedGraph()
for _u, _v in edges:
dag.ad... |
True if the directed graph dag contains a cycle. False otherwise.
The algorithm is naive, running in O(V^2) time, and not intended for serious use! For production purposes on
larger graphs consider implementing Tarjan's O(V+E)-time algorithm instead.
:type dag: DirectedGraph
def _is_cycl... |
Execute predicate on input eopatch
:param eopatch: Input `eopatch` instance
:return: The same `eopatch` instance with a `mask.valid_data` array computed according to the predicate
def execute(self, eopatch):
""" Execute predicate on input eopatch
:param eopatch: Input `eopatch` instan... |
Mask values of `feature` according to the `mask_values` in `mask_feature`
:param eopatch: `eopatch` to be processed
:return: Same `eopatch` instance with masked `feature`
def execute(self, eopatch):
""" Mask values of `feature` according to the `mask_values` in `mask_feature`
:param e... |
If given FeatureType stores a dictionary of numpy.ndarrays it returns dimensions of such arrays.
def ndim(self):
"""If given FeatureType stores a dictionary of numpy.ndarrays it returns dimensions of such arrays."""
if self.is_raster():
return {
FeatureType.DATA: 4,
... |
Returns type of the data for the given FeatureType.
def type(self):
"""Returns type of the data for the given FeatureType."""
if self is FeatureType.TIMESTAMP:
return list
if self is FeatureType.BBOX:
return BBox
return dict |
Splits the filename string by the extension of the file
def split_by_extensions(filename):
""" Splits the filename string by the extension of the file
"""
parts = filename.split('.')
idx = len(parts) - 1
while FileFormat.is_file_format(parts[idx]):
parts[idx] = FileF... |
Resets all counters, truth and classification masks.
def reset_counters(self):
"""
Resets all counters, truth and classification masks.
"""
self.truth_masks = None
self.classification_masks = None
self.pixel_truth_counts = None
self.pixel_classification_counts = ... |
Count the pixels belonging to each truth class
def _count_truth_pixels(self):
"""
Count the pixels belonging to each truth class
"""
pixel_count = np.array([[np.nonzero(mask)[0].shape[0] for mask in masktype]
for masktype in self.truth_masks])
pi... |
Count the pixels belonging to each classified class.
def _count_classified_pixels(self):
"""
Count the pixels belonging to each classified class.
"""
class_values = self.class_dictionary.values()
classification_count = np.array([[[np.count_nonzero(prediction[np.nonzero(mask)] =... |
Extracts ground truth and classification results from the EOPatch and
aggregates the results.
def add_validation_patch(self, patch):
"""
Extracts ground truth and classification results from the EOPatch and
aggregates the results.
"""
# 2. Convert 8-bit mask
self... |
Aggregate the results from all EOPatches.
def validate(self):
"""
Aggregate the results from all EOPatches.
"""
self.pixel_truth_sum = np.sum(self.pixel_truth_counts, axis=0)
self.pixel_classification_sum = np.sum(self.pixel_classification_counts, axis=0) |
Save validator object to pickle.
def save(self, filename):
"""
Save validator object to pickle.
"""
with open(filename, 'wb') as output:
pickle.dump(self, output, protocol=pickle.HIGHEST_PROTOCOL) |
Returns pandas DataFrame containing pixel counts for all truth classes,
classified classes (for each truth class), and file name of the input
EODataSet.
The data frame thus contains
N = self.n_validation_sets rows
and
M = len(self.truth_classes) + len(self.truth_clas... |
Returns the normalised confusion matrix
def confusion_matrix(self):
"""
Returns the normalised confusion matrix
"""
confusion_matrix = self.pixel_classification_sum.astype(np.float)
confusion_matrix = np.divide(confusion_matrix.T, self.pixel_truth_sum.T).T
return confus... |
Plots the confusion matrix.
def plot_confusion_matrix(self, normalised=True):
"""
Plots the confusion matrix.
"""
conf_matrix = self.confusion_matrix()
if normalised:
sns.heatmap(conf_matrix,
annot=True, annot_kws={"size": 12}, fmt='2.1f', cm... |
Prints out the summary of validation for giving scoring function.
def summary(self, scoring):
"""
Prints out the summary of validation for giving scoring function.
"""
if scoring == 'class_confusion':
print('*' * 50)
print(' Confusion Matrix ')
prin... |
:param eopatch: Input EOPatch.
:type eopatch: EOPatch
:return: Transformed eo patch
:rtype: EOPatch
def execute(self, eopatch):
"""
:param eopatch: Input EOPatch.
:type eopatch: EOPatch
:return: Transformed eo patch
:rtype: EOPatch
"""
fea... |
Execute computation of HoG features on input eopatch
:param eopatch: Input eopatch
:type eopatch: eolearn.core.EOPatch
:return: EOPatch instance with new keys holding the HoG features and HoG image for visualisation.
:rtype: eolearn.core.EOPatch
def execute(self, eopatc... |
Execute computation of local binary patterns on input eopatch
:param eopatch: Input eopatch
:type eopatch: eolearn.core.EOPatch
:return: EOPatch instance with new key holding the LBP image.
:rtype: eolearn.core.EOPatch
def execute(self, eopatch):
""" Execute com... |
Fit model parameters to data using the RANSAC algorithm
This implementation is written from pseudo-code found at
http://en.wikipedia.org/w/index.php?title=RANSAC&oldid=116358182
:param npts: A set of observed data points
:param model: A model that can be fitted to data points
:param n: The minimum... |
return n random rows of data (and also the other len(data)-n rows)
def random_partition(n, n_data):
"""return n random rows of data (and also the other len(data)-n rows)"""
all_idxs = np.arange(n_data)
np.random.shuffle(all_idxs)
idxs1 = all_idxs[:n]
idxs2 = all_idxs[n:]
return idxs1, idxs2 |
Estimate rigid transformation given a set of indices
:param idx: Array of indices used to estimate the transformation
:return: Estimated transformation matrix
def estimate_rigid_transformation(self, idx):
""" Estimate rigid transformation given a set of indices
:param idx: Array of in... |
Estimate the registration error of estimated transformation matrix
:param idx: List of points used to estimate the transformation
:param warp_matrix: Matrix estimating Euler trasnformation
:return: Square root of Target Registration Error
def score(self, idx, warp_matrix):
""" Estimate... |
Create a view of `array` which for every point gives the n-dimensional
neighbourhood of size window. New dimensions are added at the end of
`array` or after the corresponding original dimension.
Parameters
----------
array : array_like
Array to which the rolling window is applied.
... |
Method that estimates registrations and warps EOPatch objects
def execute(self, eopatch):
""" Method that estimates registrations and warps EOPatch objects
"""
self.check_params()
self.get_params()
new_eopatch = copy.deepcopy(eopatch)
f_type, f_name = next(self.registr... |
Function to warp input image given an estimated 2D linear transformation
:param warp_matrix: Linear 2x3 matrix to use to linearly warp the input images
:type warp_matrix: ndarray
:param img: Image to be warped with estimated transformation
:type img: ndarray
:param iflag: Interp... |
Static method that check if estimated linear transformation could be unplausible
This function checks whether the norm of the estimated translation or the rotation angle exceed predefined
values. For the translation, a maximum translation radius of 20 pixels is flagged, while larger rotations than
... |
Implementation of pair-wise registration using thunder-registration
For more information on the model estimation, refer to https://github.com/thunder-project/thunder-registration
This function takes two 2D single channel images and estimates a 2D translation that best aligns the pair. The
estim... |
Implementation of pair-wise registration and warping using Enhanced Correlation Coefficient
This function estimates an Euclidean transformation (x,y translation + rotation) using the intensities of the
pair of images to be registered. The similarity metric is a modification of the cross-correlation met... |
Implementation of pair-wise registration and warping using point-based matching
This function estimates a number of transforms (Euler, PartialAffine and Homography) using point-based matching.
Features descriptor are first extracted from the pair of images using either SIFT or SURF descriptors. A
... |
Normalise and scale image in 0-255 range
def rescale_image(image):
""" Normalise and scale image in 0-255 range """
s2_min_value, s2_max_value = 0, 1
out_min_value, out_max_value = 0, 255
# Clamp values in 0-1 range
image[image > s2_max_value] = s2_max_value
image[image ... |
Parameters
----------
X : array-like, shape [n x m]
The mask in form of n x m array.
def transform(self, X):
"""
Parameters
----------
X : array-like, shape [n x m]
The mask in form of n x m array.
"""
if self.mode_ == 't... |
Parameters
----------
X : array-like, shape [n x m]
The mask in form of n x m array.
def transform(self, X):
"""
Parameters
----------
X : array-like, shape [n x m]
The mask in form of n x m array.
"""
if self.binary_:
... |
Returns a new geopandas dataframe with same structure as original one (columns) except that
it contains only polygons that are contained within the given bbox.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: New EOPatch
:rtype: EOPatch
def _get_submap(self, eopatc... |
Execute function which adds new vector layer to the EOPatch
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: New EOPatch with added vector layer
:rtype: EOPatch
def execute(self, eopatch):
""" Execute function which adds new vector layer to the EOPatch
:pa... |
Vectorizes a data slice of a single time component
:param raster: Numpy array or shape (height, width, channels)
:type raster: numpy.ndarray
:param data_transform: Object holding a transform vector (i.e. geographical location vector) of the raster
:type data_transform: affine.Affine
... |
Execute function which adds new vector layer to the EOPatch
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: New EOPatch with added vector layer
:rtype: EOPatch
def execute(self, eopatch):
""" Execute function which adds new vector layer to the EOPatch
:pa... |
Returns the area of the selected polygon if index is provided or of all polygons if it's not.
def area(self, cc_index=None):
"""
Returns the area of the selected polygon if index is provided or of all polygons if it's not.
"""
if cc_index is not None:
return self.areas[cc_in... |
Sample n points from the provided raster mask. The number of points belonging
to each class is proportional to the area this class covers in the raster mask,
if weighted is set to True.
TODO: If polygon has holes the number of sampled points will be less than nsamples
:param nsamples: ... |
Returns a random polygon of any class. The probability of each polygon to be sampled
is proportional to its area if weighted is True.
def sample_cc(self, nsamples=1, weighted=True):
"""
Returns a random polygon of any class. The probability of each polygon to be sampled
is proportional ... |
Returns randomly sampled points from a polygon.
Complexity of this procedure is (A/a * nsamples) where A=area(bbox(P))
and a=area(P) where P is the polygon of the connected component cc_index
def sample_within_cc(self, cc_index, nsamples=1):
"""
Returns randomly sampled points from a p... |
Tests whether point lies within the polygon
def contains(polygon, point):
"""
Tests whether point lies within the polygon
"""
in_hole = functools.reduce(
lambda P, Q: P and Q,
[interior.covers(point) for interior in polygon.interiors]
) if polygon.interio... |
Selects a random point in interior of a rectangle
:param bounds: Rectangle coordinates (x_min, y_min, x_max, y_max)
:type bounds: tuple(float)
:return: Random point from interior of rectangle
:rtype: tuple of x and y coordinates
def random_coords(bounds):
""" Selects a random p... |
Selects a random point in interior of a triangle
def random_point_triangle(triangle, use_int_coords=True):
"""
Selects a random point in interior of a triangle
"""
xs, ys = triangle.exterior.coords.xy
A, B, C = zip(xs[:-1], ys[:-1])
r1, r2 = np.random.rand(), np.random.r... |
Finds the smallest integer value >=0 that is not in `labels`
:return: Value that is not in the labels
:rtype: int
def _get_unknown_value(self):
""" Finds the smallest integer value >=0 that is not in `labels`
:return: Value that is not in the labels
:rtype: int
"""
... |
Sample `nsamples_per_label` points from the binary mask corresponding to `label`
Randomly sample `nsamples_per_label` point form the binary mask corresponding to `label`. Sampling with
replacement is used if the required `nsamples_per_label` is larger than the available `label_count`
:param im... |
Sample `nsamples` points form raster
:param raster: Input 2D or single-channel 3D label image
:type raster: uint8 numpy array
:param n_samples: Number of points to sample in total
:type n_samples: uint32
:return: List of row indices of samples, list of column indices of samples
... |
Execute random spatial sampling of time-series stored in the input eopatch
:param eopatch: Input eopatch to be sampled
:type eopatch: EOPatch
:param seed: Setting seed of random sampling. If None no seed will be used.
:type seed: int or None
:return: An EOPatch with spatially sa... |
Saves the EOPatch to disk: `folder/eopatch_folder`.
:param eopatch: EOPatch which will be saved
:type eopatch: EOPatch
:param eopatch_folder: name of EOPatch folder containing data
:type eopatch_folder: str
:return: The same EOPatch
:rtype: EOPatch
def execute(self, eop... |
Loads the EOPatch from disk: `folder/eopatch_folder`.
:param eopatch_folder: name of EOPatch folder containing data
:type eopatch_folder: str
:return: EOPatch loaded from disk
:rtype: EOPatch
def execute(self, *, eopatch_folder):
"""Loads the EOPatch from disk: `folder/eopatch_... |
Returns the EOPatch with added features.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:param data: data to be added to the feature
:type data: object
:return: input EOPatch with the specified feature
:rtype: EOPatch
def execute(self, eopatch, data):
"""R... |
Returns the EOPatch with removed features.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: input EOPatch without the specified feature
:rtype: EOPatch
def execute(self, eopatch):
"""Returns the EOPatch with removed features.
:param eopatch: input EOPatch
... |
Returns the EOPatch with renamed features.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: input EOPatch with the renamed features
:rtype: EOPatch
def execute(self, eopatch):
"""Returns the EOPatch with renamed features.
:param eopatch: input EOPatch
... |
Calculate percentile of numpy stack and return the index of the chosen pixel.
numpy percentile function is used with one of the following interpolations {'linear', 'lower', 'higher',
'midpoint', 'nearest'}
def _numpy_index_by_percentile(self, data, percentile):
""" Calculate percentile... |
Calculate percentile of numpy stack and return the index of the chosen pixel.
def _geoville_index_by_percentile(self, data, percentile):
""" Calculate percentile of numpy stack and return the index of the chosen pixel. """
# no_obs = bn.allnan(arr_tmp["data"], axis=0)
data_tmp = np.array(data, ... |
Compute indices along temporal dimension corresponding to the sought percentile
:param data: Input 3D array holding the reference band
:type data: numpy array
:return: 2D array holding the temporal index corresponding to percentile
def _get_indices(self, data):
""" Compute ... |
Compute composite array merging temporal frames according to the compositing method
:param eopatch: eopatch holding time-series
:return: eopatch with composite image of time-series
def execute(self, eopatch):
""" Compute composite array merging temporal frames according to the composit... |
Extract the NDVI band from time-series
:param data: 4D array from which to compute the NDVI reference band
:type data: numpy array
:return: 3D array containing the NDVI reference band
def _get_reference_band(self, data):
""" Extract the NDVI band from time-series
:param data: ... |
Extract the NDWI band from time-series
:param data: 4D array from which to compute the NDWI reference band
:type data: numpy array
:return: 3D array containing the NDWI reference band
def _get_reference_band(self, data):
""" Extract the NDWI band from time-series
:param data: ... |
Extract the max-ratio band from time-series
The max-ratio is defined as max(NIR,SWIR1)/BLUE
:param data: 4D array from which to compute the max-ratio reference band
:type data: numpy array
:return: 3D array containing the max-ratio reference band
def _get_reference_ban... |
Perform histogram matching of the time-series with respect to a reference scene
:param eopatch: eopatch holding the time-series and reference data
:type eopatch: EOPatch
:return: The same eopatch instance with the normalised time-series
def execute(self, eopatch):
""" Perfo... |
Checks if value fits the feature type. If not it tries to fix it or raise an error
:raises: ValueError
def _parse_feature_value(self, value):
""" Checks if value fits the feature type. If not it tries to fix it or raise an error
:raises: ValueError
"""
if isinstance(val... |
Helper method for loading old version of pickled BBox object
:param bbox: BBox object which was incorrectly loaded with pickle
:type bbox: sentinelhub.BBox
:param path: Path to file where BBox object is stored
:type path: str
:param is_zipped: `True` if file is zipped and ... |
Method which loads data from the file
def load(self):
""" Method which loads data from the file
"""
# pylint: disable=too-many-return-statements
if not os.path.isdir(self.patch_path):
raise OSError('EOPatch does not exist in path {} anymore'.format(self.patch_path))
... |
Creates a filename with file path
def get_file_path(self, path):
""" Creates a filename with file path
"""
feature_filename = self._get_filename_path(path)
feature_filename += self.file_format.extension()
if self.compress_level:
feature_filename += FileFormat... |
Helper function for creating filename without file extension
def _get_filename_path(self, path):
""" Helper function for creating filename without file extension
"""
feature_filename = os.path.join(path, self.feature_type.value)
if self.feature_name is not None:
featu... |
Method which does the saving
:param eopatch: EOPatch containing the data which will be saved
:type eopatch: EOPatch
:param use_tmp: If `True` data will be saved to temporary file, otherwise it will be saved to intended
(i.e. final) location
:type use_tmp: bool
def save(se... |
Masks values of data feature with a given mask of given mask type. The masking is done by assigning
`numpy.nan` value.
:param feature_data: Data array which will be masked
:type feature_data: numpy.ndarray
:param mask: Mask array
:type mask: numpy.ndarray
:param mask_typ... |
Find NaN values in data that either start or end the time-series
Function to return a binary array of same size as data where `True` values correspond to NaN values present at
beginning or end of time-series. NaNs internal to the time-series are not included in the binary mask.
:param data: Ar... |
Replace duplicate acquisitions which have same values on the chosen time scale with their average.
The average is calculated with numpy.nanmean, meaning that NaN values are ignored when calculating the average.
:param data: Array in a shape of t x nobs, where nobs = h x w x n
:type data: numpy.... |
Copy features from old EOPatch
:param new_eopatch: New EOPatch container where the old features will be copied to
:type new_eopatch: EOPatch
:param old_eopatch: Old EOPatch container where the old features are located
:type old_eopatch: EOPatch
:param copy_features: List of tupl... |
Interpolates data feature
:param data: Array in a shape of t x nobs, where nobs = h x w x n
:type data: numpy.ndarray
:param times: Array of reference times relative to the first timestamp
:type times: numpy.array
:param resampled_times: Array of reference times relative to the ... |
Initializes interpolation model
:param times: Array of reference times in second relative to the first timestamp
:type times: numpy.array
:param series: One dimensional array of time series
:type series: numpy.array
:return: Initialized interpolation model class
def get_interpo... |
Takes a list of timestamps and generates new list of timestamps according to ``resample_range``
:param timestamp: list of timestamps
:type timestamp: list(datetime.datetime)
:return: new list of timestamps
:rtype: list(datetime.datetime)
def get_resampled_timestamp(self, timestamp):
... |
Execute method that processes EOPatch and returns EOPatch
def execute(self, eopatch):
""" Execute method that processes EOPatch and returns EOPatch
"""
# pylint: disable=too-many-locals
feature_type, feature_name, new_feature_name = next(self.feature(eopatch))
# Make a copy not... |
Interpolates data feature
:param data: Array in a shape of t x nobs, where nobs = h x w x n
:type data: numpy.ndarray
:param times: Array of reference times in second relative to the first timestamp
:type times: numpy.array
:param resampled_times: Array of reference times in sec... |
Initializes interpolation model
:param times: Array of reference times in second relative to the first timestamp
:type times: numpy.array
:param data: One dimensional array of time series
:type data: numpy.array
:return: Initialized interpolation model class
def get_interpolati... |
return inner text in pyquery element
def get_text(element):
''' return inner text in pyquery element '''
_add_links_to_text(element)
try:
return element.text(squash_space=False)
except TypeError:
return element.text() |
Simple wrapper around urlretrieve that uses tqdm to display a progress
bar of download progress
def download_file(url, local_filename):
""" Simple wrapper around urlretrieve that uses tqdm to display a progress
bar of download progress """
local_filename = os.path.abspath(local_filename)
path = os.... |
Try to find GCC on OSX for OpenMP support.
def extract_gcc_binaries():
"""Try to find GCC on OSX for OpenMP support."""
patterns = ['/opt/local/bin/g++-mp-[0-9].[0-9]',
'/opt/local/bin/g++-mp-[0-9]',
'/usr/local/bin/g++-[0-9].[0-9]',
'/usr/local/bin/g++-[0-9]']
... |
Try to use GCC on OSX for OpenMP support.
def set_gcc():
"""Try to use GCC on OSX for OpenMP support."""
# For macports and homebrew
if 'darwin' in platform.platform().lower():
gcc = extract_gcc_binaries()
if gcc is not None:
os.environ["CC"] = gcc
os.environ["CXX"... |
returns the non zeroes of a row in csr_matrix
def nonzeros(m, row):
""" returns the non zeroes of a row in csr_matrix """
for index in range(m.indptr[row], m.indptr[row+1]):
yield m.indices[index], m.data[index] |
checks to see if using OpenBlas/Intel MKL. If so, warn if the number of threads isn't set
to 1 (causes severe perf issues when training - can be 10x slower)
def check_blas_config():
""" checks to see if using OpenBlas/Intel MKL. If so, warn if the number of threads isn't set
to 1 (causes severe perf issues... |
Reads the original dataset PSV as a pandas dataframe
def _read_dataframe(filename):
""" Reads the original dataset PSV as a pandas dataframe """
import pandas
# read in triples of user/artist/playcount from the input dataset
# get a model based off the input params
start = time.time()
log.debu... |
Returns the lastfm360k dataset, downloading locally if necessary.
Returns a tuple of (artistids, userids, plays) where plays is a CSR matrix
def get_lastfm():
""" Returns the lastfm360k dataset, downloading locally if necessary.
Returns a tuple of (artistids, userids, plays) where plays is a CSR matrix """... |
factorizes the matrix Cui using an implicit alternating least squares
algorithm. Note: this method is deprecated, consider moving to the
AlternatingLeastSquares class instead
def alternating_least_squares(Ciu, factors, **kwargs):
""" factorizes the matrix Cui using an implicit alternating least squares
... |
For each user in Cui, calculate factors Xu for them
using least squares on Y.
Note: this is at least 10 times slower than the cython version included
here.
def least_squares(Cui, X, Y, regularization, num_threads=0):
""" For each user in Cui, calculate factors Xu for them
using least squares on Y.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.