基于 CNN,搭建一个苹果分类器(二分类)python

时间: 2024-02-15 22:01:40 浏览: 26
好的,我可以为您提供一个基于CNN的苹果分类器的实现,以下是代码: 首先,我们需要导入必要的库: ```python import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import matplotlib.pyplot as plt ``` 接下来,我们需要准备数据集。我们可以从Kaggle上下载一个包含苹果和非苹果图片的数据集,然后将其分成训练集和测试集。我们需要将苹果标记为1,非苹果标记为0。 ```python train_dir = "path/to/training/folder" test_dir = "path/to/testing/folder" train_apple_dir = os.path.join(train_dir, 'apple') train_not_apple_dir = os.path.join(train_dir, 'not_apple') test_apple_dir = os.path.join(test_dir, 'apple') test_not_apple_dir = os.path.join(test_dir, 'not_apple') train_apple_files = os.listdir(train_apple_dir) train_not_apple_files = os.listdir(train_not_apple_dir) test_apple_files = os.listdir(test_apple_dir) test_not_apple_files = os.listdir(test_not_apple_dir) train_images = [] train_labels = [] for file in train_apple_files: image_path = os.path.join(train_apple_dir, file) image = keras.preprocessing.image.load_img(image_path, target_size=(150, 150)) image_array = keras.preprocessing.image.img_to_array(image) train_images.append(image_array) train_labels.append(1) for file in train_not_apple_files: image_path = os.path.join(train_not_apple_dir, file) image = keras.preprocessing.image.load_img(image_path, target_size=(150, 150)) image_array = keras.preprocessing.image.img_to_array(image) train_images.append(image_array) train_labels.append(0) test_images = [] test_labels = [] for file in test_apple_files: image_path = os.path.join(test_apple_dir, file) image = keras.preprocessing.image.load_img(image_path, target_size=(150, 150)) image_array = keras.preprocessing.image.img_to_array(image) test_images.append(image_array) test_labels.append(1) for file in test_not_apple_files: image_path = os.path.join(test_not_apple_dir, file) image = keras.preprocessing.image.load_img(image_path, target_size=(150, 150)) image_array = keras.preprocessing.image.img_to_array(image) test_images.append(image_array) test_labels.append(0) train_images = np.array(train_images) train_labels = np.array(train_labels) test_images = np.array(test_images) test_labels = np.array(test_labels) ``` 接下来,我们可以定义模型。我们可以使用卷积层和池化层构建模型。在最后添加一个全连接层和输出层。我们使用ReLU激活函数和Sigmoid激活函数。 ```python model = keras.Sequential([ layers.Conv2D(16, 3, padding='same', activation='relu', input_shape=(150, 150 ,3)), layers.MaxPooling2D(), layers.Conv2D(32, 3, padding='same', activation='relu'), layers.MaxPooling2D(), layers.Conv2D(64, 3, padding='same', activation='relu'), layers.MaxPooling2D(), layers.Flatten(), layers.Dense(128, activation='relu'), layers.Dense(1, activation='sigmoid') ]) ``` 接下来,我们可以编译模型,设置损失函数和优化器。 ```python model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) ``` 训练模型并输出结果。 ```python history = model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels)) test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print('\nTest accuracy:', test_acc) ``` 最后,我们可以绘制训练和验证准确性的图表。 ```python acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs_range = range(10) plt.figure(figsize=(8, 8)) plt.subplot(2, 1, 1) plt.plot(epochs_range, acc, label='Training Accuracy') plt.plot(epochs_range, val_acc, label='Validation Accuracy') plt.legend(loc='lower right') plt.title('Training and Validation Accuracy') plt.subplot(2, 1, 2) plt.plot(epochs_range, loss, label='Training Loss') plt.plot(epochs_range, val_loss, label='Validation Loss') plt.legend(loc='upper right') plt.title('Training and Validation Loss') plt.xlabel('epoch') plt.show() ``` 以上就是基于CNN搭建苹果分类器的代码,希望能对您有所帮助。

相关推荐

最新推荐

recommend-type

详解tensorflow训练自己的数据集实现CNN图像分类

本篇文章了tensorflow训练自己的数据集实现CNN图像分类,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
recommend-type

在Keras中CNN联合LSTM进行分类实例

我就废话不多说,大家还是直接看代码吧~ def get_model(): n_classes = 6 inp=Input(shape=(40, 80)) reshape=Reshape((1,40,80))(inp) # pre=ZeroPadding2D(padding=(1, 1))(reshape) # 1 ...
recommend-type

Pytorch 使用CNN图像分类的实现

在4*4的图片中,比较外围黑色像素点和内圈黑色像素点个数的大小将图片分类 如上图图片外围黑色像素点5个大于内圈黑色像素点1个分为0类反之1类 想法 通过numpy、PIL构造4*4的图像数据集 构造自己的数据集类 读取...
recommend-type

钢桁架结构振动特性渐变分析工具

钢桁架结构振动特性渐变分析工具
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

可见光定位LED及其供电硬件具体型号,广角镜头和探测器,实验设计具体流程步骤,

1. 可见光定位LED型号:一般可使用5mm或3mm的普通白色LED,也可以选择专门用于定位的LED,例如OSRAM公司的SFH 4715AS或Vishay公司的VLMU3500-385-120。 2. 供电硬件型号:可以使用常见的直流电源供电,也可以选择专门的LED驱动器,例如Meanwell公司的ELG-75-C或ELG-150-C系列。 3. 广角镜头和探测器型号:一般可采用广角透镜和CMOS摄像头或光电二极管探测器,例如Omron公司的B5W-LA或Murata公司的IRS-B210ST01。 4. 实验设计流程步骤: 1)确定实验目的和研究对象,例如车辆或机器人的定位和导航。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依