2017-01-23 149 views
0

平均行我在numpy的以下函数:插入在tensorflow张量

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,因为似乎没有相同的功能。

回答

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 
+0

这看起来不错,但它仍然使用numpy的,而不是tensorflow的。我的问题是,我似乎无法找到可用于翻译此代码的tensorflow等价物。 – Qubix

+0

@Qubix所以'tensorflow'不支持数组初始化? – Divakar

+0

我在说像“np.setdiff1d”这样的函数可能没有相同的功能。我正在查看文档。 – Qubix