part one:TypeError: train() missing 1 required positional argument: 'self'

发现原来是我要用使用定义某一class ,并没有先实例化:


'''在Python中,应该先对类进行实例化,然后在应用类。注意,实例化的过程是应该待括号的。
'''
class TestClass:
    def __init__(self):
        print('In init')
    def testFunc(self):
        print('In testFunc')

'''
ERROR1:
#错误方式:未实例化
print(TestClass.testFunc())
TypeError: testFunc() missing 1 required positional argument: 'self'


ERROR2:
#错误方式,TestClass:未带括号
testInstance = TestClass
print(testInstance.testFunc())
TypeError: testFunc() missing 1 required positional argument: 'self'
'''

#正确方式,TestClass():带着括号
testInstance = TestClass()
print(testInstance.testFunc())

in init
In test testFunc
None

然后进行相应的修正,在使用之前定义的某一类时,我先进行了实例化就可以了。

 

part two :TypeError: type numpy.ndarray doesn't define __round__ method

对于该问题的解决方案,网上给出的答案也有所不同,确实是每个人的书写方式和环境不一样

根据自己的情况选择以下方法进行尝试:

 

1)

解决问题

TypeError: type numpy.ndarray doesn't define __round__ method

解决方案:

类型错误:numpy.ndarray 类型数据不能定义__round__ method方法
将round方法改为np.round即可!

 

2)需求 进行item()函数的添加,这是由于版本不一样的问题。

                   

 

 

3) 有的时候需要对数据类型进行转换(个人遇到的解决方案)

我的需求是:对于得到的loss值进行打印处理或者报错。但是生成的loss值是pytorch中的variable数据类型,需要将其转成numpy才能取需求的保留几位小数,则进行如下处理:

np.round(float(Ieval_loss.data.numpy()), 4)
# or
str(np.round(float(Ieval_loss.data.numpy()), 4))

注:pytorch中各种数据类型的转换可以参见以下博客:

pytorch中variable、tensor、numpy的相互转换

 

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐