教你使用TensorFlow2判断细胞图像是否感染
在本教程中,我们将使用 TensorFlow (Keras API) 实现一个用于二进制分类任务的深度学习模型,该任务包括将细胞的图像标记为感染或未感染疟疾。
数据集来源:https://www.kaggle.com/iarunava/cell-images-for-detecting-malaria
数据集包含2个文件夹
感染::13780张图片 未感染:13780张图片
总共27558张图片。
此数据集取自NIH官方网站:https://ceb.nlm.nih.gov/repositories/malaria-datasets/
环境:kaggle,天池实验室或者gogole colab都可以。
导入相关模块
import cv2 import tensorflow教你 as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten, Activation from sklearn.model_selection import train_test_split import numpy as np import 使用;matplotlib.pyplot as plt import glob import os
对于图片数据存在形状不一样的情况,因此需要使用 OpenCV 进行图像预处理。
将图片变成 numpy 数组(数字格式)的形式转换为灰度,并将其调整为一个(70x70)形状。
img_dir="../input/cell-images-for-detecting-malaria/cell_images" img_size=70 def load_img_data(path): # 打乱数据 Te image_files = glob.glob(os.path.join(path, "Parasitized/*.png")) + glob.glob(os.path.join(path, "Uninfected/*.png")) X, y = [], ns;[] for image_file in image_files: # 命名标签 0 for uninfected and 1 for infected label = 0 if "Uninfected" in image_filore else 1 # load the image in gray scale 变成灰度图片 img_arr = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE) # resize theFl image to (70x70) 调整图片大小 img_resized = cv2.resize(img_arr, (img_size, img_size)) X.append(img_resized) y.append(label) &nowbsp; return X, y X, y = load_img_data(img_dir)
查看X的shape。
print(X.shape)
X的shape为(27558, 70, 70, 1),27558表示图片的数据,70*70表示图片的长和宽像素。
另外,为了帮助网络更快收敛,我们应该进行数据归一化。在sklearn 中有一些缩放方法,例如:
在这里我们将除以255,因为像素可以达到的最大值是255,这将导致应用缩放后像素范围在 0 和 1 之间。
X, y = load_img_data(img_dir) # reshape to 2判;(n_samples, 70, 70, 1) (to fit the NN) X = np.array(X).reshape(-1, img_size, img_size, 1) #从[0,255]到[0,1]缩放像素 帮助神经网络更快地训练 X = X / 255 # shuffle & split the dataset X_train, X_test, y_tra断细in, y_test = train_test_split(X, y, test_size=0.1, stratify=y) print("Total training samples:", X_train.shape) print("Total validation samples:", X_test.shape[0])
使用sklearn的train_test_split()方法将数据集划分为训练集和测试集,我们使用总数据的 10% 稍后对其进行验证。
在建立的模型中,我们将添加 3 个卷积层,然后Flatten是由层组成的全连接Dense胞图层。
model = Sequential() model.add(Conv2D(64, (3, 3), input_shape=X_train.shape[1:])) model.add(Activation("relu")) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation("relu")) model.add(MaxPool2D(pool_size=(2, 2))) 像是model.add(Conv2D(64, (3, 3))) model.add(Activation("relu")) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(64)) model.add(Activation("relu")) model.add(Dense(64)) model.add(Activation("relu")) model.add(Dense(1)) model.add(Activatio否感n("sigmoid")) model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]) print(model.summary())
由于输出是二进制的(感染或未感染),我们使用Sigmoid 函数作为输出层的激活函数。
# train the model with 10 epochs, 64 batch size model.fit(X_train, np.array(y_train),&nbs教你p;batch_size=64, epochs=10, validation_split=0.2)
在训练数据集及其验证拆分上实现了94%的准确率。
现在使用evaluate() 来评估测试数据集上的模型
loss, accuracy = model.evaluate(X_test, np.array(y_test), verbose=0) print(f"Testing on {len(X_test)} images, the results are Accuracy: {accuracy}&nb使用sp;| Loss: {loss}")
输出如下
Testing on 2756 images, the results are Accuracy: 0.9404934644699097 | Loss: 0.1666732281446457
该模型在测试数据中也表现OK,准确率达到94%
最后,我们将通过保存我们的模型来结束所有这个过程。
model.save("model.h5")
(责任编辑:科技前沿)
- 2025云栖大会剧透来了!今年有这些AI新看点
- 13年Gartner魔力象限看云计算风云 亚马逊云科技霸榜11年
- Firefox全球上线AI搜索引擎Perplexity:用户可自主选择是否启用AI搜索
- 斥资100亿美元,亚马逊宣布在美国密苏里州建设数据中心园区
- 谷歌宣布Google Lens新增拍照购物功能
- 微软批评索尼:老游戏几年之后登陆PC 再收割一波
- IDC报告:2026年二季度中国智能手机市场连跌五季,华为苹果逆势大涨
- 亚马逊正在进一步蚕食传统媒体的市场份额
- 标签: 齐俊元 豆包 阶跃星辰 Teambition
- 标签: Suno AI音乐 Menlo Ventures NVentures
- 开源!腾讯混元图像3.0正式上线,支持中英文精准渲染、长文本生成
- 标签: OpenAI GPT-5.2 Sam Altman 壁街见闻
- Canva免费放出Affinity专业设计套件,Adobe订阅制遭遇最强挑战
- YouTube 推出 AI “肖像识别” 工具,打击虚假内容
- 媒体再次获得胜利:Facebook和默多克新闻集团达成澳洲业务合作
- 彭斯克集团起诉 Google,指控 AI 摘要侵权并威胁数字媒体未来
- 火山引擎发布豆包大模型1.6升级版,日均 Tokens 调用量突破30万亿!
- 标签: 东鹏饮料 东鹏特饮 功能饮料 港交所上市
- 标签: 完美世界 异环 诛仙世界 女神异闻录:夜幕魅影
- 泰森中国宣布与阿里云达成战略合作 将在智慧供应链等方向展开合作
- https://www.world-architects.com/en/search?term=谷歌maps群发程序|软件【tg:seogoogle987】,swC views+
- https://www.usslexington.com/?action=QUERY&s=谷歌maps群发程序|软件【tg:seogoogle987】,poF views+
- https://www.pearlstonecenter.org/search/谷歌maps群发程序|软件【tg:seogoogle987】,0PK views+
- https://www.mdbg.net/chinese/dictionary?page=worddict&wdrst=0&wdqb=谷歌maps群发程序|软件【tg:seogoogle987】,Vfv views+
- https://www2.ual.es/ProyectoLates/?s=谷歌maps群发程序|软件【tg:seogoogle987】,rCM views+
- https://www.qylaws.com/search/谷歌maps群发程序|软件【tg:seogoogle987】,pwV views+
- https://www.laoairlines.com/?action=QUERY&s=谷歌maps群发程序|软件【tg:seogoogle987】,zhj views+
- https://www.kaskus.co.id/search?q=谷歌maps群发程序|软件【tg:seogoogle987】,1i5 views+
- https://www.remit.co.jp/pt/?action=CHECK&s=谷歌maps群发程序|软件【tg:seogoogle987】,HRB views+
- https://www.writingforward.com/?action=SEARCH&s=谷歌maps群发程序|软件【tg:seogoogle987】,Akc views+
