简体   繁体   中英

How to pack and unpack lists of type numpy.ndarray

I am given the following code but I want to customize it based on my needs. Given the method call:

        best_n_hidden = hyperparam_selection(
            train_network,
            n_hidden_range=[10, 128],
            func_args=[tr_X, ts_X, tr_y, ts_y],
            n_iter=6,
        )

def hyperparam_selection(func, n_hidden_range, func_args=None, n_iter=20):
    if func_args is None:
        func_args = []

    scores = []
    parameters = []

    min_n_hidden, max_n_hidden = n_hidden_range
    n_hidden_choices = np.arange(min_n_hidden, max_n_hidden + 1)

    # To be able to perform gaussian process we need to
    # have at least 2 samples.
    n_hidden = random.randint(min_n_hidden, max_n_hidden)
    score = func(n_hidden, *func_args) # ISSUE HERE!!
    parameters.append(n_hidden)
    scores.append(score)
    n_hidden = random.randint(min_n_hidden, max_n_hidden)

The problem is that tr_X, ts_X, tr_y, ts_y are of type <type 'numpy.ndarray'> so when unpacking them using star operator *func_args in the line score = func(n_hidden, *func_args) gives me a problem. I don't know what is the eqivalent packing and unpacking approach in numpy that I can use for this case numpy.stack or numpy.packbits . Any hint is appreciated.

There's nothing special about arrays in this context.

In the call, func_args=[tr_X, ts_X, tr_y, ts_y], , [...] is a list of 4 items. It doesn't matter what they are.

Inside the function, it looks like func_args will always be a list, possibly the empty one [] .

In the call score = func(n_hidden, *func_args) , that list will be expanded into.

I expect that a

def func(n_hidden, x1, x2, y1, y2):
     ...

would work (if you are always passing 4 objects). Or

def func(n_hidden, *args):
    n = len(args)
    # args is a tuple.
    if len(args)==4:
        x1, x2, y1, y2 = args
        # or work with
        args[0], args[1], etc.

You aren't packing or unpacking the arrays. Rather you are dealing with a list or tuple of arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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