Tensor

@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. Desembala N tensores deste tensor por lascar-lo ao longo do axis dimensão, onde N é inferida a partir da forma este tensor. Por exemplo, dado um tensor com a forma [A, B, C, D] :

    • Se axis == 0 , em seguida, o i -simo tensor na matriz retornada é a fatia self[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ário Tensor.split(numSplits:alongAxis) , ou Tensor.split(sizes:alongAxis) ).
    • Se axis == 1 , em seguida, o i -simo tensor na matriz retornada é a fatia value[:, 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) , onde rank é 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.

  • Divide um tensor em vários tensores. O tensor é dividido ao longo da dimensão axis em count tensores menores. Isto requer que count uniformemente divide shape[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ão axis uniformemente.

    Condição prévia

    axis deve estar no intervalo [-rank, rank) , onde rank é 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 do i peça -ésimo tem a mesma forma que este tensor excepto ao longo dimensão axis , 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ão axis .

    Condição prévia

    axis deve estar no intervalo [-rank, rank) , onde rank é 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ído i 'th dimensão tem self.shape[i] * multiples[i] elementos, e os valores deste tensor são replicados multiples[i] vezes ao longo da i ' th dimensão. Por exemplo, a telha [abcd] por [2] produz [abcdabcd] .

    Condição prévia

    A esperada rank de múltiplos deve ser 1 .

    Condição prévia

    A forma de multiples deve ser [tensor.rank] .

    Condição prévia

    Todos os escalares em multiples 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ído i 'th dimensão tem self.shape[i] * multiples[i] elementos, e os valores deste tensor são replicados multiples[i] vezes ao longo da i ' th dimensão. Por exemplo, a telha [abcd] por [2] produz [abcdabcd] .

    Condição prévia

    A esperada rank de múltiplos deve ser 1 .

    Condição prévia

    A forma de multiples 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 em axes devem estar na faixa -rank..<rank .

    Condição prévia

    Não deve haver duplicação de axes .

    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 em axes devem estar na faixa -rank..<rank .

    Condição prévia

    Não deve haver duplicação de axes .

    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 em axes devem estar na faixa -rank..<rank .

    Condição prévia

    Não deve haver duplicação de axes .

    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 do axis dimensão

    Para 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 e M = 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 do axis dimensão, enquanto ignoram os primeiros batchDimensionCount 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 é agora shape[..<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 a batchDimensionCount .

    Condição prévia

    batchDimensionCount deve ser inferior a indices.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 , ea mask da forma deve coincidir com as primeiras dimensões K do tensor da forma. Temos então: tensor.gathering(where: mask)[i, j1, ..., jd] = tensor[i1, ..., iK, j1, ..., jd] , onde [i1, ..., iK] é o i th true entrada de mask (ordem de linha principal).

    O axis pode ser usado com mask para indicar o eixo para mascarar a partir. Nesse caso, axis + mask.rank <= tensor.rank ea mask 's shape must match the first eixos + mask.rank dimensions 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 que K + axis <= self.rank .

    Valor de retorno

    (self.rank - K + 1) tensor -dimensional povoada por entradas neste tensor correspondentes aos true valores na mask .

  • 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 de self , 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 de self , 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 de self , 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 uma cópia do other no dado Device .

    Declaração

    public init(copying other: Tensor, to device: Device)
  • 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 do axis dimensão, para um novo posto tensor com um mais elevado do que o tensor de corrente e cada tensor em tensors .

    Dado que tensors têm forma [A, B, C] , e tensors.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) , onde rank é 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.

  • Concatenates tensors ao longo do axis dimensão.

    Dado que tensors[i].shape = [D0, D1, ... Daxis(i), ...Dn] , então o resultado concatenado tem a forma [D0, D1, ... Raxis, ...Dn] , onde Raxis = sum(Daxis(i)) . Ou seja, os dados dos tensores de entrada é acompanhado ao longo do axis 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) , onde rank é 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, onde mask é true .

    Condição prévia

    self e other deve ter a mesma forma. Se self e other são escalares, então mask também deve ser escalar. Se self e other têm classificação maior do que ou igual a 1 , então mask deve ser ou têm a mesma forma como self ou ser um 1-D Tensor de tal modo que mask.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 para BFloat16 tipo escalar física.

    Declaração

    public var toReducedPrecision: `Self` { get }
  • Retorna uma cópia do self convertido para Scalar 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 se rank é igual a 0 e false caso contrário.

    Declaração

    public var isScalar: Bool { get }
  • Retorna o elemento escalar único caso rank é igual a 0 e nil 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

    uso fullDescription 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 do edgeElementCount .

    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 }

Disponível onde `Scalar`:` Numeric`

  • 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

Disponível onde `Scalar`:` Numeric` & `Comparable`

  • 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>

Disponível onde `Scalar`:` Equatable`

  • 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>

Disponível onde `Scalar`:` TensorFlowFloatingPoint` e `Equatable`

  • Retorna um tensor de valores booleano que indica se os elementos de self são aproximadamente iguais aos de other .

    Condição prévia

    self e other deve ser da mesma forma.

    Declaração

    public func elementsAlmostEqual(
      _ other: Tensor,
      tolerance: Scalar = Scalar.ulpOfOne.squareRoot()
    ) -> Tensor<Bool>

Disponível onde `Scalar`:` TensorFlowFloatingPoint`

  • Retorna true se todos os elementos de self são aproximadamente iguais aos de other .

    Condição prévia

    self e other deve ser da mesma forma.

    Declaração

    public func isAlmostEqual(
      to other: Tensor,
      tolerance: Scalar = Scalar.ulpOfOne.squareRoot()
    ) -> Bool

Disponível onde `Scalar`:` TensorFlowNumeric`

  • 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)

Disponível onde `Scalar`:` TensorFlowFloatingPoint`

Disponível onde `Scalar`:` Numeric`

  • 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

Disponível onde `Scalar`:` TensorFlowFloatingPoint`

Disponível onde `Scalar`:` Numeric`

  • 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 valor onValue ( 1 por padrão), enquanto todos os outros locais levá valor offValue ( 0 por padrão). Se a entrada indices é posto n , o novo tensor terá posto n+1 . O novo eixo é criado na dimensão axis (por defeito, o novo eixo é anexado no final).

    Se indices é um escalar, a forma do novo tensor será um vetor de comprimento depth .

    Se indices é um vector de comprimento features , a forma de saída será: características x profundidade, se o eixo == -1 profundidade x características, se o eixo == 0

    Se 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 == 0

    Declaraçã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.

Disponível onde `Scalar`:` TensorFlowFloatingPoint`

  • 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 , e count 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.

Disponível onde `Scalar`:` TensorFlowIndex`

  • Cria um tensor com a forma especificada, a amostragem de valores escalares aleatoriamente a partir de uma distribuição uniforme entre lowerBound e upperBound .

    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.

Disponível onde `Scalar`:` TensorFlowFloatingPoint`

  • Cria um tensor com a forma especificada, a amostragem de valores escalares aleatoriamente a partir de uma distribuição uniforme entre lowerBound e upperBound .

    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.

Disponível onde `Scalar`:` TensorFlowIndex`

  • 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) .

Disponível onde `Scalar`:` TensorFlowFloatingPoint`

  • 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 e limit gerado pelo gerador de números aleatórios padrão, onde limit é sqrt(6 / (fanIn + fanOut)) e fanIn / 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ão sqrt(2 / (fanIn + fanOut)) gerado pelo gerador de padrão de número aleatório, onde fanIn / 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 e limit gerado pelo gerador de números aleatórios padrão, onde limit é sqrt(6 / fanIn) e fanIn 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ão sqrt(2 / fanIn)) gerado pelo gerador de números aleatórios padrão, onde fanIn 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 e limit gerado pelo gerador de números aleatórios padrão, onde limit é sqrt(3 / fanIn) e fanIn 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ão sqrt(1 / fanIn) gerado pelo gerador de números aleatórios padrão, onde fanIn 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.

Disponível onde `Scalar`:` TensorFlowNumeric`

  • 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 que K é igual a min(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 que self é 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 em diagonal .

    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.

Disponível onde `Scalar`:` TensorFlowFloatingPoint`

  • 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 superiores r , de tal modo que o tensor é igual a matmul(q, r) .

    Declaração

    public func qrDecomposition(fullMatrices: Bool = false) -> (
      q: Tensor<Scalar>, r: Tensor<Scalar>
    )

    Parâmetros

    fullMatrices

    Se true , calcule de tamanho q e r . Caso contrário calcular apenas o líder min(shape[rank - 1], shape[rank - 2]) colunas de q .

  • Devolve o valor de decomposição singular de self , dado que self é uma matriz opcionalmente agrupadas.

    A decomposição do valor singular (SVD) da matriz opcionalmente agrupadas self é valores s , u , e v , 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 como u e v , respectivamente. Se false , nil valores são retornados como u e v .

    fullMatrices

    If true , u and v respectively have shapes [..., M, M] and [..., N, N] . If false , u and v respectively have shapes [..., M, K] and [..., K, N] . Ignored when computeUV 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.
  • 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 , or e**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 if y 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 the n th power.

    The product of n copies of x .

    Declaração

    @differentiable
    public static func pow(_ x: `Self`, _ n: Int) -> Tensor<Scalar>
  • The n th root of x .

    For real types, if x is negative and n 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>

Available where `Scalar`: `Numeric`

  • 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)

Available where `Scalar` == `Bool`

  • 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, broadcasting other .

    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, broadcasting other .

    Declaração

    public func elementsLogicalOr(_ other: Scalar) -> Tensor

Available where `Scalar`: `TensorFlowNumeric`

  • 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

Available where `Scalar`: `SignedNumeric`

  • Returns the negation of the specified tensor element-wise.

    Declaração

    @differentiable
    public prefix static func - (rhs: Tensor) -> Tensor

Available where `Scalar`: `Numeric`

  • Declaração

    @differentiable(wrt: self)
    public func squared() -> Tensor

Available where `Scalar`: `TensorFlowFloatingPoint`

  • 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 }

Available where `Scalar` == `Bool`

  • Returns true if all scalars are equal to true . Otherwise, returns false .

    Declaração

    public func all() -> Bool
  • Returns true if any scalars are equal to true . Otherwise, returns false .

    Declaração

    public func any() -> Bool
  • Performs a logical AND operation along the specified axes. The reduced dimensions are removed.

    Precondition

    Each value in axes 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 in axes 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 in axes 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 in axes must be in the range -rank..<rank .

    Declaração

    public func any(alongAxes axes: Int...) -> Tensor

    Parameters

    axes

    The dimensions to reduce.

Available where `Scalar`: `Numeric` & `Comparable`

  • 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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>

Available where `Scalar`: `Numeric`

  • Returns the sum along the specified axes. The reduced dimensions are removed.

    Precondition

    Each value in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 to true , 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 to true , 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 to true , 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 to true , 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 be 0 .

    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 to true , 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 to true , 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 to true , 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 to true , 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 rank 0 .

    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.

Available where `Scalar`: `TensorFlowFloatingPoint`

  • 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 in axes 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 the exp of large inputs and underflows caused by computing the log of small inputs.

    Precondition

    Each value in axes 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 the exp of large inputs and underflows caused by computing the log of small inputs.

    Precondition

    Each value in axes 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 the exp of large inputs and underflows caused by computing the log of small inputs.

    Precondition

    Each value in axes 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 the exp of large inputs and underflows caused by computing the log 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 value 1 .

    This function is more numerically stable than computing log(exp(self).sum(alongAxes: axes)) directly. It avoids overflows caused by computing the exp of large inputs and underflows caused by computing the log of small inputs.

    Precondition

    Each value in axes 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 value 1 .

    This function is more numerically stable than computing log(exp(self).sum(alongAxes: axes)) directly. It avoids overflows caused by computing the exp of large inputs and underflows caused by computing the log of small inputs.

    Precondition

    Each value in axes 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 value 1 .

    This function is more numerically stable than computing log(exp(self).sum(alongAxes: axes)) directly. It avoids overflows caused by computing the exp of large inputs and underflows caused by computing the log of small inputs.

    Precondition

    Each value in axes 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 rank 1 .

    Precondition

    Each value in axes 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 in axes 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 in axes 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 rank 1 .

    Precondition

    Each value in axes 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 in axes 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 in axes 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.

Available where `Scalar`: `Numeric`

  • Performs matrix multiplication between two tensors and produces the result.

    Declaração

    @differentiable
    public static func  (lhs: Tensor, rhs: Tensor) -> Tensor

Available where `Scalar`: `TensorFlowFloatingPoint`

  • 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 where mu and var are respectively the mean and variance of self along axis .

    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)

Available where `Scalar`: `Equatable`

  • Declaração

    public static func == (lhs: Tensor, rhs: Tensor) -> Bool
  • Declaração

    public static func != (lhs: Tensor, rhs: Tensor) -> Bool

Available where `Scalar`: `Codable`

  • Declaração

    public func encode(to encoder: Encoder) throws
  • Declaração

    public init(from decoder: Decoder) throws

Available where `Scalar`: `Numeric`

  • 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
  • one

    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

Available where `Scalar`: `TensorFlowFloatingPoint`

  • 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>
    )