哈喽,大家好!我是风哥,一个资深Python工程师。今天给大家介绍机器学习领域的王者——TensorFlow!想入门人工智能但不知从何开始?TensorFlow就是你的最佳选择,它不仅功能强大,还有着完善的生态系统和丰富的学习资源!
让我们开始这段AI之旅吧!
一、安装
1pip install tensorflow
二、基础概念和操作
1. 张量(Tensor)基础操作:
1import tensorflow as tf
2
3# 创建张量
4def tensor_basics():
5 # 创建常量张量
6 tensor1 = tf.constant([[1, 2], [3, 4]])
7 tensor2 = tf.constant([[5, 6], [7, 8]])
8
9 # 基本运算
10 add = tf.add(tensor1, tensor2) # 加法
11 sub = tf.subtract(tensor1, tensor2) # 减法
12 mul = tf.multiply(tensor1, tensor2) # 乘法
13 div = tf.divide(tensor1, tensor2) # 除法
14
15 # 矩阵运算
16 matmul = tf.matmul(tensor1, tensor2) # 矩阵乘法
17
18 return add, sub, mul, div, matmul
构建简单神经网络:
1import tensorflow as tf
2from tensorflow.keras import layers, models
3
4def create_simple_nn():
5 # 创建序列模型
6 model = models.Sequential([
7 layers.Dense(64, activation='relu', input_shape=(28*28,)),
8 layers.Dropout(0.2),
9 layers.Dense(32, activation='relu'),
10 layers.Dense(10, activation='softmax')
11 ])
12
13 # 编译模型
14 model.compile(
15 optimizer='adam',
16 loss='sparse_categorical_crossentropy',
17 metrics=['accuracy']
18 )
19
20 return model
三、高级应用
卷积神经网络(CNN):
1def create_cnn():
2 model = models.Sequential([
3 # 卷积层
4 layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
5 layers.MaxPooling2D((2, 2)),
6 layers.Conv2D(64, (3, 3), activation='relu'),
7 layers.MaxPooling2D((2, 2)),
8
9 # 打平层
10 layers.Flatten(),
11
12 # 全连接层
13 layers.Dense(64, activation='relu'),
14 layers.Dropout(0.5),
15 layers.Dense(10, activation='softmax')
16 ])
17
18 model.compile(
19 optimizer='adam',
20 loss='sparse_categorical_crossentropy',
21 metrics=['accuracy']
22 )
23
24 return model
循环神经网络(RNN):
1def create_rnn():
2 model = models.Sequential([
3 # LSTM层
4 layers.LSTM(64, return_sequences=True,
5 input_shape=(None, 1)),
6 layers.LSTM(32),
7
8 # 全连接层
9 layers.Dense(16, activation='relu'),
10 layers.Dense(1)
11 ])
12
13 model.compile(
14 optimizer='adam',
15 loss='mse'
16 )
17
18 return model
四、实战案例
图像分类:
1import tensorflow as tf
2from tensorflow.keras.preprocessing import image
3import numpy as np
4
5class ImageClassifier:
6 def __init__(self):
7 # 加载预训练模型
8 self.model = tf.keras.applications.MobileNetV2(
9 weights='imagenet',
10 include_top=True
11 )
12
13 def preprocess_image(self, img_path):
14 # 加载和预处理图像
15 img = image.load_img(img_path, target_size=(224, 224))
16 x = image.img_to_array(img)
17 x = np.expand_dims(x, axis=0)
18 x = tf.keras.applications.mobilenet_v2.preprocess_input(x)
19 return x
20
21 def predict(self, img_path):
22 # 预测图像类别
23 processed_img = self.preprocess_image(img_path)
24 predictions = self.model.predict(processed_img)
25 decoded_predictions = tf.keras.applications.mobilenet_v2.decode_predictions(
26 predictions, top=3
27 )[0]
28
29 return decoded_predictions
文本分类:
1import tensorflow as tf
2import tensorflow_hub as hub
3
4class TextClassifier:
5 def __init__(self):
6 # 加载预训练的BERT模型
7 self.bert_layer = hub.KerasLayer(
8 "https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4",
9 trainable=True
10 )
11
12 # 构建模型
13 self.model = self.build_model()
14
15 def build_model(self):
16 # 输入层
17 input_ids = tf.keras.layers.Input(shape=(128,), dtype=tf.int32)
18 input_mask = tf.keras.layers.Input(shape=(128,), dtype=tf.int32)
19 segment_ids = tf.keras.layers.Input(shape=(128,), dtype=tf.int32)
20
21 # BERT层
22 pooled_output, sequence_output = self.bert_layer(
23 [input_ids, input_mask, segment_ids]
24 )
25
26 # 分类层
27 x = tf.keras.layers.Dense(64, activation='relu')(pooled_output)
28 x = tf.keras.layers.Dropout(0.2)(x)
29 output = tf.keras.layers.Dense(2, activation='softmax')(x)
30
31 # 构建模型
32 model = tf.keras.Model(
33 inputs=[input_ids, input_mask, segment_ids],
34 outputs=output
35 )
36
37 return model
五、性能优化技巧
GPU加速:
1def check_gpu():
2 # 检查GPU是否可用
3 if tf.test.is_built_with_cuda():
4 print("CUDA可用")
5 print("可用的GPU设备:", tf.config.list_physical_devices('GPU'))
6 else:
7 print("仅使用CPU")
8
9def configure_gpu():
10 # GPU内存增长配置
11 gpus = tf.config.experimental.list_physical_devices('GPU')
12 if gpus:
13 try:
14 for gpu in gpus:
15 tf.config.experimental.set_memory_growth(gpu, True)
16 except RuntimeError as e:
17 print(e)
数据加载优化:
1def optimize_data_loading(dataset, batch_size=32):
2 # 数据预取和缓存
3 dataset = dataset.cache()
4 dataset = dataset.shuffle(buffer_size=1000)
5 dataset = dataset.batch(batch_size)
6 dataset = dataset.prefetch(tf.data.AUTOTUNE)
7
8 return dataset
六、模型部署
保存和加载模型:
1def save_and_load_model(model, save_path):
2 # 保存模型
3 model.save(save_path)
4
5 # 加载模型
6 loaded_model = tf.keras.models.load_model(save_path)
7 return loaded_model
8
9# TensorFlow Lite转换
10def convert_to_tflite(model, save_path):
11 converter = tf.lite.TFLiteConverter.from_keras_model(model)
12 tflite_model = converter.convert()
13
14 with open(save_path, 'wb') as f:
15 f.write(tflite_model)
使用TensorFlow时的一些建议:
始终注意数据预处理的重要性
合理使用批量大小和学习率
注意模型过拟合问题
善用TensorBoard进行可视化
定期保存模型检查点
今天的Python学习之旅就到这里啦!记得动手敲代码,有问题随时在评论区问风哥哦。祝大家学习愉快,收获满满!