[英]How to fix TypeError: unsupported operand type(s) for +: 'int' and 'list'
Hello i am setting a code for rmse but it happen error 您好我正在为rmse设置代码,但它发生错误
import numpy as np
import matplotlib.pyplot as plt
import random
data=[[235,591],[216,539],[148,413],[35,310],[85,308],[204,519],[49,325],[25,332],[173,498],[191,498],[134,392],[99,334],[117,385],[112,387],[162,425],[272,659],[159,400],[159,427],[59,319],[198,522]]
x_data=[x_row[0] for x_row in data]
y_data=[y_row[1] for y_row in data]
a=np.random.randint(0,10)
b=np.random.randint(0,100)
def f(x):
return b+a*x
def E(x,y):
return 0.5*np.sum((y-f(x))**2)
n=1e-3
D=1
count=0
error=E(x_data,y_data)
while D>1e-2:
tmp0=b-n*np.sum((f(x_data)-y_data))
tmp1=a-n*np.sum((f(x_data)-y_data)*x_data)
b=tmp0
a=tmp1
current_error=E(x_data,y_data)
D=error-current_error
count=count+1
if count % 100 == 0 :
print(count,a,b,current_error,D)
error is 错误是
Traceback (most recent call last):
return b+a*x
TypeError: unsupported operand type(s) for +: 'int' and 'list'
The problem is with 问题在于
def f(x):
return b+a*x
In this context, a
and b
are being interpreted as integers while x
is being interpreted as a list. 在此上下文中,
a
和b
被解释为整数,而x
被解释为列表。
If your intent is to apply the calculation to every element in x
, try something like this: 如果您的意图是将计算应用于
x
每个元素,请尝试以下方法:
def f(x):
out = []
for i in x:
out.append(b+a*i)
return out
You will have similar errors when trying to do more calculations later on where you are using lists in calculations. 尝试稍后在计算中使用列表的位置进行更多计算时,您将遇到类似的错误。 You will have to make similar changes.
您将不得不进行类似的更改。
For example: 例如:
def E(x,y):
return 0.5*np.sum((y-f(x))**2)
Will have to be changed to something like: 将不得不改为:
def E(x,y):
out = []
for xi, yi in zip(y, f(x)):
out.append(0.5*np.sum((yi-xi**2)))
return out
To avoid a TypeError: unsupported operand type(s) for -: 'list' and 'list'
为了避免
TypeError: unsupported operand type(s) for -: 'list' and 'list'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.