python - TF map_fn 太慢了
问题描述
我想在 tensorflow 中创建一个自定义层,它应该将函数f
应用于传入的张量。因此,如果批次由张量组成,T = [T1, T2, ..., Tn]
它应该返回张量[f(T1), f(T2), ..., f(Tn)]
。
这样做的预期方法似乎是使用该tf.map_fn
功能。但是,我注意到这个函数非常慢。下面是一个 MWE,它在我的笔记本电脑上产生以下性能:
- ~61us/step 无身份层
- ~62us/step with identity layer
output=inputs
- ~120us/step with identity layer
output=tf.map_fn(...)
有什么方法可以加快批量大小的迭代?
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
class Identity(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super(Identity, self).__init__(**kwargs)
def call(self, inputs):
output = tf.map_fn(lambda x: x, inputs)
# output = inputs
return output
def compute_output_shape(self, input_shape):
return input_shape
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
Identity(),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5, batch_size=100)
解决方案
推荐阅读
- vb.net - VB .NET - 左侧的全文对齐标题表单
- php - 如何将多个表的foreach限制为一个表
- java - 空指针异常,在控制器类中为 Oauth 编写 Junit/Mockito 测试用例时,JSON 响应
- scheme - 使用 Lilypond 音乐替换功能传递和返回音乐
- java - 空指针异常 Kotlin 应用程序
- mongodb - 可以在 <1 秒内通过 SQL 运行此查询,但聚合 MongoDB 不能在 45 分钟内从具有相同索引的同一数据集运行
- bash - 在 bash 命令行工具中将字符串或数组转换为单独的输入
- firebase - Firestore 中授权写入的安全规则
- spring - Spring Boot 的 spring-boot:run 不遵守指定的配置文件
- javascript - 在Javascript中按降序对字符串进行排序(最有效)?