@frozen
public struct Tensor<Scalar> where Scalar : TensorFlowScalar
extension Tensor: Collatable
extension Tensor: CopyableToDevice
extension Tensor: AnyTensor
extension Tensor: ExpressibleByArrayLiteral
extension Tensor: CustomStringConvertible
extension Tensor: CustomPlaygroundDisplayConvertible
extension Tensor: CustomReflectable
extension Tensor: TensorProtocol
extension Tensor: TensorGroup
extension Tensor: ElementaryFunctions where Scalar: TensorFlowFloatingPoint
extension Tensor: VectorProtocol where Scalar: TensorFlowFloatingPoint
extension Tensor: Mergeable where Scalar: TensorFlowFloatingPoint
extension Tensor: Equatable where Scalar: Equatable
extension Tensor: Codable where Scalar: Codable
extension Tensor: AdditiveArithmetic where Scalar: Numeric
extension Tensor: PointwiseMultiplicative where Scalar: Numeric
extension Tensor: Differentiable & EuclideanDifferentiable where Scalar: TensorFlowFloatingPoint
extension Tensor: DifferentiableTensorProtocol
where Scalar: TensorFlowFloatingPoint
Um array multidimensional de elementos que é uma generalização de vetores e matrizes para dimensões potencialmente mais altas.
O parâmetro genérico Scalar
descreve o tipo de escalares do tensor (tais como Int32
, Float
, etc).
O subjacente
TensorHandle
.Observação
handle
é público para permitir ops definidos pelo usuário, mas não deve ser utilizado normalmente.Declaração
public let handle: TensorHandle<Scalar>
Declaração
public init(handle: TensorHandle<Scalar>)
Desembala a dimensão dada de um rank
R
tensor em rank múltipla(R-1)
tensores. DesembalaN
tensores deste tensor por lascar-lo ao longo doaxis
dimensão, ondeN
é inferida a partir da forma este tensor. Por exemplo, dado um tensor com a forma[A, B, C, D]
:- Se
axis == 0
, em seguida, oi
-simo tensor na matriz retornada é a fatiaself[i, :, :, :]
e cada tensor em que matriz terá forma[B, C, D]
. (Note-se que a dimensão não embalada ao longo se foi, ao contrárioTensor.split(numSplits:alongAxis)
, ouTensor.split(sizes:alongAxis)
). - Se
axis == 1
, em seguida, oi
-simo tensor na matriz retornada é a fatiavalue[:, i, :, :]
e cada tensor em que matriz terá forma[A, C, D]
. - Etc.
Este é o oposto do
Tensor.init(stacking:alongAxis:)
.Condição prévia
axis
deve estar no intervalo[-rank, rank)
, onderank
é a classificação dos tensores previstos.Declaração
@differentiable public func unstacked(alongAxis axis: Int = 0) -> [Tensor]
Parâmetros
axis
Dimensão ao longo da qual desempilhar. Os valores negativos são agrupados.
Valor de retorno
Array contendo os tensores desempilhados.
- Se
Divide um tensor em vários tensores. O tensor é dividido ao longo da dimensão
axis
emcount
tensores menores. Isto requer quecount
uniformemente divideshape[axis]
.Por exemplo:
// 'value' is a tensor with shape [5, 30] // Split 'value' into 3 tensors along dimension 1: let parts = value.split(count: 3, alongAxis: 1) parts[0] // has shape [5, 10] parts[1] // has shape [5, 10] parts[2] // has shape [5, 10]
Condição prévia
count
deve dividir o tamanho da dimensãoaxis
uniformemente.Condição prévia
axis
deve estar no intervalo[-rank, rank)
, onderank
é a classificação dos tensores previstos.Declaração
@differentiable public func split(count: Int, alongAxis axis: Int = 0) -> [Tensor]
Parâmetros
count
Número de divisões a serem criadas.
axis
A dimensão ao longo da qual dividir este tensor. Os valores negativos são agrupados.
Valor de retorno
Uma matriz contendo a parte dos tensores.
Divide um tensor em vários tensores. O tensor é dividido em
sizes.shape[0]
peças. A forma doi
peça -ésimo tem a mesma forma que este tensor excepto ao longo dimensãoaxis
, onde o tamanho ésizes[i]
.Por exemplo:
// 'value' is a tensor with shape [5, 30] // Split 'value' into 3 tensors with sizes [4, 15, 11] along dimension 1: let parts = value.split(sizes: Tensor<Int32>([4, 15, 11]), alongAxis: 1) parts[0] // has shape [5, 4] parts[1] // has shape [5, 15] parts[2] // has shape [5, 11]
Condição prévia
Os valores em
sizes
devem somar o tamanho da dimensãoaxis
.Condição prévia
axis
deve estar no intervalo[-rank, rank)
, onderank
é a classificação dos tensores previstos.Declaração
@differentiable(wrt: self) public func split(sizes: Tensor<Int32>, alongAxis axis: Int = 0) -> [Tensor]
Parâmetros
sizes
Tensor 1-D contendo o tamanho de cada divisão.
axis
Dimensão ao longo da qual dividir este tensor. Os valores negativos são agrupados.
Valor de retorno
Array contendo as partes dos tensores.
Declaração
@differentiable(wrt: self) public func split(sizes: [Int], alongAxis axis: Int = 0) -> [Tensor]
Retorna um tensor lado a lado, construído ao lado desse tensor.
Este construtor cria um novo tensor, replicando esse tensor
multiples
vezes. O tensor é construídoi
'th dimensão temself.shape[i] * multiples[i]
elementos, e os valores deste tensor são replicadosmultiples[i]
vezes ao longo dai
' th dimensão. Por exemplo, a telha[abcd]
por[2]
produz[abcdabcd]
.Condição prévia
A forma demultiples
deve ser[tensor.rank]
.Condição prévia
Todos os escalares emmultiples
devem ser não-negativo.Declaração
@differentiable(wrt: self) public func tiled(multiples: [Int]) -> Tensor
Retorna um tensor lado a lado, construído ao lado desse tensor.
Este construtor cria um novo tensor, replicando esse tensor
multiples
vezes. O tensor é construídoi
'th dimensão temself.shape[i] * multiples[i]
elementos, e os valores deste tensor são replicadosmultiples[i]
vezes ao longo dai
' th dimensão. Por exemplo, a telha[abcd]
por[2]
produz[abcdabcd]
.Condição prévia
A forma demultiples
deve ser[tensor.rank]
.Declaração
@differentiable(wrt: self) public func tiled(multiples: Tensor<Int32>) -> Tensor
Alterar forma para a forma do especificado
Tensor
.Condição prévia
O número de escalares corresponde à nova forma.Declaração
@differentiable(wrt: self) public func reshaped<T>(like other: Tensor<T>) -> Tensor where T : TensorFlowScalar
Remodele para a forma especificada.
Condição prévia
O número de escalares corresponde à nova forma.Declaração
@differentiable(wrt: self) public func reshaped(to newShape: TensorShape) -> Tensor
Alterar forma ao especificado
Tensor
representando uma forma de.Condição prévia
O número de escalares corresponde à nova forma.Declaração
@differentiable(wrt: self) public func reshaped(toShape newShape: Tensor<Int32>) -> Tensor
Devolver uma cópia do tensor de colapso em uma 1-D
Tensor
, a fim de linha maior.Declaração
@differentiable(wrt: self) public func flattened() -> Tensor
Devolve uma expandida em forma de
Tensor
, com uma dimensão de 1 inserido nos índices forma especificada.Declaração
@differentiable(wrt: self) public func expandingShape(at axes: Int...) -> Tensor
Devolve uma expandida em forma de
Tensor
, com uma dimensão de 1 inserido nos índices forma especificada.Declaração
@differentiable(wrt: self) public func expandingShape(at axes: [Int]) -> Tensor
Retorna uma levantou-rank
Tensor
com uma dimensão líder de 1.Declaração
@differentiable(wrt: self) public func rankLifted() -> Tensor
Remove as dimensões especificadas de tamanho 1 da forma de um tensor. Se nenhuma dimensão for especificada, todas as dimensões de tamanho 1 serão removidas.
Declaração
@differentiable(wrt: self) public func squeezingShape(at axes: Int...) -> Tensor
Remove as dimensões especificadas de tamanho 1 da forma de um tensor. Se nenhuma dimensão for especificada, todas as dimensões de tamanho 1 serão removidas.
Declaração
@differentiable(wrt: self) public func squeezingShape(at axes: [Int]) -> Tensor
Retorna um tensor transposto, com dimensões permutadas na ordem especificada.
Declaração
@differentiable(wrt: self) public func transposed(permutation: Tensor<Int32>) -> Tensor
Retorna um tensor transposto, com dimensões permutadas na ordem especificada.
Declaração
@available(*, deprecated, renamed: "transposed(permutation:﹚") @differentiable(wrt: self) public func transposed(withPermutations permutations: Tensor<Int32>) -> Tensor
Retorna um tensor transposto, com dimensões permutadas na ordem especificada.
Declaração
@differentiable(wrt: self) public func transposed(permutation: [Int]) -> Tensor
Retorna um tensor transposto, com dimensões permutadas na ordem especificada.
Declaração
@available(*, deprecated, renamed: "transposed(permutation:﹚") @differentiable(wrt: self) public func transposed(withPermutations permutations: [Int]) -> Tensor
Retorna um tensor transposto, com dimensões permutadas na ordem especificada.
Declaração
@differentiable(wrt: self) public func transposed(permutation: Int...) -> Tensor
Retorna um tensor transposto, com dimensões permutadas na ordem especificada.
Declaração
@available(*, deprecated, renamed: "transposed(permutation:﹚") @differentiable(wrt: self) public func transposed(withPermutations permutations: Int...) -> Tensor
Retorna um tensor transposto, com dimensões permutadas na ordem reversa.
Declaração
@differentiable(wrt: self) public func transposed() -> Tensor
Retorna um tensor com as dimensões especificadas invertidas.
Condição prévia
Cada valor emaxes
devem estar na faixa-rank..<rank
.Condição prévia
Não deve haver duplicação deaxes
.Declaração
@differentiable(wrt: self) public func reversed(inAxes axes: Tensor<Int32>) -> Tensor
Retorna um tensor com as dimensões especificadas invertidas.
Condição prévia
Cada valor emaxes
devem estar na faixa-rank..<rank
.Condição prévia
Não deve haver duplicação deaxes
.Declaração
@differentiable(wrt: self) public func reversed(inAxes axes: [Int]) -> Tensor
Retorna um tensor com as dimensões especificadas invertidas.
Condição prévia
Cada valor emaxes
devem estar na faixa-rank..<rank
.Condição prévia
Não deve haver duplicação deaxes
.Declaração
@differentiable(wrt: self) public func reversed(inAxes axes: Int...) -> Tensor
Retorna um tensor concatenado ao longo do eixo especificado.
Condição prévia
Os tensores devem ter as mesmas dimensões, exceto para o eixo especificado.Condição prévia
O eixo deve estar na faixa-rank..<rank
.Declaração
@differentiable public func concatenated(with other: Tensor, alongAxis axis: Int = 0) -> Tensor
Operador de concatenação.
Observação
++
é um operador personalizado que não existe no Swift, mas faz em Haskell / Scala. Sua adição não é uma alteração insignificante da linguagem e pode ser controversa. A existência / nomeando de++
serão discutidos durante a fase de projeto API mais tarde.Declaração
@differentiable public static func ++ (lhs: Tensor, rhs: Tensor) -> Tensor
Retorna um tensor através da recolha de fatias de entrada em
indices
ao longo doaxis
dimensãoPara 0-D (escalares)
indices
:result[p_0, ..., p_{axis-1}, p_{axis + 1}, ..., p_{N-1}] = self[p_0, ..., p_{axis-1}, indices, p_{axis + 1}, ..., p_{N-1}]
Para 1-D (vector)
indices
:result[p_0, ..., p_{axis-1}, i, p_{axis + 1}, ..., p_{N-1}] = self[p_0, ..., p_{axis-1}, indices[i], p_{axis + 1}, ..., p_{N-1}]
No caso geral, produz um tensor resultante onde:
result[p_0, ..., p_{axis-1}, i_{batch\_dims}, ..., i_{M-1}, p_{axis + 1}, ..., p_{N-1}] = self[p_0, ..., p_{axis-1}, indices[i_0, ..., i_{M-1}], p_{axis + 1}, ..., p_{N-1}]
onde
N = self.rank
eM = indices.rank
.A forma do tensor resultante é:
self.shape[..<axis] + indices.shape + self.shape[(axis + 1)...]
.Observação
Na CPU, se um índice fora do intervalo for encontrado, um erro será gerado. Na GPU, se um índice fora do intervalo for encontrado, um 0 é armazenado nos valores de saída correspondentes.
Condição prévia
axis
deve estar no intervalo[-rank, rank)
.Declaração
@differentiable(wrt: self) public func gathering<Index: TensorFlowIndex>( atIndices indices: Tensor<Index>, alongAxis axis: Int = 0 ) -> Tensor
Parâmetros
indices
Contém os índices a serem reunidos.
axis
Dimensão ao longo da qual reunir. Os valores negativos são agrupados.
Valor de retorno
O tensor reunido.
Retornos fatias de este tensor em
indices
ao longo doaxis
dimensão, enquanto ignoram os primeirosbatchDimensionCount
dimensões que correspondem às dimensões de lote. A coleta é executada ao longo da primeira dimensão sem lote.Realiza funcionalidade semelhante a
gathering
, a não ser que a forma tensor resultante é agorashape[..<axis] + indices.shape[batchDimensionCount...] + shape[(axis + 1)...]
.Condição prévia
axis
deve estar na gama-rank..<rank
, enquanto também é maior do que ou igual abatchDimensionCount
.Condição prévia
batchDimensionCount
deve ser inferior aindices.rank
.Declaração
@differentiable(wrt: self) public func batchGathering<Index: TensorFlowIndex>( atIndices indices: Tensor<Index>, alongAxis axis: Int = 1, batchDimensionCount: Int = 1 ) -> Tensor
Parâmetros
indices
Contém os índices a serem coletados.
axis
Dimensão ao longo da qual reunir. Os valores negativos são agrupados.
batchDimensionCount
Número de dimensões de lote principais a serem ignoradas.
Valor de retorno
O tensor reunido.
Retorna um tensor reunindo os valores após aplicar a máscara booleana fornecida à entrada.
Por exemplo:
// 1-D example // tensor is [0, 1, 2, 3] // mask is [true, false, true, false] tensor.gathering(where: mask) // is [0, 2] // 2-D example // tensor is [[1, 2], [3, 4], [5, 6]] // mask is [true, false, true] tensor.gathering(where: mask) // is [[1, 2], [5, 6]]
Em geral,
0 < mask.rank = K <= tensor.rank
, eamask
da forma deve coincidir com as primeiras dimensões K dotensor
da forma. Temos então:tensor.gathering(where: mask)[i, j1, ..., jd] = tensor[i1, ..., iK, j1, ..., jd]
, onde[i1, ..., iK]
é oi
thtrue
entrada demask
(ordem de linha principal).O
axis
pode ser usado commask
para indicar o eixo para mascarar a partir. Nesse caso,axis + mask.rank <= tensor.rank
eamask
's shape must match the first
eixos + mask.rankdimensions of the
forma de tensor`.Condição prévia
A
mask
não pode ser um escalar:mask.rank != 0
.Declaração
@differentiable(wrt: self) public func gathering(where mask: Tensor<Bool>, alongAxis axis: Int = 0) -> Tensor
Parâmetros
mask
KD booleano tensor, onde
K <= self.rank
.axis
0 D-tensor número inteiro que representa o eixo de
self
para mascarar a partir de, em queK + axis <= self.rank
.Valor de retorno
(self.rank - K + 1)
tensor -dimensional povoada por entradas neste tensor correspondentes aostrue
valores namask
.Retorna as localizações de valores diferentes de zero / verdadeiros neste tensor.
As coordenadas são retornadas em um tensor 2-D onde a primeira dimensão (linhas) representa o número de elementos diferentes de zero e a segunda dimensão (colunas) representa as coordenadas dos elementos diferentes de zero. Lembre-se de que a forma do tensor de saída pode variar dependendo de quantos valores verdadeiros existem neste tensor. Os índices são produzidos na ordem maior da linha.
Por exemplo:
// 'input' is [[true, false], [true, false]] // 'input' has 2 true values and so the output has 2 rows. // 'input' has rank of 2, and so the second dimension of the output has size 2. input.nonZeroIndices() // is [[0, 0], [1, 0]] // 'input' is [[[ true, false], [ true, false]], // [[false, true], [false, true]], // [[false, false], [false, true]]] // 'input' has 5 true values and so the output has 5 rows. // 'input' has rank 3, and so the second dimension of the output has size 3. input.nonZeroIndices() // is [[0, 0, 0], // [0, 1, 0], // [1, 0, 1], // [1, 1, 1], // [2, 1, 1]]
Declaração
public func nonZeroIndices() -> Tensor<Int64>
Valor de retorno
Um tensor com forma
(num_true, rank(condition))
.Declaração
@differentiable(wrt: self) public func broadcasted(toShape shape: Tensor<Int32>) -> Tensor
Declaração
@differentiable(wrt: self) public func broadcasted(to shape: TensorShape) -> Tensor
Broadcast para a mesma forma que o especificado
Tensor
.Condição prévia
A forma especificada deve ser compatível para transmissão.Declaração
@differentiable(wrt: self) public func broadcasted<OtherScalar>(like other: Tensor<OtherScalar>) -> Tensor where OtherScalar : TensorFlowScalar
Declaração
public static func .= (lhs: inout Tensor, rhs: Tensor)
Extrai uma fatia do tensor definido pelos limites inferior e superior de cada dimensão.
Declaração
@differentiable(wrt: self) public func slice(lowerBounds: [Int], upperBounds: [Int]) -> Tensor
Parâmetros
lowerBounds
Os limites inferiores em cada dimensão.
upperBounds
Os limites superiores em cada dimensão.
Declaração
@differentiable(wrt: self) public func slice(lowerBounds: Tensor<Int32>, sizes: Tensor<Int32>) -> Tensor
Declaração
@differentiable(wrt: self) public func slice(lowerBounds: [Int], sizes: [Int]) -> Tensor
Declaração
@differentiable(wrt: self) public subscript(ranges: TensorRangeExpression...) -> Tensor { get set }
Verifica que cada elemento de
axes
indica um eixo deself
, e interrompe o programa com um diagnóstico de outra forma.Declaração
func ensureValid( axes: Tensor<Int32>, function: StaticString = #function, file: StaticString = #file, line: UInt = #line )
Verifica que cada elemento de
axes
indica um eixo deself
, e interrompe o programa com um diagnóstico de outra forma.Declaração
func ensureValid( axes: [Int], function: StaticString = #function, file: StaticString = #file, line: UInt = #line )
Verifica que
k
indica um eixo deself
, e interrompe o programa com um diagnóstico de outra forma.Declaração
func ensureValid( axis k: Int, function: StaticString = #function, file: StaticString = #file, line: UInt = #line )
Declaração
public init<BatchSamples: Collection>(collating samples: BatchSamples) where BatchSamples.Element == Self
Cria um tensor com a forma especificada e um único valor escalar repetido.
Declaração
@available(*, deprecated, renamed: "init(repeating:shape:﹚") public init(shape: TensorShape, repeating repeatedValue: Scalar)
Parâmetros
shape
As dimensões do tensor.
repeatedValue
O valor escalar a ser repetido.
Cria um tensor com a forma especificada e um único valor escalar repetido.
Declaração
@differentiable public init( repeating repeatedValue: Scalar, shape: TensorShape, on device: Device = .default )
Parâmetros
repeatedValue
O valor escalar a ser repetido.
shape
As dimensões do tensor.
Cria um tensor transmitindo o escalar fornecido para uma determinada classificação com todas as dimensões sendo 1.
Declaração
public init(broadcasting scalar: Scalar, rank: Int, on device: Device = .default)
Cria um tensor a partir de uma matriz de tensores (que podem ser escalares).
Declaração
@differentiable public init(_ elements: [Tensor])
Pilhas
tensors
, ao longo doaxis
dimensão, para um novo posto tensor com um mais elevado do que o tensor de corrente e cada tensor emtensors
.Dado que
tensors
têm forma[A, B, C]
, etensors.count = N
, então:- Se
axis == 0
, em seguida, o tensor resultante terá a forma[N, A, B, C]
. - Se
axis == 1
, em seguida, o tensor resultante terá a forma[A, N, B, C]
. - etc.
Por exemplo:
// 'x' is [1, 4] // 'y' is [2, 5] // 'z' is [3, 6] Tensor(stacking: [x, y, z]) // is [[1, 4], [2, 5], [3, 6]] Tensor(stacking: [x, y, z], alongAxis: 1) // is [[1, 2, 3], [4, 5, 6]]
Isto é o oposto do
Tensor.unstacked(alongAxis:)
.Condição prévia
Todos os tensores devem ter a mesma forma.
Condição prévia
axis
deve estar no intervalo[-rank, rank)
, onderank
é a classificação dos tensores previstos.Declaração
@differentiable public init(stacking tensors: [Tensor], alongAxis axis: Int = 0)
Parâmetros
tensors
Tensores para empilhar.
axis
Dimensão ao longo da qual empilhar. Os valores negativos são agrupados.
Valor de retorno
O tensor empilhado.
- Se
Concatenates
tensors
ao longo doaxis
dimensão.Dado que
tensors[i].shape = [D0, D1, ... Daxis(i), ...Dn]
, então o resultado concatenado tem a forma[D0, D1, ... Raxis, ...Dn]
, ondeRaxis = sum(Daxis(i))
. Ou seja, os dados dos tensores de entrada é acompanhado ao longo doaxis
dimensão.Por exemplo:
// t1 is [[1, 2, 3], [4, 5, 6]] // t2 is [[7, 8, 9], [10, 11, 12]] Tensor(concatenating: [t1, t2]) // is [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] Tensor(concatenating: [t1, t2], alongAxis: 1) // is [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]] // t3 has shape [2, 3] // t4 has shape [2, 3] Tensor(concatenating: [t3, t4]) // has shape [4, 3] Tensor(concatenating: [t3, t4], alongAxis: 1) // has shape [2, 6]
Observação
Se você está concatenando ao longo de um novo eixo considerar o uso
Tensor.init(stacking:alongAxis:)
.Condição prévia
Todos os tensores devem ter o mesmo valor e todas as dimensões, exceto
axis
devem ser iguais.Condição prévia
axis
deve estar no intervalo[-rank, rank)
, onderank
é a classificação dos tensores previstos.Declaração
@differentiable public init(concatenating tensors: [Tensor], alongAxis axis: Int = 0)
Parâmetros
tensors
Tensores para concatenar.
axis
Dimensão ao longo da qual concatenar. Os valores negativos são agrupados.
Valor de retorno
O tensor concatenado.
Substitui elementos deste tensor com
other
nas pistas, ondemask
étrue
.Condição prévia
self
eother
deve ter a mesma forma. Seself
eother
são escalares, entãomask
também deve ser escalar. Seself
eother
têm classificação maior do que ou igual a1
, entãomask
deve ser ou têm a mesma forma comoself
ou ser um 1-DTensor
de tal modo quemask.scalarCount == self.shape[0]
.Declaração
@differentiable(wrt: (self, other) ) public func replacing(with other: Tensor, where mask: Tensor<Bool>) -> Tensor
Retorna verdadeiro se o tipo escalar físico for de precisão reduzida.
Atualmente, reduziu precisão tipos escalares físicas incluir apenas
BFloat16
.Declaração
public var isReducedPrecision: Bool { get }
Promove um escalar a um tensor com o mesmo dispositivo e precisão do tensor fornecido.
Declaração
@differentiable public init(_ value: Scalar, deviceAndPrecisionLike tensor: Tensor)
Retorna uma cópia do
self
convertido paraBFloat16
tipo escalar física.Declaração
public var toReducedPrecision: `Self` { get }
Retorna uma cópia do
self
convertido paraScalar
tipo escalar física.Declaração
public var toFullPrecision: `Self` { get }
O número de dimensões do
Tensor
.Declaração
public var rank: Int { get }
A forma do
Tensor
.Declaração
public var shape: TensorShape { get }
O número de escalares do
Tensor
.Declaração
public var scalarCount: Int { get }
A classificação do tensor, representado como um
Tensor<Int32>
.Declaração
public var rankTensor: Tensor<Int32> { get }
As dimensões do tensor, representada como uma
Tensor<Int32>
.Declaração
public var shapeTensor: Tensor<Int32> { get }
O número de escalares no tensor, representado como um
Tensor<Int32>
.Declaração
public var scalarCountTensor: Tensor<Int32> { get }
Retorna
true
serank
é igual a 0 efalse
caso contrário.Declaração
public var isScalar: Bool { get }
Retorna o elemento escalar único caso
rank
é igual a 0 enil
contrário.Declaração
public var scalar: Scalar? { get }
Remodele para escalar.
Condição prévia
O tensor possui exatamente um escalar.Declaração
@differentiable public func scalarized() -> Scalar
Declaração
public var array: ShapedArray<Scalar> { get }
Declaração
@differentiable public var scalars: [Scalar] { get }
Cria um tensor 0-D a partir de um valor escalar.
Declaração
@differentiable public init(_ value: Scalar, on device: Device = .default)
Cria um tensor 1D de escalares.
Declaração
@differentiable public init(_ scalars: [Scalar], on device: Device = .default)
Cria um tensor 1D de escalares.
Declaração
public init<C: Collection>( _ vector: C, on device: Device = .default ) where C.Element == Scalar
Cria um tensor com a forma especificada e escalares contíguos na ordem da linha principal.
Condição prévia
O produto das dimensões da forma deve ser igual ao número de escalares.Declaração
@differentiable public init(shape: TensorShape, scalars: [Scalar], on device: Device = .default)
Parâmetros
shape
A forma do tensor.
scalars
O conteúdo escalar do tensor.
Cria um tensor com a forma especificada e escalares contíguos na ordem da linha principal.
Condição prévia
O produto das dimensões da forma deve ser igual ao número de escalares.Declaração
public init( shape: TensorShape, scalars: UnsafeBufferPointer<Scalar>, on device: Device = .default )
Parâmetros
shape
A forma do tensor.
scalars
O conteúdo escalar do tensor.
Cria um tensor com a forma especificada e escalares contíguos na ordem da linha principal.
Condição prévia
O produto das dimensões da forma deve ser igual ao número de escalares.Cria um tensor com a forma especificada e escalares contíguos na ordem da linha principal.
Condição prévia
O produto das dimensões da forma deve ser igual ao número de escalares.Declaração
public init<C: Collection>( shape: TensorShape, scalars: C, on device: Device = .default ) where C.Element == Scalar
Parâmetros
shape
A forma do tensor.
scalars
O conteúdo escalar do tensor.
O tipo dos elementos de um literal de matriz.
Declaração
public typealias ArrayLiteralElement = _TensorElementLiteral<Scalar>
Cria um tensor inicializado com os elementos fornecidos.
Declaração
public init(arrayLiteral elements: _TensorElementLiteral<Scalar>...)
Uma representação textual do tensor.
Observação
usofullDescription
para uma descrição não-muito-impresso mostrando todos os escalares.Declaração
public var description: String { get }
Uma representação textual do tensor. Retorna uma descrição resumida, se
summarize
é verdadeiro e a contagem de elemento exceder o dobro doedgeElementCount
.Declaração
public func description( lineWidth: Int = 80, edgeElementCount: Int = 3, summarizing: Bool = false ) -> String
Parâmetros
lineWidth
A largura máxima da linha para impressão. Usado para determinar o número de escalares a serem impressos por linha.
edgeElementCount
O número máximo de elementos para imprimir antes e depois sumarização via reticências (
...
).summarizing
Se for verdade, resumir descrição se contagem de elementos excede duas vezes
edgeElementCount
.Uma representação textual completa e não impressa do tensor, mostrando todos os escalares.
Declaração
public var fullDescription: String { get }
Declaração
public var playgroundDescription: Any { get }
Declaração
public var customMirror: Mirror { get }
As anotações que descrevem este tensor.
Declaração
public var annotations: String { get }
Um alias para anotações.
Declaração
public var summary: String { get }
Declaração
public init(_owning tensorHandles: UnsafePointer<CTensorHandle>?)
Declaração
public init<C: RandomAccessCollection>( _handles: C ) where C.Element: _AnyTensorHandle
Declaração
public init(_ array: ShapedArray<Scalar>, on device: Device = .default)
Declaração
init(_xla: XLATensor)
Declaração
init(_xlaHandle: UnsafeMutablePointer<OpaqueXLATensor>)
Declaração
var xlaHandle: UnsafeMutablePointer<OpaqueXLATensor> { get }
Declaração
var xlaTensor: XLATensor { get }
Declaração
@differentiable(wrt: self) public func unbroadcasted(toShape otherShape: Tensor<Int32>) -> Tensor
Declaração
@differentiable(wrt: self) public func unbroadcasted<OtherScalar>(like other: Tensor<OtherScalar>) -> Tensor where OtherScalar : TensorFlowScalar
Declaração
@differentiable(wrt: self) public func unbroadcasted(to shape: TensorShape) -> Tensor
Um modo que determina como um tensor é preenchido.
Declaração
public enum PaddingMode
Retorna um tensor preenchido com constante de acordo com os tamanhos de preenchimento especificados.
Declaração
@differentiable(wrt: self) public func padded(forSizes sizes: [(before: Int, after: Int)], with value: Scalar = 0) -> Tensor
Retorna um tensor preenchido de acordo com os tamanhos e modo de preenchimento especificados.
Declaração
@differentiable(wrt: self) public func padded(forSizes sizes: [(before: Int, after: Int)], mode: PaddingMode) -> Tensor
Retorna um tensor de escalares booleanas computando
lhs < rhs
elemento-wise.Declaração
public static func .< (lhs: Tensor, rhs: Tensor) -> Tensor<Bool>
Retorna um tensor de escalares booleanas computando
lhs <= rhs
elemento-wise.Declaração
public static func .<= (lhs: Tensor, rhs: Tensor) -> Tensor<Bool>
Retorna um tensor de escalares booleanas por computação
lhs > rhs
elemento-wise.Declaração
public static func .> (lhs: Tensor, rhs: Tensor) -> Tensor<Bool>
Retorna um tensor de escalares booleanas por computação
lhs >= rhs
elemento-wise.Declaração
public static func .>= (lhs: Tensor, rhs: Tensor) -> Tensor<Bool>
Retorna um tensor de escalares booleanas computando
lhs < rhs
elemento-wise.Observação
.<
Suportes radiodifusão.Declaração
public static func .< (lhs: Scalar, rhs: Tensor) -> Tensor<Bool>
Retorna um tensor de escalares booleanas computando
lhs <= rhs
elemento-wise.Observação
.<=
Suportes transmitindo.Declaração
public static func .<= (lhs: Scalar, rhs: Tensor) -> Tensor<Bool>
Retorna um tensor de escalares booleanas por computação
lhs > rhs
elemento-wise.Observação
.>
Suportes de radiodifusão.Declaração
public static func .> (lhs: Scalar, rhs: Tensor) -> Tensor<Bool>
Retorna um tensor de escalares booleanas por computação
lhs >= rhs
elemento-wise.Observação
.>=
Suportes de radiodifusão.Declaração
public static func .>= (lhs: Scalar, rhs: Tensor) -> Tensor<Bool>
Retorna um tensor de escalares booleanas computando
lhs < rhs
elemento-wise.Observação
.<
Suportes radiodifusão.Declaração
public static func .< (lhs: Tensor, rhs: Scalar) -> Tensor<Bool>
Retorna um tensor de escalares booleanas computando
lhs <= rhs
elemento-wise.Observação
.<=
Suportes transmitindo.Declaração
public static func .<= (lhs: Tensor, rhs: Scalar) -> Tensor<Bool>
Retorna um tensor de escalares booleanas por computação
lhs > rhs
elemento-wise.Observação
.>
Suportes de radiodifusão.Declaração
public static func .> (lhs: Tensor, rhs: Scalar) -> Tensor<Bool>
Retorna um tensor de escalares booleanas por computação
lhs >= rhs
elemento-wise.Observação
.>=
Suportes de radiodifusão.Declaração
public static func .>= (lhs: Tensor, rhs: Scalar) -> Tensor<Bool>
Retorna um tensor de escalares booleanas computando
lhs == rhs
elemento-wise.Observação
.==
suportes transmitindo.Declaração
public static func .== (lhs: Tensor, rhs: Tensor) -> Tensor<Bool>
Retorna um tensor de escalares booleanas computando
lhs != rhs
elemento-wise.Observação
.!=
Suportes transmitindo.Declaração
public static func .!= (lhs: Tensor, rhs: Tensor) -> Tensor<Bool>
Retorna um tensor de escalares booleanas computando
lhs == rhs
elemento-wise.Observação
.==
suportes transmitindo.Declaração
public static func .== (lhs: Scalar, rhs: Tensor) -> Tensor<Bool>
Retorna um tensor de escalares booleanas computando
lhs != rhs
elemento-wise.Observação
.!=
Suportes transmitindo.Declaração
public static func .!= (lhs: Scalar, rhs: Tensor) -> Tensor<Bool>
Retorna um tensor de escalares booleanas computando
lhs == rhs
elemento-wise.Observação
.==
suportes transmitindo.Declaração
public static func .== (lhs: Tensor, rhs: Scalar) -> Tensor<Bool>
Retorna um tensor de escalares booleanas computando
lhs != rhs
elemento-wise.Observação
.!=
Suportes transmitindo.Declaração
public static func .!= (lhs: Tensor, rhs: Scalar) -> Tensor<Bool>
Retorna um tensor de valores booleano que indica se os elementos de
self
são aproximadamente iguais aos deother
.Condição prévia
self
eother
deve ser da mesma forma.Declaração
public func elementsAlmostEqual( _ other: Tensor, tolerance: Scalar = Scalar.ulpOfOne.squareRoot() ) -> Tensor<Bool>
Retorna
true
se todos os elementos deself
são aproximadamente iguais aos deother
.Condição prévia
self
eother
deve ser da mesma forma.Declaração
public func isAlmostEqual( to other: Tensor, tolerance: Scalar = Scalar.ulpOfOne.squareRoot() ) -> Bool
Executa uma soma de réplica cruzada para este tensor. A mesma soma de réplica cruzada deve acontecer em cada um dos outros dispositivos que participam da soma.
Declaração
public mutating mutating func crossReplicaSum(_ scale: Double)
Declaração
@derivative init(repeating: shape)
Executar uma conversão do tipo de elemento a elemento a partir de um
Bool
tensor.Declaração
public init(_ other: Tensor<Bool>)
Executar uma conversão elemento-wise de outro
Tensor
.Declaração
@differentiable public init<OtherScalar>(_ other: Tensor<OtherScalar>) where OtherScalar : Numeric, OtherScalar : TensorFlowScalar
Declaração
@derivative init(_: <<error type>>)
Declaração
@derivative init(stacking: alongAxis)
Declaração
@derivative init(concatenating: alongAxis)
Cria um tensor com todos os escalares definidos como zero.
Declaração
public init(zeros shape: TensorShape, on device: Device = .default)
Parâmetros
shape
Forma do tensor.
Cria um tensor com todos os escalares definidos como um.
Declaração
public init(ones shape: TensorShape, on device: Device = .default)
Parâmetros
shape
Forma do tensor.
Cria um tensor com todos os escalares definidos como zero que têm a mesma forma e tipo do tensor fornecido.
Declaração
public init(zerosLike other: Tensor)
Parâmetros
other
Tensor cuja forma e tipo de dados usar.
Cria um tensor com todos os escalares definidos para um que tenha a mesma forma e tipo do tensor fornecido.
Declaração
public init(onesLike other: Tensor)
Parâmetros
other
Tensor cuja forma e tipo de dados usar.
Cria um tensor 1-D que representa uma sequência de um valor inicial até, mas não incluindo, um valor final, avançando pela quantidade especificada.
Declaração
public init( rangeFrom start: Scalar, to end: Scalar, stride: Scalar, on device: Device = .default )
Parâmetros
start
O valor inicial a ser usado para a sequência. Se a sequência contém quaisquer valores, o primeiro é
start
.end
Um valor final para limitar a sequência.
end
nunca é um elemento da sequência resultante.stride
A quantidade a ser analisada em cada iteração.
stride
deve ser positivo.Cria um tensor 1-D que representa uma sequência de um valor inicial até, mas não incluindo, um valor final, avançando pela quantidade especificada.
Declaração
public init(rangeFrom start: Tensor<Scalar>, to end: Tensor<Scalar>, stride: Tensor<Scalar>)
Parâmetros
start
O valor inicial a ser usado para a sequência. Se a sequência contém quaisquer valores, o primeiro é
start
.end
Um valor final para limitar a sequência.
end
nunca é um elemento da sequência resultante.stride
A quantidade a ser analisada em cada iteração.
stride
deve ser positivo.Cria um tensor one-hot em determinados índices. Os locais representadas por
indices
tomar valoronValue
(1
por padrão), enquanto todos os outros locais levá valoroffValue
(0
por padrão). Se a entradaindices
é poston
, o novo tensor terá poston+1
. O novo eixo é criado na dimensãoaxis
(por defeito, o novo eixo é anexado no final).Se
indices
é um escalar, a forma do novo tensor será um vetor de comprimentodepth
.Se
indices
é um vector de comprimentofeatures
, a forma de saída será: características x profundidade, se o eixo == -1 profundidade x características, se o eixo == 0Se
indices
é uma matriz (em lotes) com forma[batch, features]
, a forma de saída será: lote x apresenta x profundidade, se características eixo == -1 lote x profundidade x, se o eixo == 1 x profundidade x lote recursos , se eixo == 0Declaração
public init( oneHotAtIndices indices: Tensor<Int32>, depth: Int, onValue: Scalar = 1, offValue: Scalar = 0, axis: Int = -1 )
Parâmetros
indices
A
Tensor
de índices.depth
Um escalar que define a profundidade de uma dimensão quente.
onValue
Um escalar define o valor no local referido por alguns índice em
indices
.offValue
Um escalar definindo o valor em um local que não é referido por qualquer índice de
indices
.axis
O eixo a ser preenchido. O padrão é
-1
, um novo mais interna do eixo.
Cria um tensor 1-D que representa uma sequência de um valor inicial, até e incluindo um valor final, espaçado uniformemente para gerar o número de valores especificados.
Declaração
public init( linearSpaceFrom start: Scalar, to end: Scalar, count: Int, on device: Device = .default )
Parâmetros
start
O valor inicial a ser usado para a sequência. Se a sequência contém quaisquer valores, o primeiro é
start
.end
Um valor final para limitar a sequência.
end
é o último elemento da sequência resultante.count
O número de valores na sequência resultante.
count
deve ser positivo.Cria um tensor 1-D que representa uma sequência de um valor inicial, até e incluindo um valor final, espaçado uniformemente para gerar o número de valores especificados.
Condição prévia
start
,to
, ecount
deve ser tensores contendo um único valor escalar.Declaração
public init(linearSpaceFrom start: Tensor<Scalar>, to end: Tensor<Scalar>, count: Tensor<Int32>)
Parâmetros
start
O valor inicial a ser usado para a sequência. Se a sequência contém quaisquer valores, o primeiro é
start
.end
Um valor final para limitar a sequência.
end
é o último elemento da sequência resultante.count
O número de valores na sequência resultante.
count
deve ser positivo.
Cria um tensor com a forma especificada, a amostragem de valores escalares aleatoriamente a partir de uma distribuição uniforme entre
lowerBound
eupperBound
.Declaração
public init( randomUniform shape: TensorShape, lowerBound: Tensor<Scalar>? = nil, upperBound: Tensor<Scalar>? = nil, seed: TensorFlowSeed = Context.local.randomSeed, on device: Device = .default )
Parâmetros
shape
As dimensões do tensor.
lowerBound
O limite inferior da distribuição.
upperBound
O limite superior da distribuição.
seed
O valor da semente.
Cria um tensor com a forma especificada, a amostragem de valores escalares aleatoriamente a partir de uma distribuição uniforme entre
lowerBound
eupperBound
.Declaração
public init( randomUniform shape: TensorShape, lowerBound: Tensor<Scalar>? = nil, upperBound: Tensor<Scalar>? = nil, seed: TensorFlowSeed = Context.local.randomSeed, on device: Device = .default )
Parâmetros
shape
As dimensões do tensor.
lowerBound
O limite inferior da distribuição.
upperBound
O limite superior da distribuição.
seed
O valor da semente.
Cria um tensor com a forma especificada, amostrando aleatoriamente os valores escalares de uma distribuição normal.
Declaração
public init( randomNormal shape: TensorShape, mean: Tensor<Scalar>? = nil, standardDeviation: Tensor<Scalar>? = nil, seed: TensorFlowSeed = Context.local.randomSeed, on device: Device = .default )
Parâmetros
shape
As dimensões do tensor.
mean
A média da distribuição.
standardDeviation
O desvio padrão da distribuição.
seed
O valor da semente.
Cria um tensor com a forma especificada, amostrando aleatoriamente os valores escalares de uma distribuição Normal truncada.
Declaração
public init( randomTruncatedNormal shape: TensorShape, mean: Tensor<Scalar>? = nil, standardDeviation: Tensor<Scalar>? = nil, seed: TensorFlowSeed = Context.local.randomSeed, on device: Device = .default )
Parâmetros
shape
As dimensões do tensor.
mean
A média da distribuição.
standardDeviation
O desvio padrão da distribuição.
seed
O valor da semente.
Cria um tensor desenhando amostras de uma distribuição categórica.
Declaração
public init<T: TensorFlowFloatingPoint>( randomCategorialLogits: Tensor<T>, sampleCount: Int32, seed: TensorFlowSeed = Context.local.randomSeed )
Parâmetros
randomCategorialLogits
2-D Tensor com forma
[batchSize, classCount]
. Cada fatia[i, :]
representa as probabilidades de log não normalizadas para todas as classes.sampleCount
0-D. Número de amostras independentes para desenhar para cada fatia da linha.
seed
O valor da semente.
Valor de retorno
2-D Tensor com forma
[batchSize, sampleCount]
. Cada fatia[i, :]
contém as etiquetas de classe tirada com intervalo[0, classCount)
.
Cria um tensor com a forma especificada executando a inicialização uniforme Glorot (Xavier).
Baseia-se amostras aleatórias de uma distribuição uniforme entre
-limit
elimit
gerado pelo gerador de números aleatórios padrão, ondelimit
ésqrt(6 / (fanIn + fanOut))
efanIn
/fanOut
representam o número de entrada e de saída possui multiplicado pelo receptivo tamanho do campo.Referência: “Compreender a dificuldade de formação de redes profunda feedforward neural”
Declaração
public init( glorotUniform shape: TensorShape, seed: TensorFlowSeed = Context.local.randomSeed, on device: Device = .default )
Parâmetros
shape
As dimensões do tensor.
seed
O valor da semente.
Cria um tensor com a forma especificada executando a inicialização normal Glorot (Xavier).
Baseia-se amostras aleatórias de uma distribuição normal truncada centrado em
0
com um desvio padrãosqrt(2 / (fanIn + fanOut))
gerado pelo gerador de padrão de número aleatório, ondefanIn
/fanOut
representam o número de entrada e de saída possui multiplicado pelo campo receptivo Tamanho.Referência: “Compreender a dificuldade de formação de redes profunda feedforward neural”
Declaração
public init( glorotNormal shape: TensorShape, seed: TensorFlowSeed = Context.local.randomSeed, on device: Device = .default )
Parâmetros
shape
As dimensões do tensor.
seed
O valor da semente.
Cria um tensor com a forma especificada executando a inicialização uniforme de He (Kaiming).
Baseia-se amostras aleatórias de uma distribuição uniforme entre
-limit
elimit
gerado pelo gerador de números aleatórios padrão, ondelimit
ésqrt(6 / fanIn)
efanIn
representa o número de entrada possui multiplicada pelo tamanho do campo receptivo.Referência: “mergulhar profundamente em Rectifiers: Superando Human Performance Nível sobre IMAGEnet Classification”
Declaração
public init( heUniform shape: TensorShape, seed: TensorFlowSeed = Context.local.randomSeed, on device: Device = .default )
Parâmetros
shape
As dimensões do tensor.
seed
O valor da semente.
Cria um tensor com a forma especificada executando a inicialização normal de He (Kaiming).
Baseia-se amostras aleatórias de uma distribuição normal truncada centrado em
0
com desvio padrãosqrt(2 / fanIn))
gerado pelo gerador de números aleatórios padrão, ondefanIn
representa o número de entrada possui multiplicada pelo tamanho do campo receptivo.Referência: “mergulhar profundamente em Rectifiers: Superando Human Performance Nível sobre IMAGEnet Classification”
Declaração
public init( heNormal shape: TensorShape, seed: TensorFlowSeed = Context.local.randomSeed, on device: Device = .default )
Parâmetros
shape
As dimensões do tensor.
seed
O valor da semente.
Cria um tensor com a forma especificada executando a inicialização uniforme LeCun.
Baseia-se amostras aleatórias de uma distribuição uniforme entre
-limit
elimit
gerado pelo gerador de números aleatórios padrão, ondelimit
ésqrt(3 / fanIn)
efanIn
representa o número de entrada possui multiplicada pelo tamanho do campo receptivo.Referência: “Retropropagação Eficiente”
Declaração
public init( leCunUniform shape: TensorShape, seed: TensorFlowSeed = Context.local.randomSeed, on device: Device = .default )
Parâmetros
shape
As dimensões do tensor.
seed
O valor da semente.
Cria um tensor com a forma especificada executando a inicialização normal LeCun.
Baseia-se amostras aleatórias de uma distribuição normal truncada centrado em
0
com um desvio padrãosqrt(1 / fanIn)
gerado pelo gerador de números aleatórios padrão, ondefanIn
representa o número de entrada possui multiplicada pelo tamanho do campo receptivo.Referência: “Retropropagação Eficiente”
Declaração
public init( leCunNormal shape: TensorShape, seed: TensorFlowSeed = Context.local.randomSeed, on device: Device = .default )
Parâmetros
shape
As dimensões do tensor.
seed
O valor da semente.
Cria uma matriz ortogonal ou tensor.
Se a forma do tensor a ser inicializado for bidimensional, ele será inicializado com uma matriz ortogonal obtida da decomposição QR de uma matriz de números aleatórios extraída de uma distribuição normal. Se a matriz tiver menos linhas do que colunas, a saída terá linhas ortogonais. Caso contrário, a saída terá colunas ortogonais.
Se a forma do tensor para inicializar é mais do que bidimensional, uma matriz de forma
[shape[0] * ... * shape[rank - 2], shape[rank - 1]]
é inicializado. A matriz é posteriormente remodelada para fornecer um tensor com a forma desejada.Declaração
public init( orthogonal shape: TensorShape, gain: Tensor<Scalar> = Tensor<Scalar>(1), seed: TensorFlowSeed = Context.local.randomSeed )
Parâmetros
shape
A forma do tensor.
gain
Um fator multiplicativo a ser aplicado ao tensor ortogonal.
seed
Uma tupla de dois inteiros para propagar o gerador de números aleatórios.
Retorna a parte diagonal [em lote] de um tensor [em lote]. Para o exemplo do tensor da forma
[..., M, N]
, a saída é um tensor da forma[..., K]
, em queK
é igual amin(N, M)
.Por exemplo:
// 't' is [[1, 0, 0, 0] // [0, 2, 0, 0] // [0, 0, 3, 0] // [0, 0, 0, 4]] t.diagonalPart() // [1, 2, 3, 4]
Declaração
@differentiable public func diagonalPart() -> Tensor
Constrói uma matriz diagonal [em lote]. Para o exemplo do tensor da forma
[..., M]
, a saída é um tensor da forma[..., M, M]
.Por exemplo:
// 't' is [1, 2, 3, 4] t.diagonal() // [[1, 0, 0, 0] // [0, 2, 0, 0] // [0, 0, 3, 0] // [0, 0, 0, 4]]
Declaração
@differentiable public func diagonal() -> Tensor
Retornos
self
com novos valores de diagonal, dado queself
é uma matriz opcionalmente agrupadas.O tensor devolvido tem a mesma forma e os valores como
self
, excepto para as diagonais especificadas das matrizes mais profundos que são substituídos pelos valores emdiagonal
.Parâmetro diagonal: Um tensor com classificação
rank - 1
representando os novos valores diagonais.Declaração
public func withDiagonal(_ diagonal: Tensor<Scalar>) -> Tensor
Declaração
@differentiable(wrt: self) public func bandPart(_ subdiagonalCount: Int, _ superdiagonalCount: Int) -> Tensor
Retorna uma cópia de um tensor interno definido pelos limites de uma banda central. A saída é um tensor da mesma forma que o exemplo
[..., :, :]
.Por exemplo:
// 't' is [[ 0, 1, 2, 3] // [-1, 0, 1, 2] // [-2, -1, 0, 1] // [-3, -2, -1, 0]] t.bandPart(1, -1) // [[ 0, 1, 2, 3] // [-1, 0, 1, 2] // [ 0, -1, 0, 1] // [ 0, 0, -1, 0]] t.bandPart(2, 1) // [[ 0, 1, 0, 0] // [-1, 0, 1, 0] // [-2, -1, 0, 1] // [ 0, -2, -1, 0]]
Declaração
@differentiable public func bandPart(subdiagonalCount: Int, superdiagonalCount: Int) -> Tensor
Parâmetros
subdiagonalCount
O número de subdiagonais a serem mantidos. Se negativo, mantenha o triângulo inferior inteiro.
superdiagonalCount
O número de superdiagonais a serem mantidos. Se negativo, mantenha o triângulo superior inteiro.
Retorna a decomposição de QR de cada matriz interna no tensor, um tensor com interior matrizes ortogonais
q
e um tensor com matrizes triangulares interiores superioresr
, de tal modo que o tensor é igual amatmul(q, r)
.Declaração
public func qrDecomposition(fullMatrices: Bool = false) -> ( q: Tensor<Scalar>, r: Tensor<Scalar> )
Parâmetros
fullMatrices
Se
true
, calcule de tamanhoq
er
. Caso contrário calcular apenas o lídermin(shape[rank - 1], shape[rank - 2])
colunas deq
.Devolve o valor de decomposição singular de
self
, dado queself
é uma matriz opcionalmente agrupadas.A decomposição do valor singular (SVD) da matriz opcionalmente agrupadas
self
é valoress
,u
, ev
, de tal modo que:self[..., :, :] = u[..., :, :] • s[..., :, :].diagonal() • v[..., :, :].transposed()`
auto
must be a tensor with shape
[..., M, N]. Let
K = min (M, N) `.Condição prévia
self
deve ser um tensor com a forma[..., M, N]
.Declaração
public func svd(computeUV: Bool = true, fullMatrices: Bool = false) -> ( s: Tensor<Scalar>, u: Tensor<Scalar>?, v: Tensor<Scalar>? )
Parâmetros
computeUV
Se
true
, os vetores singulares esquerdo e direito são calculados e retornados comou
ev
, respectivamente. Sefalse
,nil
valores são retornados comou
ev
.fullMatrices
If
true
,u
andv
respectively have shapes[..., M, M]
and[..., N, N]
. Iffalse
,u
andv
respectively have shapes[..., M, K]
and[..., K, N]
. Ignored whencomputeUV
is false.Return Value
- s: The singular values, with shape
[..., K]
. Within each vector, the singular values are sorted in descending order. - u: The left singular vectors.
- v: The right singular vectors.
- s: The singular values, with shape
The square root of
x
.For real types, if
x
is negative the result is.nan
. For complex types there is a branch cut on the negative real axis.Declaração
@differentiable public static func sqrt(_ x: `Self`) -> Tensor<Scalar>
The cosine of
x
, interpreted as an angle in radians.Declaração
@differentiable public static func cos(_ x: `Self`) -> Tensor<Scalar>
The sine of
x
, interpreted as an angle in radians.Declaração
@differentiable public static func sin(_ x: `Self`) -> Tensor<Scalar>
The tangent of
x
, interpreted as an angle in radians.Declaração
@differentiable public static func tan(_ x: `Self`) -> Tensor<Scalar>
The inverse cosine of
x
in radians.Declaração
@differentiable public static func acos(_ x: `Self`) -> Tensor<Scalar>
The inverse sine of
x
in radians.Declaração
@differentiable public static func asin(_ x: `Self`) -> Tensor<Scalar>
The inverse tangent of
x
in radians.Declaração
@differentiable public static func atan(_ x: `Self`) -> Tensor<Scalar>
The hyperbolic cosine of
x
.Declaração
@differentiable public static func cosh(_ x: `Self`) -> Tensor<Scalar>
The hyperbolic sine of
x
.Declaração
@differentiable public static func sinh(_ x: `Self`) -> Tensor<Scalar>
The hyperbolic tangent of
x
.Declaração
@differentiable public static func tanh(_ x: `Self`) -> Tensor<Scalar>
The inverse hyperbolic cosine of
x
.Declaração
@differentiable public static func acosh(_ x: `Self`) -> Tensor<Scalar>
The inverse hyperbolic sine of
x
.Declaração
@differentiable public static func asinh(_ x: `Self`) -> Tensor<Scalar>
The inverse hyperbolic tangent of
x
.Declaração
@differentiable public static func atanh(_ x: `Self`) -> Tensor<Scalar>
The exponential function applied to
x
, ore**x
.Declaração
@differentiable public static func exp(_ x: `Self`) -> Tensor<Scalar>
Two raised to to power
x
.Declaração
@differentiable public static func exp2(_ x: `Self`) -> Tensor<Scalar>
Ten raised to to power
x
.Declaração
@differentiable public static func exp10(_ x: `Self`) -> Tensor<Scalar>
exp(x) - 1
evaluated so as to preserve accuracy close to zero.Declaração
@differentiable public static func expm1(_ x: `Self`) -> Tensor<Scalar>
The natural logarithm of
x
.Declaração
@differentiable public static func log(_ x: `Self`) -> Tensor<Scalar>
The base-two logarithm of
x
.Declaração
@differentiable public static func log2(_ x: `Self`) -> Tensor<Scalar>
The base-ten logarithm of
x
.Declaração
@differentiable public static func log10(_ x: `Self`) -> Tensor<Scalar>
log(1 + x)
evaluated so as to preserve accuracy close to zero.Declaração
@differentiable public static func log1p(_ x: `Self`) -> Tensor<Scalar>
exp(y log(x))
computed without loss of intermediate precision.For real types, if
x
is negative the result is NaN, even ify
has an integral value. For complex types, there is a branch cut on the negative real axis.Declaração
@differentiable public static func pow(_ x: `Self`, _ y: `Self`) -> Tensor<Scalar>
x
raised to then
th power.The product of
n
copies ofx
.Declaração
@differentiable public static func pow(_ x: `Self`, _ n: Int) -> Tensor<Scalar>
The
n
th root ofx
.For real types, if
x
is negative andn
is even, the result is NaN. For complex types, there is a branch cut along the negative real axis.Declaração
@differentiable public static func root(_ x: `Self`, _ n: Int) -> Tensor<Scalar>
Declaração
public typealias VectorSpaceScalar = Float
Declaração
public func scaled(by scale: Float) -> Tensor<Scalar>
Declaração
public func adding(_ scalar: Float) -> Tensor<Scalar>
Declaração
public func subtracting(_ scalar: Float) -> Tensor<Scalar>
Adds the scalar to every scalar of the tensor and produces the sum.
Declaração
@differentiable public static func + (lhs: Scalar, rhs: Tensor) -> Tensor
Adds the scalar to every scalar of the tensor and produces the sum.
Declaração
@differentiable public static func + (lhs: Tensor, rhs: Scalar) -> Tensor
Subtracts the scalar from every scalar of the tensor and produces the difference.
Declaração
@differentiable public static func - (lhs: Scalar, rhs: Tensor) -> Tensor
Subtracts the scalar from every scalar of the tensor and produces the difference
Declaração
@differentiable public static func - (lhs: Tensor, rhs: Scalar) -> Tensor
Adds two tensors and stores the result in the left-hand-side variable.
Observação
+=
supports broadcasting.Declaração
public static func += (lhs: inout Tensor, rhs: Tensor)
Adds the scalar to every scalar of the tensor and stores the result in the left-hand-side variable.
Declaração
public static func += (lhs: inout Tensor, rhs: Scalar)
Subtracts the second tensor from the first and stores the result in the left-hand-side variable.
Observação
-=
supports broadcasting.Declaração
public static func -= (lhs: inout Tensor, rhs: Tensor)
Subtracts the scalar from every scalar of the tensor and stores the result in the left-hand-side variable.
Declaração
public static func -= (lhs: inout Tensor, rhs: Scalar)
Returns the tensor produced by multiplying the two tensors.
Observação
*
supports broadcasting.Declaração
@differentiable public static func * (lhs: Tensor, rhs: Tensor) -> Tensor
Returns the tensor by multiplying it with every scalar of the tensor.
Declaração
@differentiable public static func * (lhs: Scalar, rhs: Tensor) -> Tensor
Multiplies the scalar with every scalar of the tensor and produces the product.
Declaração
@differentiable public static func * (lhs: Tensor, rhs: Scalar) -> Tensor
Multiplies two tensors and stores the result in the left-hand-side variable.
Observação
*=
supports broadcasting.Declaração
public static func *= (lhs: inout Tensor, rhs: Tensor)
Multiplies the tensor with the scalar, broadcasting the scalar, and stores the result in the left-hand-side variable.
Declaração
public static func *= (lhs: inout Tensor, rhs: Scalar)
Returns the quotient of dividing the first tensor by the second.
Observação
/
supports broadcasting.Declaração
@differentiable public static func / (lhs: Tensor, rhs: Tensor) -> Tensor
Returns the quotient of dividing the scalar by the tensor, broadcasting the scalar.
Declaração
@differentiable public static func / (lhs: Scalar, rhs: Tensor) -> Tensor
Returns the quotient of dividing the tensor by the scalar, broadcasting the scalar.
Declaração
@differentiable public static func / (lhs: Tensor, rhs: Scalar) -> Tensor
Divides the first tensor by the second and stores the quotient in the left-hand-side variable.
Declaração
public static func /= (lhs: inout Tensor, rhs: Tensor)
Divides the tensor by the scalar, broadcasting the scalar, and stores the quotient in the left-hand-side variable.
Declaração
public static func /= (lhs: inout Tensor, rhs: Scalar)
Returns the remainder of dividing the first tensor by the second.
Observação
%
supports broadcasting.Declaração
public static func % (lhs: Tensor, rhs: Tensor) -> Tensor
Returns the remainder of dividing the tensor by the scalar, broadcasting the scalar.
Declaração
public static func % (lhs: Tensor, rhs: Scalar) -> Tensor
Returns the remainder of dividing the scalar by the tensor, broadcasting the scalar.
Declaração
public static func % (lhs: Scalar, rhs: Tensor) -> Tensor
Divides the first tensor by the second and stores the remainder in the left-hand-side variable.
Declaração
public static func %= (lhs: inout Tensor, rhs: Tensor)
Divides the tensor by the scalar and stores the remainder in the left-hand-side variable.
Declaração
public static func %= (lhs: inout Tensor, rhs: Scalar)
Returns
!self
element-wise.Declaração
public func elementsLogicalNot() -> Tensor
Returns
self && other
element-wise.Observação
&&
supports broadcasting.Declaração
public func elementsLogicalAnd(_ other: Tensor) -> Tensor
Returns
self && other
element-wise, broadcastingother
.Declaração
public func elementsLogicalAnd(_ other: Scalar) -> Tensor
Returns
self || other
element-wise.Declaração
public func elementsLogicalOr(_ other: Tensor) -> Tensor
Returns
self || other
element-wise, broadcastingother
.Declaração
public func elementsLogicalOr(_ other: Scalar) -> Tensor
Returns
max(min(self, max), min)
.Declaração
@differentiable public func clipped(min: Tensor, max: Tensor) -> Tensor
Returns
max(min(self, max), min)
.Declaração
@differentiable(wrt: (self, min) ) public func clipped(min: Tensor, max: Scalar) -> Tensor
Returns
max(min(self, max), min)
.Declaração
@differentiable(wrt: (self, max) ) public func clipped(min: Scalar, max: Tensor) -> Tensor
Returns
max(min(self, max), min)
.Declaração
@differentiable(wrt: self) public func clipped(min: Scalar, max: Scalar) -> Tensor
Returns the negation of the specified tensor element-wise.
Declaração
@differentiable public prefix static func - (rhs: Tensor) -> Tensor
Declaração
@differentiable(wrt: self) public func squared() -> Tensor
Returns a boolean tensor indicating which elements of
x
are finite.Declaração
public var isFinite: Tensor<Bool> { get }
Returns a boolean tensor indicating which elements of
x
are infinite.Declaração
public var isInfinite: Tensor<Bool> { get }
Returns a boolean tensor indicating which elements of
x
are NaN-valued.Declaração
public var isNaN: Tensor<Bool> { get }
Returns
true
if all scalars are equal totrue
. Otherwise, returnsfalse
.Declaração
public func all() -> Bool
Returns
true
if any scalars are equal totrue
. Otherwise, returnsfalse
.Declaração
public func any() -> Bool
Performs a logical AND operation along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
public func all(squeezingAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Performs a logical AND operation along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
public func any(squeezingAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Performs a logical AND operation along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
public func all(alongAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Performs a logical OR operation along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
public func any(alongAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Declaração
@differentiable public func min() -> Tensor
Declaração
@differentiable public func max() -> Tensor
Returns the maximum values along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func max(squeezingAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the maximum values along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func max(squeezingAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the maximum values along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func max(squeezingAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the minimum values along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func min(squeezingAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the minimum values along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func min(squeezingAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the minimum values along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func min(squeezingAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the indices of the maximum values along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
public func argmax(squeezingAxis axis: Int) -> Tensor<Int32>
Parameters
axes
The dimensions to reduce.
Returns the indices of the minimum values along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
public func argmin(squeezingAxis axis: Int) -> Tensor<Int32>
Parameters
axes
The dimensions to reduce.
Returns the minimum along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func min(alongAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the minimum along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func min(alongAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the minimum along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func min(alongAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the minimum along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func max(alongAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the minimum along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func max(alongAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the minimum along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func max(alongAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the index of the maximum value of the flattened scalars.
Declaração
public func argmax() -> Tensor<Int32>
Returns the index of the minimum value of the flattened scalars.
Declaração
public func argmin() -> Tensor<Int32>
Returns the sum along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank...rank
.Declaração
@differentiable(wrt: self) public func sum(squeezingAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the sum along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank...rank
.Declaração
@differentiable(wrt: self) public func sum(squeezingAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the sum along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank...rank
.Declaração
@differentiable(wrt: self) public func sum(squeezingAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Declaração
@differentiable(wrt: self) public func sum() -> Tensor
Returns the sum along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func sum(alongAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the sum along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func sum(alongAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the sum along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func sum(alongAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the product along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank...rank
.Declaração
@differentiable(wrt: self) public func product(squeezingAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the product along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank...rank
.Declaração
@differentiable(wrt: self) public func product(squeezingAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the product along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank...rank
.Declaração
@differentiable(wrt: self) public func product(squeezingAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Declaração
@differentiable(wrt: self) public func product() -> Tensor
Returns the product along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
public func product(alongAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the product along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
public func product(alongAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the product along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
public func product(alongAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the arithmetic mean along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank...rank
.Declaração
@differentiable(wrt: self) public func mean(squeezingAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the arithmetic mean along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank...rank
.Declaração
@differentiable(wrt: self) public func mean(squeezingAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the arithmetic mean along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank...rank
.Declaração
@differentiable(wrt: self) public func mean(squeezingAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Declaração
@differentiable(wrt: self) public func mean() -> Tensor
Returns the arithmetic mean along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func mean(alongAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the arithmetic mean along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func mean(alongAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the arithmetic mean along the specified axes. The reduced dimensions are retained with value 1.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func mean(alongAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the variance along the specified axes. The reduced dimensions are removed. Does not apply Bessel's correction.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func variance(squeezingAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the variance along the specified axes. The reduced dimensions are removed. Does not apply Bessel's correction.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func variance(squeezingAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the variance along the specified axes. The reduced dimensions are retained with value 1. Does not apply Bessel's correction.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func variance(squeezingAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Declaração
@differentiable(wrt: self) public func variance() -> Tensor
Returns the variance along the specified axes. The reduced dimensions are retained with value 1. Does not apply Bessel's correction.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func variance(alongAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the variance along the specified axes. The reduced dimensions are retained with value 1. Does not apply Bessel's correction.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func variance(alongAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the variance along the specified axes. The reduced dimensions are retained with value 1. Does not apply Bessel's correction.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func variance(alongAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the cumulative sum of this tensor along the specified axis. By default, this function performs an inclusive cumulative sum which means that the first element of the input is identical to the first element of the output:
Tensor<Float>([a, b, c]).cumulativeSum() = Tensor<Float>([a, a + b, a + b + c])
By setting the
exclusive
argument totrue
, an exclusive cumulative sum is performed instead:Tensor<Float>([a, b, c]).cumulativeSum(exclusive: true) = Tensor<Float>([0, a, a + b])
By setting the
reverse
argument totrue
, the cumulative sum is performed in the opposite direction:Tensor<Float>([a, b, c]).cumulativeSum(reverse: true) == Tensor<Float>([a + b + c, a + b, a])
This is more efficient than separately reversing the resulting tensor.
Precondition
axis
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func cumulativeSum( alongAxis axis: Int, exclusive: Bool = false, reverse: Bool = false ) -> Tensor
Parameters
axis
Axis along which to perform the cumulative sum operation.
exclusive
Indicates whether to perform an exclusive cumulative sum.
reverse
Indicates whether to perform the cumulative sum in reversed order.
Return Value
Result of the cumulative sum operation.
Returns the cumulative sum of this tensor along the specified axis. By default, this function performs an inclusive cumulative sum which means that the first element of the input is identical to the first element of the output:
Tensor<Float>([a, b, c]).cumulativeSum() = Tensor<Float>([a, a + b, a + b + c])
By setting the
exclusive
argument totrue
, an exclusive cumulative sum is performed instead:Tensor<Float>([a, b, c]).cumulativeSum(exclusive: true) = Tensor<Float>([0, a, a + b])
By setting the
reverse
argument totrue
, the cumulative sum is performed in the opposite direction:Tensor<Float>([a, b, c]).cumulativeSum(reverse: true) == Tensor<Float>([a + b + c, a + b, a])
This is more efficient than separately reversing the resulting tensor.
Precondition
axis.rank
must be0
.Precondition
axis
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func cumulativeSum( alongAxis axis: Tensor<Int32>, exclusive: Bool = false, reverse: Bool = false ) -> Tensor
Parameters
axis
Axis along which to perform the cumulative sum operation.
exclusive
Indicates whether to perform an exclusive cumulative sum.
reverse
Indicates whether to perform the cumulative sum in reversed order.
Return Value
Result of the cumulative sum operation.
Returns the cumulative product of this tensor along the specified axis. By default, this function performs an inclusive cumulative product which means that the first element of the input is identical to the first element of the output:
Tensor<Float>([a, b, c]).cumulativeProduct() = Tensor<Float>([a, a * b, a * b * c])
By setting the
exclusive
argument totrue
, an exclusive cumulative product is performed instead:Tensor<Float>([a, b, c]).cumulativeProduct(exclusive: true) = Tensor<Float>([1, a, a * b])
By setting the
reverse
argument totrue
, the cumulative product is performed in the opposite direction:Tensor<Float>([a, b, c]).cumulativeProduct(reverse: true) == Tensor<Float>([a * b * c, a * b, a])
This is more efficient than separately reversing the resulting tensor.
Precondition
axis
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func cumulativeProduct( alongAxis axis: Int, exclusive: Bool = false, reverse: Bool = false ) -> Tensor
Parameters
axis
Axis along which to perform the cumulative product operation.
exclusive
Indicates whether to perform an exclusive cumulative product.
reverse
Indicates whether to perform the cumulative product in reversed order.
Return Value
Result of the cumulative product operation.
Returns the cumulative product of this tensor along the specified axis. By default, this function performs an inclusive cumulative product which means that the first element of the input is identical to the first element of the output:
Tensor<Float>([a, b, c]).cumulativeProduct() = Tensor<Float>([a, a * b, a * b * c])
By setting the
exclusive
argument totrue
, an exclusive cumulative product is performed instead:Tensor<Float>([a, b, c]).cumulativeProduct(exclusive: true) = Tensor<Float>([1, a, a * b])
By setting the
reverse
argument totrue
, the cumulative product is performed in the opposite direction:Tensor<Float>([a, b, c]).cumulativeProduct(reverse: true) == Tensor<Float>([a * b * c, a * b, a])
This is more efficient than separately reversing the resulting tensor.
Precondition
axis
must have rank0
.Precondition
axis
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func cumulativeProduct( alongAxis axis: Tensor<Int32>, exclusive: Bool = false, reverse: Bool = false ) -> Tensor
Parameters
axis
Axis along which to perform the cumulative product operation.
exclusive
Indicates whether to perform an exclusive cumulative product.
reverse
Indicates whether to perform the cumulative product in reversed order.
Return Value
Result of the cumulative product operation.
Returns the standard deviation of the elements along the specified axes. The reduced dimensions are retained with value
1
. Does not apply Bessel's correction.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func standardDeviation(squeezingAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the standard deviation of the elements along the specified axes. The reduced dimensions are retained with value
1
. Does not apply Bessel's correction.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func standardDeviation(squeezingAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the standard deviation of the elements along the specified axes. The reduced dimensions are retained with value
1
. Does not apply Bessel's correction.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func standardDeviation(squeezingAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the standard deviation of all elements in this tensor. Does not apply Bessel's correction.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func standardDeviation() -> Tensor
Returns the standard deviation of the elements along the specified axes. The reduced dimensions are retained with value
1
. Does not apply Bessel's correction.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func standardDeviation(alongAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the standard deviation of the elements along the specified axes. The reduced dimensions are retained with value
1
. Does not apply Bessel's correction.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func standardDeviation(alongAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the standard deviation of the elements along the specified axes. The reduced dimensions are retained with value
1
. Does not apply Bessel's correction.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func standardDeviation(alongAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns
log(exp(self).sum(squeezingAxes: axes))
. The reduced dimensions are removed.This function is more numerically stable than computing
log(exp(self).sum(squeezingAxes: axes))
directly. It avoids overflows caused by computing theexp
of large inputs and underflows caused by computing thelog
of small inputs.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func logSumExp(squeezingAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns
log(exp(self).sum(squeezingAxes: axes))
. The reduced dimensions are removed.This function is more numerically stable than computing
log(exp(self).sum(squeezingAxes: axes))
directly. It avoids overflows caused by computing theexp
of large inputs and underflows caused by computing thelog
of small inputs.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func logSumExp(squeezingAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns
log(exp(self).sum(squeezingAxes: axes))
. The reduced dimensions are removed.This function is more numerically stable than computing
log(exp(self).sum(squeezingAxes: axes))
directly. It avoids overflows caused by computing theexp
of large inputs and underflows caused by computing thelog
of small inputs.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func logSumExp(squeezingAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns
log(exp(self).sum())
. The result is a scalar.This function is more numerically stable than computing
log(exp(self).sum())
directly. It avoids overflows caused by computing theexp
of large inputs and underflows caused by computing thelog
of small inputs.Declaração
@differentiable(wrt: self) public func logSumExp() -> Tensor
Returns
log(exp(self).sum(alongAxes: axes))
. The reduced dimensions are retained with value1
.This function is more numerically stable than computing
log(exp(self).sum(alongAxes: axes))
directly. It avoids overflows caused by computing theexp
of large inputs and underflows caused by computing thelog
of small inputs.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func logSumExp(alongAxes axes: Tensor<Int32>) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns
log(exp(self).sum(alongAxes: axes))
. The reduced dimensions are retained with value1
.This function is more numerically stable than computing
log(exp(self).sum(alongAxes: axes))
directly. It avoids overflows caused by computing theexp
of large inputs and underflows caused by computing thelog
of small inputs.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func logSumExp(alongAxes axes: [Int]) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns
log(exp(self).sum(alongAxes: axes))
. The reduced dimensions are retained with value1
.This function is more numerically stable than computing
log(exp(self).sum(alongAxes: axes))
directly. It avoids overflows caused by computing theexp
of large inputs and underflows caused by computing thelog
of small inputs.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func logSumExp(alongAxes axes: Int...) -> Tensor
Parameters
axes
The dimensions to reduce.
Returns the mean and variance of this tensor along the specified axes. The reduced dimensions are removed.
Precondition
axes
must have rank1
.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func moments(squeezingAxes axes: Tensor<Int32>) -> Moments<Scalar>
Parameters
axes
The dimensions to reduce.
Returns the mean and variance of this tensor along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func moments(squeezingAxes axes: [Int]) -> Moments<Scalar>
Parameters
axes
The dimensions to reduce.
Returns the mean and variance of this tensor along the specified axes. The reduced dimensions are removed.
Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func moments(squeezingAxes axes: Int...) -> Moments<Scalar>
Parameters
axes
The dimensions to reduce.
Returns the mean and variance of this tensor's elements.
Declaração
@differentiable(wrt: self) public func moments() -> Moments<Scalar>
Returns the mean and variance of this tensor along the specified axes. The reduced dimensions are retained with value
1
.Precondition
axes
must have rank1
.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func moments(alongAxes axes: Tensor<Int32>) -> Moments<Scalar>
Parameters
axes
The dimensions to reduce.
Returns the mean and variance of this tensor along the specified axes. The reduced dimensions are retained with value
1
.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func moments(alongAxes axes: [Int]) -> Moments<Scalar>
Parameters
axes
The dimensions to reduce.
Returns the mean and variance of this tensor along the specified axes. The reduced dimensions are retained with value
1
.Precondition
Each value inaxes
must be in the range-rank..<rank
.Declaração
@differentiable(wrt: self) public func moments(alongAxes axes: Int...) -> Moments<Scalar>
Parameters
axes
The dimensions to reduce.
Performs matrix multiplication between two tensors and produces the result.
Declaração
@differentiable public static func • (lhs: Tensor, rhs: Tensor) -> Tensor
Declaração
static func vjpInitDeviceAndPrecisionLike( _ value: Scalar, deviceAndPrecisionLike tensor: Tensor ) -> (value: Tensor, pullback: (Tensor) -> (Scalar, Tensor))
Returns a tensor computed from batch-normalizing the input along the specified axis.
Specifically, returns
(self - mu) / (var + epsilon) * gamma + beta
wheremu
andvar
are respectively the mean and variance ofself
alongaxis
.Declaração
@differentiable(wrt: (self, offset, scale) public func batchNormalized( alongAxis axis: Int, offset: Tensor = Tensor(0), scale: Tensor = Tensor(1), epsilon: Scalar = 0.001 ) -> Tensor
Parameters
axis
The batch dimension.
offset
The offset, also known as beta.
scale
The scale, also known as gamma.
epsilon
A small value added to the denominator for numerical stability.
Concatenates two tensors along last axis.
Declaração
@differentiable public static func concatenate(_ lhs: Tensor, _ rhs: Tensor) -> Tensor
Adds two values and produces their sum.
Declaração
@differentiable public static func sum(_ lhs: Tensor, _ rhs: Tensor) -> Tensor
Averages two values.
Declaração
@differentiable public static func average(_ lhs: Tensor, _ rhs: Tensor) -> Tensor
Multiplies two values.
Declaração
@differentiable public static func multiply(_ lhs: Tensor, _ rhs: Tensor) -> Tensor
Stack two values.
Declaração
@differentiable public static func stack(_ lhs: Tensor, _ rhs: Tensor) -> Tensor
Declaração
@derivative init(shape: scalars)
Declaração
public static func == (lhs: Tensor, rhs: Tensor) -> Bool
Declaração
public static func != (lhs: Tensor, rhs: Tensor) -> Bool
Declaração
public func encode(to encoder: Encoder) throws
Declaração
public init(from decoder: Decoder) throws
The scalar zero tensor.
Declaração
public static var zero: Tensor { get }
Adds two tensors and produces their sum.
Observação
+
supports broadcasting.Declaração
@differentiable public static func + (lhs: Tensor, rhs: Tensor) -> Tensor
Subtracts one tensor from another and produces their difference.
Observação
-
supports broadcasting.Declaração
@differentiable public static func - (lhs: Tensor, rhs: Tensor) -> Tensor
The scalar one tensor.
Declaração
public static var one: Tensor { get }
Returns the element-wise reciprocal of
self
.Declaração
public var reciprocal: Tensor { get }
Multiplies two tensors element-wise and produces their product.
Observação
.*
supports broadcasting.Declaração
public static func .* (lhs: Tensor, rhs: Tensor) -> Tensor
Declaração
public typealias TangentVector = Tensor
Declaração
public var zeroTangentVectorInitializer: () -> TangentVector { get }
Adds an annotation.
Note: Only X10 is supported. For other backends, umodified
self
is returned.Declaração
@differentiable(wrt: self) public func annotate(_ annotation: String) -> Tensor<Scalar>
Parameters
annotation
The annotation to be added.
Return Value
The annotated tensor.
Declaração
@derivative func vjpAnnotate(_ annotation: String) -> ( value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> Tensor<Scalar> )