tensorflow张量
发布时间
阅读量:
阅读量
# 张量
import tensorflow as tf
"""
1. 定义:
6. tensorflow想象成一个n维 数组, 类型 tf.tensor, tensor里面有两个重要概念:
a. 类型:
dtype: 定义类型:
tf.placeholder(dtype = tf.float)
b. shape
2. 转换:
18. a. 类型转换:
tf.case(转换张量, 转换的类型)
b. 形状转换: shape
i.动态转换
reshape:
ii.静态转换
set_shape:
"""
def shape():
"""
show 张量的形状
:return:
"""
a = tf.constant(10) # 标量 shape=()
b = tf.constant([1, 2, 3, 4]) # 向量 shape=(4,)
c = tf.constant([[1, 2, 3], [4, 5, 6]]) # shape=(2, 3)
print(a)
print(b)
print(c)
return None
def create():
"""
创建张量
:return:
"""
# 创建一个全部都是0的张量
zero = tf.zeros(dtype=tf.float32, shape=[2,3])
# 创建一个全部都是1的张量
one = tf.ones(dtype=tf.int32, shape=[4,4])
# 创建固定张量
constant = tf.constant([[1,2,3],[2,2,2],[3,3,3]])
# 创建随机张量
random = tf.random_normal(dtype=tf.float32, shape=[2,3])
# 访问内部的值,开启会话
with tf.Session() as sess:
print("zero :", sess.run(zero))
print("one :", sess.run(one))
print("constant :", sess.run(constant))
print("random :", sess.run(random))
return None
def change():
"""
tensorflow类型转化
:return:
"""
tensor = tf.ones(dtype=tf.int32, shape=[2, 3])
print(tensor)
a = tf.cast(tensor, tf.float32)
# Tensor("ones:0", shape=(2, 3), dtype=int32)
# Tensor("Cast:0", shape=(2, 3), dtype=float32)
print(a)
def change_shape():
"""
形状转换
:return:
"""
a = tf.constant([1, 2, 3, 4]) # shape(4,)
ph = tf.placeholder(dtype=tf.float32, shape=[None, 4])
# 动态转换
# a1 = tf.reshape(a, [3, 2])
# 静态转换: 静态转换是不能够跨阶转换的
# a.set_shape([2, 2]) Shapes (4,) and (2, 2) are not compatible
# 塑形只能有塑形一次
ph.set_shape([5, 4])
# ph.set_shape([3, 4])
print(ph)
with tf.Session() as sess:
print("a1 :", sess.run(a))
change_shape()
python

全部评论 (0)
还没有任何评论哟~
