Dogs vs. Cats

2024-05-24 22:48
文章标签 vs dogs cats

本文主要是介绍Dogs vs. Cats,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

二分类问题
我的方案:

import os
import sys
import cv2
import random
import pandas as pdimport matplotlib.pyplot as plt
import matplotlib.image as mpimg
import seaborn as sns
import itertools
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrixfrom keras.utils.np_utils import to_categorical # convert to one-hot-encoding
from keras.models import Sequential
from keras.models import load_model
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D
from keras.optimizers import RMSprop
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ReduceLROnPlateau
from keras.callbacks import EarlyStopping
from keras.preprocessing.image import load_img,img_to_arrayimport numpy as np
root_path=sys.path[0]
train_path=r'./input/train/'
test_path=r'./input/test/'
train_list=next(os.walk(root_path+r'\input\train'))[2]
test_list=next(os.walk(root_path+r'\input\test'))[2]IMAGE_WIDTH=224
IMAGE_HEIGHT=224# train_path="../input/train/"
# test_path="../input/test/"
# train_list=next(os.walk(train_path))[2]
# test_list=next(os.walk(test_path))[2]# 根据图片路径获取图片标签
def get_img_label(img_paths):img_labels = []for img_path in img_paths:animal = img_path.split("/")[-1].split('.')[0]if animal == 'cat':img_labels.append(0)else:img_labels.append(1)img_labels=to_categorical(img_labels,2)return img_labels#读取图片
def load_batch_image(img_path,train_set=True,target_size=(IMAGE_WIDTH,IMAGE_HEIGHT)):im=load_img(img_path,target_size=target_size)if train_set:return img_to_array(im)else:return img_to_array(im)/255.0#建立一个数据迭代器
def get_dataset_shuffle(X_sample,batch_size,train_set=True):random.shuffle(X_sample)batch_num=int(len(X_sample)/batch_size)max_len=batch_num*batch_sizeX_sample=np.array(X_sample[:max_len])y_samples=get_img_label(X_sample)X_batches=np.split(X_sample,batch_num)y_batches=np.split(y_samples,batch_num)for i in range(len(X_batches)):if train_set:x=np.array(list(map(load_batch_image,X_batches[i],[True for _ in range(batch_size)])))else:x=np.array(list(map(load_batch_image,X_batches[i],[False for _ in range(batch_size)])))y=np.array(y_batches[i])yield x,y#数据增强处理train_datagen = ImageDataGenerator(rescale=1. / 255,rotation_range=10,width_shift_range=0.2,height_shift_range=0.2,shear_range=0.2,zoom_range=0.2,horizontal_flip=True)def build_model():# Define the modelmodel = Sequential()model.add(Conv2D(filters=32, kernel_size=(5, 5), padding='Same',activation='relu', input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, 3)))model.add(Conv2D(filters=32, kernel_size=(5, 5), padding='Same',activation='relu'))model.add(MaxPool2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Conv2D(filters=64, kernel_size=(3, 3), padding='Same',activation='relu'))model.add(Conv2D(filters=64, kernel_size=(3, 3), padding='Same',activation='relu'))model.add(MaxPool2D(pool_size=(2, 2), strides=(2, 2)))model.add(Dropout(0.25))model.add(Flatten())model.add(Dense(256, activation="relu"))model.add(Dropout(0.5))model.add(Dense(2, activation="sigmoid"))# Define the optimizeroptimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)# Compile the modelmodel.compile(optimizer=optimizer, loss="categorical_crossentropy", metrics=["accuracy"])return modeldef train():model=build_model()train_X=[train_path+item for item in train_list]# Set the random seedrandom_seed = 2# Split the train and the validation set for the fittingtrain_X, val_X = train_test_split(train_X, test_size = 0.1, random_state=random_seed)n_epoch=20batch_size=16for e in range(n_epoch):print('epoch',e)batch_num=0loss_sum=np.array([0.0,0.0])for X_train,y_train in get_dataset_shuffle(train_X,batch_size,True):for X_batch,y_batch in train_datagen.flow(X_train,y_train,batch_size=batch_size):loss=model.train_on_batch(X_batch,y_batch)loss_sum+=lossbatch_num+=1break#手动breakif batch_num%200==0:print("epoch %s, batch %s: train_loss = %.4f, train_acc = %.4f" % (e, batch_num, loss_sum[0] / 200, loss_sum[1] / 200))loss_sum = np.array([0.0, 0.0])res=model.evaluate_generator(get_dataset_shuffle(val_X,batch_size,False),int(len(val_X)/batch_size))print("val_loss = %.4f, val_acc = %.4f: " % (res[0], res[1]))model.save('weight.h5')def test():model=load_model('weight.h5')X_test_path=[test_path+item for item in test_list]results=[]for path in X_test_path:X_test=np.array(load_batch_image(path,False))X_test=np.expand_dims(X_test,axis=0)results.append(model.predict(X_test))results=np.array(results)results=np.argmax(results,axis=2)test_df=pd.read_csv('./input/sample_submission.csv')test_df['label']=resultstest_df.to_csv('result1.csv', index=False)if __name__=='__main__':train()test()

这篇关于Dogs vs. Cats的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/999754

相关文章

Android平台播放RTSP流的几种方案探究(VLC VS ExoPlayer VS SmartPlayer)

技术背景 好多开发者需要遴选Android平台RTSP直播播放器的时候,不知道如何选的好,本文针对常用的方案,做个大概的说明: 1. 使用VLC for Android VLC Media Player(VLC多媒体播放器),最初命名为VideoLAN客户端,是VideoLAN品牌产品,是VideoLAN计划的多媒体播放器。它支持众多音频与视频解码器及文件格式,并支持DVD影音光盘,VCD影

VS Code 调试go程序的相关配置说明

用 VS code 调试Go程序需要在.vscode/launch.json文件中增加如下配置:  // launch.json{// Use IntelliSense to learn about possible attributes.// Hover to view descriptions of existing attributes.// For more information,

解决服务器VS Code中Jupyter突然崩溃的问题

问题 本来在服务器Anaconda的Python环境里装其他的包,装完了想在Jupyter里写代码验证一下有没有装好,一运行发现Jupyter崩溃了!?报错如下所示 Failed to start the Kernel. ImportError: /home/hujh/anaconda3/envs/mia/lib/python3.12/lib-dynload/_sqlite3.cpython-

VSC++: 括号对称比较

括号的使用规则:大括号,中括号,小括号{[()]};中括号,小括号[()];小括号();大括号、中括号、小括号、中括号、小括号、大括号{[()][()]};大括号,中括号,小括号,小括号{[(())]};大括号,中括号,小括号,小括号{[()()]};小括号不能嵌套,小括号可连续使用。 {[]}、{()}、([])、({})、[{}]、{}、[]、{[}]、[(])都属非法。 char aa[

Apache Kylin VS Apache Doris全方位对比

1 系统架构 1.1 What is Kylin1.2 What is Doris2 数据模型 2.1 Kylin的聚合模型2.2 Doris的聚合模型2.3 Kylin Cuboid VS Doris RollUp2.4 Doris的明细模型3 存储引擎4 数据导入5 查询6 精确去重7 元数据8 高性能9 高可用10 可维护性 10.1 部署10.2 运维10.3 客服11 易用性 11.1

vs环境下C++dll生成和使用

动态库和静态库: 动态库:全名动态链接库,用于将你的函数封装,让别人只能调用,不能看你的实现代码。由引入库和dll组成:引入库包含导出的函数和变量名,dll包含实际的函数和数据,运行时加载访问dll文件。  Windows API中的所有函数都封装在dll里面,最重要的三个: Kernel32.dll:包含管理内存、进程和线程的各个函数。User32.dll:包含用于执行用户界面任务,如窗口和

VS Code与SVN关联

VS Code是一款轻量级的集成开发环境,可通过安装插件与SVN进行关联。以下是将VS Code与SVN关联的步骤: 安装SVN插件:在VS Code中打开Extensions(快捷键:Ctrl+Shift+X),搜索并安装"svn"插件。 安装SVN命令行工具:在计算机上安装SVN命令行工具,确保在命令行中可以运行svn命令。 配置SVN路径:在VS Code中打开用户设置(快捷键:Ct

学习记录-VS踩坑记录

一、安装VS2015后,CMAKE执行错误: CMAKE_C_COMPILER-NOTFOUND" was not found.   CMAKE_CXX_COMPILER-NOTFOUND" was not found.  环境: 1.公司内网,无法上外网; 2.文件加密系统; 3.数字公司杀毒软件; 解决方法: 清理环境,添加USBwifi,安全模式卸载数字软件; 1.设置环

面试题41:和为s的两个数VS和为s的连续正数数列

问题说明: 1.和为s的两个数问题是从一个排序的数组中找出和为s的两个数; 2.原题是找出一个即可,现在全部找出; 3.和为s的连续正数数列是给定一个数找出所有连续正数数列的和为s,例如s为9,(2,3,4)就是其中一组。 (一)和为s的两个数问题 public static int findNumbersWithSum(int[] sorted, int fromIndex, in

vs中使用c#\sqlite数据库开发(1)

开发前: 之前在java开发中使用过sqlite,对它有些印象。在用winform或wpf开发小应用程序时,发现用sqlite数据库也是不错的。就像一个会员管理软件,开发完毕后,可以省去想sqlserver那些复杂的操作。软件安装时,不需要额外的数据库环境。简单、便捷。但对于大并发量、大数据量的开发就不要使用sqlite了。如果你用过h2数据库,可以对比一下两者的优劣。 开发前准备: 1.下