【问题标题】:How to align shape of a tensor returned by an iterator with a tensorflow variable如何将迭代器返回的张量的形状与张量流变量对齐
【发布时间】:2019-07-11 21:44:42
【问题描述】:

这可能是一个非常简单的问题,但是我对 tensorflow 还很陌生,并且一直被困在这个问题上。我使用 tensorflow 1.12 和 python 3。

我的问题是,设置迭代器返回的张量对象的形状的正确方法是什么?

使用占位符,我可以使类似这样的代码工作,但我想在没有占位符的情况下使用 tensorflow 数据集来完成这项工作。

我不知道如何将张量的形状与矩阵对齐以使用 tf.matmul。

我收到的错误是:ValueError: Shape must be rank 2 but is rank 1 for 'MatMul_19' (op: 'MatMul') with input shapes: [2], [2,1].强>

迭代器的数据集指定为:TensorSliceDataset 形状:(2,),类型:tf.float32>

提前致谢!

import tensorflow as tf
import numpy as np

batch_size = 200

# this simulates a dataset read from a csv.....
x=np.array([[0., 0.], [1., 0.], [0., 1.], [1., 1.]],dtype="float32")
y=np.array([0, 0, 0, 1],dtype="float32")

dataset = tf.data.Dataset.from_tensor_slices((x))
print(dataset)                  # <TensorSliceDataset shapes: (2,), types: tf.float32>
dataset = dataset.repeat(10000)
print('repeat ds ', dataset)    # repeat ds  <RepeatDataset shapes: (2,), types: tf.float32>

iter = dataset.make_initializable_iterator()
print('iterator ', iter)        # iterator  <tensorflow.python.data.ops.iterator_ops.Iterator object at 0x0000028589C62550>

sess = tf.Session()
sess.run(iter.initializer)
next_elt= iter.get_next()

print('shape of dataset ', dataset , '[iterator] elt ', next_elt)  # shape of dataset  <RepeatDataset shapes: (2,), types: tf.float32> [iterator] elt  Tensor("IteratorGetNext_105:0", shape=(2,), dtype=float32)
print('shape of it ', next_elt.shape) #s hape of it  (2,)
for i in range(4):
    print(sess.run(next_elt))
    ''' outputs: 
    [0. 0.]
    [1. 0.]
    [0. 1.]
    [1. 1.]

    '''

w = tf.Variable(tf.random_uniform([2,1], -1, 1, seed = 1234),name="weights_layer_1")
# this is where the error is because of shape mismatch of iterator and w variable.
# How od I make the shape of the iterator (2,1) so that matmul can be used?
# What is the proper way of aligning a tensor shape with inut data
# The output of the error:
#     ValueError: Shape must be rank 2 but is rank 1 for 'MatMul_19' (op: 'MatMul') with input shapes: [2], [2,1].
H = tf.matmul( sess.run(next_elt) , w)

【问题讨论】:

    标签: tensorflow dataset


    【解决方案1】:

    您可以使用 tf.reshape。只需在 matmul op 之前添加 tf.reshape(next_elt, [1,2]) 更多关于重塑https://www.tensorflow.org/api_docs/python/tf/reshape

    【讨论】:

    • 谢谢!这正是我所需要的。我在声明 next_elt 之后添加了 next_elt = tf.reshape(next_elt, [1,2]) 并且它有效。
    猜你喜欢
    • 2018-12-13
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多