首页 > 其他分享 >TensorFlow手写AlexNet识别10-monkey-species

TensorFlow手写AlexNet识别10-monkey-species

时间:2025-01-21 15:22:08浏览次数:1  
标签:acc 10 monkey val loss keras layers 34 TensorFlow

  In [1]:

from tensorflow import keras
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
  In [9]:
def AlexNet(height=224, width=224, classes=10):
    input_image = keras.layers.Input(shape=(height, width, 3), dtype=tf.float32)
    x = keras.layers.ZeroPadding2D(((1,2), (1,2)))(input_image)
    x = keras.layers.Conv2D(48, kernel_size=11, strides=4, activation='selu')(x)
    x = keras.layers.MaxPool2D(pool_size=3, strides=2)(x)
    x = keras.layers.Conv2D(128, kernel_size=5, padding='same', activation='selu')(x)
    x = keras.layers.MaxPool2D(pool_size=3, strides=2)(x)
    x = keras.layers.Conv2D(192, kernel_size=3, padding='same', activation='selu')(x)
    x = keras.layers.MaxPool2D(pool_size=3, strides=2)(x)
    x = keras.layers.Conv2D(192, kernel_size=3, padding='same', activation='selu')(x)
    x = keras.layers.Conv2D(192, kernel_size=3, padding='same', activation='selu')(x)
    x = keras.layers.Conv2D(128, kernel_size=3, padding='same', activation='selu')(x)
    x = keras.layers.MaxPool2D(pool_size=3, strides=2)(x)
    # 全连接
    x = keras.layers.Flatten()(x)
    x = keras.layers.AlphaDropout(0.2)(x)
    x = keras.layers.Dense(2048, activation='selu')(x)
    x = keras.layers.AlphaDropout(0.2)(x)
    x = keras.layers.Dense(2048, activation='selu')(x)
    x = keras.layers.Dense(classes)(x)
    predict = keras.layers.Softmax()(x)

    return keras.models.Model(inputs=input_image, outputs=predict)
  In [3]:
# 文件下载地址  https://www.kaggle.com/datasets/slothkong/10-monkey-species
train_dir = './10-monkey-species/training/training'
valid_dir = './10-monkey-species/validation/validation'
label_file = './10-monkey-species/monkey_labels.txt'
df = pd.read_csv(label_file, header=0)
df
  Out[3]:  
 LabelLatin NameCommon NameTrain ImagesValidation Images
0 n0 alouatta_palliata\t mantled_howler 131 26
1 n1 erythrocebus_patas\t patas_monkey 139 28
2 n2 cacajao_calvus\t bald_uakari 137 27
3 n3 macaca_fuscata\t japanese_macaque 152 30
4 n4 cebuella_pygmea\t pygmy_marmoset 131 26
5 n5 cebus_capucinus\t white_headed_capuchin 141 28
6 n6 mico_argentatus\t silvery_marmoset 132 26
7 n7 saimiri_sciureus\t common_squirrel_monkey 142 28
8 n8 aotus_nigriceps\t black_headed_night_monkey 133 27
9 n9 trachypithecus_johnii nilgiri_langur 132 26
  In [4]:
# 图片数据生成器
height = 224
width = 224
channels = 3
batch_size = 32
classes = 10
train_datagen = keras.preprocessing.image.ImageDataGenerator(
    rescale = 1. / 255,    # 归一化&浮点数
    rotation_range = 40,   # 随机旋转 0~40°之间
    width_shift_range = 0.2, # 随机水平移动
    height_shift_range = 0.2, # 随机垂直移动
    shear_range = 0.2, # 随机裁剪比例
    zoom_range = 0.2, # 随机缩放比例
    horizontal_flip = True,  # 随机水平翻转
    vertical_flip = True, # 随机垂直翻转
    fill_mode = 'nearest', # 填充模式
)
train_generator = train_datagen.flow_from_directory(train_dir, target_size=(height, width),
                                                    batch_size=batch_size, shuffle=True, class_mode='categorical')

valid_datagen = keras.preprocessing.image.ImageDataGenerator(
    rescale = 1. / 255,    # 归一化&浮点数
)
valid_generator = valid_datagen.flow_from_directory(valid_dir, target_size=(height, width),
                                                    batch_size=batch_size, shuffle=False, class_mode='categorical')
   
Found 1098 images belonging to 10 classes.
Found 272 images belonging to 10 classes.
  In [5]:
# 配置网络
model = AlexNet(height=height, width=width, classes=classes)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc'])
model.summary()
   
Model: "model"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 input_1 (InputLayer)             [(None, 224, 224, 3)]     0                                                   
 zero_padding2d (ZeroPadding2D)   (None, 227, 227, 3)       0                                                                                                 
 conv2d (Conv2D)                  (None, 55, 55, 48)        17472                                             
 max_pooling2d (MaxPooling2D)     (None, 27, 27, 48)        0                                                                                         
 conv2d_1 (Conv2D)                (None, 27, 27, 128)       153728                                            
 max_pooling2d_1 (MaxPooling2D)   (None, 13, 13, 128)       0                                                                                           
 conv2d_2 (Conv2D)                (None, 13, 13, 192)       221376                                               
 max_pooling2d_2 (MaxPooling2D)   (None, 6, 6, 192)         0                                                                                          
 conv2d_3 (Conv2D)                (None, 6, 6, 192)         331968                                                 
 conv2d_4 (Conv2D)                (None, 6, 6, 192)         331968                                                  
 conv2d_5 (Conv2D)                (None, 6, 6, 128)         221312                                                  
 max_pooling2d_3 (MaxPooling2D)   (None, 2, 2, 128)         0                                                                                             
 flatten (Flatten)                (None, 512)               0                                                                
 alpha_dropout (AlphaDropout)     (None, 512)               0                                                                                              
 dense (Dense)                    (None, 2048)              1050624                                            
 alpha_dropout_1 (AlphaDropout)   (None, 2048)              0                                                                                           
 dense_1 (Dense)                  (None, 2048)              4196352                                                  
 dense_2 (Dense)                  (None, 10)                20490                                                        
 softmax (Softmax)                (None, 10)                0                                                            
=================================================================
Total params: 6545290 (24.97 MB)
Trainable params: 6545290 (24.97 MB)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________
  In [6]:
# 训练
history = model.fit(train_generator, steps_per_epoch=train_generator.samples//batch_size, epochs=150,
                    validation_data=valid_generator, validation_steps=valid_generator.samples//batch_size)
   
Epoch 1/150
34/34 [==============================] - 20s 561ms/step - loss: 23.3229 - acc: 0.0901 - val_loss: 5.9779 - val_acc: 0.1016
Epoch 2/150
34/34 [==============================] - 19s 559ms/step - loss: 4.7627 - acc: 0.0769 - val_loss: 2.6323 - val_acc: 0.1016
Epoch 3/150
34/34 [==============================] - 19s 570ms/step - loss: 2.6522 - acc: 0.0910 - val_loss: 2.6220 - val_acc: 0.1094
Epoch 4/150
34/34 [==============================] - 19s 539ms/step - loss: 2.4508 - acc: 0.0919 - val_loss: 2.3987 - val_acc: 0.1016
Epoch 5/150
34/34 [==============================] - 18s 539ms/step - loss: 2.5152 - acc: 0.0985 - val_loss: 2.5122 - val_acc: 0.1094
......
Epoch 65/150
34/34 [==============================] - 18s 536ms/step - loss: 2.0745 - acc: 0.2693 - val_loss: 2.2072 - val_acc: 0.3086
Epoch 66/150
34/34 [==============================] - 18s 526ms/step - loss: 1.9485 - acc: 0.2983 - val_loss: 1.9713 - val_acc: 0.3867
Epoch 67/150
34/34 [==============================] - 18s 541ms/step - loss: 2.0011 - acc: 0.2777 - val_loss: 2.0079 - val_acc: 0.3672
Epoch 68/150
34/34 [==============================] - 18s 533ms/step - loss: 1.9882 - acc: 0.2936 - val_loss: 2.3509 - val_acc: 0.3320
Epoch 69/150
34/34 [==============================] - 18s 539ms/step - loss: 2.0199 - acc: 0.2871 - val_loss: 2.0326 - val_acc: 0.3555
Epoch 70/150
.......
Epoch 146/150
34/34 [==============================] - 18s 533ms/step - loss: 1.3461 - acc: 0.5235 - val_loss: 1.6899 - val_acc: 0.5898
Epoch 147/150
34/34 [==============================] - 18s 543ms/step - loss: 1.4630 - acc: 0.5122 - val_loss: 1.6531 - val_acc: 0.6172
Epoch 148/150
34/34 [==============================] - 18s 530ms/step - loss: 1.4329 - acc: 0.5056 - val_loss: 1.6652 - val_acc: 0.5898
Epoch 149/150
34/34 [==============================] - 19s 545ms/step - loss: 1.3375 - acc: 0.5281 - val_loss: 1.8808 - val_acc: 0.5273
Epoch 150/150
34/34 [==============================] - 18s 539ms/step - loss: 1.4911 - acc: 0.5159 - val_loss: 1.4701 - val_acc: 0.5859
  In [7]:
pd.DataFrame(history.history).plot(figsize=(8, 5))
plt.grid()
plt.gca().set_ylim(0, 10)
plt.show()
    No description has been provided for this image   In [8]:
model.evaluate(valid_generator)
   
9/9 [==============================] - 2s 255ms/step - loss: 1.4895 - acc: 0.5699
Out[8]:
[1.4895002841949463, 0.5698529481887817]

标签:acc,10,monkey,val,loss,keras,layers,34,TensorFlow
From: https://www.cnblogs.com/funsion/p/18683629

相关文章

  • 【模拟电子技术】10-基本放大电路的构成
    【模拟电子技术】10-基本放大电路的构成交流骑在直流源上产生IB控制IC加上集电极反偏直流电压源后,满足工作在放大区的条件现在考虑如何输出我们用IB控制IC,得到的是电流,想得到电压信号,加电阻即可。但是如果直接在Uo两端接负载,那么输出的会有直流,体现不出交流,因此需要图中Rc......
  • 「CF1101F」Trucks and Cities
    题意描述有\(N\)座城市,第\(i\)座坐标为\(a_i\),有\(M\)辆卡车,第\(i\)辆卡车要从城市\(s_i\)前往城市\(e_i\),每单位长度耗油量为\(c_i\),可以在中途城市加满油\(r_i\)次,求让所有卡车都能到达目的地最小的油箱容积。传送门思考&做法step1先来思考暴力,二分答案......
  • Linux安装TensorFlow2.x
    首先注意:TensorFlow2.11开始就不支持Windows的GPU,若要在Windows下安装GPU版本的,只能安装2.10及以下的版本。下面是官网提示直接安装,直接安装的话是最新版本的:若要安装指定版本,使用命令:pipinstalltensorflow[and-cuda]==2.xx注意安装版本要和python版本以及cuDNN、CUDA版......
  • MIPI RAW10 RAW12 RAW14格式解析
    看了一些关于mipi格式的文章,不是图示错误,就是废话太多,不然就是代码辣眼睛。raw14用7*8个byte表示4*14格式的像素raw12用3*8个byte表示2*12格式的像素raw10用5*8个byte表示4*10格式的像素解析代码如下://raw14b1,b2,b3,b4,b5,b6,b7分别为连续读出的七个uint8类型的数据,p1,p......
  • 通过sqlserver添加修改系统管理员账号.120510
    一,思路:在其他服务器B,通过sa账号远程登录需增加/修改系统管理员账号的服务器A,用sqlserver的xp_cmdshell功能,模拟cmd通过netuser命令进行添加或者修改系统管理员账号。特别提示:此解决方案只适用于服务器没有加域且忘记管理员密码的用户使用,请不要作为非法用途!二,解决方法:0,在服务......
  • Xcopy屡试不爽.110411
    就一句:xcopy/s/c/d/k/yE:\IISLogE:\IISLog\Xinnet就可以将E:\IISLog的子目录和非空目录copy到E:\IISLog\Xinnnet中~详细解释:Xcopy复制文件和目录,包括子目录。语法xcopySource[Destination][/w][/p][/c][/v][/q][/f][/l][/g][/d[:mm-dd-yyyy]][/u][/i......
  • SQLServer2005恢复Master库.110509
    master库对于SQLServer来说,是很重要的系统数据库,保存着所有Sqlserver的用户信息、数据库信息等,当数据库崩溃时,master数据库的恢复成功与否起着重要的作用。这就跟Oracle的System表空间一样,非常的重要。备份数据前期准备:(1)在备用机准备好和生产机器一样的sql2005数据库环境(注意数......
  • win10 屏幕常量
    要在Windows10中设置屏幕常亮,你需要调整计算机的电源和睡眠设置。以下是详细步骤:打开“设置”应用:点击“开始”菜单,然后选择“设置”图标(齿轮形状)。进入“系统”设置:在“设置”窗口中,选择“系统”。调整“电源和睡眠”设置:在左侧菜单中,选择“电源和睡眠”。......
  • PAT甲级-1019 General Palindromic Number
    题目题目大意如果一个十进制数在其它进制下为回文数,则输出“Yes”,否则输出“No”。再输出该回文数。思路简单模拟,十进制转n进制,除留取余法。需要注意,如果用字符串存储,当余数>9时,用reverse会改变这个余数,测试点2和测试点4报错。因此用数组来存储。vector容器可以直接通过=......
  • Go语言如何实现限制用户 1 分钟内最多请求 1000 次?
    文章精选推荐1JetBrainsAiassistant编程工具让你的工作效率翻倍2ExtraIcons:JetBrainsIDE的图标增强神器3IDEA插件推荐-SequenceDiagram,自动生成时序图4BashSupportPro这个ides插件主要是用来干嘛的?5IDEA必装的插件:SpringBootHelper的使用与功能特点6A......