簡體   English   中英

我怎樣才能重塑張量

[英]How can I reshape the tensor

tensor([[17,  0],
        [93,  0],
        [ 4,  0],
        [72,  0],
        [83,  0],
        [67,  0],
        [34,  0],
        [21,  0],
        [19,  0])

我想把這個二維數組的tensor去掉0,變成一維數組。

我怎樣才能用下面的張量制作這個張量?

tensor([[17],
        [93],
        [4],
        [72],
        [83],
        [67],
        [34],
        [21],
        [19])

假設張量是一個numpy數組。

首先,使用x= x.flatten()展平矩陣

然后使用x = x[x!=0]刪除所有出現的zeros

然后使用x = np.reshape(x, ( -1, x.shape[0] ))在 2D 中重塑數組

這 ( x ) 會返回給你:

array([[17, 93,  4, 72, 83, 67, 34, 21, 19]])

Tensorflow中,您可以簡單地使用boolean_mask

import tensorflow as tf

tensor = tf.constant([[17,  0],
        [93,  0],
        [ 4,  0],
        [72,  0],
        [83,  0],
        [67,  0],
        [34,  0],
        [21,  0],
        [19,  0]])
tensor = tf.boolean_mask(tensor, tf.cast(tensor, dtype=tf.bool), axis=0)
tf.Tensor([17 93  4 72 83 67 34 21 19], shape=(9,), dtype=int32)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM