背景
tensorflow中需要对张量x添加噪声,x是占位符,其shape的第一维为None(即我们的batch_size不固定),若直接使用noise = tf.random_uniform(shape=(None, 2)
,报错“TypeError: Failed to convert object of type <class ‘tuple’> to Tensor. Contents: (None, 2). Consider casting elements to a supported type.”。
解决
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2021/9/20 19:31
# @Author : muyi
# @File : test_dimension.py
import tensorflow as tf
import numpy as np
x = tf.placeholder(tf.float32, (None, 2))
# noise = tf.random_uniform(shape=tf.shape(x))
noise = tf.random.truncated_normal(shape=tf.shape(x), mean=0, stddev=0.05/2)
# noise = tf.random.truncated_normal(shape=(None, 2), mean=0, stddev=0.05/2) # error
z = tf.add(x, noise)
data = np.zeros((6, 2))
sess = tf.Session()
print(sess.run(z, feed_dict={x:data}))