【Python机器学习】实验16 卷积、下采样、经典卷积网络

文章目录

  • 卷积、下采样、经典卷积网络
    • 1. 对图像进行卷积处理
    • 2. 池化
    • 3. VGGNET
    • 4. 采用预训练的Resnet实现猫狗识别
  • TensorFlow2.2基本应用
    • 5. 使用深度学习进行手写数字识别

卷积、下采样、经典卷积网络

1. 对图像进行卷积处理

import cv2
path = 'data\instance\p67.jpg' 
input_img = cv2.imread(path)
import cv2 
import numpy as np 
#分别将三个通道进行卷积,然后合并通道def conv(image, kernel): conv_b = convolve(image[:, :, 0], kernel) conv_g = convolve(image[:, :, 1], kernel) conv_r = convolve(image[:, :, 2], kernel) output = np.dstack([conv_b, conv_g, conv_r]) return output#卷积处理
def convolve(image, kernel): h_kernel, w_kernel = kernel.shape h_image, w_image = image.shapeh_output = h_image - h_kernel + 1 w_output = w_image - w_kernel + 1 output = np.zeros((h_output, w_output), np.uint8) for i in range(h_output): for j in range(w_output): output[i, j] = np.multiply(image[i:i + h_kernel, j:j + w_kernel], kernel).sum() return outputif __name__ == '__main__': path = 'data\instance\p67.jpg' input_img = cv2.imread(path) # 1.锐化卷积核 #kernel = np.array([[-1,-1,-1],[-1,9,-1],[-1,-1,-1]]) # 2.模糊卷积核kernel = np.array([[0.1,0.1,0.1],[0.1,0.2,0.1],[0.1,0.1,0.1]])     output_img = conv(input_img, kernel)cv2.imwrite(path.replace('.jpg', '-processed.jpg'), output_img) cv2.imshow('Output Image', output_img) cv2.waitKey(0)

2. 池化

img = cv2.imread('data\instance\dog.jpg')
img.shape
(4064, 3216, 3)
import numpy as np
from PIL import Image
import cv2
import matplotlib.pyplot as plt#均值池化
def AVGpooling(imgData, strdW, strdH):W,H = imgData.shapenewImg = []for i in range(0,W,strdW):line = []for j in range(0,H,strdH):x = imgData[i:i+strdW,j:j+strdH]     #获取当前待池化区域avgValue=np.sum(x)/(strdW*strdH)  #求该区域的均值line.append(avgValue)     newImg.append(line)return np.array(newImg)#最大池化
def MAXpooling(imgData, strdW, strdH):W,H = imgData.shapenewImg = []for i in range(0,W,strdW):line = []for j in range(0,H,strdH):x = imgData[i:i+strdW,j:j+strdH]    #获取当前待池化区域maxValue=np.max(x)            #求该区域的最大值line.append(maxValue)        newImg.append(line)return np.array(newImg)img = cv2.imread('data\instance\dog.jpg')
imgData= img[:,:,1]   #绿色通道#显示原图
plt.subplot(221)
plt.imshow(img)
plt.axis('off')#显示原始绿通道图
plt.subplot(222)
plt.imshow(imgData)
plt.axis('off')#显示平均池化结果图
AVGimg = AVGpooling(imgData, 2, 2)
plt.subplot(223)
plt.imshow(AVGimg)
plt.axis('off')#显示最大池化结果图
MAXimg = MAXpooling(imgData, 2, 2)
plt.subplot(224)
plt.imshow(MAXimg)
plt.axis('off')
plt.show()

1

3. VGGNET

import numpy as np 
from tensorflow.keras import backend as K 
import matplotlib.pyplot as plt 
from tensorflow.keras.applications import vgg16   # Keras内置 VGG-16模块,直接可调用。 
from tensorflow.keras.preprocessing import image 
from tensorflow.keras.applications.vgg16 import preprocess_input
import math
input_size = 224   # 网络输入图像的大小,长宽相等 
kernel_size = 64   # 可视化卷积核的大小,长宽相等 
layer_vis = True    # 特征图是否可视化
kernel_vis = True   # 卷积核是否可视化
each_layer = False  # 卷积核可视化是否每层都做
which_layer = 1    # 如果不是每层都做,那么第几个卷积层
path = 'data\instance\p67.jpg' img = image.load_img(path, target_size=(input_size, input_size)) 
img = image.img_to_array(img) 
img = np.expand_dims(img, axis=0) 
img = preprocess_input(img)  #标准化预处理
model = vgg16.VGG16(include_top=True, weights='imagenet')def network_configuration(): all_channels = [64, 64, 64, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512, 512, 512, 512, 512] down_sampling = [1, 1, 1 / 2, 1 / 2, 1 / 2, 1 / 4, 1 / 4, 1 / 4, 1 / 4, 1 / 8, 1 / 8, 1 / 8, 1 / 8, 1 / 16, 1 / 16, 1 / 16, 1 / 16, 1 / 32] conv_layers = [1, 2, 4, 5, 7, 8, 9, 11, 12, 13, 15, 16, 17] conv_channels = [64, 64, 128, 128, 256, 256, 256, 512, 512, 512, 512, 512, 512] return all_channels, down_sampling, conv_layers, conv_channelsdef layer_visualization(model, img, layer_num, channel, ds): # 设置可视化的层 layer = K.function([model.layers[0].input], [model.layers[layer_num].output]) f = layer([img])[0] feature_aspect = math.ceil(math.sqrt(channel)) single_size = int(input_size * ds)plt.figure(figsize=(8, 8.5)) plt.suptitle('Layer-' + str(layer_num), fontsize=22)plt.subplots_adjust(left=0.02, bottom=0.02, right=0.98, top=0.94, wspace=0.05, hspace=0.05) for i_channel in range(channel): print('Channel-{} in Layer-{} is running.'.format(i_channel + 1, layer_num)) show_img = f[:, :, :, i_channel] show_img = np.reshape(show_img, (single_size, single_size)) plt.subplot(feature_aspect, feature_aspect, i_channel + 1) plt.imshow(show_img)  plt.axis('off') fig = plt.gcf() fig.savefig('data/instance/feature_kernel_images/layer_' + str(layer_num).zfill(2) + '.png', format='png', dpi=300)plt.show()all_channels, down_sampling, conv_layers, conv_channels = network_configuration()
if layer_vis: for i in range(len(all_channels)): layer_visualization(model, img, i + 1, all_channels[i], down_sampling[i])

4. 采用预训练的Resnet实现猫狗识别

from tensorflow.keras.applications.resnet50 import ResNet50 
from tensorflow.keras.preprocessing import image 
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions 
import numpy as np 
from PIL import ImageFont, ImageDraw, Image 
import cv2
img_path = 'data\instance\dog.jpg'     #进行狗的判断
#img_path = 'cat.jpg'     #进行猫的判断
#img_path = 'deer.jpg'    #进行鹿的判断
weights_path = 'resnet50_weights.h5'
img = image.load_img(img_path, target_size=(224, 224)) 
x = image.img_to_array(img) 
x = np.expand_dims(x, axis=0) 
x = preprocess_input(x)
def get_model(): model = ResNet50(weights=weights_path) # 导入模型以及预训练权重print(model.summary()) # 打印模型概况 return model
model = get_model() 
Model: "resnet50"
__________________________________________________________________________________________________Layer (type)                   Output Shape         Param #     Connected to                     
==================================================================================================input_4 (InputLayer)           [(None, 224, 224, 3  0           []                               )]                                                                conv1_pad (ZeroPadding2D)      (None, 230, 230, 3)  0           ['input_4[0][0]']                conv1_conv (Conv2D)            (None, 112, 112, 64  9472        ['conv1_pad[0][0]']              )                                                                 conv1_bn (BatchNormalization)  (None, 112, 112, 64  256         ['conv1_conv[0][0]']             )                                                                 conv1_relu (Activation)        (None, 112, 112, 64  0           ['conv1_bn[0][0]']               )                                                                 pool1_pad (ZeroPadding2D)      (None, 114, 114, 64  0           ['conv1_relu[0][0]']             )                                                                 pool1_pool (MaxPooling2D)      (None, 56, 56, 64)   0           ['pool1_pad[0][0]']              conv2_block1_1_conv (Conv2D)   (None, 56, 56, 64)   4160        ['pool1_pool[0][0]']             conv2_block1_1_bn (BatchNormal  (None, 56, 56, 64)  256         ['conv2_block1_1_conv[0][0]']    ization)                                                                                         conv2_block1_1_relu (Activatio  (None, 56, 56, 64)  0           ['conv2_block1_1_bn[0][0]']      n)                                                                                               conv2_block1_2_conv (Conv2D)   (None, 56, 56, 64)   36928       ['conv2_block1_1_relu[0][0]']    conv2_block1_2_bn (BatchNormal  (None, 56, 56, 64)  256         ['conv2_block1_2_conv[0][0]']    ization)                                                                                         conv2_block1_2_relu (Activatio  (None, 56, 56, 64)  0           ['conv2_block1_2_bn[0][0]']      n)                                                                                               conv2_block1_0_conv (Conv2D)   (None, 56, 56, 256)  16640       ['pool1_pool[0][0]']             conv2_block1_3_conv (Conv2D)   (None, 56, 56, 256)  16640       ['conv2_block1_2_relu[0][0]']    conv2_block1_0_bn (BatchNormal  (None, 56, 56, 256)  1024       ['conv2_block1_0_conv[0][0]']    ization)                                                                                         conv2_block1_3_bn (BatchNormal  (None, 56, 56, 256)  1024       ['conv2_block1_3_conv[0][0]']    ization)                                                                                         conv2_block1_add (Add)         (None, 56, 56, 256)  0           ['conv2_block1_0_bn[0][0]',      'conv2_block1_3_bn[0][0]']      conv2_block1_out (Activation)  (None, 56, 56, 256)  0           ['conv2_block1_add[0][0]']       conv2_block2_1_conv (Conv2D)   (None, 56, 56, 64)   16448       ['conv2_block1_out[0][0]']       conv2_block2_1_bn (BatchNormal  (None, 56, 56, 64)  256         ['conv2_block2_1_conv[0][0]']    ization)                                                                                         conv2_block2_1_relu (Activatio  (None, 56, 56, 64)  0           ['conv2_block2_1_bn[0][0]']      n)                                                                                               conv2_block2_2_conv (Conv2D)   (None, 56, 56, 64)   36928       ['conv2_block2_1_relu[0][0]']    conv2_block2_2_bn (BatchNormal  (None, 56, 56, 64)  256         ['conv2_block2_2_conv[0][0]']    ization)                                                                                         conv2_block2_2_relu (Activatio  (None, 56, 56, 64)  0           ['conv2_block2_2_bn[0][0]']      n)                                                                                               conv2_block2_3_conv (Conv2D)   (None, 56, 56, 256)  16640       ['conv2_block2_2_relu[0][0]']    conv2_block2_3_bn (BatchNormal  (None, 56, 56, 256)  1024       ['conv2_block2_3_conv[0][0]']    ization)                                                                                         conv2_block2_add (Add)         (None, 56, 56, 256)  0           ['conv2_block1_out[0][0]',       'conv2_block2_3_bn[0][0]']      conv2_block2_out (Activation)  (None, 56, 56, 256)  0           ['conv2_block2_add[0][0]']       conv2_block3_1_conv (Conv2D)   (None, 56, 56, 64)   16448       ['conv2_block2_out[0][0]']       conv2_block3_1_bn (BatchNormal  (None, 56, 56, 64)  256         ['conv2_block3_1_conv[0][0]']    ization)                                                                                         conv2_block3_1_relu (Activatio  (None, 56, 56, 64)  0           ['conv2_block3_1_bn[0][0]']      n)                                                                                               conv2_block3_2_conv (Conv2D)   (None, 56, 56, 64)   36928       ['conv2_block3_1_relu[0][0]']    conv2_block3_2_bn (BatchNormal  (None, 56, 56, 64)  256         ['conv2_block3_2_conv[0][0]']    ization)                                                                                         conv2_block3_2_relu (Activatio  (None, 56, 56, 64)  0           ['conv2_block3_2_bn[0][0]']      n)                                                                                               conv2_block3_3_conv (Conv2D)   (None, 56, 56, 256)  16640       ['conv2_block3_2_relu[0][0]']    conv2_block3_3_bn (BatchNormal  (None, 56, 56, 256)  1024       ['conv2_block3_3_conv[0][0]']    ization)                                                                                         conv2_block3_add (Add)         (None, 56, 56, 256)  0           ['conv2_block2_out[0][0]',       'conv2_block3_3_bn[0][0]']      conv2_block3_out (Activation)  (None, 56, 56, 256)  0           ['conv2_block3_add[0][0]']       conv3_block1_1_conv (Conv2D)   (None, 28, 28, 128)  32896       ['conv2_block3_out[0][0]']       conv3_block1_1_bn (BatchNormal  (None, 28, 28, 128)  512        ['conv3_block1_1_conv[0][0]']    ization)                                                                                         conv3_block1_1_relu (Activatio  (None, 28, 28, 128)  0          ['conv3_block1_1_bn[0][0]']      n)                                                                                               conv3_block1_2_conv (Conv2D)   (None, 28, 28, 128)  147584      ['conv3_block1_1_relu[0][0]']    conv3_block1_2_bn (BatchNormal  (None, 28, 28, 128)  512        ['conv3_block1_2_conv[0][0]']    ization)                                                                                         conv3_block1_2_relu (Activatio  (None, 28, 28, 128)  0          ['conv3_block1_2_bn[0][0]']      n)                                                                                               conv3_block1_0_conv (Conv2D)   (None, 28, 28, 512)  131584      ['conv2_block3_out[0][0]']       conv3_block1_3_conv (Conv2D)   (None, 28, 28, 512)  66048       ['conv3_block1_2_relu[0][0]']    conv3_block1_0_bn (BatchNormal  (None, 28, 28, 512)  2048       ['conv3_block1_0_conv[0][0]']    ization)                                                                                         conv3_block1_3_bn (BatchNormal  (None, 28, 28, 512)  2048       ['conv3_block1_3_conv[0][0]']    ization)                                                                                         conv3_block1_add (Add)         (None, 28, 28, 512)  0           ['conv3_block1_0_bn[0][0]',      'conv3_block1_3_bn[0][0]']      conv3_block1_out (Activation)  (None, 28, 28, 512)  0           ['conv3_block1_add[0][0]']       conv3_block2_1_conv (Conv2D)   (None, 28, 28, 128)  65664       ['conv3_block1_out[0][0]']       conv3_block2_1_bn (BatchNormal  (None, 28, 28, 128)  512        ['conv3_block2_1_conv[0][0]']    ization)                                                                                         conv3_block2_1_relu (Activatio  (None, 28, 28, 128)  0          ['conv3_block2_1_bn[0][0]']      n)                                                                                               conv3_block2_2_conv (Conv2D)   (None, 28, 28, 128)  147584      ['conv3_block2_1_relu[0][0]']    conv3_block2_2_bn (BatchNormal  (None, 28, 28, 128)  512        ['conv3_block2_2_conv[0][0]']    ization)                                                                                         conv3_block2_2_relu (Activatio  (None, 28, 28, 128)  0          ['conv3_block2_2_bn[0][0]']      n)                                                                                               conv3_block2_3_conv (Conv2D)   (None, 28, 28, 512)  66048       ['conv3_block2_2_relu[0][0]']    conv3_block2_3_bn (BatchNormal  (None, 28, 28, 512)  2048       ['conv3_block2_3_conv[0][0]']    ization)                                                                                         conv3_block2_add (Add)         (None, 28, 28, 512)  0           ['conv3_block1_out[0][0]',       'conv3_block2_3_bn[0][0]']      conv3_block2_out (Activation)  (None, 28, 28, 512)  0           ['conv3_block2_add[0][0]']       conv3_block3_1_conv (Conv2D)   (None, 28, 28, 128)  65664       ['conv3_block2_out[0][0]']       conv3_block3_1_bn (BatchNormal  (None, 28, 28, 128)  512        ['conv3_block3_1_conv[0][0]']    ization)                                                                                         conv3_block3_1_relu (Activatio  (None, 28, 28, 128)  0          ['conv3_block3_1_bn[0][0]']      n)                                                                                               conv3_block3_2_conv (Conv2D)   (None, 28, 28, 128)  147584      ['conv3_block3_1_relu[0][0]']    conv3_block3_2_bn (BatchNormal  (None, 28, 28, 128)  512        ['conv3_block3_2_conv[0][0]']    ization)                                                                                         conv3_block3_2_relu (Activatio  (None, 28, 28, 128)  0          ['conv3_block3_2_bn[0][0]']      n)                                                                                               conv3_block3_3_conv (Conv2D)   (None, 28, 28, 512)  66048       ['conv3_block3_2_relu[0][0]']    conv3_block3_3_bn (BatchNormal  (None, 28, 28, 512)  2048       ['conv3_block3_3_conv[0][0]']    ization)                                                                                         conv3_block3_add (Add)         (None, 28, 28, 512)  0           ['conv3_block2_out[0][0]',       'conv3_block3_3_bn[0][0]']      conv3_block3_out (Activation)  (None, 28, 28, 512)  0           ['conv3_block3_add[0][0]']       conv3_block4_1_conv (Conv2D)   (None, 28, 28, 128)  65664       ['conv3_block3_out[0][0]']       conv3_block4_1_bn (BatchNormal  (None, 28, 28, 128)  512        ['conv3_block4_1_conv[0][0]']    ization)                                                                                         conv3_block4_1_relu (Activatio  (None, 28, 28, 128)  0          ['conv3_block4_1_bn[0][0]']      n)                                                                                               conv3_block4_2_conv (Conv2D)   (None, 28, 28, 128)  147584      ['conv3_block4_1_relu[0][0]']    conv3_block4_2_bn (BatchNormal  (None, 28, 28, 128)  512        ['conv3_block4_2_conv[0][0]']    ization)                                                                                         conv3_block4_2_relu (Activatio  (None, 28, 28, 128)  0          ['conv3_block4_2_bn[0][0]']      n)                                                                                               conv3_block4_3_conv (Conv2D)   (None, 28, 28, 512)  66048       ['conv3_block4_2_relu[0][0]']    conv3_block4_3_bn (BatchNormal  (None, 28, 28, 512)  2048       ['conv3_block4_3_conv[0][0]']    ization)                                                                                         conv3_block4_add (Add)         (None, 28, 28, 512)  0           ['conv3_block3_out[0][0]',       'conv3_block4_3_bn[0][0]']      conv3_block4_out (Activation)  (None, 28, 28, 512)  0           ['conv3_block4_add[0][0]']       conv4_block1_1_conv (Conv2D)   (None, 14, 14, 256)  131328      ['conv3_block4_out[0][0]']       conv4_block1_1_bn (BatchNormal  (None, 14, 14, 256)  1024       ['conv4_block1_1_conv[0][0]']    ization)                                                                                         conv4_block1_1_relu (Activatio  (None, 14, 14, 256)  0          ['conv4_block1_1_bn[0][0]']      n)                                                                                               conv4_block1_2_conv (Conv2D)   (None, 14, 14, 256)  590080      ['conv4_block1_1_relu[0][0]']    conv4_block1_2_bn (BatchNormal  (None, 14, 14, 256)  1024       ['conv4_block1_2_conv[0][0]']    ization)                                                                                         conv4_block1_2_relu (Activatio  (None, 14, 14, 256)  0          ['conv4_block1_2_bn[0][0]']      n)                                                                                               conv4_block1_0_conv (Conv2D)   (None, 14, 14, 1024  525312      ['conv3_block4_out[0][0]']       )                                                                 conv4_block1_3_conv (Conv2D)   (None, 14, 14, 1024  263168      ['conv4_block1_2_relu[0][0]']    )                                                                 conv4_block1_0_bn (BatchNormal  (None, 14, 14, 1024  4096       ['conv4_block1_0_conv[0][0]']    ization)                       )                                                                 conv4_block1_3_bn (BatchNormal  (None, 14, 14, 1024  4096       ['conv4_block1_3_conv[0][0]']    ization)                       )                                                                 conv4_block1_add (Add)         (None, 14, 14, 1024  0           ['conv4_block1_0_bn[0][0]',      )                                 'conv4_block1_3_bn[0][0]']      conv4_block1_out (Activation)  (None, 14, 14, 1024  0           ['conv4_block1_add[0][0]']       )                                                                 conv4_block2_1_conv (Conv2D)   (None, 14, 14, 256)  262400      ['conv4_block1_out[0][0]']       conv4_block2_1_bn (BatchNormal  (None, 14, 14, 256)  1024       ['conv4_block2_1_conv[0][0]']    ization)                                                                                         conv4_block2_1_relu (Activatio  (None, 14, 14, 256)  0          ['conv4_block2_1_bn[0][0]']      n)                                                                                               conv4_block2_2_conv (Conv2D)   (None, 14, 14, 256)  590080      ['conv4_block2_1_relu[0][0]']    conv4_block2_2_bn (BatchNormal  (None, 14, 14, 256)  1024       ['conv4_block2_2_conv[0][0]']    ization)                                                                                         conv4_block2_2_relu (Activatio  (None, 14, 14, 256)  0          ['conv4_block2_2_bn[0][0]']      n)                                                                                               conv4_block2_3_conv (Conv2D)   (None, 14, 14, 1024  263168      ['conv4_block2_2_relu[0][0]']    )                                                                 conv4_block2_3_bn (BatchNormal  (None, 14, 14, 1024  4096       ['conv4_block2_3_conv[0][0]']    ization)                       )                                                                 conv4_block2_add (Add)         (None, 14, 14, 1024  0           ['conv4_block1_out[0][0]',       )                                 'conv4_block2_3_bn[0][0]']      conv4_block2_out (Activation)  (None, 14, 14, 1024  0           ['conv4_block2_add[0][0]']       )                                                                 conv4_block3_1_conv (Conv2D)   (None, 14, 14, 256)  262400      ['conv4_block2_out[0][0]']       conv4_block3_1_bn (BatchNormal  (None, 14, 14, 256)  1024       ['conv4_block3_1_conv[0][0]']    ization)                                                                                         conv4_block3_1_relu (Activatio  (None, 14, 14, 256)  0          ['conv4_block3_1_bn[0][0]']      n)                                                                                               conv4_block3_2_conv (Conv2D)   (None, 14, 14, 256)  590080      ['conv4_block3_1_relu[0][0]']    conv4_block3_2_bn (BatchNormal  (None, 14, 14, 256)  1024       ['conv4_block3_2_conv[0][0]']    ization)                                                                                         conv4_block3_2_relu (Activatio  (None, 14, 14, 256)  0          ['conv4_block3_2_bn[0][0]']      n)                                                                                               conv4_block3_3_conv (Conv2D)   (None, 14, 14, 1024  263168      ['conv4_block3_2_relu[0][0]']    )                                                                 conv4_block3_3_bn (BatchNormal  (None, 14, 14, 1024  4096       ['conv4_block3_3_conv[0][0]']    ization)                       )                                                                 conv4_block3_add (Add)         (None, 14, 14, 1024  0           ['conv4_block2_out[0][0]',       )                                 'conv4_block3_3_bn[0][0]']      conv4_block3_out (Activation)  (None, 14, 14, 1024  0           ['conv4_block3_add[0][0]']       )                                                                 conv4_block4_1_conv (Conv2D)   (None, 14, 14, 256)  262400      ['conv4_block3_out[0][0]']       conv4_block4_1_bn (BatchNormal  (None, 14, 14, 256)  1024       ['conv4_block4_1_conv[0][0]']    ization)                                                                                         conv4_block4_1_relu (Activatio  (None, 14, 14, 256)  0          ['conv4_block4_1_bn[0][0]']      n)                                                                                               conv4_block4_2_conv (Conv2D)   (None, 14, 14, 256)  590080      ['conv4_block4_1_relu[0][0]']    conv4_block4_2_bn (BatchNormal  (None, 14, 14, 256)  1024       ['conv4_block4_2_conv[0][0]']    ization)                                                                                         conv4_block4_2_relu (Activatio  (None, 14, 14, 256)  0          ['conv4_block4_2_bn[0][0]']      n)                                                                                               conv4_block4_3_conv (Conv2D)   (None, 14, 14, 1024  263168      ['conv4_block4_2_relu[0][0]']    )                                                                 conv4_block4_3_bn (BatchNormal  (None, 14, 14, 1024  4096       ['conv4_block4_3_conv[0][0]']    ization)                       )                                                                 conv4_block4_add (Add)         (None, 14, 14, 1024  0           ['conv4_block3_out[0][0]',       )                                 'conv4_block4_3_bn[0][0]']      conv4_block4_out (Activation)  (None, 14, 14, 1024  0           ['conv4_block4_add[0][0]']       )                                                                 conv4_block5_1_conv (Conv2D)   (None, 14, 14, 256)  262400      ['conv4_block4_out[0][0]']       conv4_block5_1_bn (BatchNormal  (None, 14, 14, 256)  1024       ['conv4_block5_1_conv[0][0]']    ization)                                                                                         conv4_block5_1_relu (Activatio  (None, 14, 14, 256)  0          ['conv4_block5_1_bn[0][0]']      n)                                                                                               conv4_block5_2_conv (Conv2D)   (None, 14, 14, 256)  590080      ['conv4_block5_1_relu[0][0]']    conv4_block5_2_bn (BatchNormal  (None, 14, 14, 256)  1024       ['conv4_block5_2_conv[0][0]']    ization)                                                                                         conv4_block5_2_relu (Activatio  (None, 14, 14, 256)  0          ['conv4_block5_2_bn[0][0]']      n)                                                                                               conv4_block5_3_conv (Conv2D)   (None, 14, 14, 1024  263168      ['conv4_block5_2_relu[0][0]']    )                                                                 conv4_block5_3_bn (BatchNormal  (None, 14, 14, 1024  4096       ['conv4_block5_3_conv[0][0]']    ization)                       )                                                                 conv4_block5_add (Add)         (None, 14, 14, 1024  0           ['conv4_block4_out[0][0]',       )                                 'conv4_block5_3_bn[0][0]']      conv4_block5_out (Activation)  (None, 14, 14, 1024  0           ['conv4_block5_add[0][0]']       )                                                                 conv4_block6_1_conv (Conv2D)   (None, 14, 14, 256)  262400      ['conv4_block5_out[0][0]']       conv4_block6_1_bn (BatchNormal  (None, 14, 14, 256)  1024       ['conv4_block6_1_conv[0][0]']    ization)                                                                                         conv4_block6_1_relu (Activatio  (None, 14, 14, 256)  0          ['conv4_block6_1_bn[0][0]']      n)                                                                                               conv4_block6_2_conv (Conv2D)   (None, 14, 14, 256)  590080      ['conv4_block6_1_relu[0][0]']    conv4_block6_2_bn (BatchNormal  (None, 14, 14, 256)  1024       ['conv4_block6_2_conv[0][0]']    ization)                                                                                         conv4_block6_2_relu (Activatio  (None, 14, 14, 256)  0          ['conv4_block6_2_bn[0][0]']      n)                                                                                               conv4_block6_3_conv (Conv2D)   (None, 14, 14, 1024  263168      ['conv4_block6_2_relu[0][0]']    )                                                                 conv4_block6_3_bn (BatchNormal  (None, 14, 14, 1024  4096       ['conv4_block6_3_conv[0][0]']    ization)                       )                                                                 conv4_block6_add (Add)         (None, 14, 14, 1024  0           ['conv4_block5_out[0][0]',       )                                 'conv4_block6_3_bn[0][0]']      conv4_block6_out (Activation)  (None, 14, 14, 1024  0           ['conv4_block6_add[0][0]']       )                                                                 conv5_block1_1_conv (Conv2D)   (None, 7, 7, 512)    524800      ['conv4_block6_out[0][0]']       conv5_block1_1_bn (BatchNormal  (None, 7, 7, 512)   2048        ['conv5_block1_1_conv[0][0]']    ization)                                                                                         conv5_block1_1_relu (Activatio  (None, 7, 7, 512)   0           ['conv5_block1_1_bn[0][0]']      n)                                                                                               conv5_block1_2_conv (Conv2D)   (None, 7, 7, 512)    2359808     ['conv5_block1_1_relu[0][0]']    conv5_block1_2_bn (BatchNormal  (None, 7, 7, 512)   2048        ['conv5_block1_2_conv[0][0]']    ization)                                                                                         conv5_block1_2_relu (Activatio  (None, 7, 7, 512)   0           ['conv5_block1_2_bn[0][0]']      n)                                                                                               conv5_block1_0_conv (Conv2D)   (None, 7, 7, 2048)   2099200     ['conv4_block6_out[0][0]']       conv5_block1_3_conv (Conv2D)   (None, 7, 7, 2048)   1050624     ['conv5_block1_2_relu[0][0]']    conv5_block1_0_bn (BatchNormal  (None, 7, 7, 2048)  8192        ['conv5_block1_0_conv[0][0]']    ization)                                                                                         conv5_block1_3_bn (BatchNormal  (None, 7, 7, 2048)  8192        ['conv5_block1_3_conv[0][0]']    ization)                                                                                         conv5_block1_add (Add)         (None, 7, 7, 2048)   0           ['conv5_block1_0_bn[0][0]',      'conv5_block1_3_bn[0][0]']      conv5_block1_out (Activation)  (None, 7, 7, 2048)   0           ['conv5_block1_add[0][0]']       conv5_block2_1_conv (Conv2D)   (None, 7, 7, 512)    1049088     ['conv5_block1_out[0][0]']       conv5_block2_1_bn (BatchNormal  (None, 7, 7, 512)   2048        ['conv5_block2_1_conv[0][0]']    ization)                                                                                         conv5_block2_1_relu (Activatio  (None, 7, 7, 512)   0           ['conv5_block2_1_bn[0][0]']      n)                                                                                               conv5_block2_2_conv (Conv2D)   (None, 7, 7, 512)    2359808     ['conv5_block2_1_relu[0][0]']    conv5_block2_2_bn (BatchNormal  (None, 7, 7, 512)   2048        ['conv5_block2_2_conv[0][0]']    ization)                                                                                         conv5_block2_2_relu (Activatio  (None, 7, 7, 512)   0           ['conv5_block2_2_bn[0][0]']      n)                                                                                               conv5_block2_3_conv (Conv2D)   (None, 7, 7, 2048)   1050624     ['conv5_block2_2_relu[0][0]']    conv5_block2_3_bn (BatchNormal  (None, 7, 7, 2048)  8192        ['conv5_block2_3_conv[0][0]']    ization)                                                                                         conv5_block2_add (Add)         (None, 7, 7, 2048)   0           ['conv5_block1_out[0][0]',       'conv5_block2_3_bn[0][0]']      conv5_block2_out (Activation)  (None, 7, 7, 2048)   0           ['conv5_block2_add[0][0]']       conv5_block3_1_conv (Conv2D)   (None, 7, 7, 512)    1049088     ['conv5_block2_out[0][0]']       conv5_block3_1_bn (BatchNormal  (None, 7, 7, 512)   2048        ['conv5_block3_1_conv[0][0]']    ization)                                                                                         conv5_block3_1_relu (Activatio  (None, 7, 7, 512)   0           ['conv5_block3_1_bn[0][0]']      n)                                                                                               conv5_block3_2_conv (Conv2D)   (None, 7, 7, 512)    2359808     ['conv5_block3_1_relu[0][0]']    conv5_block3_2_bn (BatchNormal  (None, 7, 7, 512)   2048        ['conv5_block3_2_conv[0][0]']    ization)                                                                                         conv5_block3_2_relu (Activatio  (None, 7, 7, 512)   0           ['conv5_block3_2_bn[0][0]']      n)                                                                                               conv5_block3_3_conv (Conv2D)   (None, 7, 7, 2048)   1050624     ['conv5_block3_2_relu[0][0]']    conv5_block3_3_bn (BatchNormal  (None, 7, 7, 2048)  8192        ['conv5_block3_3_conv[0][0]']    ization)                                                                                         conv5_block3_add (Add)         (None, 7, 7, 2048)   0           ['conv5_block2_out[0][0]',       'conv5_block3_3_bn[0][0]']      conv5_block3_out (Activation)  (None, 7, 7, 2048)   0           ['conv5_block3_add[0][0]']       avg_pool (GlobalAveragePooling  (None, 2048)        0           ['conv5_block3_out[0][0]']       2D)                                                                                              predictions (Dense)            (None, 1000)         2049000     ['avg_pool[0][0]']               ==================================================================================================
Total params: 25,636,712
Trainable params: 25,583,592
Non-trainable params: 53,120
__________________________________________________________________________________________________
None
preds = model.predict(x)
1/1 [==============================] - 1s 854ms/step
print('Predicted:', decode_predictions(preds, top=5)[0])
Predicted: [('n02108422', 'bull_mastiff', 0.3921146), ('n02110958', 'pug', 0.2944119), ('n02093754', 'Border_terrier', 0.14356579), ('n02108915', 'French_bulldog', 0.057976846), ('n02099712', 'Labrador_retriever', 0.052499186)]

TensorFlow2.2基本应用

import tensorflow as tf
x=tf.random.normal([2,16])
w1=tf.Variable(tf.random.truncated_normal([16,8],stddev=0.1))
b1=tf.Variable(tf.zeros([8]))
o1=tf.matmul(x,w1)+b1
o1=tf.nn.relu(o1)
o1

<tf.Tensor: id=8263, shape=(2, 8), dtype=float32, numpy=
array([[0.16938789, 0. , 0.08883161, 0.14095941, 0.34751543,
0.353898 , 0. , 0.13356908],
[0. , 0. , 0.48546872, 0.37623546, 0.5447475 ,
0.21755993, 0.40121362, 0. ]], dtype=float32)>

from tensorflow.keras import layers
x=tf.random.normal([4,16*16])
fc=layers.Dense(5,activation=tf.nn.relu)
h1=fc(x)
h1

<tf.Tensor: id=8296, shape=(4, 5), dtype=float32, numpy=
array([[0. , 0. , 0. , 0.14286758, 0. ],
[0. , 2.2727172 , 0. , 0. , 0.34961763],
[0.1311972 , 0. , 1.4005635 , 0. , 0. ],
[0. , 1.7266206 , 0.64711714, 1.3494569 , 0. ]],
dtype=float32)>

#获取权值矩阵w
fc.kernel

<tf.Variable ‘dense/kernel:0’ shape=(256, 5) dtype=float32, numpy=
array([[-0.0339304 , 0.02273461, -0.12746884, 0.14963049, 0.00773269],
[-0.05978647, 0.07886668, -0.09110804, 0.14902723, 0.13007113],
[ 0.10187459, 0.13089484, 0.14367685, 0.12212327, -0.06235344],
…,
[ 0.10417426, 0.05112691, 0.12206474, 0.01141772, -0.05271714],
[ 0.03493455, -0.13473712, -0.01317982, -0.09485313, 0.04731715],
[ 0.12421742, 0.00030141, -0.00211757, -0.04196439, -0.03638943]],
dtype=float32)>

fc.bias

<tf.Variable ‘dense/bias:0’ shape=(5,) dtype=float32, numpy=array([0., 0., 0., 0., 0.], dtype=float32)>

fc.trainable_variables

[<tf.Variable ‘dense/kernel:0’ shape=(256, 5) dtype=float32, numpy=
array([[-0.0339304 , 0.02273461, -0.12746884, 0.14963049, 0.00773269],
[-0.05978647, 0.07886668, -0.09110804, 0.14902723, 0.13007113],
[ 0.10187459, 0.13089484, 0.14367685, 0.12212327, -0.06235344],
…,
[ 0.10417426, 0.05112691, 0.12206474, 0.01141772, -0.05271714],
[ 0.03493455, -0.13473712, -0.01317982, -0.09485313, 0.04731715],
[ 0.12421742, 0.00030141, -0.00211757, -0.04196439, -0.03638943]],
dtype=float32)>,
<tf.Variable ‘dense/bias:0’ shape=(5,) dtype=float32, numpy=array([0., 0., 0., 0., 0.], dtype=float32)>]

fc.variables

[<tf.Variable ‘dense/kernel:0’ shape=(256, 5) dtype=float32, numpy=
array([[-0.0339304 , 0.02273461, -0.12746884, 0.14963049, 0.00773269],
[-0.05978647, 0.07886668, -0.09110804, 0.14902723, 0.13007113],
[ 0.10187459, 0.13089484, 0.14367685, 0.12212327, -0.06235344],
…,
[ 0.10417426, 0.05112691, 0.12206474, 0.01141772, -0.05271714],
[ 0.03493455, -0.13473712, -0.01317982, -0.09485313, 0.04731715],
[ 0.12421742, 0.00030141, -0.00211757, -0.04196439, -0.03638943]],
dtype=float32)>,
<tf.Variable ‘dense/bias:0’ shape=(5,) dtype=float32, numpy=array([0., 0., 0., 0., 0.], dtype=float32)>]

5. 使用深度学习进行手写数字识别

import tensorflow as tf#载入MNIST 数据集。
mnist = tf.keras.datasets.mnist
#拆分数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
#将样本进行预处理,并从整数转换为浮点数
x_train, x_test = x_train / 255.0, x_test / 255.0#使用tf.keras.Sequential将模型的各层堆叠,并设置参数
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape=(28, 28)),tf.keras.layers.Dense(128, activation='relu'),tf.keras.layers.Dropout(0.2),tf.keras.layers.Dense(10, activation='softmax')
])
#设置模型的优化器和损失函数
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])
#训练并验证模型
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test,  y_test, verbose=2)
Train on 60000 samples
Epoch 1/5
60000/60000 [==============================] - 6s 95us/sample - loss: 0.2931 - accuracy: 0.9146
Epoch 2/5
60000/60000 [==============================] - 5s 77us/sample - loss: 0.1419 - accuracy: 0.9592
Epoch 3/5
60000/60000 [==============================] - 5s 78us/sample - loss: 0.1065 - accuracy: 0.9683
Epoch 4/5
60000/60000 [==============================] - 5s 78us/sample - loss: 0.0852 - accuracy: 0.9738
Epoch 5/5
60000/60000 [==============================] - 6s 100us/sample - loss: 0.0735 - accuracy: 0.9769
10000/1 - 0s - loss: 0.0338 - accuracy: 0.9795
[0.0666636555833742, 0.9795]

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/48756.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux 线程同步——条件变量

一、条件变量的概念 如果说互斥锁是用于同步线程对共享数据的访问的话&#xff0c;那么条件变量则是用于在线程之间同步共享数据的值。条件变量提供了一种线程间的通知机制&#xff1a;当某个共享数据达到某个值的时候&#xff0c;唤醒等待这个共享数据的线程。如下图所示&…

vue3中使用第三方插件mitt实现任意组件通讯

vue3中使用第三方插件mitt实现任意组件通讯 组件通讯是vue3组合式开发的核心之一&#xff0c;现在我在写代码时&#xff0c;一个组件的代码超过了200行&#xff0c;基本都会拆分组件。组件拆分后&#xff0c;组件之间的通讯就很重要&#xff0c;总结了一下&#xff0c;目前有这…

【SQL应知应会】索引(三)• MySQL版:聚簇索引与非聚簇索引;查看索引与删除索引;索引方法

欢迎来到爱书不爱输的程序猿的博客, 本博客致力于知识分享&#xff0c;与更多的人进行学习交流 本文收录于SQL应知应会专栏,本专栏主要用于记录对于数据库的一些学习&#xff0c;有基础也有进阶&#xff0c;有MySQL也有Oracle 索引 • MySQL版 前言一、索引1.简介2.索引类型之逻…

【李沐】3.2线性回归从0开始实现

%matplotlib inline import random import torch from d2l import torch as d2l1、生成数据集&#xff1a; 看最后的效果&#xff0c;用正态分布弄了一些噪音 上面这个具体实现可以看书&#xff0c;又想了想还是上代码把&#xff1a; 按照上面生成噪声&#xff0c;其中最后那…

利用大模型反馈故障的解决方案

背景 观测云有两个错误巡检脚本&#xff0c;RUM 错误巡检和 APM 错误巡检&#xff0c;代码均开源。 错误巡检的主要目的是发现新出现的错误消息(error stack)&#xff0c;原有的巡检在上报了相应的事件报告后&#xff0c;只是定位了问题&#xff0c;并没有给出合适的解决方案。…

Pandas基础知识

文章目录 Pandas的数据结构Series --- 由数据和索引组成&#xff08;索引&#xff08;index&#xff09;在左&#xff0c;数据&#xff08;values&#xff09;在右&#xff09;DataFrame --- 索引包括行索引和列索引&#xff0c;每列数据可以是不同的类型 Pandas的索引操作 ---…

SpringMVC拦截器学习笔记

SpringMVC拦截器 拦截器知识 拦截器(Interceptor)用于对URL请求进行前置/后置过滤 Interceptor与Filter用途相似但实现方式不同 Interceptor底层就是基于Spring AOP面向切面编程实现 拦截器开发流程 Maven添加依赖包servlet-api <dependency><groupId>javax.se…

nginx代理webSocket链接,webSocket频繁断开重连

一、场景 1、使用nginx代理webSocket链接&#xff0c;消息发送和接收都是正常的&#xff0c;但webSocket链接会频繁断开重连 2、如果不使用nginx代理则一切正常 3、程序没有做webSocket心跳处理 如下图 二、nginx代理配置 upstream cloud_ass {#ip_hash;server 192.168.1.…

2023年国赛数学建模思路 - 案例:随机森林

文章目录 1 什么是随机森林&#xff1f;2 随机深林构造流程3 随机森林的优缺点3.1 优点3.2 缺点 4 随机深林算法实现 建模资料 ## 0 赛题思路 &#xff08;赛题出来以后第一时间在CSDN分享&#xff09; https://blog.csdn.net/dc_sinor?typeblog 1 什么是随机森林&#xff…

从2023年世界机器人大会发现机器人新趋势

机器人零部件为何成2023年世界机器人大会关注热门&#xff1f; 在原先&#xff0c;机器人的三大核心零部件是控制系统中的控制器、驱动系统中的伺服电机和机械系统中的精密减速器。如今&#xff0c;机器人的主体框架结构已经落实&#xff0c;更多机器人已经开始深入到各类场景中…

Prompt本质解密及Evaluation实战(一)

一、基于evaluation的prompt使用解析 基于大模型的应用评估与传统应用程序的评估不太一样&#xff0c;特别是基于GPT系列或者生成式语言模型&#xff0c;因为模型生成的内容与传统意义上所说的内容或者标签不太一样。 以下是借用了ChatGPT官方的evaluation指南提出的对结果的具…

kali的一些使用和ms08-067、ms17-010漏洞

VM虚拟机-三种网络连接方式&#xff08;桥接、NAT、仅主机模式&#xff09; 虚拟机网络连接 一、Bridged&#xff08;桥接&#xff09; 二、NAT&#xff08;网络地址转换&#xff09; 三、Host-Only&#xff08;仅主机&#xff09; 在vmware软件中&#xff0c;选项栏的“编…

[计算机入门] 窗口操作

3.3 窗口操作 之前介绍过如何调整窗口大小。接下来介绍如何对窗口进行排布等操作。 当我们想要将某个窗口调整到整个屏幕的左边或者右边(占整个屏幕的一半)&#xff0c;可以在选中并激活窗口后&#xff0c;按Win ←/→ 进行调整。 此时&#xff0c;还可以通过Win↑/↓调整该…

docker版jxTMS使用指南:使用jxTMS提供数据

本文讲解了如何jxTMS的数据访问框架&#xff0c;整个系列的文章请查看&#xff1a;docker版jxTMS使用指南&#xff1a;4.4版升级内容 docker版本的使用&#xff0c;请查看&#xff1a;docker版jxTMS使用指南 4.0版jxTMS的说明&#xff0c;请查看&#xff1a;4.0版升级内容 4…

Python 合并多个 PDF 文件并建立书签目录

今天在用 WPS 的 PDF 工具合并多个文件的时候&#xff0c;非常不给力&#xff0c;居然卡死了好几次&#xff0c;什么毛病&#xff1f;&#xff01; 心里想&#xff0c;就这么点儿功能&#xff0c;居然收了我会员费都实现不了&#xff1f;不是吧…… 只能自己来了&#xff0c;…

Android6:片段和导航

创建项目Secret Message strings.xml <resources><string name"app_name">Secret Message</string><string name"welcome_text">Welcome to the Secret Message app!Use this app to encrypt a secret message.Click on the Star…

maven 从官网下载指定版本

1. 进入官网下载页面 Maven – Download Apache Maven 点击下图所示链接 2. 进入文件页&#xff0c;选择需要的版本 3. 选binaries 4. 选文件&#xff0c;下载即可

JMETER基本原理

Jmeter基本原理是建立一个线程池&#xff0c;多线程运行取样器产生大量负载&#xff0c;在运行过程中通过断言来验证结果的正确性&#xff0c;可以通过监听来记录测试结果&#xff1b; JMETER是运行在JVM虚拟机上的&#xff0c;每个进程的开销比loadrunner的进程开销大&#x…

Windows系统下安装Nginx以及相关端口问题的解决方法详解

系列文章目录 安装Tomac服务器——安装步骤以及易出现问题的解决方法 文章目录 系列文章目录 一 背景 二 安装 2.1 下载Nginx 2.2 选择Nginx版本 2.3 解压Nginx 三 Nginx的使用 3.1 Nginx基本目录 3.2查看80端口是否被占用 3.3 Nginx启动方式 第一种&#xff1a;双…

飞天使-k8s基础组件分析-控制器

文章目录 控制器含义解释pod的标签与注释ReplicaControllerReplicaSetDeploymentsDaemonSetJobCronjob参考文档 控制器含义解释 空调遥控器知道吧ReplicationController: ReplicationController确保在任何时候都运行指定数量的pod副本。换句话说&#xff0c;一个ReplicationCo…