提到机器学习,深度学习这些,大家都会立马想起Python。但R的实力也不容小觑。今天就用R来演示一个基于TensorFlow的图像识别的例子。如果你想运行这些代码,就必须先安装配置好TensorFlow,我是在Linux系统上面运行的。如何配置TensorFlow尽量看看官方文档,虽然是英文的,但是最新的,也是最准确的。
废话不说,直接来看代码,在代码中我也做了详细的注释,看起来应该不是很困难。
library(tensorflow) #加载TensorFlow包
library(magrittr) #数据处理包,可以使用管道函数
slim= tf$contrib$slim #slim是一个使构建,训练,评估神经网络变得简单的库。
# slim提供了很多计算机视觉方面的著名模型(VGG, AlexNet等),我们不仅可以直接使用,甚至能以各种方式进行扩展。
tf$reset_default_graph() #在每次运行中清除当前图形,以避免变量重复#Session会话 张量的具体值和操作,会话关闭时,张量的任何具体值都会丢失
images = tf$placeholder(tf$float32, shape(NULL, NULL, NULL, 3))# 创建占位符
imgs_scaled = tf$image$resize_images(images, shape(224,224)) #设置图片大小# slim$conv2d自带卷积功能+激励函数
fc8 = slim$conv2d(imgs_scaled, 64, shape(3,3), scope='vgg_16/conv1/conv1_1') %>%
slim$conv2d(64, shape(3,3), scope='vgg_16/conv1/conv1_2') %>%
slim$max_pool2d( shape(2, 2), scope='vgg_16/pool1') %>% #池化操作
slim$conv2d(128, shape(3,3), scope='vgg_16/conv2/conv2_1') %>%
slim$conv2d(128, shape(3,3), scope='vgg_16/conv2/conv2_2') %>%
slim$max_pool2d( shape(2, 2), scope='vgg_16/pool2') %>%
slim$conv2d(256, shape(3,3), scope='vgg_16/conv3/conv3_1') %>%
slim$conv2d(256, shape(3,3), scope&