首页 > 解决方案 > python 不支持的浮点和整数操作数数据类型

问题描述

嘿,我正在尝试使用梯度下降进行线性回归,但我一直面临这个错误

TypeError: unsupported operand type(s) for &: 'float' and 'int'

代码如下

b = 0
a = 0
L = 0.0001
epochs = 10000
n = len(X)
n = 1
epsilon = 0.0001  # Stop algorithm when absolute difference between 2 consecutive x-values is less than epsilon
diff = 1
while diff > epsilon & n < epochs:  # 2 stopping criteria is set
    Y_pred = b*X + a
    cost = (1/n)*sum([val**2 for val in (Y-Y_pred)])
    D_b = (-2/n) * sum(X*(Y - Y_pred))
    D_a = (-2/n) * sum(Y - Y_pred)
    b = b - L*D_b
    a = a - L*D_a
    diff = abs(Y_pred -Y)
    j = j + 1
    y = Y_pred
    print('x')

print('The value of b is {},cost is {} and the value of a is {} when itstheminimum'.format(b,cost,a))

错误在这一行

while diff > epsilon & n < epochs:  # 2 stopping criteria is set

任何建议或替代方案将不胜感激

标签: pythonlinear-regression

解决方案


它返回错误是因为您使用&来表示and逻辑运算符。在 Python 中,您应该使用and如下所示:

while diff > epsilon and n < epochs:

推荐阅读