基于 TensorFlow 的图像识别(R实现)

提到机器学习,深度学习这些,大家都会立马想起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')
  • 4
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
下面是一个基于 TensorFlow图像识别代码示例,使用了预训练模型 Inception V3: ```python import tensorflow as tf import numpy as np import os import re import sys from PIL import Image # 加载预训练模型 Inception V3 model_path = './inception_v3_graph_def.pb' with tf.gfile.FastGFile(model_path, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def, name='') # 定义标签列表 label_path = './imagenet_slim_labels.txt' labels = [] with open(label_path, 'r') as f: for line in f: labels.append(line.rstrip()) # 读取图片并进行预处理 image_path = './images/test.jpg' img = Image.open(image_path) if img.mode != 'RGB': img = img.convert('RGB') img = img.resize((299, 299)) img = np.array(img) img = (img - 128.0) / 128.0 # 进行图像识别 with tf.Session() as sess: input_tensor = sess.graph.get_tensor_by_name('input:0') output_tensor = sess.graph.get_tensor_by_name('InceptionV3/Predictions/Reshape_1:0') predictions = sess.run(output_tensor, {input_tensor: [img]}) top_k = predictions[0].argsort()[-5:][::-1] for i in top_k: print(labels[i], predictions[0][i]) ``` 其中,`inception_v3_graph_def.pb` 和 `imagenet_slim_labels.txt` 分别是 Inception V3 模型的二进制文件和标签文件,可以从 TensorFlow 官网下载。`test.jpg` 是待识别的图片。该代码通过加载预训练模型 Inception V3 对图片进行识别,并输出前 5 个最有可能的标签及其对应的概率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值