TensorFlow学习笔记......更新中......
tensorflow官方的教程https://tensorflow.google.cn/tutorials/customization/basics
初学者快速入门
import tensorflow as tf #载入并准备好MNIST数据集,将样本从整数转换为浮点数 mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 #将模型的各层堆叠起来,以搭建tf.keras.Sequential模型。为训练选择优化器和损失函数 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) #训练并检验模型 model.fit(x_train, y_train, epochs=5) model.evaluate(x_test, y_test, verbose=2)
输出:
张量(Tensors)
1.张量是一个多维数组。与 NumPyndarray
对象类似,tf.Tensor
对象具有数据类型和形状。此外,tf.Tensor
s 可以驻留在加速器内存中(如 GPU)。TensorFlow 提供了一个丰富的操作库(tf.add、tf.matmul、tf.linalg.inv等)来消费和生产tf.Tensor
s。这些操作会自动转换内置的 Python 类型(官网翻译)
print(tf.add(1,2)) print(tf.add([1,2],[3,4])) print(tf.square(5)) print(tf.reduce_sum([1,2,3])) #operator overloading is also supported 还支持操作符重载 print(tf.square(2) + tf.square(3))
输出:
tf.Tensor(3, shape=(), dtype=int32) tf.Tensor([4 6], shape=(2,), dtype=int32) tf.Tensor(25, shape=(), dtype=int32) tf.Tensor(6, shape=(), dtype=int32) tf.Tensor(13, shape=(), dtype=int32)
2.每个tf.Tensor
都有一个形状和一个数据类型:
x = tf.matmul([[1]], [[2,3]]) print(x) print(x.shape) print(x.dtype)
输出:
tf.Tensor([[2 3]], shape=(1, 2), dtype=int32)
(1, 2)
<dtype: 'int32'>
3.NumPy 兼容性
TensorFlowtf.Tensor
和 NumPy之间的转换ndarray
很容易:
- TensorFlow 操作会自动将 NumPy ndarray 转换为张量。
- NumPy 操作会自动将张量转换为 NumPy ndarray。
张量使用他们的方法显式转换为 NumPy ndarray .numpy()
。如果可能的话,这些转换通常很便宜,因为数组并tf.Tensor
共享底层内存表示。然而,共享底层表示并不总是可能的,因为它tf.Tensor
可能托管在 GPU 内存中,而 NumPy 数组总是由主机内存支持,并且转换涉及从 GPU 到主机内存的复制。
import numpy as np ndarray = np.ones([3,3]) print("将数组转换成张量") tensor = tf.multiply(ndarray,42) print(tensor) print("将张量转换为数组") print(np.add(tensor,1)) print(".numpy()方法显式地将张量转换为numpy数组") print(tensor.numpy())
输出:
将数组转换成张量
tf.Tensor(
[[42. 42. 42.]
[42. 42. 42.]
[42. 42. 42.]], shape=(3, 3), dtype=float64)
将张量转换为数组
[[43. 43. 43.]
[43. 43. 43.]
[43. 43. 43.]]
.numpy()方法显式地将张量转换为numpy数组
[[42. 42. 42.]
[42. 42. 42.]
[42. 42. 42.]]
4.数据集:该tf.data.Dataset
API 用于从简单、可重用的部分构建高性能、复杂的输入管道,这些部分将为模型的训练或评估循环提供数据。
创建源Dataset:使用工厂函数之一创建源Dataset.from_tensors
数据集,如,Dataset.from_tensor_slices
或使用从文件中读取的对象,如TextLineDataset
或TFRecordDataset
。
ds_tensors = tf.data.Dataset.from_tensor_slices([1,2,3,4,5,6]) #创建一个csv文件 import tempfile _,filename = tempfile.mkstemp() with open(filename, 'w') as f: f.write("""Line 1 Line 2 Line 3 """) ds_file = tf.data.TextLineDataset(filename)
应用转换:使用 、 和 等转换函数map
将batch
转换shuffle
应用于数据集记录。
ds_tensors = ds_tensors.map(tf.square).shuffle(2).batch(2)
ds_file = ds_file.batch(2)
迭代:tf.data.Dataset
对象支持迭代以循环记录:
print('ds_tensors的元素') for x in ds_tensors: print(x) print('\nds_file的元素') for x in ds_file: print(x)
输出:
TensorFlow常数 (TensorFlow Constants)
constant(value, dtype=None, shape=None, name='Const', verify_shape=False)
创建
myConstant = tf.constant(4.5, name="x", dtype=tf.float32)
TensorFlow变量 (TensorFlow Variables)
在TensorFlow中,当我们训练模型时变量非常有用。 作为常量,我们必须调用构造函数来初始化变量,初始值可以作为参数传递。 创建变量很容易,可以按照以下步骤进行:
myVariable = tf.Variable(tf.zeros([1]), name="myVariable")
如果我们只想将变量用于计算并且不应该对其进行训练,则可以使用可训练标志,如下所示:
k = tf.Variable(tf.add(a, b), trainable=False)
占位符(Placeholder)
占位符,用于表示输入输出数据的格式,声明了数据位置,允许传入指定类型和形状的数据,通过会话中的feed_dict参数获取数据,在计算图运行时使用获取的数据进行计算,计算完毕后获取的数据就会消失。
x = tf.compat.v1.placeholder(tf.int32) y = tf.compat.v1.placeholder(tf.int32) z = tf.add(x, y) session = tf.compat.v1.Session() with session: print(session.run([z], feed_dict={x: [1, 2], y: [2, 3]}))
输出:
[array([3, 5])]
网址:
Tensorflow基础 - 菜鸟教程 | BootWiki.com
(1条消息) Python TensorFlow教程_cunchi4221的博客-CSDN博客
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律