![](/img/trans.png)
[英]How to fix “TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'”
[英]How to fix TypeError: unsupported operand type(s) for +: 'int' and 'list'
您好我正在為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)
錯誤是
Traceback (most recent call last):
return b+a*x
TypeError: unsupported operand type(s) for +: 'int' and 'list'
問題在於
def f(x):
return b+a*x
在此上下文中, a
和b
被解釋為整數,而x
被解釋為列表。
如果您的意圖是將計算應用於x
每個元素,請嘗試以下方法:
def f(x):
out = []
for i in x:
out.append(b+a*i)
return out
嘗試稍后在計算中使用列表的位置進行更多計算時,您將遇到類似的錯誤。 您將不得不進行類似的更改。
例如:
def E(x,y):
return 0.5*np.sum((y-f(x))**2)
將不得不改為:
def E(x,y):
out = []
for xi, yi in zip(y, f(x)):
out.append(0.5*np.sum((yi-xi**2)))
return out
為了避免TypeError: unsupported operand type(s) for -: 'list' and 'list'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.