在我的以下代码中
class cnnUtils:
def get_weight(shape):
init=tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(init)
def get_bias(shape):
init=tf.constant(0.1,shape=shape)
return tf.Variable(init)
def conv2d(x,w):
return tf.nn.conv2d(x,w,strides=[1,1,1,1],padding="SAME")
def maxpool_2d(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
def conv_layer(input,shape):
b=get_bias([shape[3]])
w=get_weight(shape)
return tf.nn.relu(conv2d(input,w)+b)
def full_layer(input,size):
in_size=int(input.get_shape()[1])
w=get_weight([in_size,size])
b=get_bias([size])
return tf.matmul(input,w)+b
utils=CnnUtils()
x=tf.placeholder(tf.float32,shape=[None,32,32,3])
y=tf.placeholder(tf.float32,shape=[None,10])
conv1=utils.conv_layer(x,shape=[5,5,3,32])
我遇到以下错误
TypeError跟踪(最近一次通话) 在 ----> 1 conv1 = utils.conv_layer(x,shape = [5,5,3,32])
TypeError:conv_layer()得到了意外的关键字参数'shape'
但是当我移动class关键字并将代码作为
之类的简单函数调用使用时conv1 = conv_layer(x,shape = [5,5,3,32])
犯错了。有人可以解释一下这里发生了什么吗?我的理解是,关键字“ shape”在这里很乱。
答案 0 :(得分:1)
在conv_layer作为CnnUtils类的方法的情况下,conv_layer方法的第一个参数(输入)引用类CnnUtils的实例。因此,当您调用utils.conv_layer(x,shape = [5,5,3,32])时,x被指定为shape的值。 [只需在conv_layer方法中打印输入和形状的值]。因此,有效的实现如下:
import tensorflow as tf
class CnnUtils:
def get_weight(self, shape):
init=tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(init)
def get_bias(self, shape):
init=tf.constant(0.1,shape=shape)
return tf.Variable(init)
def conv2d(self, x, w):
return tf.nn.conv2d(x,w,strides=[1,1,1,1],padding="SAME")
def maxpool_2d(self, x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
def conv_layer(self, input, shape):
b=self.get_bias([shape[3]])
w=self.get_weight(shape)
return tf.nn.relu(self.conv2d(input,w)+b)
def full_layer(self, input, size):
in_size=int(input.get_shape()[1])
w=self.get_weight([in_size,size])
b=self.get_bias([size])
return tf.matmul(input,w)+b
utils=CnnUtils()
x=tf.placeholder(tf.float32,shape=[None,32,32,3])
y=tf.placeholder(tf.float32,shape=[None,10])
conv1=utils.conv_layer(x, shape=[5,5,3,32])