【发布时间】:2017-06-08 08:18:41
【问题描述】:
所以我有一个形状为(50, ?, 1, 100) 的张量h_in,现在我想通过在轴1 上取最大值来转换为形状(50, 1, 1, 100)。
我该怎么做?
我试过了
h_out = max_pool(h_in)
与
def max_pool(h,ksize=[1,-1,1,1],strides=[1,1,1,1],padding='VALID'):
return tf.nn.max_pool(h,ksize=ksize,strides=strides,padding=padding)
但这似乎并没有减少尺寸。
可运行示例:
import tensorflow as tf
import numpy as np
import numpy.random as nprand
def _weight_variable(shape,name):
initial = tf.truncated_normal(shape,stddev=0.1)
v = tf.Variable(initial,name=name)
return v
def _bias_variable(shape,name):
initial = tf.constant(0.1,shape=shape)
v = tf.Variable(initial,name=name)
return v
def _embedding_variable(shape,name):
initial = tf.truncated_normal(shape)
v = tf.Variable(initial,name=name)
return v
def conv2d(x,W,strides=[1,1,1,1],padding='VALID'):
return tf.nn.conv2d(x,W,strides=strides,padding=padding)
def max_pool(h,ksize=[1,-1,1,1],strides=[1,1,1,1],padding='VALID'):
return tf.nn.max_pool(h,ksize=ksize,strides=strides,padding=padding)
nof_embeddings= 55000
dim_embeddings = 300
batch_size = 50
filter_size = 100
x_input = tf.placeholder(tf.int32, shape=[batch_size, None])
def _model():
embeddings = _embedding_variable([nof_embeddings,dim_embeddings],'embeddings')
h_lookup = tf.nn.embedding_lookup(embeddings,x_input)
h_embed = tf.reshape(h_lookup,[batch_size,-1,dim_embeddings,1])
f = 3
W_conv1f = _weight_variable([f,dim_embeddings,1,filter_size],f'W_conv1_{f}')
b_conv1f = _bias_variable([filter_size],f'b_conv1_{f}')
h_conv1f = tf.nn.relu(conv2d(h_embed,W_conv1f) + b_conv1f)
h_pool1f = max_pool(h_conv1f)
print("h_embed:",h_embed.get_shape())
print()
print(f'h_conv1_{f}:',h_conv1f.get_shape())
print(f'h_pool1_{f}:',h_pool1f.get_shape())
print()
return tf.shape(h_pool1f)
if __name__ == '__main__':
tensor_length = 35
model = _model()
with tf.Session() as sess:
tf.global_variables_initializer().run()
batch = nprand.randint(0,nof_embeddings,size=[batch_size,tensor_length])
shape = sess.run(model,
feed_dict ={
x_input : batch
})
print('result:',shape)
哪个输出
h_embed: (50, ?, 300, 1)
h_conv1_3: (50, ?, 1, 100)
h_pool1_3: (50, ?, 1, 100)
result: [ 50 35 1 100]
假设我改为硬编码我想要的大小:
h_pool1f = max_pool(h_conv1f,ksize=[1,35-f+1,1,1])
这行得通。
但是现在我一更改tensor_length 就遇到了麻烦(这是在运行时确定的,所以不,我不能对其进行硬编码)。
一个“解决方案”是通过填充或其他方式将输入放大到固定的最大长度,但话又说回来,这会引入不必要的计算和人为的上限,我非常希望避免这两种情况。
那么,有没有
- 一种让 tensorflow “正确”识别
k_size中的-1的方法? - 或其他计算最大值的方法?
【问题讨论】:
-
我认为
tf.reduce_max是你要找的东西 -
@PietroTortella 对其进行了一些测试,愿意相信它正在做我正在寻找的事情,谢谢。想要将您的评论扩展为答案?
标签: python python-3.x tensorflow max pooling