您可以在Tensorflow的占位符中转置/反转形状吗?

时间:2018-12-02 07:04:40

标签: python tensorflow neural-network

让我们说我的输入数据x的形状为(2000,2),其中2000是样本数,2是要素数。

因此对于此输入数据,我可以像这样设置一个占位符: x = tf.placeholder(tf.float32,shape = [None,2],name ='features')

我的问题是,如果我将输入数据x换位,以使形状现在为(2,2000),其中2000仍然是样本数,我将如何更改tf.placeholder中的“ shape”参数?

我尝试设置shape = [2,None],但是我刚遇到一个错误。 “ shape”参数中的第一个元素是否必须始终为“ None”? 在这里,我得到的错误是:“ ValueError:应该定义Dense的输入的最后维度。找到None。”

import tensorflow as tf
# Binary Classifier Implementation

# Training data
x_train = np.transpose(X) #shape=(2, 2000)
y_train = np.hstack((np.zeros((1, 1000)),np.zeros((1, 1000)) + 1)) #shape=(1, 2000)


# Variables
x = tf.placeholder(tf.float32, shape=[2, None], name='features')
y_ = tf.placeholder(tf.int64, shape=[1, None], name='labels')
h1 = tf.layers.dense(inputs=x, units=50, activation=tf.nn.relu) #one hidden layer with 50 neurons
y = tf.layers.dense(inputs=h1, units=1, activation=tf.nn.sigmoid) #one output layer with 1 neuron


# Functions
#loss
cross_entropy = tf.losses.sigmoid_cross_entropy(multi_class_labels=y_, logits=y)
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy)


# Initializer
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for i in range(1000):
        sess.run([cross_entropy], feed_dict={x: x_train, y_: y_train})

1 个答案:

答案 0 :(得分:0)

我认为您可能会遇到形状不一致的问题,而不是因为第一个暗角以外的其他地方而不是换位或具有不确定的尺寸大小。
以下内容对我来说很好:

import tensorflow as tf

x = tf.placeholder(tf.float32, shape=[None, 2])
x_t = tf.transpose(x)
y = tf.placeholder(tf.float32, shape=[2, None])

print(x_t.shape)
>> TensorShape([Dimension(2), Dimension(None)])

print(y.shape)
>> TensorShape([Dimension(2), Dimension(None)])

我假设第一个尺寸可能是您的批量大小?您可能与此不一致或输入错误的数据吗?
或者也许您正在尝试手动更改张量的形状? (如果是这样,则无需这样做。在我的示例中,tf会处理该问题。)
这是您最大的帮助,而您无需了解所得到的错误,代码段或含糊而笼统的描述,但我希望它能对您有所帮助。
祝好运!


由于更新的问题而更新:
您遇到的错误是在告诉您确切的问题是什么。您可以随意转置任何内容,但是dense层不能接受 last 维度为None的张量。这很有道理;您将无法创建完全连接的图层,例如不知道权重矩阵的大小。
如果您要转置x,则表示您具有2000个要素(和2个数据点),并且NN需要知道才能创建您要的参数要去训练
如果您仍然认为自己具有2个功能和许多示例,那么您不应该首先使用形状(2,2000)!
请尝试以下操作:

# Training data
x_train = X #shape=(2000, 2)
y_train = np.hstack((np.zeros((1000, 1)),np.zeros((1000, 1)) + 1)) #shape=(2000, 1)


# Variables
x = tf.placeholder(tf.float32, shape=[None, 2], name='features')
y_ = tf.placeholder(tf.int64, shape=[None, 1], name='labels')
h1 = tf.layers.dense(inputs=x, units=50, activation=tf.nn.relu) #one hidden layer with 50 neurons
y = tf.layers.dense(inputs=h1, units=1, activation=tf.nn.sigmoid) #one output layer with 1 neuron


# Functions
#loss
cross_entropy = tf.losses.sigmoid_cross_entropy(multi_class_labels=y_, logits=y)
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy)


# Initializer
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for i in range(1000):
        sess.run([cross_entropy], feed_dict={x: x_train, y_: y_train})

希望这会有所帮助。


另一个完全不相关的注解:我希望您知道将2个要素以这种方式嵌入50维空间时的操作。