PyTorch 定义与使用class 时注意事项

PyTorch 定义与使用class 时注意事项

class my_model(torch.nn.module):
	def  __init__(self,a,b,c,...):
		super (my_model,self)__init__():
		self.my_model_a = a
		self.b = b
		self.c = c
		...
	def forward(self, input_1, imput_2):
		input_x1 = imput_1
		input_x2 = input_2
		output = input_x1 + input_x2
		return output
在使用上述定义时:
	1.首先导入参数:
		my_model_1 = my_model(a, b, c, ...)
	2.然后使用forward调用函数
		y_out = my_model_1(input_1, input_2)

另一种实例化方式:	
class my_model(torch.nn.module):
	def  __init__(self):
 		pass
  ...
 	def __call__(self):
  		pass

1.
def function(a, b, c, d, e)
function(1, 2, 3, x =  4, y = 5)
2.当数量不确定时function(1, 2, 3..., x =  4, y = 5, ...)
def function(*args, **kwargs)
	print(args)
	print(kwargs)
	print('Hello' + str(''))
function(1, 2, 3, x =  4, y = 5)
使用上述定义时:![在这里插入图片描述](https://img-blog.csdnimg.cn/20201223172044981.JPG?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMDgxNTkz,size_16,color_FFFFFF,t_70#pic_center)

class A():
	def __init__(self, origion_apple):
	   super().__init__()
	   print('我原来有苹果个数是:',origion_apple)
	   self.origion_apple= origion_apple
	def __call__(self, added_apples):
	        res = self.forward(added_apples)
	    return res
	def forward(self, input_apples):
	    print('forward 函数被调用了')
	    return input_apples + self.origion_apple
print('对象初始化')
a = A(5)
all_num_apples = a(2)
print("我现在苹果个数是:", all_num_apples )

# __init__  初始化
# __call__  调用函数(内部调用forward函数)









		

猜你喜欢

转载自blog.csdn.net/qq_41081593/article/details/111593952
今日推荐