首页 > 解决方案 > * 不支持的操作数类型:“int”和“NoneType”

问题描述

确切的错误如下:

Traceback (most recent call last):
File "C:/Users/Name/Downloads/MachineLearning.py", line 73, in <module>
class d0:
File "C:/Users/Name/Downloads/MachineLearning.py", line 83, in d0
z = hypothesis1(W0,W1,W2,W3,Z0,Z1,Z2,Z3)
File "C:/Users/Name/Downloads/MachineLearning.py", line 41, in hypothesis1
W0 * Z0 + W1 * Z1 + W2 * Z2 + W3 * Z3
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

这是导致错误的代码:

x0 = 1
z0 = 1
x1 = int(input("Enter 0 or 1: "))
x2 = int(input("Enter 0 or 1: "))
y = ""
learning_rate = 0.1

w1 = 1
w2 = 1
w3 = 1
w4 = 1
w5 = 1
w6 = 1
w7 = 1
w8 = 1
w9 = 1

v1 = 1
v2 = 1
v3 = 1
v4 = 1

if x1 == 0 and x2 == 0:
    y = 0
elif x1 == 1 and x2 == 0:
    y = 1
elif x1 == 0 and x2 == 1:
    y = 1
elif x1 == 1 and x2 == 1:
    y = 0
else:
    y = 0

def hypothesis(W0,W1,W2,X0,X1,X2):
    W0 * X0 + W1 * X1 + W2 * X2

def hypothesis1(W0,W1,W2,W3,Z0,Z1,Z2,Z3):
    (W0 * Z0) + (W1 * Z1) + (W2 * Z2) + (W3 * Z3)

class z1:
    W0 = w1
    W1 = w4
    W2 = w7
    X0 = x0
    X1 = x1
    X2 = x2   
    z = hypothesis(W0,W1,W2,X0,X1,X2)

class z2:
    W0 = w2
    W1 = w5
    W2 = w8
    X0 = x0
    X1 = x1
    X2 = x2    
    z = hypothesis(W0,W1,W2,X0,X1,X2)

class z3:
    W0 = w3
    W1 = w6
    W2 = w9
    X0 = x0
    X1 = x1
    X2 = x2
    z = hypothesis(W0,W1,W2,X0,X1,X2)

class d0:
    W0 = v1
    W1 = v2
    W2 = v3
    W3 = v4
    Z0 = z0
    Z1 = z1.z
    Z2 = z2.z
    Z3 = z3.z
    z = hypothesis1(W0,W1,W2,W3,Z0,Z1,Z2,Z3)

    print(z1.z)

该错误似乎只与 class 一致d0,所以如果可以的话,有人可以解释它为什么会发生以及我该如何解决它?我已经尝试将其完全注释掉,但它仍然会出现上述错误。但是,当我尝试打印其他的时,它又回来了None

标签: python

解决方案


功能

def hypothesis(W0,W1,W2,X0,X1,X2):
    W0 * X0 + W1 * X1 + W2 * X2

def hypothesis1(W0,W1,W2,W3,Z0,Z1,Z2,Z3):
    (W0 * Z0) + (W1 * Z1) + (W2 * Z2) + (W3 * Z3)

目前没有显式返回任何东西,所以它们隐式返回None。由于您将此返回值分配给zin classes z1z2并且z3,当您稍后尝试在 class d0via中访问它们时z1.z,您会得到一个None值,并且您的乘法hypothesis1会引发您看到的错误。

相反,您可能意味着返回计算结果,即:

def hypothesis(W0,W1,W2,X0,X1,X2):
    return W0 * X0 + W1 * X1 + W2 * X2

def hypothesis1(W0,W1,W2,W3,Z0,Z1,Z2,Z3):
    return (W0 * Z0) + (W1 * Z1) + (W2 * Z2) + (W3 * Z3)

推荐阅读