【问题标题】:Inserting average rows in tensorflow tensor在张量流张量中插入平均行
【发布时间】:2017-01-23 09:23:03
【问题描述】:

我在numpy中有如下函数:

A = np.array([[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9],
          [10, 11, 12]])


def insert_row_averages(A, n=2):
    slice2 = A[n::n]
    v = (A[n-1::n][:slice2.shape[0]] + slice2)/2.0
    np.insert(A.astype(float),n*np.arange(1,v.shape[0]+1),v,axis=0)

它基本上取上下行的平均值,并每隔 n 间隔将其插入两者之间。

知道如何在 Tensorflow 中完成这项工作吗?具体来说,我可以用什么来代替 np.insert,因为似乎没有等效的功能。

【问题讨论】:

    标签: arrays numpy insert tensorflow


    【解决方案1】:

    您可以使用基于初始化的方法来解决它,就像这样 -

    def insert_row_averages_iniitalization_based(A, n=1):
    
        # Slice and compute averages   
        slice2 = A[n::n]
        v = (A[n-1::n][:slice2.shape[0]] + slice2)/2.0
    
        # Compute number of rows for o/p array
        nv = v.shape[0]
        nrows = A.shape[0] + nv
    
        # Row indices where the v values are the inserted in o/p array
        v_rows = (n+1)*np.arange(nv)+n
    
        # Initialize o/p array
        out = np.zeros((nrows,A.shape[1]))
    
        # Insert/assign v in output array
        out[v_rows] = v  # Assign v
    
        # Create 1D mask of length equal to no. of rows in o/p array, such that its
        # TRUE at places where A is to be assigned and FALSE at places where values
        # from v were assigned in previous step.
        mask = np.ones(nrows,dtype=bool)
        mask[v_rows] = 0
    
        # Use the mask to assign A.
        out[mask] = A
        return out
    

    【讨论】:

    • 看起来不错,但它仍然使用 numpy 而不是 tensorflow。我的问题是我似乎无法找到可用于翻译此代码的 tensorflow 等效项。
    • @Quubix 那么,tensorflow 不支持数组的初始化?
    • 我是说像“np.setdiff1d”这样的函数可能没有等价物。我现在正在查看文档。
    • @Quubix 替换为更简单的函数。查看修改!
    • 谢谢,如果可行,将尝试在 tesorflow 中实现并在此处写下答案。
    猜你喜欢
    • 1970-01-01
    • 2016-12-12
    • 2018-06-30
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    相关资源
    最近更新 更多