繁体   English   中英

如何修复TypeError:+:'int'和'list'的不支持的操作数类型

[英]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

在此上下文中, ab被解释为整数,而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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM