将sqlite与keras生成器一起使用

安东·洛舍夫(Anton Losev)

我正在尝试使用keras生成器对cnn进行批处理。我的数据在SQLITE数据库中。SQLITE无法使用多线程代码,因此每次我需要导入批处理时,我都会打开与db的连接,接下来,我尝试执行简单的sql查询(查询在简单脚本中执行时没有错误),并且出现此错误:

File "<ipython-input-4-6c84648166ec>", line 1, in <module>
    db_cursor.execute(sql_query)
TypeError: convert_array() takes 1 positional argument but 2 were given

我的代码:

import numpy as np
import keras
import sqlite3
import io

class DataGenerator(keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, path, num_features, end_index, start_index=1,    augmentation_ratio=2, batch_size=250,
                 shuffle=True, exclude = []):
        'Initialization'
        sqlite3.register_adapter(np.ndarray, self.adapt_array)
        sqlite3.register_converter("array", self.convert_array)
        self.path = path
        self.db = sqlite3.connect(self.path, detect_types=sqlite3.PARSE_DECLTYPES, check_same_thread=False)
        self.db_cursor = self.db.cursor()
        self.exclude = exclude
        self.N = num_features
        self.start_index = start_index
        self.end_index = end_index
        self.augmentation_ratio = augmentation_ratio
        self.batch_size = int(batch_size)
        self.shuffle = shuffle
        self.import_size = int(np.floor(self.batch_size / self.augmentation_ratio))
        if exclude.__len__() == 0:
            self.sample_index = np.arange(self.start_index, self.end_index)
        else:
            query = 'SELECT ind FROM TABLE WHERE ind > ? AND ind < ? AND class NOT IN ({})'. \
                format(','.join(str(label) for label in self.exclude))
            self.db_cursor.execute(query, [self.start_index, self.end_index])
            self.sample_index = np.asarray(self.db_cursor.fetchall())
        self.n_samples = self.sample_index.shape[0]
        self.on_epoch_end()
        self.db.close()




    def __len__(self):
        'Denotes the number of batches per epoch'
        return int(np.floor(self.n_samples / self.import_size))

    def __getitem__(self, index):
        'Generate one batch of data'
        # Generate indexes of the batch
        samples_batch = np.arange((index - 1) * self.import_size, index * self.import_size)

        # Generate data
        x, y = self.__data_generation(samples_batch)

        augmented_x = self.augment_data(x)

        samples = np.concatenate((x, augmented_x))
        y_mat = np.concatenate((y, y))
        # return X_reshaped, xData_complete
        return  samples, y_mat

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        if self.shuffle:
            np.random.shuffle(self.sample_index)

    def __data_generation(self, samples_batch):
        'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
        # Initialization
        x = np.empty((self.import_size, self.N, 1))
        y = np.empty((self.import_size, 1))
        inds = self.sample_index[samples_batch]
        sqlite3.register_adapter(np.ndarray, self.adapt_array)
        sqlite3.register_converter("array", self.convert_array)
        db = sqlite3.connect(self.path, detect_types=sqlite3.PARSE_DECLTYPES)
        db_cursor = db.cursor()
        sql_query = "SELECT class,features FROM TABLE WHERE ind in ({})".\
            format(','.join(str(ind[0]) for ind in inds))
        db_cursor.execute(sql_query)
        for i in range(self.import_size):
            line = db_cursor.fetchone()
            y[i] = line[0]
            x[i, :] = line[1]
        y = keras.utils.to_categorical(y)
        return x, y

    def adapt_array(arr):
        out = io.BytesIO()
        np.save(out, arr)
        out.seek(0)
        return sqlite3.Binary(out.read())

    def convert_array(text):
        out = io.BytesIO(text)
        out.seek(0)
        return np.load(out)

我究竟做错了什么?

离子溶液

您的adapt_arrayconvert_array方法缺少self参数:

def convert_array(self, text):
    out = io.BytesIO(text)
    out.seek(0)
    return np.load(out)

另外,您可以使用@staticmethod装饰器:

@staticmethod
def convert_array(text):
    out = io.BytesIO(text)
    out.seek(0)
    return np.load(out)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将MongoDB与Sequence类或Keras的生成器一起使用?

使用绑定与将指针与随机数生成器一起使用

如何将Python的随机数生成器与本地种子一起使用?

如何将ShowCaseView v5生成器与片段一起使用?

如何将Bluebird Promisification与生成器+并行Prom一起使用

将LINQ与EF反向POCO生成器一起使用?

将 TF 估计器与 TFRecord 生成器一起使用

将socket.io与Express 4生成器一起使用

将样式生成器与AppCompat一起使用时出错

Keras:将生成器与model.fit_generator一起用于多输出模型

如何将Keras数据生成器(或不同方法)与多个不同长度的.npy文件一起使用?

如何将TypeScript 1.6与Visual Studio Code一起使用以获得生成器支持?

是否可以将Yeoman Angular生成器与Yeoman Angular全栈组织一起使用?

将 `conan.cmake` 与 `conan_multi` 生成器一起使用,缺少 build_type 参数?

将ES5数组方法与ES6生成器一起使用

我在python 3中将生成器与输入函数一起使用时遇到问题

在报表生成器3.0中使用的SQL查询:将结果分组在一起

为什么此生成器与for循环一起使用,而不与next()一起使用?

如何在Haskell中将随机生成器使用函数与fmap一起使用?

Laravel 5.0查询与联接一起使用查询生成器

Javascript Templete文字无法与随机数生成器一起使用

Python如何与多个“发送”调用生成器一起使用?

没有__iter __()方法但类实例与next()一起使用的类生成器

在Python中将str.join与生成器表达式一起使用

随机数生成器不能与parseInt一起使用吗?

MVC:如何与自定义代码生成器一起使用

koa-router无法与生成器一起使用

如何将python生成器与通过x_train和y_train变量接收数据的神经网络一起使用?

防止对将查询生成器与DB :: raw()组合在一起的查询进行SQL注入