将 SQL 数据集读入 Tensorflow 的最佳方法是什么?

数据挖掘 机器学习 深度学习 张量流 数据集 sql
2022-02-14 22:20:12

将 SQL 数据库读入 TensorFlow 的最佳方法是什么?

目前,我在服务器上使用 Postgres,并使用 Jupyter Lab 在 Tensorflow 上开发 DL 算法。如何使用tf.dataAPI 将数据导入 Jupyter Lab?我不想将数据存储在磁盘中并在新数据到达时继续运行算法。

似乎tf.data.experimental.SqlDataset只支持 sqlite。

(注意:我没有升级我的 Tensorflow,所以,我使用 tf.contrib.data.SqlDataset()的是最小的工作示例。)

我将数据从 PostgreSQL 迁移到 SQLite3 并使用

#Ignore the warnings
import warnings
warnings.filterwarnings("ignore")

import tensorflow as tf
#To start an input pipeline, you must define a source
dataset = tf.contrib.data.SqlDataset("sqlite", "/home/musara1/musara_dev.sqlite3",
                                 "SELECT * FROM basetable LIMIT 10",
                                 (tf.string, tf.int32, tf.int32, tf.int32, tf.int32, tf.int32, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.int32, tf.int32, tf.int32))

iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()
# Prints the rows of the result set of the above query.
sess=tf.InteractiveSession()

print(sess.run(next_element))

我可以打印下一个元素。但是,我需要对数据集进行其他转换。例如拆分为培训/验证/测试并删除一些列等等。但是,输出tf.contrib.data.SqlDataset()对我来说是 <SqlDataset shapes: ((), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), ()), types: (tf.string, tf.int32, tf.int32, tf.int32, tf.int32, tf.int32, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.float64, tf.int32, tf.int32, tf.int32)>

我有 25 列并tf.contrib.data.SqlDataset()创建 25 个不同的tensorflow.python.framework.ops.Tensor. 我怎样才能把它们放在一起?因此,我可以使用tf.data.Dataset.from_tensor_slices()?

3个回答

您使用SqlDataset上的方法来操作数据。例如,使用以下命令创建一个训练/测试拆分:

test_dataset = dataset.take(1000) 
train_dataset = dataset.skip(1000)

我会删除SELECT语句中不需要的列,以尽早减小数据的大小。

那个导入步骤看起来不对。你可以这样试试吗?

import pypyodbc 
cnxn = pypyodbc.connect("Driver={SQL Server Native Client 11.0};"
                        "Server=ServerName;"
                        "Database=TestDB;"
                        "Trusted_Connection=yes;")

cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Actions')

for row in cursor:
    print('row = %r' % (row,))

我迟到了,但对于以后阅读这篇文章的人来说:SQLAlchemy 是处理任何 SQL 接口的好方法。只需创建一个与您的数据库模式匹配的模型类,然后使用查询 API 来获取您的数据。

如果您有非常大的数据集,您可以使用 useyield_perslice轻松地以块的形式检索它,如 de