tensorflow v2.0入门教程——02基本操作
个人博客
tensor
tensor即张量,张量的数学含义是多维数组,标量(数字)可以看作是0维的张量。一维数组称为1维向量,二维数组称为矩阵。在神经网络学习中,几乎所有的数据都可以看作张量,如神经网络的权重,偏置等。
输出hello world
import tensorflow as tf
hello = tf.constant('hello world') # 创建一个常量
print(hello) # 输出
print(hello.numpy()) # 输出张量的值
print(hello.shape) # 输出维度
print(hello.dtype) # 输出张量类型
输出结果
tf.Tensor(b'hello world', shape=(), dtype=string)
b'hello world'
shape是维度,标量是0维,[1,2,3]
是1维。[[1,2],[3,4]]
是2维,shape=(2,2)。
dtype是张量类型。
基本张量操作
import tensorflow as tf
# 定义常量
a = tf.constant(3)
b = tf.constant(4)
c = tf.constant(5)
matrix1 = tf.constant([[1., 2.], [3., 4.]])
matrix2 = tf.constant([[5., 6.], [7., 8.]])
add = tf.add(a, b) # 求和
sub = tf.subtract(a, b) # 求差
mul = tf.multiply(a, b) # 求积
div = tf.divide(a, b) # 相除
mean = tf.reduce_mean([a, b, c]) # 求平均数
sum = tf.reduce_sum([a, b, c]) # 求和
product = tf.matmul(matrix1, matrix2) # 矩阵相乘
# 输出张量的值
print("add =", add.numpy())
print("sub =", sub.numpy())
print("mul =", mul.numpy())
print("div =", div.numpy())
print("mean =", mean.numpy())
print("sum =", sum.numpy())
print("product=", product.numpy())
输出结果
add = 7
sub = -1
mul = 12
div = 0.75
mean = 4
sum = 12
product= [[19. 22.]
[43. 50.]]
个人博客
还没有评论,来说两句吧...