在Redis中存储Numpy数组的最快方法

我在AI项目上使用Redis。

这个想法是让多个环境模拟器在许多cpu内核上运行策略。模拟器将体验(状态/操作/奖励元组列表)写入Redis服务器(重播缓冲区)。然后,培训过程将经验作为数据集读取以生成新策略。将新策略部署到模拟器,删除先前运行的数据,然后继续该过程。

大部分经验都记录在“状态”中。通常将其表示为尺寸为80 x 80的大型numpy数组。模拟器会以cpu允许的最快速度生成它们。

为此,是否有人有最好/最快/最简单的方法来编写大量numpy数组来进行redis的构想或经验?这些都在同一台机器上,但是以后可以在一组云服务器上。代码示例欢迎!

回答:

我不知道它是否最快,但是您可以尝试类似的方法…

将一个Numpy数组存储到Redis就像这样-see function toRedis()

  • 获得Numpy数组的形状并进行编码
  • 将Numpy数组作为字节附加到形状
  • 将编码的数组存储在提供的密钥下

检索一个Numpy数组是这样的-see function fromRedis()

  • 从Redis检索与提供的密钥相对应的编码字符串
  • 从字符串中提取Numpy数组的形状
  • 提取数据并重新填充Numpy数组,重塑为原始形状


#!/usr/bin/env python3

import struct

import redis

import numpy as np

def toRedis(r,a,n):

"""Store given Numpy array 'a' in Redis under key 'n'"""

h, w = a.shape

shape = struct.pack('>II',h,w)

encoded = shape + a.tobytes()

# Store encoded data in Redis

r.set(n,encoded)

return

def fromRedis(r,n):

"""Retrieve Numpy array from Redis key 'n'"""

encoded = r.get(n)

h, w = struct.unpack('>II',encoded[:8])

a = np.frombuffer(encoded, dtype=np.uint16, offset=8).reshape(h,w)

return a

# Create 80x80 numpy array to store

a0 = np.arange(6400,dtype=np.uint16).reshape(80,80)

# Redis connection

r = redis.Redis(host='localhost', port=6379, db=0)

# Store array a0 in Redis under name 'a0array'

toRedis(r,a0,'a0array')

# Retrieve from Redis

a1 = fromRedis(r,'a0array')

np.testing.assert_array_equal(a0,a1)

您可以通过dtype对Numpy数组的以及形状进行编码来增加灵活性。我之所以没有这样做,是因为您可能已经知道所有数组都属于一种特定类型,然后代码会变得更大且更难于无故读取。

80x80 Numpy array of np.uint16   => 58 microseconds to write

200x200 Numpy array of np.uint16 => 88 microseconds to write


:Python,Numpy,Redis,数组,序列化,序列化,键,incr,唯一

以上是 在Redis中存储Numpy数组的最快方法 的全部内容, 来源链接: utcz.com/qa/434639.html

回到顶部