简体   繁体   English

从集合中随机选择一个/多个函数并应用组合

[英]Randomly select one/more functions from collection and apply combinations

I have a list of n functions: f1(),f2()..fn() etc and need to select n randomly and apply one/more of those in sequence to an object.我有一个包含 n 个函数的列表: f1(),f2()..fn()等,需要随机选择 n 个并将其中的一个/多个依次应用于对象。 What's the Pythonic way to do this?这样做的 Pythonic 方法是什么?

The use-case is to generate augmentations for images (for training an ML model) from a set of images, and apply (one/more) augmentation functions to an image.用例是从一组图像生成图像增强(用于训练 ML 模型),并将(一个/多个)增强函数应用于图像。

这个functools.reduce(lambda acc, f: f(acc), random.sample(funs, n), image)怎么样?

Assuming I understand the question this could be done using reduce.假设我理解这个问题可以使用reduce来完成。

Assumption:假设:

  1. You have a list of functions f1, ... fN你有一个函数列表 f1, ... fN
  2. You want to select a sublist randomly, say k of them.您想随机选择一个子列表,比如其中的 k 个。
  3. You want to apply the sublist in sequence to an object您希望将子列表按顺序应用于对象

Solution using reduce使用reduce解决

from functools import reduce
#from numpy.random import choice   # use if your Python < 3.6
from random import choices         # available in Python 3.6+

# Define function on object (number in this case)
# included print so we can see each function being called
def f1(x):
    print("func1 x + 1: {} -> {}".format(x, x+1))
    return x + 1

def f2(x):
    print("func2 x * 2: {} -> {}".format(x, x*2))
    return x * 2

def f3(x):
    print("func3 x % 2:  {} -> {}".format(x, x%2))
    return x % 2

def f4(x):
    print("func4 x - 5:  {} -> {}".format(x, x-5))
    return x - 5

def f5(x):
    print("func5 x / 2:  {} -> {}".format(x, x/2))
    return x / 2

def f6(x):
    print("func6 x * 3:  {} -> {}".format(x, x/2))
    return x / 2

def f7(x):
    print("func7 x * 5:  {} -> {}".format(x, x/2))
    return x / 2

def f8(x):
    print("func8 x / 10:  {} -> {}".format(x, x/2))
    return x / 2

# Function which applies a function to an object def apply_func(x, f): return f(x) # 将函数应用于对象的函数 def apply_func(x, f): return f(x)

# List of functions
funcs = [f1, f2, f3, f4, f5, f6, f7, f8]

# Test (choose 3 functions at random)
random_funcs = choices(funcs, k = 3)

# Apply the functions to object (value 1)
obj = 1
answer = reduce(apply_func, random_funcs, obj)
print('Answer:', answer)

Example Output示例输出

func1 x + 1: 3 -> 4
func7 x * 5:  4 -> 2.0
func4 x - 5:  2.0 -> -3.0
Answer: -3.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM