Class SparseVector
- All Implemented Interfaces:
Serializable,Iterable<VectorTuple>,SGDVector,Tensor,ProtoSerializable<org.tribuo.math.protos.TensorProto>
Uses binary search to look up a specific index, so it's usually faster to use the iterator to iterate the values.
This vector has immutable indices. It cannot get new indices after construction,
and will throw IllegalArgumentException if such an operation is tried.
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intProtobuf serialization version.protected final int[]The indices array.protected final double[]The values array.Fields inherited from interface org.tribuo.protos.ProtoSerializable
DESERIALIZATION_METHOD_NAME, PROVENANCE_SERIALIZER -
Constructor Summary
ConstructorsConstructorDescriptionSparseVector(int size, int[] indices, double value) Creates a sparse vector of the specified size, with the supplied value at each of the indices. -
Method Summary
Modifier and TypeMethodDescriptionvoidadd(int index, double value) Addsvalueto the element atindex.Addsotherto this vector, producing a newSGDVector.copy()Returns a deep copy of this vector.static SparseVectorcreateSparseVector(int dimension, int[] indices, double[] values) Defensively copies the input, and checks that the indices are sorted.static SparseVectorcreateSparseVector(int dimension, Map<Integer, Double> indexMap) Builds a SparseVector from a map.static <T extends Output<T>>
SparseVectorcreateSparseVector(Example<T> example, ImmutableFeatureMap featureInfo, boolean addBias) Builds aSparseVectorfrom anExample.densify()Returns a dense vector copying this sparse vector.static SparseVectordeserializeFromProto(int version, String className, com.google.protobuf.Any message) Deserialization factory.int[]difference(SparseVector other) Generates an array of the indices that are active in this vector but are not present inother.doubledistance(SGDVector other, DoubleUnaryOperator transformFunc, DoubleUnaryOperator normalizeFunc) Computes the distance between this vector and the other vector.doubleCalculates the dot product between this vector andother.booleanEquals is defined mathematically, that is two SGDVectors are equal iff they have the same indices and the same values at those indices.doubleeuclideanDistance(SGDVector other) The l2 or euclidean distance between this vector and the other vector.voidApplies aToDoubleBiFunctionelementwise to thisSGDVector.voidApplies aDoubleUnaryOperatorelementwise to thisSGDVector.doubleget(int index) Gets an element from this vector.int[]getShape()Returns an int array specifying the shape of thisTensor.voidhadamardProductInPlace(Tensor other, DoubleUnaryOperator f) Updates thisTensorwith the Hadamard product (i.e., a term by term multiply) of this andother.inthashCode()intReturns the index of the maximum value.voidintersectAndAddInPlace(Tensor other, DoubleUnaryOperator f) Updates thisTensorby adding all the values from the intersection withother.int[]intersection(SparseVector other) Generates an array of the indices that are active in both this vector andotheriterator()doublel1Distance(SGDVector other) The l1 or Manhattan distance between this vector and the other vector.doublemaxValue()Returns the maximum value.doubleminValue()Returns the minimum value.voidnormalize(VectorNormalizer normalizer) Normalizes the vector using the supplied vector normalizer.intReturns the number of non-zero elements (on construction, an element could be set to zero and it would still remain active).doubleoneNorm()Calculates the Manhattan norm for this vector.This generates the outer product when dotted with anotherSparseVector.doublereduce(double initial, DoubleUnaryOperator transform, DoubleBinaryOperator reduction) Reduces the vector, applying the transformation to every value (including the implicit zeros) and reducing the output by applying the supplied reduction operator (where the right argument is the current reduction value, and the left argument is the transformed value).reshape(int[] newShape) Reshapes the Tensor to the supplied shape.scale(double coefficient) Generates a new vector with each element scaled bycoefficient.org.tribuo.math.protos.TensorProtoSerializes this object to a protobuf.voidset(int index, double value) Sets theindexto thevalue.intsize()Returns the dimensionality of this vector.Subtractsotherfrom this vector, producing a newSGDVector.doublesum()Calculates the sum of this vector.double[]toArray()Returns an array containing all the values in the vector (including any implicit zeros).double[]Deprecated.toString()static <T extends Output<T>>
SparseVector[]Converts a dataset of row-major examples into an array of column-major sparse vectors.static <T extends Output<T>>
SparseVector[]transpose(Dataset<T> dataset, ImmutableFeatureMap fMap) Converts a dataset of row-major examples into an array of column-major sparse vectors.static SparseVector[]transpose(SparseVector[] input) Transposes an array of sparse vectors from row-major to column-major or vice versa.doubletwoNorm()Calculates the euclidean norm for this vector.doublevariance(double mean) Calculates the variance of this vector based on the supplied mean.Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, waitMethods inherited from interface java.lang.Iterable
forEach, spliteratorMethods inherited from interface org.tribuo.math.la.SGDVector
cosineDistance, cosineSimilarity, l2Distance, varianceMethods inherited from interface org.tribuo.math.la.Tensor
hadamardProductInPlace, intersectAndAddInPlace, scalarAddInPlace, scaleInPlace
-
Field Details
-
CURRENT_VERSION
public static final int CURRENT_VERSIONProtobuf serialization version.- See Also:
-
indices
protected final int[] indicesThe indices array. -
values
protected final double[] valuesThe values array.
-
-
Constructor Details
-
SparseVector
public SparseVector(int size, int[] indices, double value) Creates a sparse vector of the specified size, with the supplied value at each of the indices.- Parameters:
size- The vector size.indices- The active indices.value- The value for those indices.
-
-
Method Details
-
createSparseVector
public static <T extends Output<T>> SparseVector createSparseVector(Example<T> example, ImmutableFeatureMap featureInfo, boolean addBias) Builds aSparseVectorfrom anExample.Used in training and inference.
Throws
IllegalArgumentExceptionif the Example contains NaN-valued features.- Type Parameters:
T- The type parameter of theexample.- Parameters:
example- The example to convert.featureInfo- The feature information, used to calculate the dimension of this SparseVector.addBias- Add a bias feature.- Returns:
- A SparseVector representing the example's features.
-
createSparseVector
Defensively copies the input, and checks that the indices are sorted. If not, it sorts them.Throws
IllegalArgumentExceptionif the arrays are not the same length, or if size is less than the max index.- Parameters:
dimension- The dimension of this vector.indices- The indices of the non-zero elements.values- The values of the non-zero elements.- Returns:
- A SparseVector encapsulating the indices and values.
-
createSparseVector
Builds a SparseVector from a map.Throws
IllegalArgumentExceptionif dimension is less than the max index.- Parameters:
dimension- The dimension of this vector.indexMap- The map from indices to values.- Returns:
- A SparseVector.
-
deserializeFromProto
public static SparseVector deserializeFromProto(int version, String className, com.google.protobuf.Any message) throws com.google.protobuf.InvalidProtocolBufferException Deserialization factory.- Parameters:
version- The serialized object version.className- The class name.message- The serialized data.- Returns:
- The deserialized object.
- Throws:
com.google.protobuf.InvalidProtocolBufferException- If the protobuf could not be parsed from themessage.
-
serialize
public org.tribuo.math.protos.TensorProto serialize()Description copied from interface:ProtoSerializableSerializes this object to a protobuf.- Specified by:
serializein interfaceProtoSerializable<org.tribuo.math.protos.TensorProto>- Returns:
- The protobuf.
-
copy
-
getShape
-
reshape
Description copied from interface:TensorReshapes the Tensor to the supplied shape. ThrowsIllegalArgumentExceptionif the shape isn't compatible. -
size
-
numActiveElements
public int numActiveElements()Description copied from interface:SGDVectorReturns the number of non-zero elements (on construction, an element could be set to zero and it would still remain active).- Specified by:
numActiveElementsin interfaceSGDVector- Returns:
- The number of non-zero elements.
-
equals
Equals is defined mathematically, that is two SGDVectors are equal iff they have the same indices and the same values at those indices. -
hashCode
-
add
Addsotherto this vector, producing a newSGDVector. Ifotheris aSparseVectorthen the returned vector is also aSparseVectorotherwise it's aDenseVector. -
subtract
Subtractsotherfrom this vector, producing a newSGDVector. Ifotheris aSparseVectorthen the returned vector is also aSparseVectorotherwise it's aDenseVector. -
intersectAndAddInPlace
Description copied from interface:TensorUpdates thisTensorby adding all the values from the intersection withother.The function
fis applied to all values fromotherbefore the addition.Each value is updated as value += f(otherValue).
- Specified by:
intersectAndAddInPlacein interfaceTensor- Parameters:
other- The otherTensor.f- A function to apply.
-
hadamardProductInPlace
Description copied from interface:TensorUpdates thisTensorwith the Hadamard product (i.e., a term by term multiply) of this andother.The function
fis applied to all values fromotherbefore the addition.Each value is updated as value *= f(otherValue).
- Specified by:
hadamardProductInPlacein interfaceTensor- Parameters:
other- The otherTensor.f- A function to apply.
-
foreachInPlace
Applies aDoubleUnaryOperatorelementwise to thisSGDVector.Only applies the function to the elements which are present.
If you need to operate over the whole vector then densify it first.
- Specified by:
foreachInPlacein interfaceTensor- Parameters:
f- The function to apply.
-
foreachIndexedInPlace
Applies aToDoubleBiFunctionelementwise to thisSGDVector.The first argument to the function is the index, the second argument is the current value.
Only applies the function to the elements which are present.
If you need to operate over the whole vector then densify it first.
- Specified by:
foreachIndexedInPlacein interfaceSGDVector- Parameters:
f- The function to apply.
-
scale
Description copied from interface:SGDVectorGenerates a new vector with each element scaled bycoefficient. -
add
-
dot
-
outer
This generates the outer product when dotted with anotherSparseVector.It throws an
IllegalArgumentExceptionif used with aDenseVector.- Specified by:
outerin interfaceSGDVector- Parameters:
other- A vector.- Returns:
- A
DenseSparseMatrixrepresenting the outer product.
-
sum
-
twoNorm
-
oneNorm
-
get
-
set
-
indexOfMax
public int indexOfMax()Description copied from interface:SGDVectorReturns the index of the maximum value. Requires probing the array.- Specified by:
indexOfMaxin interfaceSGDVector- Returns:
- The index of the maximum value.
-
maxValue
-
minValue
-
difference
Generates an array of the indices that are active in this vector but are not present inother.- Parameters:
other- The vector to compare.- Returns:
- An array of indices that are active only in this vector.
-
intersection
Generates an array of the indices that are active in both this vector andother- Parameters:
other- The vector to intersect.- Returns:
- An array of indices that are active in both vectors.
-
normalize
Description copied from interface:SGDVectorNormalizes the vector using the supplied vector normalizer. -
reduce
Description copied from interface:SGDVectorReduces the vector, applying the transformation to every value (including the implicit zeros) and reducing the output by applying the supplied reduction operator (where the right argument is the current reduction value, and the left argument is the transformed value). The reduction operation is seeded with the initial value. -
euclideanDistance
Description copied from interface:SGDVectorThe l2 or euclidean distance between this vector and the other vector.- Specified by:
euclideanDistancein interfaceSGDVector- Parameters:
other- The other vector.- Returns:
- The euclidean distance between them.
-
l1Distance
Description copied from interface:SGDVectorThe l1 or Manhattan distance between this vector and the other vector.- Specified by:
l1Distancein interfaceSGDVector- Parameters:
other- The other vector.- Returns:
- The l1 distance.
-
distance
public double distance(SGDVector other, DoubleUnaryOperator transformFunc, DoubleUnaryOperator normalizeFunc) Computes the distance between this vector and the other vector.- Parameters:
other- The other vector.transformFunc- The transformation function to apply to each paired dimension difference.normalizeFunc- The normalization to apply after summing the transformed differences.- Returns:
- The distance between the two vectors.
-
toString
-
densify
Returns a dense vector copying this sparse vector.- Returns:
- A dense copy of this vector.
-
toDenseArray
Deprecated.Generates a dense array copy of this SparseVector.- Returns:
- A dense array containing this vector along with the implicit zeros.
-
toArray
-
variance
-
iterator
- Specified by:
iteratorin interfaceIterable<VectorTuple>
-
transpose
Transposes an array of sparse vectors from row-major to column-major or vice versa.- Parameters:
input- Input sparse vectors.- Returns:
- A column-major array of SparseVectors.
-
transpose
Converts a dataset of row-major examples into an array of column-major sparse vectors.- Type Parameters:
T- The type of the dataset.- Parameters:
dataset- Input dataset.- Returns:
- A column-major array of SparseVectors.
-
transpose
public static <T extends Output<T>> SparseVector[] transpose(Dataset<T> dataset, ImmutableFeatureMap fMap) Converts a dataset of row-major examples into an array of column-major sparse vectors.- Type Parameters:
T- The type of the dataset.- Parameters:
dataset- Input dataset.fMap- The feature map to use. If it's different to the feature map used by the dataset then behaviour is undefined.- Returns:
- A column-major array of SparseVectors.
-