基于英特尔 oneAPI AI 工具包进行皮肤癌分类

摘要

最近,人工智能在医疗领域的应用越来越受到关注。借助英特尔的 oneAPI AI 工具包,我们可以开发一个面向大众的个性化健康管理工具,其中一个重要的功能是皮肤癌分类。通过收集用户的健康数据,结合人工智能技术进行数据分析和处理,我们可以为用户提供个性化的健康管理方案,并帮助他们更好地管理和改善自己的身体健康状态。

本项目使用英特尔的 oneAPI AI 工具包,旨在开发一个基于人工智能的皮肤癌分类系统。这个系统可以对用户提供的皮肤病变图像进行分类,以判断是否存在皮肤癌的风险。通过使用深度学习算法和卷积神经网络模型,我们可以准确地对皮肤病变进行分类和诊断。

项目大概内容

在开始项目之前,需要先安装 Anaconda 和英特尔 oneAPI AI 工具包。Anaconda 是一个流行的 Python 数据科学平台,而英特尔 oneAPI AI 工具包则提供了优化的 Python 和 Tensorflow,以加速机器学习和深度学习任务。安装完这些工具后,我们可以继续进行项目的开发。

首先,我们需要准备数据集。由于项目数据集图片较多,本次是精简后的项目。我们将使用包含皮肤病变图像的数据集来训练和测试我们的分类模型。接下来,我们需要安装一些 Python 依赖项,以便能够训练和测试分类模型。这些依赖项包括 matplotlib、keras_preprocessing、Pillow、opencv-python、numpy 和 scikit-image。安装完成后,我们可以进入保存数据集和代码的目录,并按以下步骤进行操作。

首先,我们运行 “Train.py” 文件以训练并保存分类模型。在训练过程中,我们使用数据集中的图像进行训练,并通过迭代优化模型的参数。训练完成后,我们将保存训练好的模型,以便后续的测试和应用。

接下来,我们可以运行 “Test.py” 文件,使用保存的模型对新的图像进行分类测试。通过加载之前保存的模型,我们可以对用户提供的皮肤病变图像进行分类,并判断是否存在皮肤癌的风险。这样,我们就可以为用户提供及时的健康建议和指导,帮助他们更好地管理自己的健康状况。

通过这个基于英特尔oneAPI AI 工具包的皮肤癌分类项目,我们能够将先进的人工智能技术应用于医疗领域,提供个性化的健康管理方案,以促进人们的身体健康和生活质量的提高。

这个项目的核心是深度学习算法和卷积神经网络模型。深度学习是一种机器学习方法,它模拟人类大脑神经网络的结构和功能。卷积神经网络是深度学习的一种重要架构,专门用于处理图像和视觉数据。通过训练这样的网络模型,我们可以让计算机学会从图像中提取有用的特征,并进行准确的分类和诊断。

训练过程

在训练过程中,我们使用包含皮肤病变图像的数据集。这些图像涵盖了不同类型的皮肤病变,包括正常皮肤、良性病变和恶性病变。我们将数据集划分为训练集和测试集,用于训练和评估模型的性能。通过迭代优化模型的参数,我们可以逐步提高模型的准确性和泛化能力。

训练完成后,我们将保存训练好的模型。这样,在实际应用中,我们只需要加载保存的模型,并输入用户提供的皮肤病变图像,就可以快速进行分类和诊断。系统将根据模型的预测结果,判断是否存在皮肤癌的风险,并给出相应的建议和指导。这种个性化的健康管理方案可以帮助用户及时了解自己的健康状况,并采取相应的措施,以预防和治疗皮肤癌等疾病。

除了皮肤癌分类,该工具还具有社交功能。用户可以与好友或家人一起使用该工具进行健康管理,分享健康数据和经验,相互监督和支持。这种社交化的健康管理方式可以增强用户的参与和动力,培养健康的生活方式,并促进整个社区的健康发展。

通过深度学习和卷积神经网络模型,我们可以对用户提供的皮肤病变图像进行准确分类和诊断,帮助他们及时了解自己的健康状况。该工具通过收集用户的健康数据,并结合人工智能技术进行数据分析和处理,为用户提供个性化的健康管理方案。

使用该工具,用户可以随时跟踪和监测自己的身体状况。他们可以拍摄或上传皮肤病变的图像,并通过工具进行分类和诊断。工具会分析图像中的特征和模式,然后使用训练好的模型进行预测。根据预测结果,用户可以了解是否存在皮肤癌的风险,并根据建议采取相应的措施。

除了皮肤癌分类,该工具还可以提供其他健康管理功能。它可以帮助用户记录和分析身体指标,如体重、血压、心率等。用户可以设置健康目标,并跟踪自己的进展。工具还可以根据用户的健康数据生成个性化的健康建议和指导,帮助用户改善生活习惯,达到更好的健康状况。

此外,该工具具有社交功能,用户可以与好友或家人一起使用。他们可以共享健康数据和经验,相互鼓励和支持。这种社交化的健康管理方式可以增强用户的动力和参与度,形成健康的生活方式,并促进整个社区的健康发展。

在实现上述功能时,我们使用了英特尔的 oneAPI AI 工具包。这个工具包提供了优化的 Python 和 Tensorflow,以加速机器学习和深度学习任务。通过利用英特尔的硬件和软件优化,我们可以提高模型的训练和推理性能,使用户能够快速获得准确的健康诊断和建议。

安装 Anaconda 和 Intel oneAPI AI 工具包

首先,我们需要安装 Anaconda,这是一个流行的Python数据科学平台,用于提供一个便捷的开发环境。此外,我们还需要安装英特尔 oneAPI AI 工具包,这个工具包提供了优化的Python和TensorFlow,以加速机器学习和深度学习任务。

以下是安装步骤:

  1. 下载并安装 Anaconda。

  2. 打开 Anaconda 中的命令提示符(CMD.exe)。

  3. 在命令提示符中运行以下命令,使用conda安装英特尔优化的Python:

    conda install -c intel intelpython3_full
    
  4. 使用英特尔优化的Python创建虚拟环境,运行以下命令:

    conda create -n <环境名称> intelpython3_full python=3.8
    
  5. 激活虚拟环境,运行以下命令:

    conda activate <环境名称>
    
  6. 添加英特尔频道,运行以下命令:

    conda config --add channels intel
    
  7. 安装英特尔优化的TensorFlow,运行以下命令之一:

    conda install intel-tensorflow
    

    或者

    pip install intel-tensorflow
    
  8. 如果遇到重复错误,请运行以下命令以避免错误:

    set KMP_DUPLICATE_LIB_OK=TRUE
    

安装 Python 依赖项以能够训练和测试分类模型

在训练和测试分类模型之前,我们需要安装一些Python依赖项,以确保项目的顺利运行。这些依赖项包括:matplotlib、keras_preprocessing、Pillow、opencv-python、numpy和scikit-image。

以下是安装步骤:

  • 运行以下命令以安装matplotlib:

    conda install matplotlib
    
  • 运行以下命令以安装keras_preprocessing:

    pip install keras_preprocessing
    
  • 运行以下命令以安装Pillow:

    pip install Pillow
    
  • 运行以下命令以安装opencv-python:

    pip install opencv-python
    
    • 运行以下命令以安装numpy:

      pip install numpy
      
    • 运行以下命令以安装scikit-image:

      pip install scikit-image
      

    用法

    在完成上述安装步骤后,我们可以开始使用基于英特尔 oneAPI AI 工具包进行皮肤癌分类的项目。

    1. 首先,进入保存数据集和代码的目录,运行以下命令:

      cd health-tool
      
    2. 运行Train.py文件以训练并保存模型:

      python Train.py
      

      这将开始训练过程,并将训练好的模型保存在指定的目录中。

    3. 运行Test.py文件以使用保存的模型测试图像:

      python Test.py
      

      这将加载之前训练好的模型,并使用测试图像进行分类和诊断。

    通过以上步骤,我们可以利用英特尔 oneAPI AI 工具包实现皮肤癌分类的功能。这个工具可以帮助用户及时了解自身的健康状况,并提供个性化的健康管理方案。它结合了深度学习和卷积神经网络模型,在图像中提取特征并进行准确的分类和诊断。同时,该工具还具备社交功能,让用户与他人分享健康数据和经验,共同促进健康生活方式的养成。

    注意: 在运行项目代码之前,请确保已安装所有必需的依赖项,并按照给定的文件结构和命令运行代码。

由于项目整体过大,这里只展示部分代码,如需要完整代码请私信。

Train.py

def Create_ResNet50V2_Model(num_classes, img_shape_x, img_shape_y):
    ResNet50V2 = tf.keras.applications.ResNet50V2(input_shape=(img_shape_x, img_shape_y, 3),
    include_top= False,
    weights='imagenet'
    )
    ResNet50V2.trainable = True

    for layer in ResNet50V2.layers[:-50]:
        layer.trainable = False


    model = Sequential([
                    ResNet50V2,
                    Dropout(.25),
                    BatchNormalization(),
                    Flatten(),
                    Dense(64, activation='relu'),
                    BatchNormalization(),
                    Dropout(.5),
                    Dense(num_classes,activation='softmax')
                    ])
    return model

def train_model():
    train_data_path = train_dir_var.get()
    val_data_path = val_dir_var.get()
    img_shape_x = img_shape_x_var.get()
    img_shape_y = img_shape_y_var.get()
    batch_size = batch_size_var.get()
    save_model_path = save_model_path_var.get()
    save_model_name = save_model_name_var.get()
    num_epoch = num_epoch_var.get()

    train_preprocessor = ImageDataGenerator(
        rescale = 1 / 255.,
        rotation_range=10,
        zoom_range=0.2,
        width_shift_range=0.1,
        height_shift_range=0.1,
        horizontal_flip=True,                                        
        fill_mode='nearest',
    )

    val_preprocessor = ImageDataGenerator(
        rescale = 1 / 255.,
    )

    train_data = train_preprocessor.flow_from_directory(
        train_data_path,
        class_mode="categorical",
        target_size=(img_shape_x,img_shape_y),
        color_mode='rgb', 
        shuffle=True,
        batch_size=batch_size,
        subset='training', 
    )

    val_data = val_preprocessor.flow_from_directory(
        val_data_path,
        class_mode="categorical",
        target_size=(img_shape_x,img_shape_y),
        color_mode="rgb",
        shuffle=False,
        batch_size=batch_size,
    )

    num_classes = train_data.num_classes

    ResNet50V2_Model = Create_ResNet50V2_Model(num_classes, img_shape_x, img_shape_y)
    ResNet50V2_Model.summary()

    ResNet50V2_Model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

    checkpoint_path = os.path.join(save_model_path, save_model_name)
    ModelCheckpoint(checkpoint_path, monitor="val_accuracy", save_best_only=True)

    Early_Stopping = EarlyStopping(monitor = 'val_accuracy', patience = 7, restore_best_weights = True, verbose=1)

    Reducing_LR = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss',
                                                factor=0.2,
                                                patience=2,
                                                verbose=1)

    callbacks = [Early_Stopping, Reducing_LR]

    steps_per_epoch = train_data.n // train_data.batch_size
    validation_steps = val_data.n // val_data.batch_size

    ResNet50V2_history = ResNet50V2_Model.fit(train_data ,validation_data = val_data , epochs=num_epoch, batch_size=batch_size,
                                        callbacks = callbacks, steps_per_epoch=steps_per_epoch, validation_steps=validation_steps)
    ResNet50V2_Model.save(os.path.join(save_model_path, save_model_name + '.h5'))
    def plot_curves(history):

        loss = history.history["loss"]
        val_loss = history.history["val_loss"]

        accuracy = history.history["accuracy"]
        val_accuracy = history.history["val_accuracy"]

        epochs = range(len(history.history["loss"]))

        plt.figure(figsize=(15,5))

        plt.subplot(1, 2, 1)
        plt.plot(epochs, loss, label = "training_loss")
        plt.plot(epochs, val_loss, label = "val_loss")
        plt.title("Loss")
        plt.xlabel("epochs")
        plt.legend()

        plt.subplot(1, 2, 2)
        plt.plot(epochs, accuracy, label = "training_accuracy")
        plt.plot(epochs, val_accuracy, label = "val_accuracy")
        plt.title("Accuracy")
        plt.xlabel("epochs")
        plt.legend()

        plt.show()
        
    plot_curves(ResNet50V2_history)
    messagebox.showinfo(title="训练已完成", message="模型已成功训练!")

train_button = tk.Button(root, text="Train", command=train_model)
train_button.grid(row=8, column=1, padx=5, pady=5)

Text.py

def load_and_prep_image(filename, img_shape_x=200, img_shape_y=200):
    img = cv2.imread(filename)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = cv2.resize(img, (img_shape_x, img_shape_y))
    img = preprocess_input(img)
    return img


def pred_and_plot(filename, model, class_names, img_shape_x=200, img_shape_y=200):
    img = load_and_prep_image(filename, img_shape_x, img_shape_y)
    image = io.imread(filename)
    gray_image = np.mean(image, axis=2)

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))

    ax1.imshow(gray_image, cmap='hot')
    ax1.set_title('Heat Map')
    ax1.set_axis_off()

    pred = model.predict(np.expand_dims(img, axis=0))
    pred_class = class_names[pred.argmax()]
    img = cv2.cvtColor(cv2.imread(filename), cv2.COLOR_BGR2RGB)
    ax2.imshow(img)
    ax2.set_title(f"Prediction: {
      
      pred_class}")
    ax2.set_axis_off()

    plt.show()



def select_image():
    global panel, image_path
    image_path = filedialog.askopenfilename()
    image = Image.open(image_path)
    image = image.resize((300, 300))
    image = ImageTk.PhotoImage(image)
    if panel is None:
        panel = tk.Label(image=image)
        panel.image = image
        panel.pack(padx=10, pady=10)
    else:
        panel.configure(image=image)
        panel.image = image


def select_class_dir():
    class_dir = filedialog.askdirectory()
    class_dir_entry.delete(0, tk.END)
    class_dir_entry.insert(0, class_dir)


def select_model_file():
    model_file = filedialog.askopenfilename()
    model_file_entry.delete(0, tk.END)
    model_file_entry.insert(0, model_file)


def predict():
    global image_path, model, classes, img_shape_x, img_shape_y
    if image_path is None:
        return
    class_dir = class_dir_entry.get()
    model_file = model_file_entry.get()
    img_shape_x = int(img_shape_x_entry.get())
    img_shape_y = int(img_shape_y_entry.get())
    classes = []
    for file in os.listdir(class_dir):
        d = os.path.join(class_dir, file)
        if os.path.isdir(d):
            classes.append(file)
    model = load_model(model_file)
    pred_and_plot(image_path, model, classes, img_shape_x, img_shape_y)

root = tk.Tk()
root.title("图像预测器")
root.resizable(False, False)

panel = None

image_path = None
model = None
classes = []
img_shape_x = 200
img_shape_y = 200

class_dir_label = tk.Label(root, text="Class Directory:")
class_dir_label.grid(row=0, column=0, padx=10, pady=10)
class_dir_entry = tk.Entry(root)
class_dir_entry.grid(row=0, column=1, padx=10, pady=10)
class_dir_button = tk.Button(root, text="Browse", command=select_class_dir)
class_dir_button.grid(row=0, column=2, padx=10, pady=10)

model_file_label = tk.Label(root, text="Model File Path:")
model_file_label.grid(row=1, column=0, padx=10, pady=10)
model_file_entry = tk.Entry(root)
model_file_entry.grid(row=1, column=1, padx=10, pady=10)
model_file_button = tk.Button(root, text="Browse", command=select_model_file)
model_file_button.grid(row=1, column=2, padx=10, pady=10)

img_shape_x_label = tk.Label(root, text="Image Shape X:")
img_shape_x_label.grid(row=2, column=0, padx=10, pady=10)
img_shape_x_entry = tk.Entry(root)
img_shape_x_entry.grid(row=2, column=1, padx=10, pady=10)

img_shape_y_label = tk.Label(root, text="Image Shape Y:")
img_shape_y_label.grid(row=3, column=0, padx=10, pady=10)
img_shape_y_entry = tk.Entry(root)
img_shape_y_entry.grid(row=3, column=1, padx=10, pady=10)

select_button = tk.Button(root, text="Select Image", command=select_image)
select_button.grid(row=4, column=0, padx=10, pady=10)

predict_button = tk.Button(root, text="Predict", command=predict)
predict_button.grid(row=4, column=1, padx=10, pady=10)

猜你喜欢

转载自blog.csdn.net/weixin_42469135/article/details/131318926
今日推荐