- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
为了使模型的训练更快,在CPU上填充/生成批次并在GPU上并行运行模型的训练似乎是一个好习惯。为此,可以使用Python编写一个生成器类,该类继承Sequence
类。
这是文档的链接:
https://www.tensorflow.org/api_docs/python/tf/keras/utils/Sequence
该文档指出的重要内容是:
Sequence
are a safer way to do multiprocessing. This structure guarantees that the network will only train once on each sample per epoch which is not the case with generators.
from skimage.io import imread
from skimage.transform import resize
import numpy as np
import math
# Here, `x_set` is list of path to the images
# and `y_set` are the associated classes.
class CIFAR10Sequence(Sequence):
def __init__(self, x_set, y_set, batch_size):
self.x, self.y = x_set, y_set
self.batch_size = batch_size
def __len__(self):
return math.ceil(len(self.x) / self.batch_size)
def __getitem__(self, idx):
batch_x = self.x[idx * self.batch_size:(idx + 1) *
self.batch_size]
batch_y = self.y[idx * self.batch_size:(idx + 1) *
self.batch_size]
return np.array([
resize(imread(file_name), (200, 200))
for file_name in batch_x]), np.array(batch_y)
fit_generator(...)
函数。
gen = CIFAR10Sequence(x_set, y_set, batch_size)
# Train the model
model.fit_generator(generator=gen,
use_multiprocessing=True,
workers=6)
The use of
keras.utils.Sequence
guarantees the ordering and guarantees the single use of every input per epoch when usinguse_multiprocessing=True
.
use_multiprocessing
可能未设置为True。似乎只能在Linux上将其设置为True。 (我不知道在其他平台上情况如何。)但是
workers
参数仍然可以设置为大于0的值。
workers:
Integer. Maximum number of processes to spin up when using process-based threading. If unspecified, workers will default to 1. If 0, will execute the generator on the main thread.
use_multiprocessing:
Boolean. If True, use process-based threading. If unspecified, use_multiprocessing will default to False. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes.
workers
参数,似乎可以创建多个进程来独立于
use_multiprocessing
是否为True来加快训练速度。
Sequence
的生成器类(在Windows 10上为
,),则必须将
use_multiprocessing
设置为False,如下所示:
gen = CIFAR10Sequence(x_set, y_set, batch_size)
# Train the model
model.fit_generator(generator=gen,
use_multiprocessing=False, # CHANGED
workers=6)
use_multiprocessing
参数设置为False之后,此设置是否仍然是线程安全的,或者线程安全特性现在丢失了吗?根据文档,我无法明确说明。
最佳答案
在看过这篇文章的人中,似乎没有人给出最终答案,因此我想给出对我有用的答案。由于该领域缺乏文档,我的答案可能缺少一些相关细节。请随时添加我在这里没有提及的更多信息。
看来,在 Windows 中不支持使用Python编写继承Sequence
类的生成器类。 (您似乎可以使其在Linux上运行。)要使其运行,您需要设置参数use_multiprocessing=True
(使用类方法)。但是如上所述,它在Windows上不起作用,因此您必须将use_multiprocessing
设置为False
(在Windows上)。
但是,这并不意味着多重处理在Windows上不起作用。即使您设置了use_multiprocessing=False
,使用以下设置运行代码时仍可以支持多处理,您只需将workers
参数设置为任何大于1的值即可。
例子:
history = \
merged_model.fit_generator(generator=train_generator,
steps_per_epoch=trainset_steps_per_epoch,
epochs=300,
verbose=1,
use_multiprocessing=False,
workers=3,
max_queue_size=4)
The use of keras.utils.Sequence guarantees the ordering and guarantees the single use of every input per epoch when using use_multiprocessing=True.
use_multiprocessing=False
,则生成器不再是线程安全的,这使得编写继承
Sequence
的
生成器类变得很困难。
import tensorflow as tf
import threading
class threadsafe_iter:
"""Takes an iterator/generator and makes it thread-safe by
serializing call to the `next` method of given iterator/generator.
"""
def __init__(self, it):
self.it = it
self.lock = threading.Lock()
def __iter__(self):
return self
def __next__(self): # Py3
return next(self.it)
#def next(self): # Python2 only
# with self.lock:
# return self.it.next()
def threadsafe_generator(f):
"""A decorator that takes a generator function and makes it thread-safe.
"""
def g(*a, **kw):
return threadsafe_iter(f(*a, **kw))
return g
@threadsafe_generator
def generate_data(tfrecord_file_path_list, ...):
dataset = tf.data.TFRecordDataset(tfrecord_file_path_list)
# example proto decode
def _parse_function(example_proto):
...
return batch_data
# Parse the record into tensors.
dataset = dataset.map(_parse_function)
dataset = dataset.shuffle(buffer_size=100000)
# Repeat the input indefinitly
dataset = dataset.repeat()
# Generate batches
dataset = dataset.batch(batch_size)
# Create an initializable iterator
iterator = dataset.make_initializable_iterator()
# Get batch data
batch_data = iterator.get_next()
iterator_init_op = iterator.make_initializer(dataset)
with tf.Session() as sess:
sess.run(iterator_init_op)
while True:
try:
batch_data = sess.run(batch_data)
except tf.errors.OutOfRangeError:
break
yield batch_data
use_multiprocessing
设置为False
。 Sequence
的生成器类。 (我猜这是一个Tensorflow/Keras问题)。 workers
设置为大于1的数字。关于python - Keras/Tensorflow中的类生成器(继承序列)线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52932406/
我使用以下代码和嵌套生成器迭代文本文档并使用 get_train_minibatch() 返回训练示例。我想保留( pickle )生成器,这样我就可以回到文本文档中的相同位置。但是,您不能 pick
在本教程中,您将借助示例了解 JavaScript 生成器。在 JavaScript 中,生成器提供了一种使用函数和迭代器的新方法。 使用生成器, 您可以从函数内部的任何位置停止执行函数 并从
LESS is very cool .我一直想知道是否有任何好的 html 生成器可以让我更轻松地编写表单或做其他事情。除了 html,是否有一些类似的东西? 最佳答案 已尝试 Haml ? 从它的网
前言 如果是做python或者其他语言的小伙伴,对于生成器应该不陌生。但很多php开发者或许都不知道生成器这个功能,可能是因为生成器是php 5.5.0才引入的功能,也可以是生成器作用不是很明显。
我正在尝试编写一个使用生成器语法生成日期时间列表的函数: let dateRange = let endDate = System.DateTime.Parse("6/1/2010")
我遇到了一些看起来像的代码: [func(val) for val in iterable] 有一个可迭代对象(在我的例子中是一个生成器),用户想要为其副作用调用每个值的函数(例如 func 可以只是
Delphi 有内置的东西来生成 UUID 吗? 最佳答案 program Guid; {$APPTYPE CONSOLE} uses SysUtils; var Uid: TGuid; Result
我正在深入研究 javascript 生成器,但我真的很困惑。 我使用 node@0.11.x 运行此示例: function find() { process.nextTick(functi
有人知道一些关于如何为 hibernate 创建自定义 ID 生成器的好教程吗? 最佳答案 在 Google 上粗略搜索“hibernate 自定义 id 生成器教程”发现了以下可能性。我排除了那些看
我正在关注 Python 大师 David Beazley 的幻灯片。它指出“生成器也用于并发。这是一个示例: from collections import deque def countdown(
我有一个生成事件的生成器,我想用可以从 API 获取的附加元数据来丰富它。 某些事件具有与其链接的对象 ID,而其他事件则具有对象的哈希值,但不能同时具有两者。我无法根据哈希获取对象 id,我只能执行
假设我有一个自定义类: public class CustomClass { private String name; private String data; public
我正在考虑实现一个函数来在 SQL 请求中“构建”WHERE 子句,如下所示: "SELECT * FROM table $where" 使用如下所示的循环构建 $where: $arr=array(
我正在寻找执行此操作的标准函数: def Forever(v): while True: yield v 这看起来太琐碎了,我不敢相信没有标准版本。 就此而言,有人知道指向所有标准生成器函
我知道这个网站上有几个非常相似的相关问题,但是在看了这部剧之后,我相信这个问题本身就是独一无二的。如果有人能找到并提供证据证明我的问题完全被骗了,我会自己撤回它(所以请不要否决这个!)。 我是 Jav
void __fastcall TForm1::Button1Click(TObject *Sender) { int size = MemoEnter->GetTextLen() + 1;
按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我试图在我的生成器的以下两个定义之间做出决定。哪个更好?哪个“更像 python ”?无论如何,有没有办法减轻每一个的缺点? def myGenerator1(howMany): result
我有一个 Python 生成器 lexg,它在每次迭代时生成一个列表。该代码似乎在传统的 for 循环意义上工作,即 for i in lexg(2,2): print(i) 产生: [2, 0] [
我希望这不会超出 Python 生成器的能力,但我想构建一个这样,每次调用该函数时,它都会返回下一分钟直到结束时间。 因此该函数读取开始时间和结束时间,并以分钟为单位返回时间,直到涵盖其间的所有时间。
我是一名优秀的程序员,十分优秀!