gpt4 book ai didi

python - 当尝试次数多于对象时,我的随机播放算法会崩溃

转载 作者:行者123 更新时间:2023-12-01 09:15:22 26 4
gpt4 key购买 nike

我正在尝试做一个实验,扫描文件夹中的图像。对于每次试验,都会显示一个目标和一些 (7) 个干扰图像。之后,在一半的试验中,人们会看到目标图像,而在另一半的试验中,他们会看到之前显示中没有的图像。

我当前的代码可以工作,但前提是试验次数少于对象:

repeats = 20

# Scan dir for images
jpgs = []

for path, dirs, files in os.walk(directory):
for f in files:
if f.endswith('.jpg'):
jpgs.append(f)

# Shuffle up jpgs
np.random.shuffle(jpgs)

# Create list with target and probe object, Half random, half identical
display = []
question = []
sameobject = []
position = np.repeat([0,1,2,3,4,5,6,7], repeats)
for x in range(1,(repeats*8)+1):
display.append(jpgs[x])
if x % 2 == 0:
question.append(jpgs[-x])
sameobject.append(0)
else:
question.append(jpgs[x])
sameobject.append(1)

# Concatonate objects together
together = np.c_[display,question,position,sameobject]
np.random.shuffle(together)

for x in together:
# Shuffle and set image
np.random.shuffle(jpgs)
myList = [i for i in jpgs if i != together[trial,0]]
myList = [i for i in myList if i != together[trial,1]]

# Set correct image for target
myList[int(together[trial,2])] = together[trial,0]

首先,我知道这是一段糟糕的代码。但它完成的工作很粗糙。如果有 200 张 jpg 和重复 20 张,就可以了。如果重复设置为 30,则会崩溃。

以下是重复次数过高的示例:

  File "H:\Code\Stims\BetaObjectPosition.py", line 214, in <module>
display.append(jpgs[x])
IndexError: list index out of range

有没有一种方法可以更新我的代码,允许进行更多试验,同时在整个实验中尽可能均匀地使用所有对象(一个对象不应显示 3 次,而另一个对象则显示 0 次)?

Full, reproducible example

如果有人能找到一种明显的方法来平衡 7 个干扰图像的选择方式,那就加分了。

感谢您花时间阅读本文。希望您能继续帮助我。

最佳答案

对代码进行最少更改的解决方案应该是将 jpgs[x] 的每次调用更改为 jpgs[x % len(jpgs)]1 。这应该摆脱 IndexError;它基本上将列表索引“围绕边缘”包裹起来,确保它永远不会太大。尽管我不确定它将如何与 jpgs[-x] 调用交互。

另一种方法是实现一个类,该类从较短的对象序列中生成较长的对象序列。示例:

from random import shuffle


class InfiniteRepeatingSequence(object):
def __init__(self, source_list):
self._source = source_list
self._current = []

def next(self):
if len(self._current) == 0:
# copy the source
self._current = self._source[:]

shuffle(self._current)

# get and remove an item from a list
return self._current.pop()

此类无限期地重复该列表。它确保在重新使用列表之前使用每个元素一次。它可以很容易地变成一个迭代器(尝试将 next 更改为 __next__)。但要小心,因为上面的类会产生无限的元素序列。

<小时/>

1 有关模运算符的说明,请参阅“How does % work in Python? ”。

编辑:添加了模数问题的链接。

关于python - 当尝试次数多于对象时,我的随机播放算法会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51321595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com