简介:TensorFlow 安装及使用
TensorFlow 安装及使用
引言
TensorFlow 是一款由 Google 开发的开源机器学习库,广泛应用于深度学习、人工智能等领域。它提供了一种灵活的方式来构建和训练神经网络,并且支持各种语言,包括 Python、C++、Java 等。本文将详细介绍 TensorFlow 的安装及使用过程,帮助读者更好地理解和应用这款强大的工具。
安装流程
如果您需要 GPU 支持,请安装 tensorflow-gpu:
pip install tensorflow==<version>
pip install tensorflow-gpu==<version>
如果输出 TensorFlow 的版本号,则表示安装成功。
python -c "import tensorflow as tf; print(tf.__version__)"
import tensorflow as tf
# 导入 MNIST 数据集(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()# 数据预处理x_train, x_test = x_train / 255.0, x_test / 255.0# 构建模型model = tf.keras.Sequential([tf.keras.layers.Flatten(input_shape=(28, 28)),tf.keras.layers.Dense(128, activation='relu'),tf.keras.layers.Dense(10)])# 编译模型model.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=['accuracy'])# 训练模型model.fit(x_train, y_train, epochs=5)# 评估模型model.evaluate(x_test, y_test)
常见问题及解决方法
# 加载模型model = tf.keras.models.load_model('model.h5')# 推断示例图像image = tf.keras.preprocessing.image.load_img('example.jpg', target_size=(28, 28))image = tf.keras.preprocessing.image.img_to_array(image)image = tf.expand_dims(image, axis=0)image = image / 255.0prediction = model.predict(image)# 输出预测结果print(prediction)