这可能是一个非常简单的问题,但是我对tensorflow还是比较陌生,并且一直停留在这个问题上。我使用tensorflow 1.12和python 3。
我的问题是,设置迭代器返回的张量对象的形状的正确方法是什么?
使用占位符,我可以使类似此代码的内容起作用,但是我想在没有占位符且使用tensorflow数据集的情况下使其起作用。
我无法弄清楚如何使张量的形状与矩阵对齐才能使用tf.matmul。
我收到的错误是: ValueError:形状必须为2级,但对于'MatMul_19'(op:'MatMul')而言,其形状为1级,输入形状为[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)
答案 0 :(得分:0)
您可以使用tf.reshape。只需在matmul op之前添加tf.reshape(next_elt, [1,2])
重塑https://www.tensorflow.org/api_docs/python/tf/reshape