【问题标题】:Trying to learn Convolution Neural Network with CIFAR-10尝试用 CIFAR-10 学习卷积神经网络
【发布时间】:2019-06-22 12:43:55
【问题描述】:

我想实现一个具有以下架构的简单 CNN:

  1. conv1:卷积和修正线性激活 (RELU)

  2. pool1:最大池化

  3. FC2:具有校正线性激活 (RELU) 的全连接层

  4. softmax 层:最终输出预测,即分类为十个之一 类。

我正在关注这个指南:https://towardsdatascience.com/cifar-10-image-classification-in-tensorflow-5b501f7dc77c,但这里的 CNN 非常复杂。有人可以指导我如何缩短此实现或代码吗?我也对 conv2d、权重和偏差的维度感到困惑。

下面是我开始使用的代码!

import pickle
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf

dir = 'C:/PythonProjects/cifar-10-batches-py/'

def unpickle(file):
    with open(file, 'rb') as fo:
        dict = pickle.load(fo, encoding='bytes')
    return dict

def to_onehot(labels, nclasses):
    outlabels = np.zeros((len(labels),nclasses))
    for i,l in enumerate(labels):
        outlabels[i,l]=1
    return outlabels

def normalize(x):
    """
        argument
            - x: input image data in numpy array [32, 32, 3]
        return
            - normalized x 
    """
    min_val = np.min(x)
    max_val = np.max(x)
    x = (x-min_val) / (max_val-min_val)
    return x


data_dash = unpickle(dir+'data_batch_1')
data_test = unpickle(dir+'test_batch')

X = data_dash[b'data'] # m * n
X_test = data_test[b'data'] # m * n

train_X = X.reshape(-1, 32, 32, 3)
train_y = np.array(data_dash[b'labels'])
train_y = to_onehot(train_y,10)

test_X = X_test.reshape(-1,32,32,3)
test_y = np.array(data_test[b'labels'])
test_y = to_onehot(test_y,10)

【问题讨论】:

    标签: python-3.x tensorflow computer-vision conv-neural-network


    【解决方案1】:

    最好从 Keras API 开始。请参考此 Cifar10 教程。

    https://github.com/keras-team/keras/blob/master/examples/cifar10_cnn.py

    如果您使用的是最新版本的 tensorflow,则 Keras API 在 tensorflow 中作为 tf.keras 可用。 Keras 包不需要单独安装。

    我也对 conv2d 的维度、权重和偏差感到困惑。

    从这里的源代码, https://github.com/deep-diver/CIFAR10-img-classification-tensorflow/blob/c96a0cbbe91ee280a5de1b3b872e407b0a2c7f34/CIFAR10_image_classification.py#L139

    conv_net() 方法构建网络。有4个conv层,取第一个conv层,

    conv1_filter = tf.Variable(tf.truncated_normal(shape=[3, 3, 3, 64], mean=0, stddev=0.08))
    conv1 = tf.nn.conv2d(x, conv1_filter, strides=[1,1,1,1], padding='SAME')
    

    conv1 层的权重保存在 conv1_filter 中,格式为 [filter_height, filter_width, in_channels, out_channels]。

    [3, 3, 3, 64] 是 3 x 3 滤波器,具有 3 个输入通道(RGB 输入,因为这是第一层)和 64 个输出通道。

    对于 conv2 层,输入通道将是 64,这是 conv1 层的输出通道数,依此类推。

    conv1_filter 中存储的权重在训练过程中通过梯度下降进行更新。

    这里没有使用偏见。如果需要偏差,则需要声明另一个 tf.Variable,其大小等于输出通道的数量。然后需要调用tf.nn.bias_add()方法给conv层的输出加上bias。

    【讨论】:

    • 但是我不应该用Keras,我要用tensorflow
    • 更新了答案,澄清了权重和偏差。构建网络的方法很简单。
    • 非常感谢您的解释。但我希望你能帮助修改我的代码,以便我可以从 CNN 架构的权重和偏差开始?
    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多