浮点数和整数的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

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

解决方法

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

while diff > epsilon and n < epochs: