Python环境下Keras与GPU使用及数据处理指南

需积分: 4 2 下载量 64 浏览量 更新于2024-09-03 收藏 29KB DOCX 举报
"这份文档是关于Keras的笔记整理,主要涵盖了如何在Python环境中配置虚拟环境并安装Keras,以及Keras模型的保存与加载,特别是最佳模型的保存。此外,文档还介绍了如何将数据保存为NPZ和MAT格式,并进行读取。这非常适合理工科学者或对机器学习感兴趣的同学参考学习。" 在Python中配置Keras通常需要先创建一个虚拟环境,以隔离项目依赖。可以使用`virtualenv`或`conda`来创建虚拟环境。安装Keras时,可以通过`pip`命令进行: ```bash pip install keras ``` 或者,如果你打算在GPU上运行Keras,你需要确保已经安装了支持CUDA和cuDNN的TensorFlow版本: ```bash pip install tensorflow-gpu ``` Keras模型的保存和加载是模型持久化的重要步骤。你可以使用`model.save()`方法保存整个模型,包括权重、架构和优化器状态: ```python model.save('my_model.h5') ``` 然后,通过`load_model()`函数加载模型: ```python from keras.models import load_model model = load_model('my_model.h5') ``` 对于最佳模型的保存,可以利用回调函数`ModelCheckpoint`,它会在每个epoch结束时检查模型的性能,如果性能优于之前记录的最佳值,就保存模型: ```python from keras.callbacks import ModelCheckpoint checkpoint = ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True, mode='min') model.fit(X_train, y_train, validation_data=(X_val, y_val), callbacks=[checkpoint]) ``` Keras在多GPU上运行可以通过`tf.distribute.MirroredStrategy`策略实现模型并行: ```python from tensorflow.keras.utils import multi_gpu_model strategy = tf.distribute.MirroredStrategy() with strategy.scope(): model = create_model() model.compile(optimizer=optimizer, loss=loss_function) ``` 为了在Keras开发中获得可复现的结果,需要设定随机种子,确保数据加载、权重初始化和优化器步进的确定性: ```python import numpy as np import tensorflow as tf np.random.seed(42) tf.random.set_seed(42) ``` Python中读取MAT格式数据可以使用`scipy.io.loadmat`: ```python import scipy.io as sio name_tem = './average.mat' data_tem = sio.loadmat(name_tem) I = data_tem['b'] ``` 对于NPZ格式,可以使用`numpy.load`: ```python import numpy as np name_tem = 'DATAcnn-label.npz' data_tem = np.load(name_tem) X = data_tem['X'] ``` 保存数据到MAT和NPZ格式: ```python import scipy.io as sio import numpy as np # 保存为NPZ name_tem = './DATA-test10.npz' np.savez(name_tem, X=X) # 保存为MAT name_tem1 = './cnnlabel4.mat' sio.savemat(name_tem1, {'Y': Y}) ``` 将数据保存为TXT格式,可以使用`numpy.savetxt`: ```python import numpy as np path, num, index = ... # 填充相应的路径、数字和索引 name_tem1 = f'{path}/{num}_fig{index[0]}.txt' np.savetxt(name_tem1, L, fmt="%d", delimiter=",") ``` Keras中的`EarlyStopping`回调是一个非常有用的工具,它可以在验证损失不再改善时提前停止训练,防止过拟合。通过调整`patience`参数来控制停止前允许的不改善的epoch数,例如: ```python from keras.callbacks import EarlyStopping early_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True) model.fit(X_train, y_train, validation_data=(X_val, y_val), callbacks=[early_stopping]) ``` 以上就是Keras的安装、模型保存与加载、数据读写以及训练过程中的优化策略的基本介绍。这些知识对于进行机器学习项目开发是非常基础且重要的。

import tensorflow as tf def build_model(input_shape): inputs = tf.keras.layers.Input(shape=input_shape) # encoder conv1 = tf.keras.layers.Conv2D(32, (3,3), activation='relu', padding='same')(inputs) conv1 = tf.keras.layers.BatchNormalization()(conv1) conv2 = tf.keras.layers.Conv2D(32, (3,3), activation='relu', padding='same')(conv1) conv2 = tf.keras.layers.BatchNormalization()(conv2) pool1 = tf.keras.layers.MaxPooling2D((2, 2))(conv2) conv3 = tf.keras.layers.Conv2D(64, (3,3), activation='relu', padding='same')(pool1) conv3 = tf.keras.layers.BatchNormalization()(conv3) conv4 = tf.keras.layers.Conv2D(64, (3,3), activation='relu', padding='same')(conv3) conv4 = tf.keras.layers.BatchNormalization()(conv4) pool2 = tf.keras.layers.MaxPooling2D((2, 2))(conv4) conv5 = tf.keras.layers.Conv2D(128, (3,3), activation='relu', padding='same')(pool2) conv5 = tf.keras.layers.BatchNormalization()(conv5) conv6 = tf.keras.layers.Conv2D(128, (3,3), activation='relu', padding='same')(conv5) conv6 = tf.keras.layers.BatchNormalization()(conv6) pool3 = tf.keras.layers.MaxPooling2D((2, 2))(conv6) # decoder up1 = tf.keras.layers.Conv2DTranspose(64, (2,2), strides=(2,2), padding='same')(pool3) merge1 = tf.keras.layers.concatenate([conv4, up1]) conv7 = tf.keras.layers.Conv2D(64, (3,3), activation='relu', padding='same')(merge1) conv7 = tf.keras.layers.BatchNormalization()(conv7) conv8 = tf.keras.layers.Conv2D(64, (3,3), activation='relu', padding='same')(conv7) conv8 = tf.keras.layers.BatchNormalization()(conv8) up2 = tf.keras.layers.Conv2DTranspose(32, (2,2), strides=(2,2), padding='same')(conv8) merge2 = tf.keras.layers.concatenate([conv2, up2]) conv9 = tf.keras.layers.Conv2D(32, (3,3), activation='relu', padding='same')(merge2) conv9 = tf.keras.layers.BatchNormalization()(conv9) conv10 = tf.keras.layers.Conv2D(32, (3,3), activation='relu', padding='same')(conv9) conv10 = tf.keras.layers.BatchNormalization()(conv10) outputs = tf.keras.layers.Conv2D(3, (3,3), padding='same')(conv10) model = tf.keras.models.Model(inputs=inputs, outputs=outputs) return model

2023-04-23 上传