1.张量的创建及运算

1.张量的创建

import tensorflow as tf
import numpy as np
# 1. 创建一个张量
a = tf.constant([[1, 5]], dtype = tf.int64)
print(a)
#  打印结果:tf.Tensor([[1 5]], shape=(1,2), dtype=int64) 打印出张量的内容,形状,数据类型
print(a.dtype)
print(a.shape) # shape(1,2) 逗号隔开了几个数字这个张量就是几维的,2代表张量的元素个数是2


a = tf.zeros(2)  # 一维 直接写个数
b = tf.zeros([2, 3, 4])  # 二维 用[行,列] ,多维用[m,j,k,l......]
c = tf.ones(4)
d = tf.fill([3, 3], 5)  # 指定所有元素为5
print(a)  # tf.Tensor([0. 0.], shape=(2,), dtype=float32)
print(b)
#tf.Tensor(
#[[[0. 0. 0. 0.]
 # [0. 0. 0. 0.]
 # [0. 0. 0. 0.]]
#
 #[[0. 0. 0. 0.]
  #[0. 0. 0. 0.]
  #[0. 0. 0. 0.]]], shape=(2, 3, 4), dtype=float32)
print(c)  # tf.Tensor([1. 1. 1. 1.], shape=(4,), dtype=float32)
print(d)
#tf.Tensor(
#[[5 5 5]
# [5 5 5]
# [5 5 5]], shape=(3, 3), dtype=int32)

2.将numpy的数据类型转换成Tensor的数据类型

import tensorflow as tf
import numpy as np
a = np.arange(0, 5)
b = tf.convert_to_tensor(a, dtype = tf.int64)
print(a)
print(b)

3.随机数据

d = tf.random.normal([2,2], mean=0.5, stddev=1) # 正态分布
print(d)
e = tf.random.truncated_normal([2, 2], mean=0.5, stddev=1) #  截断式正态分布,生成的数据更加集中
print(e)

f = tf.random.uniform([2, 2], minval=0, maxval=2) # 生成均匀分布的随机数[最小值,最大值)左闭右开的区间
print(f)

4.强制装换数据及元素的最大小值

x1 = tf.constant([1., 2., 3.], dtype= tf.float64)
print(x1)
x2 = tf.cast(x1, tf.int32)  # 强制转换数据的类型
print(x2)
print(tf.reduce_max(x2), tf.reduce_min(x2)) # 所有的最大值,最小值

5.求张量元素的均值(axis)与总和

x = tf.constant([[1, 2, 3], [1, 2, 3]])
print(x)
print(tf.reduce_mean(x))  # 求所有元素的均值
print(tf.reduce_mean(x, axis=0)) # axis=0 纵向操纵
print(tf.reduce_mean(x, axis=1))# axis=0 横向操纵
print(tf.reduce_sum(x, axis=0))
print(tf.reduce_sum(x, axis=1))

6.张量的运算

# 对应元素的四则运算   张量的维度要一致
a = tf.ones([1, 3])
b = tf.fill([1, 3], 3.)
print(tf.add(a, b))  # 加 张量的维度要一致
print(tf.subtract(a, b))
print(tf.multiply(a, b))
print(tf.divide(a, b))
# 源码29.py

a = tf.fill([1, 2], 3.)
print(tf.pow(a,3))  # 3 次方
print(tf.sqrt(a))   # 开方
print(tf.square(a))  # 平方

a = tf.ones([3,2])
b = tf.fill([2,3],3.)
print(tf.matmul(a,b)) # 矩阵相乘

7.切分传入张量的第一维度,生成输入特征与标签对,构建数据集

features = tf.constant([12, 23, 10, 17])
labels = tf.constant([0, 1, 1, 0])
dataset = tf.data.Dataset.from_tensor_slices((features, labels)) # 输入特征与标签配对
for element in dataset:
    print(element)


#数据集的建立
features = tf.constant()
labels = tf.constant()
dataset = tf.data.Dataset.from_tensr_slices((features,labels))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值