tensorflow实现的一个最基本cnn

huangzifu huangzifu     2022-09-21     530

关键词:

原理可以参考

https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/

以及《神经网络与深度学习》

上代码:

import tensorflow as tf
from tqdm import tqdm_notebook
from tensorflow.examples.tutorials.mnist import input_data

"""
the cnn we are going to make: 
conv?relu?pool?affine?relu?affine?softmax
"""

# ==fc== straightforward
def relu(X):
    return tf.maximum(X, tf.zeros_like(X))

# ==fc== fully connected layer calculator
def affine(X, W, b):
    n = X.get_shape()[0].value # number of samples
    X_flat = tf.reshape(X, [n, -1])
    return tf.matmul(X_flat, W) + b

def flatten(X, window_h, window_w, window_c, out_h, out_w, stride=1, padding=0):
    X_padded = tf.pad(X, [[0, 0], [padding, padding], [padding, padding], [0, 0]])
    windows = []
    for y in range(out_h):
        for x in range(out_w):
            window = tf.slice(X_padded, [0, y * stride, x * stride, 0], [-1, window_h, window_w, -1])
            windows.append(window)
    stacked = tf.stack(windows)  # shape : [out_h, out_w, n, filter_h, filter_w, c]
    return tf.reshape(stacked, [-1, window_c * window_w * window_h])

# ==fc==
def max_pool(X, pool_h, pool_w, padding, stride):
    n, h, w, c = [d.value for d in X.get_shape()]
    out_h = (h + 2 * padding - pool_h) // stride + 1
    out_w = (w + 2 * padding - pool_w) // stride + 1
    X_flat = flatten(X, pool_h, pool_w, c, out_h, out_w, stride, padding)
    pool = tf.reduce_max(tf.reshape(X_flat, [out_h, out_w, n, pool_h * pool_w, c]), axis=3)
    return tf.transpose(pool, [2, 0, 1, 3])

def convolution(X, W, b, padding, stride):
    n, h, w, c = map(lambda d: d.value, X.get_shape())
    filter_h, filter_w, filter_c, filter_n = [d.value for d in W.get_shape()]
    out_h = (h + 2 * padding - filter_h) // stride + 1
    out_w = (w + 2 * padding - filter_w) // stride + 1
    X_flat = flatten(X, filter_h, filter_w, filter_c, out_h, out_w, stride, padding)
    W_flat = tf.reshape(W, [filter_h * filter_w * filter_c, filter_n])
    z = tf.matmul(X_flat, W_flat) + b  # b: 1 X filter_n
    return tf.transpose(tf.reshape(z, [out_h, out_w, n, filter_n]), [2, 0, 1, 3])

def softmax(X):
    X_centered = X - tf.reduce_max(X) # to avoid overflow
    X_exp = tf.exp(X_centered)
    exp_sum = tf.reduce_sum(X_exp, axis=1)
    return tf.transpose(tf.transpose(X_exp) / exp_sum)

def accuracy(network, t):
    t_predict = tf.argmax(network, axis=1)
    t_actual = tf.argmax(t, axis=1)
    return tf.reduce_mean(tf.cast(tf.equal(t_predict, t_actual), tf.float32))

#==fc== load data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True, reshape=False)
#==fc== set batch size
batch_size = 100
#==fc== get the first batch data
example_X, example_ys = mnist.train.next_batch(batch_size)

# ==fc== create session
session = tf.InteractiveSession()

X = tf.placeholder(‘float‘, [batch_size, 28, 28, 1])
t = tf.placeholder(‘float‘, [batch_size, 10])

filter_h, filter_w, filter_c, filter_n = 5, 5, 1, 30
W1 = tf.Variable(tf.random_normal([filter_h, filter_w, filter_c, filter_n], stddev=0.01))
b1 = tf.Variable(tf.zeros([filter_n]))

conv_layer = convolution(X, W1, b1, padding=2, stride=1)

conv_activation_layer = relu(conv_layer)

pooling_layer = max_pool(conv_activation_layer, pool_h=2, pool_w=2, padding=0, stride=2)

batch_size, pool_output_h, pool_output_w, filter_n = [d.value for d in pooling_layer.get_shape()]

# number of nodes in the hidden layer
hidden_size = 100

W2 = tf.Variable(tf.random_normal([pool_output_h*pool_output_w*filter_n, hidden_size], stddev=0.01))
b2 = tf.Variable(tf.zeros([hidden_size]))

affine_layer1 = affine(pooling_layer, W2, b2)

init = tf.global_variables_initializer()
init.run()
affine_layer1.eval({X:example_X, t:example_ys})[0]

affine_activation_layer1 = relu(affine_layer1)

affine_activation_layer1.eval({X:example_X, t:example_ys})[0]
output_size = 10
W3 = tf.Variable(tf.random_normal([hidden_size, output_size], stddev=0.01))
b3 = tf.Variable(tf.zeros([output_size]))

affine_layer2 = affine(affine_activation_layer1, W3, b3)

init = tf.global_variables_initializer()
init.run()

affine_layer2.eval({X:example_X, t:example_ys})[0]



softmax_layer = softmax(affine_layer2)

softmax_layer.eval({X:example_X, t:example_ys})[0]

def cross_entropy_error(y, t):
    return -tf.reduce_mean(tf.log(tf.reduce_sum(y * t, axis=1)))

loss = cross_entropy_error(softmax_layer, t)

loss.eval({X:example_X, t:example_ys})

learning_rate = 0.1
trainer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)

# number of times to iterate over training data
training_epochs = 2

# number of batches
num_batch = int(mnist.train.num_examples/batch_size)
num_batch



for epoch in range(training_epochs):
    avg_cost = 0
    for _ in range(num_batch):
        train_X, train_ys = mnist.train.next_batch(batch_size)
        trainer.run(feed_dict={X:train_X, t:train_ys})
        avg_cost += loss.eval(feed_dict={X:train_X, t:train_ys}) / num_batch

    print("Epoch:", ‘%04d‘ % (epoch+1), "cost=", "{:.9f}".format(avg_cost), flush=True)

test_x = mnist.test.images[:batch_size]
test_t = mnist.test.labels[:batch_size]




accuracy(softmax_layer, t).eval(feed_dict={X:test_x, t:test_t})

session.close()

  

tensorflow实战-tensorflow实现卷积神经网络cnn-第5章

第5章-TensorFlow实现卷积神经网络CNN5.1卷积神经网络简介卷积神经网络CNN最初是为了解决图像识别等问题设计的,当然现在的应用已经不限于图像和视频,也可以用于时间序列信号,比如音频信号、文本数据等。在深度学习出现之... 查看详情

Tensorflow CNN 实现的准确性差

】TensorflowCNN实现的准确性差【英文标题】:PooraccuracyinTensorflowCNNimplementation【发布时间】:2018-06-1518:07:52【问题描述】:我正在尝试在Tensorflow中实现一个5层深度卷积神经网络,其中3个卷积层后跟2个全连接层。我目前的实现如... 查看详情

卷积神经网络cnn原理以及tensorflow实现

      在知乎上看到一段介绍卷积神经网络的文章,感觉讲的特别直观明了,我整理了一下。首先介绍原理部分。      通过一个图像分类问题介绍卷积神经网络是如何工作的。下面是卷... 查看详情

基于tensorflow+opencv实现cnn自定义图像分类

摘要:本篇文章主要通过Tensorflow+Opencv实现CNN自定义图像分类案例,它能解决我们现实论文或实践中的图像分类问题,并与机器学习的图像分类算法进行对比实验。本文分享自华为云社区《​​Tensorflow+Opencv实现CNN自定义图像分... 查看详情

tensorflow实现cnn案例笔记(代码片段)

本文收集了各个资源的TensorFlow实现CNN案例,为了方便学习,如对版权有冒犯,敬请告知及时删除~目录CNN知识图谱:案例1案例2案例3案例4 Tensorflow和CNN: Tensorflow——卷积神经网络(CNN)卷积神经网络... 查看详情

tensorflow简单实例(代码片段)

TF手写体识别简单实例:TensorFlow很适合用来进行大规模的数值计算,其中也包括实现和训练深度神经网络模型。下面将介绍TensorFlow中模型的基本组成部分,同时将构建一个CNN模型来对MNIST数据集中的数字手写体进行识别。基本设... 查看详情

cnn中的卷积核及tensorflow中卷积的各种实现

声明:1.我和每一个应该看这篇博文的人一样,都是初学者,都是小菜鸟,我发布博文只是希望加深学习印象并与大家讨论。2.我不确定的地方用了“应该”二字首先,通俗说一下,CNN的存在是为了解决两个主要问题:1.权值太多... 查看详情

tensorflow实现cnn中的维度问题

使用TensorFlow实现cnn,其中tf.nn.conv2d(input_tensor…)input_tensor的格式要求是[batch,in_height,in_width,in_channels]但是python中四维矩阵是[batch,in_channels,in_height,in_width]使用transpose即可 查看详情

tensorflow实现cnn中的维度问题

使用TensorFlow实现cnn,其中tf.nn.conv2d(input_tensor…)input_tensor的格式要求是[batch,in_height,in_width,in_channels]但是python中四维矩阵是[batch,in_channels,in_height,in_width]使用transpose即可 查看详情

tensorflow中使用cnn实现mnist手写体识别

  本文参考YannLeCun的LeNet5经典架构,稍加ps得到下面适用于本手写识别的cnn结构,构造一个两层卷积神经网络,神经网络的结构如下图所示:  输入-卷积-pooling-卷积-pooling-全连接层-Dropout-Softmax输出    第一层卷积利用5*... 查看详情

深度学习之tensorflow——基本使用

一、目前主流的深度学习框架Caffe,TensorFlow,MXNet,Torch,Theano比较库名称开发语言速度灵活性文档适合模型平台上手难易Caffec++/cuda快一般全面CNN所有系统中等TensorFlowc++/cuda/Python中等好中等CNN/RNNLinux,OSX难MXNetc++/cuda快好全面CNN所有系统... 查看详情

使用 Tensorflow 2.0 实现 CNN 模型

】使用Tensorflow2.0实现CNN模型【英文标题】:implementaCNNmodelusingTensorlow2.0【发布时间】:2020-03-1417:54:13【问题描述】:由于我是这个领域的新手,我在项目中面临很多错误。请帮我解决这些问题。提前致谢请下载下面的文件并在jup... 查看详情

tensorflow实战之cnn实现对鸡蛋的分类

本文标签:TensorFlowTensorFlow实战之CNN3.1问题分析为了评估N个鸡蛋中是否有圈养鸡蛋,我们利用卷积神经网络(CNN)让计算机学习圈养鸡蛋和土鸡蛋图片的特征,然后根据鸡蛋的图片将其分类。通过对图片的预处理,将其转化为32*... 查看详情

基于tensorflow+opencv实现cnn自定义图像分类(代码片段)

摘要:本篇文章主要通过Tensorflow+Opencv实现CNN自定义图像分类案例,它能解决我们现实论文或实践中的图像分类问题,并与机器学习的图像分类算法进行对比实验。本文分享自华为云社区《Tensorflow+Opencv实现CNN自... 查看详情

tensorflow训练自己的数据集实现cnn图像分类

利用卷积神经网络训练图像数据分为以下几个步骤读取图片文件产生用于训练的批次定义训练的模型(包括初始化参数,卷积、池化层等参数、网络)训练1 读取图片文件1defget_files(filename):2class_train=[]3label_train=[]4fortrain_classin... 查看详情

tensorflow实现knn(k近邻)算法

首先先介绍一下knn的基本原理:KNN是通过计算不同特征值之间的距离进行分类。整体的思路是:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别。K通常... 查看详情

tensorflow中的卷积和池化层(代码片段)

在官方tutorial的帮助下,我们已经使用了最简单的CNN用于Mnist的问题,而其实在这个过程中,主要的问题在于如何设置CNN网络,这和Caffe等框架的原理是一样的,但是tf的设置似乎更加简洁、方便,这其实完全类似于Caffe的python接... 查看详情

android+tensorflow+cnn+mnist手写数字识别实现

SyncHere  查看详情