【问题标题】:how to slice a array in tensorflow tensor?如何在张量流张量中对数组进行切片?
【发布时间】:2018-12-28 12:30:22
【问题描述】:
import tensorflow as tf
import numpy as np
import keras

a = np.array([0.1,0.2,0.3,0.4,0.5])
b = np.array([1,2,3,4,5])

def helper(m):
    x = m[0]
    y = m[1]
    idx = tf.where(x>0.3)
    y = tf.gather(y, idx)
    return y
def helper_output_shape(input_shape):
    return (2,2,1)
x1 = keras.layers.Input(shape=(1,))
x2 = keras.layers.Input(shape=(1,))
r = keras.layers.Lambda(helper, output_shape=helper_output_shape)([x1,x2])

model = keras.Model([x1,x2],r)
model.compile(optimizer='sgd',loss='mean_squared_error')
model.predict([a,b])

如代码所示,有两个数组:scores 和 target。我想根据分数对目标数组进行切片。 例如(如以上代码所示):

a = np.array([0.1,0.2,0.3,0.4,0.5]) # scores array
b = np.array([1,2,3,4,5])           # target array

# I want to keep the value that has a higher score than 0.3 in b, and remove the rest. So the result should be array([4,5])

但收到此错误。 错误:

ValueError: could not broadcast input array from shape (2,2,1) into shape (5,2,1)

我尝试使用 Lambda 中的 output_shape 来解决输入和输出之间形状不匹配的问题,但不起作用。如何解决这个问题? 谢谢!

【问题讨论】:

    标签: python tensorflow keras slice


    【解决方案1】:

    就这个特定错误而言,您可以像这样返回。

    def helper(m):
        x = m[0]
        y = m[1]
        idx = tf.where(x>0.3)
        y = tf.gather(y, idx)
        print( y.get_shape())  #This prints (?, 2, 1)
        return tf.constant([0,0,0,1,1],tf.float32)   #This can be coded generically.
    

    这个示例返回值解决了形状问题。我们匹配它所期望的 (5,2,1) 中的 5。 5 是输入中元素的数量。

    【讨论】:

    • 我不明白。如果返回一个常量,它会使所有这些变得毫无意义。不是吗?
    • 没有。我的意思是可以使用具有与输入一样多的元素的任何有效值。那是一个例子。这是专门针对此示例和错误的。
    • 我知道为什么会发生这个错误。我认为这是因为输入形状和输出形状不匹配。我想知道如何解决它。实际上,我希望输出为 array([4,5]),形状为 (2,1)。你能帮我弄清楚吗?
    • 我或其他人可以。请使用此详细信息更新您的问题,以便其他人也可以提供帮助。
    猜你喜欢
    • 2019-08-06
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 2019-04-13
    • 2019-11-02
    • 1970-01-01
    • 2018-03-15
    • 2019-03-24
    相关资源
    最近更新 更多