【发布时间】:2021-07-09 09:09:26
【问题描述】:
我正在尝试在 TF2 模型中的 call() 函数中获取 batch_size。
但是,我无法得到它,因为我知道的所有方法都返回 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, ) 作为目标提供给模型。
但如您所见,我无法在call() 函数中获取batch_size。
我需要它的原因是因为我必须为 batch_size 迭代张量,这在我的真实模型中是动态的。
例如,如果数据集大小为 10,batch size 为 3,则 last batch 中的最后一个 batch size 为 1。所以,我必须动态知道 batch size。
谁能帮帮我?
- 张量流 2.3.3
- CUDA 10.2
- python 3.6.9
【问题讨论】:
-
在
call()方法中你只需要创建你的模型。数据迭代,应该发生在train_step函数中。您确定在call()中需要batch_szie吗? -
@Kaveh 是的,我需要像here 那样做 3d 稀疏张量批量乘法。为此,据我所知,我必须知道
call()函数中的批量大小(实际上我是 pytorch 用户,所以可能是错误的。请告诉我)。
标签: tensorflow keras tensorflow2.0 tensorflow-datasets batchsize