利用tensorflow从本地加载图片训练二分类的代码
时间: 2024-11-22 10:40:14 浏览: 16
Tf session 会话分析
在TensorFlow中,我们可以使用`tf.keras.preprocessing.image.ImageDataGenerator`从本地目录加载图片并将其预处理成适合模型训练的数据。以下是一个简单的示例,展示如何训练一个二分类图像识别模型:
```python
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# 定义训练和验证数据生成器
train_datagen = ImageDataGenerator(rescale=1./255) # 预处理:将像素值缩放到0到1之间
validation_datagen = ImageDataGenerator(rescale=1./255)
# 图像路径和类别列表
image_dir_train = 'path_to_your_train_images'
image_dir_val = 'path_to_your_validation_images'
train_categories = ['class1', 'class2'] # 例如两个类别
# 创建数据集
train_generator = train_datagen.flow_from_directory(
image_dir_train,
target_size=(img_height, img_width), # 根据实际图片尺寸设置
batch_size=batch_size,
class_mode='binary' # 如果是二分类,class_mode设为'two' 或 'binary'
)
validation_generator = validation_datagen.flow_from_directory(
image_dir_val,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='binary'
)
# 构建模型
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(img_height, img_width, 3)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(64, activation='relu'),
Dense(len(train_categories), activation='sigmoid') # 输出层大小等于类别数
])
# 编译模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# 训练模型
history = model.fit(
train_generator,
epochs=num_epochs,
validation_data=validation_generator
)
阅读全文