2017-01-23 203 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