如何修改张量的列

时间:2019-10-07 11:40:06

标签: python tensorflow

我想做一个特征函数,例如:我有一个张量X,如果X [:,i]> 1则X [:,i] = 0,否则X [:,i] = 1。但是我想保留X的形状

我已经尝试过几次重塑,但是在拆开X并更改列表的值后找不到X的形状完全相同



def g_tf(self, t,X):

        x_unpacked = tf.unstack(X,num=None,axis=1)
        processed = []
        for little_x in x_unpacked: 
          tensor_10= tf.cast(tf.constant([1.0])[None, None], tf.float64)
          tensor_1=tf.reshape(tensor_10, tf.shape(x_petit))

          bool=tf.greater(little_x, tensor_1, name=None)
          bool_reshape= tf.reshape(boule, [])
          result_tensor= tf.cond(boule_reshape, lambda: tf.constant(1),lambda: tf.constant(0))
          processed.append(result_tensor)
        output=tf.stack(processed, 0) 
        print(output) #Tensor("forward/stack:0", shape=(50,), dtype=int32)
        Output__=tf.cast(output, dtype =tf.float64 )
        X_new=X  # Shape of X :  shape=(?, 50), dtype=float64)

        print(X_new[1])  #Tensor("forward/strided_slice_190:0", shape=(50,), dtype=float64)

        X_new= X_new[1].assign(Output__)  #They have the same shape : shape=(50,)

        final_op= tf.reduce_sum(X_new,1, keepdims=True)                    
        return final_op

ValueError:试图将“输入”转换为张量,但失败。错误:不支持任何值。 该错误发生在以下行:X_new= X_new[1].assign(Output__)

1 个答案:

答案 0 :(得分:0)

我希望我能正确地理解您的意图。我不太喜欢你在这里做什么。但是以下解决方案应该可以满足您的目标。

例如,如果您有数组[[2,3], [1,0], [0,0]],则希望输出为[[1,1],[0,0],[0,0]]。希望我做对了。如果这是您需要的,那么应该可以使用。

import tensorflow as tf

# some random dataset
x = tf.random.normal(shape=(5,10),mean=2.0, stddev=0.5)

# Getting the colums of the data
x_unpack = tf.unstack(x, axis=1)

processed =[]
for x_col in x_unpack:
  ones = tf.ones_like(x_col)
  # Checks if all values in x_col are greater than one
  cond_tensor = tf.reduce_all(tf.greater(x_col, ones)) 
  # Get the resulting column
  res = tf.cond(cond_tensor, lambda: tf.ones_like(x_col),lambda: tf.zeros_like(x_col)) 
  processed.append(res)

out = tf.stack(processed, axis=1)

with tf.Session() as sess:
  print(sess.run(out))