一看就懂的Tensorflow实战(Tensorflow入门)
时间:2022-07-22
本文章向大家介绍一看就懂的Tensorflow实战(Tensorflow入门),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
MNIST 数据集入门
MNIST 数据集简介
数字手写体识别数据集,常用来作为Deep Learning入门的基础数据集。它有60000
个训练样本集和10000
个测试样本集,每个样本图像的宽高为 28 * 28
。此数据集是以二进制存储的,不能直接以图像格式查看。
数据集大小:~12MB
下载地址:http://yann.lecun.com/exdb/mnist/index.html
导入tensorflow(v1.6.0版本)
import tensorflow as tf
print(tf.__version__)
1.6.0
tensorflow加载MNIST数据集
# Import MNIST
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("../../data/", one_hot=True)
# Load data
X_train = mnist.train.images
Y_train = mnist.train.labels
X_test = mnist.test.images
Y_test = mnist.test.labels
train-images-idx3-ubyte.gz: training set images (9912422 bytes)
train-labels-idx1-ubyte.gz: training set labels (28881 bytes)
t10k-images-idx3-ubyte.gz: test set images (1648877 bytes)
t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes)
Extracting ../../data/train-images-idx3-ubyte.gz
Extracting ../../data/train-labels-idx1-ubyte.gz
Extracting ../../data/t10k-images-idx3-ubyte.gz
Extracting ../../data/t10k-labels-idx1-ubyte.gz
查看并可视化MNIST数据集
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
# Get the next 64 images array and labels
batch_X, batch_Y = mnist.train.next_batch(64)
print(batch_X.astype,batch_X.shape) # (64,28*28)
print(batch_Y.astype,batch_Y.shape) # (64,10[0-9哪一类])
print(batch_Y[0]) # [ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
plt.imshow(np.reshape(batch_X[0], [28, 28]), cmap='gray')
<built-in method astype of numpy.ndarray object at 0x0000016EEF769080> (64, 784)
<built-in method astype of numpy.ndarray object at 0x0000016EEF772620> (64, 10)
[ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
<matplotlib.image.AxesImage at 0x16eef82a630>
png
tensorflow入门(hello world)
import tensorflow as tf
# TensorFlow 实现简单的 hello world
# 创建一个常量操作
# 这个常量操作会在默认的图中添加一个节点
#
# 构造函数返回的值表示常量op的输出。
hello = tf.constant('Hello, TensorFlow!')
# 启动 tf session
sess = tf.Session()
# 运行图
print(sess.run(hello))
b'Hello, TensorFlow!'
tensorflow入门(基本操作)
常量操作
# 常量基本操作
a = tf.constant(2)
b = tf.constant(3)
# 启动默认的图
with tf.Session() as sess:
print ("a: %i" % sess.run(a), "b: %i" % sess.run(b))
print ("Addition with constants: %i" % sess.run(a+b))
print ("Multiplication with constants: %i" % sess.run(a*b))
a: 2 b: 3
Addition with constants: 5
Multiplication with constants: 6
变量操作
# 作为图输入变量的基本操作。
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)
# tf 中定义的操作
add = tf.add(a, b) #加法操作
mul = tf.multiply(a, b) #乘法操作
# 启动默认的图
with tf.Session() as sess:
# 使用变量输入运行每个操作。
print ("Addition with variables: %i" % sess.run(add, feed_dict={a: 2, b: 3}))
print ("Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 3}))
Addition with variables: 5
Multiplication with variables: 6
矩阵操作
# 创建一个生成1x2矩阵的常数op。
matrix1 = tf.constant([[3., 3.]])
# 创建另一个常数,生成一个2x1矩阵。
matrix2 = tf.constant([[2.],[2.]])
# tf 中定义的操作
product = tf.matmul(matrix1, matrix2) #矩阵乘法操作
with tf.Session() as sess:
result = sess.run(product)
print(result)
[[ 12.]]
tensorflow入门(Eager API)
from __future__ import absolute_import, division, print_function
import numpy as np
import tensorflow as tf
import tensorflow.contrib.eager as tfe
# 设置 Eager API
print("Setting Eager mode...")
tfe.enable_eager_execution()
Setting Eager mode...
Eager API 常量操作
# 定义常量 tensors
print("Define constant tensors")
a = tf.constant(2)
print("a = %i" % a)
b = tf.constant(3)
print("b = %i" % b)
Define constant tensors
a = 2
b = 3
# 执行操作不需要 tf.Session
print("Running operations, without tf.Session")
c = a + b
print("a + b = %i" % c)
d = a * b
print("a * b = %i" % d)
Running operations, without tf.Session
a + b = 5
a * b = 6
Eager API 张量操作
# 与 Numpy完全兼容
print("Mixing operations with Tensors and Numpy Arrays")
# Define constant tensors
a = tf.constant([[2., 1.],
[1., 0.]], dtype=tf.float32)
print("Tensor:n a = %s" % a)
b = np.array([[3., 0.],
[5., 1.]], dtype=np.float32)
print("NumpyArray:n b = %s" % b)
Mixing operations with Tensors and Numpy Arrays
Tensor:
a = tf.Tensor(
[[2. 1.]
[1. 0.]], shape=(2, 2), dtype=float32)
NumpyArray:
b = [[3. 0.]
[5. 1.]]
# 在不需要 tf.Session 的情况下运行该操作
print("Running operations, without tf.Session")
c = a + b
print("a + b = %s" % c)
d = tf.matmul(a, b)
print("a * b = %s" % d)
Running operations, without tf.Session
a + b = tf.Tensor(
[[5. 1.]
[6. 1.]], shape=(2, 2), dtype=float32)
a * b = tf.Tensor(
[[11. 1.]
[ 3. 0.]], shape=(2, 2), dtype=float32)
# 遍历张量
print("Iterate through Tensor 'a':")
for i in range(a.shape[0]):
for j in range(a.shape[1]):
print(a[i][j])
Iterate through Tensor 'a':
tf.Tensor(2.0, shape=(), dtype=float32)
tf.Tensor(1.0, shape=(), dtype=float32)
tf.Tensor(1.0, shape=(), dtype=float32)
tf.Tensor(0.0, shape=(), dtype=float32)
参考
[TensorFlow-Examples]https://github.com/aymericdamien/TensorFlow-Examples
- ASP.NET的路由系统:根据路由规则生成URL
- ASP.NET Core 1.0中实现文件上传的两种方式(提交表单和采用AJAX)
- 通过3个Hello World应用来了解ASP.NET 5应用是如何运行的(1)
- 工业X.0将至 企业数字化转型该怎么做?
- 通过3个Hello World应用来了解ASP.NET 5应用是如何运行的(2)
- 通过3个Hello World应用来了解ASP.NET 5应用是如何运行的(3)
- 为什么说2018年互联网创业机会将变少
- ASP.NET MVC Controller激活系统详解:IoC的应用[上篇]
- ASP.NET Core的配置(1):读取配置信息
- 权限管理和备份实例
- “协变”、“逆变”与Delegate类型转换
- 如今的人工智能是不是真的已经很聪明了?
- 【Scikit-Learn 中文文档】聚类 - 无监督学习 - 用户指南 | ApacheCN
- Delegate如何进行类型转换?
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- Maven是什么? Maven的概念+作用+仓库的介绍+常用命令
- JDK8;HashMap:再散列解决hash冲突 ,源码分析和分析思路
- 写一个 Singleton
- 树莓派基础实验31:MPU6050陀螺仪加速度传感器实验
- springboot gradle mybatis mysql配置(注解)
- PHP入门之流程控制
- 常用进制转换方法(取商留余)原理解析, 附基于栈实现进制转换的代码
- 用 jdom 解析 xml 文件时如何解决中文问题?如何解析?
- PHP入门之函数
- spring boot 启动报错 org/springframework/core/ErrorCoded
- PHP入门之数组
- PHP基础之排序
- 关于mysql limit offset的一点优化
- PHP基础之查找
- PHP木马免杀的一些总结