我正在尝试在 TF2 模型中发挥作用batch_size
。call()
但是,我无法得到它,因为我知道的所有方法都返回None
或 Tensor 而不是维度元组。
这是一个简短的例子
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Model
class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
def call(self, x):
print(len(x))
print(x.shape)
print(tf.size(x))
print(np.shape(x))
print(x.get_shape())
print(x.get_shape().as_list())
print(tf.rank(x))
print(tf.shape(x))
print(tf.shape(x)[0])
print(tf.shape(x)[1])
return tf.random.uniform((2, 10))
m = MyModel()
m.compile(optimizer="Adam", loss="sparse_categorical_crossentropy", metrics=['accuracy'])
m.fit(np.array([[1,2,3,4], [5,6,7,8]]), np.array([0, 1]), epochs=1)
输出是:
Tensor("my_model_26/strided_slice:0", shape=(), dtype=int32)
(None, 4)
Tensor("my_model_26/Size:0", shape=(), dtype=int32)
(None, 4)
(None, 4)
[None, 4]
Tensor("my_model_26/Rank:0", shape=(), dtype=int32)
Tensor("my_model_26/Shape_2:0", shape=(2,), dtype=int32)
Tensor("my_model_26/strided_slice_1:0", shape=(), dtype=int32)
Tensor("my_model_26/strided_slice_2:0", shape=(), dtype=int32)
1/1 [==============================] - 0s 1ms/step - loss: 3.1796 - accuracy: 0.0000e+00
在此示例中,我将(2,4)
numpy 数组作为输入和(2, )
目标提供给模型。但正如你所见,我无法batch_size
发挥call()
作用。
我需要它的原因是因为我必须迭代batch_size
在我的真实模型中是动态的张量。
例如,如果数据集大小为 10,批量大小为 3,那么最后一批中的最后一个批量大小将为 1。所以,我必须动态知道批量大小。
谁能帮我?
- 张量流 2.3.3
- CUDA 10.2
- 蟒蛇 3.6.9