我刚开始学习CNN,最近接触了Keras。我试图将我的TensorFlow代码转换为Keras,但感到有些困惑。以下是我的TensorFlow代码。
#输入数据tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, 1, nfeatures, num_channels))tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))#变量 # 第1层weights_l1 = tf.Variable( tf.truncated_normal([patch_size, patch_size, num_channels, depth], stddev=0.01),name="weights_l1")biases_l1 = tf.Variable(tf.zeros([depth]),name="biases_l1")#第2层weights_l2 = tf.Variable( tf.truncated_normal([(block_sizeX * block_sizeY * 8), num_hidden], stddev=0.01),name="weights_l2")biases_l2 = tf.Variable(tf.zeros([num_hidden]),name="biases_l2")# 输出层weights = tf.Variable( tf.truncated_normal([num_hidden, num_labels], stddev=0.01),name="weights")biases = tf.Variable(tf.zeros([num_labels]),name="biases")global_step = tf.Variable(0.0,name="globalStep") init_var = tf.initialize_all_variables() # 操作初始化#模型 def setupNN(dSet, bDropout): input_l1 = tf.nn.conv2d(dSet, weights_l1, [1, 2, 2, 1], padding = 'SAME') output_l1 = tf.nn.relu(input_l1 + biases_l1) shape = output_l1.get_shape().as_list() reshape = tf.reshape(output_l1, [shape[0], shape[1] * shape[2] * shape[3]]) output_l3 = tf.nn.relu(tf.matmul(reshape, weights_l2) + biases_l2) return tf.matmul(output_l3, weights) + biases
现在当我将这段代码转换成Keras时,我对num_filter
和(kernel_1, kernel_2)
应该填写哪些参数以匹配TensorFlow感到困惑。这些只是我写的Keras代码的片段,不是整个模型。
#第一层model.add(Convolution2D(num_filter, (kernel_1, kernel_2), input_shape = (1, nfeatures, 1), activation = 'relu'))#第二层model.add(Convolution2D(num_filter, (kernel_1, kernel_2), input_shape = (1, nfeatures, 1), activation = 'relu'))
当我添加kernel_initializers=**
时,它会自动处理权重吗?
#全连接层model.add(Flatten())model.add(Dense(128, activation = 'relu', kernel_initializer=initializers.random_normal(stddev=0.01), bias_initializer = 'zeros'))
我知道我可以从fit()
函数中输入batch_size
model.fit(train_dataset, train_labels, batch_size=100, nb_epoch=10, verbose=1, validation_split=0.2, callbacks=[EarlyStopping(monitor='val_loss', patience=3)])
回答:
关于你的第一个问题,
num_filter
是特征输出空间,(kernel_1
, kernel_2
) 是滤波器大小/卷积窗口。在你的例子中,你可以看到你的TensorFlow代码使用了tf.nn.conv2d
。如果你查看文档,你会发现filter
是第二个参数,在你的例子中是weights_l1
。在这个例子中,patch_size, patch_size
相当于核大小,而depth
相当于num_filter
。
关于第二个问题,如果你添加了kernel_initializers=**
,这意味着权重或变量会被初始化为某些值。相同的概念也适用于TensorFlow,因为你的权重是一个变量,在开始时需要初始化为某些值。