Python 错误:TypeError: only size-1 arrays can be converted to Python scalars 和 ValueError: setting an array element with a sequence.
在使用 Python 进行数值优化时,可能会遇到以下错误信息:
TypeError Traceback (most recent call last)
TypeError: only size-1 arrays can be converted to Python scalars
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
Cell In[36], line 9
7 0<=y<=100
8 initial_guess = np.array([10,100])
----> 9 result = optimize.minimize(target_function, initial_guess, method='Nelder-Mead')
10 max_point = result.x
11 max_value = result.fun
File ~\AppData\Roaming\Python\Python39\site-packages\scipy\optimize\_minimize.py:684, in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
681 bounds = standardize_bounds(bounds, x0, meth)
683 if meth == 'nelder-mead':
--> 684 res = _minimize_neldermead(fun, x0, args, callback, bounds=bounds,
685 **options)
686 elif meth == 'powell':
687 res = _minimize_powell(fun, x0, args, callback, bounds, **options)
File ~\AppData\Roaming\Python\Python39\site-packages\scipy\optimize\_optimize.py:845, in _minimize_neldermead(func, x0, args, callback, maxiter, maxfev, disp, return_all, initial_simplex, xatol, fatol, adaptive, bounds, **unknown_options)
843 try:
844 for k in range(N + 1):
--> 845 fsim[k] = func(sim[k])
846 except _MaxFuncCallError:
847 pass
File ~\AppData\Roaming\Python\Python39\site-packages\scipy\optimize\_optimize.py:569, in _wrap_scalar_function_maxfun_validation.<locals>.function_wrapper(x, *wrapper_args)
567 ncalls[0] += 1
568 # A copy of x is sent to the user function (gh13740)
--> 569 fx = function(np.copy(x), *(wrapper_args + args))
570 # Ideally, we'd like to a have a true scalar returned from f(x). For
571 # backwards-compatibility, also allow np.array([1.3]),
572 # np.array([[1.3]]) etc.
573 if not np.isscalar(fx):
Cell In[36], line 4, in target_function(x)
2 def target_function(x):
3 X = np.zeros((1, 35))
----> 4 X[0, 0] = x
5 return reg2.predict(X)[0]
7 0<=y<=100
ValueError: setting an array element with a sequence.
这段错误信息表明,在使用 scipy.optimize.minimize 函数进行最小化时,目标函数 target_function 或初始猜测值 initial_guess 出现了问题。
具体来说,TypeError: only size-1 arrays can be converted to Python scalars 错误提示在将数组转换为 Python 标量时出现了问题,而 ValueError: setting an array element with a sequence 错误提示在将数组元素设置为序列时出现了问题。
错误原因:
-
**目标函数
target_function中的x应该是标量:**在代码中,x是一个数组,而X[0, 0]应该是一个标量。因此,需要将x的值转换为标量,例如x[0]。 -
**初始猜测值
initial_guess应该是标量:**在代码中,initial_guess是一个数组,而optimize.minimize函数期望接收一个标量作为初始猜测值。因此,需要将initial_guess的值转换为标量,例如initial_guess[0]。
解决方法:
import numpy as np
from scipy import optimize
def target_function(x):
X = np.zeros((1, 35))
X[0, 0] = x[0] # 将 x 的值转换为标量
return reg2.predict(X)[0]
initial_guess = np.array([10, 100])
result = optimize.minimize(target_function, initial_guess[0], method='Nelder-Mead') # 将 initial_guess 的值转换为标量
max_point = result.x
max_value = result.fun
注意:
- 上述代码中的
reg2是未定义的变量,你需要根据实际情况进行定义和使用。 - 在使用
optimize.minimize函数时,需要根据具体的优化问题选择合适的初始猜测值。
通过以上修改,可以解决上述错误,并成功使用 optimize.minimize 函数进行最小化。
此外,还可以根据实际情况,使用 np.squeeze() 函数将数组压缩为标量,例如:
initial_guess = np.squeeze(initial_guess)
在进行数值优化时,需要注意输入参数的类型和维度,以确保函数能够正常执行。
原文地址: https://www.cveoy.top/t/topic/fOg4 著作权归作者所有。请勿转载和采集!