tensorfrom
基础介绍
1.tensor–张量
2.op(operation):专门运算的的操作节点,所有操作都是一个op
3.图:graph:你的整个程序结构
4.绘画:session()–运算程序的图,而使用的
只要用tf定义的API的函数都是op
Session()绘画
1.tensor:前段,定义程序的图的机构
后端:运算图结构
绘画的作用
- 运行图的结构
- 分配计算资源
- 掌握资源(变量资源,队列,线程)
import tensorflow as tf
# 实现加法运算
a = tf.constant(5.0)
b = tf.constant(6.0)
sum1 = tf.add(a, b)
with tf.Session() as sess:
print(sess.run(sum1))
- 一个with 只能执行一个哦
# 指定运行另一张图
g=tf.Grap()
sum1 = tf.add(a, b)
with tf.Session(grap=g) as sess:
print(sess.run(sum1))
tf.InteractiveSession()------交互式
a = tf.constant(5.0)
b = tf.constant(6.0)
sum1 = tf.add(a, b)
# 只要有上下文就可以使用方便的eavl()
with tf.Session() as sess:
print(sum1.eval())
run()
- 不是op不能运行的哦*
placeholder----feed_dict
# placeholder 占位符,先站位了然后后期在放东西进入
plt = tf.placeholder(tf.float32, [2, 3])
with tf.Session() as sess:
print(sess.run(plt, feed_dict={plt:[[1, 2, 3], [4, 5, 89]]}))
--------------------------
[none, 3]--shape(?,3)
二.张量-----tensor
- Tensorfrom基本数据类型
- 一个类型化的N维数据类型
- 三部分:名字,形状,数据类型
阶 | 数学实例 | python |
---|---|---|
0 | 纯量 | 只有大小 |
1 | 向量 | 只有大小和方向 |
2 | 矩阵 | 数据表 |
3 | 3阶张量 | 数据立体 |
n | n阶 | 自己想 |
张量的基本属性
- a.graph-------默认图
- a.shape------形状
- a.name-------张量字符串描述
- a.op-----------操作名
打印出来形状表示
0维:()
1维:(5)
2维:(2,3)
3维:(2,3,4)—2张3行4列的表
张量的形态
动态形状和静态形状:在于有没有生成一个新的张量数据
Tensorflow中,张量具有静态形态和动态形态
- 静态形态
1.创建一个张量,初始状态的形状 - 动态形态
1.一种描述原始张量在执行过程中的形态
2.tf.reshape:创建一个具有不同形态的新张量
# 静态形状,没固定可以修改
plt = tf.placeholder(tf.float32,[None,2])
print(plt)
plt.set_shape([3, 2])
print(plt)
Tensor("Placeholder:0", shape=(?, 2), dtype=float32)
Tensor("Placeholder:0", shape=(3, 2), dtype=float32)
反之静态形状,固定不可修改
# 静态形状,没固定可以修改
plt = tf.placeholder(tf.float32,[4,2])
print(plt)
plt.set_shape([3, 2])
print(plt)
ValueError: Dimension 0 in both shapes must be equal, but are 4 and 3. Shapes are [4,2] and [3,2].
动态形状可以,创建一个张量-tf.reshape
plt = tf.placeholder(tf.float32,[None,2])
print(plt)
plt.set_shape([3, 2])
print(plt)
plt_reshape = tf.reshape(plt, [2,3])
print(plt_reshape)
Tensor("Placeholder:0", shape=(?, 2), dtype=float32)
Tensor("Placeholder:0", shape=(3, 2), dtype=float32)
Tensor("Reshape:0", shape=(2, 3), dtype=float32)
ValueError:Cannot reshape a tensor with 6 elements to shape [4,3] (12 elements) for 'Reshape_1' (op: 'Reshape') with input shapes: [3,2], [2] and wi
动态形态可以创建一个新的张量,改变时候一定要注意元素的匹配,上面是【2,3】一共6个,动态reshape只能6个
注:
- 静态形态,1D->1D,2D–>2D,不能夸维度修改
动态形态可以跨纬度修改,1D–>2D 1D–>3D - 对于已经固定或者设置静态形态的张量,不能再次设置静态形态
- tf.reshape()动态创建新张量,元素个数不能差
创建张量
-
随机张量
tf.random_normal(shape,mean=0.0,stddev=1.0,dtype=tf.float32,seed=None,name=None)
mean—平均值
stddev—标准差 -
变量转换
tf.cast([[1,2,3],[3,4,5]],tf.float32) -
切片与扩张
import tensorflow as tf
#
a=[[1,2,3],[3,4,5]]
b=[[2,2,2],[3,4,3]]
c=tf.concat([a,b], axis=0)
b=tf.concat([a,b], axis=1)
with tf.Session() as sess:
print(c.eval())
print('*'*50)
print(b.eval())
pass
[[1 2 3]
[3 4 5]
[2 2 2]
[3 4 3]]
****************
[[1 2 3 2 2 2]
[3 4 5 3 4 3]]