Coursera实验中L层神经网络Python代码报ValueError问题求助
L层神经网络函数调用ValueError解决方法
问题场景
调用L_layer_model函数时执行了以下代码:
parameters, costs = L_layer_model(train_x, train_y, layers_dims, num_iterations = 1, print_cost = False) print("Cost after first iteration: " + str(costs[0])) L_layer_model_test(L_layer_model)
触发报错:
ValueError: too many values to unpack (expected 2)
原因是L_layer_model函数仅返回parameters一个值,但调用时试图解包成两个变量(parameters和costs)。
解决方案
方案1:调整函数调用逻辑
如果不需要单独获取costs列表,仅需查看训练过程中的cost,可修改调用代码,只接收parameters并开启print_cost=True让函数自动打印cost:
parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 1, print_cost = True)
开启print_cost=True后,函数会在每100次迭代时输出对应cost,满足查看需求。
方案2:修改函数返回值(需获取costs时用)
如果需要将costs用于后续分析或可视化,可修改L_layer_model函数,让它同时返回parameters和costs:
- 更新函数的文档字符串,修正返回值说明:
""" Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID. ...(其他参数说明不变) Returns: parameters -- parameters learnt by the model. They can then be used to predict. costs -- list of costs recorded during training (only populated if print_cost=True) """
- 修改函数最后一行的return语句:
return parameters, costs
修改后,原调用代码即可正常解包。注意:若print_cost=False,costs会是空列表,此时访问costs[0]会触发索引错误,需确保开启print_cost=True或在访问前判断列表是否非空。
内容的提问来源于stack exchange,提问作者Hari narayanan
相关产品推荐
相关产品推荐

