我将自学TensorFlow的基础知识总结如下,将从理解张量的数据结构开始。
张量数据结构
张量(tensor)用作TensorFlow语言中的基本数据结构。张量表示任何称为数据流图的流程图中的连接边。张量也可以定义为多维数组或列表。
通过以下三个参数识别张量 -
秩张量中描述的维度单位称为秩,它标识了张量的维数。张量的等级可以描述为定义的张量的阶数或n维。
形状
行数和列数一起定义了Tensor的形状。
类型
Type描述分配给Tensor元素的数据类型。
一维张量
二维张量
张量处理和操作
import numpy as np
import tensorflow.compat.v1 as tf #解决TF2.0库和TF1.0代码冲突问题
tf.disable_v2_behavior() #解决TF2.0库和TF1.0代码冲突问题
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f’Hi, {name}’) # Press Ctrl+F8 to toggle the breakpoint.
#tensorflow基础
if name == ‘main’:
# print_hi(‘PyCharm’)
matrix1 = np.array([(2, 2, 2), (2, 2, 2), (2, 2, 2)], dtype=‘int32’)
matrix2 = np.array([(1, 1, 1), (1, 1, 1), (1, 1, 1)], dtype=‘int32’)
print(matrix1)
print(matrix2)
matrix1 = tf.constant(matrix1)#设常量
matrix2 = tf.constant(matrix2)
matrix_product = tf.matmul(matrix1, matrix2)#两个矩阵相乘
matrix_sum = tf.add(matrix1, matrix2)#两个矩阵相加
matrix_3 = np.array([(2, 7, 2), (1, 4, 2), (9, 0, 2)], dtype='float32')
print(matrix_3)
tf.compat.v1.disable_eager_execution()
hello = tf.constant('hello pycharm')
with tf.compat.v1.Session() as sess:
result1 = sess.run(hello)
result2 = sess.run(matrix_sum)
print(result1)
print(result2)