Dog Breed Identification

2024-05-24 22:48
文章标签 identification dog breed

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

多分类问题
我的方案:

import pandas as pd
import numpy as np
from sklearn.utils import shuffle
import cv2
from keras.preprocessing.image import load_img,img_to_array
from keras.models import Sequential
from keras.models import load_model
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from keras.applications import VGG19
from keras.callbacks import  EarlyStoppinglabels_df=pd.read_csv('./input/labels.csv')
#print(labels_df['breed'].value_counts())
#print(labels_df['breed'].describe())targets_series=pd.Series(labels_df['breed'])
one_hot=pd.get_dummies(targets_series,sparse=True)
one_hot_labels=np.asarray(one_hot)
num_classes=len(labels_df['breed'].unique())
IMAGE_SIZE=224train_img_path=['./input/train/{}.jpg'.format(item) for item in labels_df.id]#读取图片
def load_batch_image(img_path,train_set=True,target_size=(IMAGE_SIZE,IMAGE_SIZE)):im=cv2.imread(img_path)im=cv2.resize(im,target_size)if train_set:return img_to_array(im)else:return img_to_array(im)/255.0#建立一个数据迭代器
def get_dataset_shuffle(X_samples,labels,batch_size,train_set=True):X_samples,labels=shuffle(X_samples,labels)batch_num=int(len(X_samples)/batch_size)max_len=batch_num*batch_sizeX_samples=np.array(X_samples[:max_len])y_samples=labels[:max_len]X_batches=np.split(X_samples,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():vgg16_net=VGG19(weights='imagenet',include_top=False,input_shape=(IMAGE_SIZE,IMAGE_SIZE,3))vgg16_net.trainable=Falsemodel=Sequential()model.add(vgg16_net)model.add(Flatten())model.add(Dense(512,activation='relu'))model.add(Dropout(0.5))model.add(Dense(num_classes,activation='softmax'))# First: train only the top layers (which were randomly initialized)for layer in model.layers:layer.trainable = Falsemodel.compile(loss='binary_crossentropy',optimizer=Adam(lr=1e-5),metrics=['accuracy'])return modeldef train():model=build_model()random_seed=2# Split the train and the validation set for the fittingtrain_X, val_X,train_y,val_y = train_test_split(train_img_path,one_hot_labels, 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,train_y, 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+=1breakif 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, val_y,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')test_df=pd.read_csv('./input/sample_submission.csv')X_test_path=['./input/test/{}.jpg'.format(item) for item in test_df['id'] ]preds=[]for path in X_test_path:X_test=np.array(load_batch_image(path,False))X_test=np.expand_dims(X_test,axis=0)preds.append(model.predict(X_test))preds=np.squeeze(np.asarray(preds))sub = pd.DataFrame(preds)col_names = one_hot.columns.valuessub.columns = col_namessub.insert(0, 'id', test_df['id'])sub.head()

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



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

相关文章

Linux - SSH: WARNING REMOTE HOST IDENTIFICATION HAS CHANGED

一、问题     通过 SSH 登录节点时遇到的问题 二、方案     通过 vi ~/.ssh/known_hosts 删除对应节点 ip 的 rsa 信息即可

ssh_exchange_identification: read: Connection reset by peer

最近为了抢自如的房子在京东云服务器上面跑爬虫脚本,今天突然无法登陆了,ssh 连接报错ssh_exchange_identification: read: Connection reset by peer,经过检查,我的 ip 被 deny 了. 要解决此问题,请进行如下配置检查和修改: 通过 云服务器控制台的管理终端 进入系统。 通过 cat 等指令查看 /etc/hosts.deny中是

【git之窗】(十八)WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!

今天在拉取远程分支时,提示我这个: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

SSH 远程登录报错:kex_exchange_identification: Connection closed.....

一  问题起因         在公司,使用ssh登录远程服务器。有一天,mac终端提示:`kex_exchange_identification: Connection closed by remote host Connection closed by UNKNOWN port 65535`。 不知道为啥会出现这样的情形,最近这段时间登录都是正常的,不知道哪里抽风了,就提示这个。 二

Kaggle-Camera_Model_Identification 比赛记录总结[19/582(Top 4%)]

这篇博客记录自己在这次kaggle比赛中做的工作。成绩:19/582(Top 4%) Kaggle比赛地址 我的代码github地址 这次比赛是给出10个相机拍摄的照片,然后给出测试图片,区分是哪个相机拍摄的。训练集中每类照片数量相同,每类都是由同一个手机拍摄的照片。测试集中,每类的照片都是来自另外一个手机,一半的图片可能被用了八种可能的操作。 总结: 1. 更多的数据。

Causal Effect Identification in Uncertain Causal Networks

我们采用以下六个分类标准为: 数据模态: 观察数据: 这类数据是在没有研究人员任何干预的情况下收集的。它通常很容易获得,但由于潜在的混杂变量而带来挑战。例如,在流行病学中,由于实验的伦理限制,观察性研究很常见。参考文献[6]讨论了观察性研究中因果效应的识别和估计。实验数据: 这是因果推理的黄金标准,因为它涉及随机对照试验(RCT),研究人员在其中操纵治疗变量。RCT旨在最大限度地减少偏差,为因

hdu 5449 Robot Dog(期望+lca)

hdu 5449 Robot Dog(期望+lca) 题目链接:hdu 5449 Robot Dog 解题思路 n有50000,询问次数有100,每次询问的路径点数最多有100,对于不同询问去做动态规划,开一个 dp[u][i] dp[u][i]表示在第u个节点匹配了i个的期望,显然最坏情况下dp数组的每个状态都要遍历到,复杂度为 o(nqp) o(nqp),不能接受。 换个想法,如果我们

Keras深度学习框架实战(3):EfficientNet实现stanford dog分类

1、通过EfficientNet进行微调以实现图像分类概述 通过EfficientNet进行微调以实现图像分类,是一个使用EfficientNet作为预训练模型,并通过微调(fine-tuning)来适应特定图像分类任务的过程。一下是对相关重要术语的解释。 EfficientNet:这是一个高效的卷积神经网络(CNN)架构,旨在通过统一缩放网络深度、宽度和分辨率等维度来优化性能和效率。Effi

UVA 12168 - Cat vs. Dog(二分图匹配+最大独立集)

UVA 12168 - Cat vs. Dog 题目链接 题意:给定一些猫爱好者,和一些狗爱好者,每个人都有一个喜欢的猫(狗),和一个讨厌的狗(猫),要问现在给一种方案,使得尽量多的人被满足 思路:二分图匹配最大独立集,猫爱好者和狗爱好者矛盾的建边,做一次最大独立集即可 代码: #include <cstdio>#include <cstring>#include <

Aerial Cactus Identification(空中仙人掌鉴定)

Aerial Cactus Identification 空中仙人掌鉴定 二分类问题 方案一: import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)import os,cv2from IPython.display import Imagefrom keras.preprocessing impor