python数模输入样例后,报错不知道该怎么解决
问题遇到的现象和发生背景
cvxpy 支持矩阵风格的数学优化模型表示方法
数学模型如下
min = ∣∣Ax−b∣∣ 22
st.
0≤x≤1
输入格式:
第1行输入两个正整数m,n 。 m,n 是矩阵A的行数和列数
第2行输入m个数,表示向量b。
第3行到第m+2行表示矩阵A。
输出格式:
输出最优值时x的值, 小数点后精确1位数。
输入样例:
在这里给出一组输入。例如:
2,3
1,2
1,2,3
4,5,6
输出样例:
在这里给出相应的输出。例如:
0.00 0.00 0.33
问题相关代码,请勿粘贴截图
# Import packages.
import cvxpy as cp
import numpy as np
# Generate data.
m , n = input().split(",")
arr1 = input()
arr1 = [int(k) for k in arr1.split(",")]
m=int(m)
n=int(n)
line=[[0]*m]*n
for i in range(m):
line[i]=input().split(",")
x = cp.Variable(n)
cost = cp.sum_squares(line @ x - arr1)
prob = cp.Problem(cp.Minimize(cost))
prob.solve()
print(x.value)
运行结果及报错内容
/usr/local/lib/python3.7/dist-packages/cvxpy/interface/numpy_interface/ndarray_interface.py:47: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
result = numpy.asarray(value).T
TypeError: float() argument must be a string or a number, not 'list'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "a.py", line 19, in
cost = cp.sum_squares(line @ x - arr1)
File "/usr/local/lib/python3.7/dist-packages/cvxpy/expressions/expression.py", line 48, in cast_op
other = self.cast_to_const(other)
File "/usr/local/lib/python3.7/dist-packages/cvxpy/expressions/expression.py", line 478, in cast_to_const
return expr if isinstance(expr, Expression) else cvxtypes.constant()(expr)
File "/usr/local/lib/python3.7/dist-packages/cvxpy/expressions/constants/constant.py", line 48, in init
self._value = intf.DEFAULT_INTF.const_to_matrix(value)
File "/usr/local/lib/python3.7/dist-packages/cvxpy/interface/numpy_interface/ndarray_interface.py", line 53, in const_to_matrix
return result.astype(numpy.float64)
ValueError: setting an array element with a sequence.