TensorFlow2进行CIFAR-10数据集动物识别,保存模型并且进行外部下载图片测试

这篇具有很好参考价值的文章主要介绍了TensorFlow2进行CIFAR-10数据集动物识别,保存模型并且进行外部下载图片测试。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

首先,你已经安装好anaconda3、创建好环境、下载好TensorFlow2模块并且下载好jupyter了,那么我们就直接打开jupyter开始进行CIFAR10数据集的训练。

第一步:下载CIFAR10数据集

下载网址:http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz

将数据集下载到合适的路径,方便模型训练的时候调用

第二步:导入该导的库

# tensorflow1.x
import tensorflow as tf
import numpy as np
import os
from matplotlib import pyplot as plt

第三步:加载刚刚下载的数据集,如果你下载了 cifar-10-python.tar.gz那么就先解压这个压缩包,将里面的文件放入一个文件夹,我这里放在为cifar-10-batches-py目录下,所有文件如图

TensorFlow2进行CIFAR-10数据集动物识别,保存模型并且进行外部下载图片测试

 然后加载该数据集

import pickle

def unpickle(file):
    with open(file, 'rb') as fo:
        dict = pickle.load(fo, encoding='bytes')
    return dict

def load_data(path):
    # 读取训练数据
    train_images = []
    train_labels = []
    for i in range(1, 6):
        file = path + "/data_batch_{}".format(i)
        data = unpickle(file)
        train_images.append(data[b"data"])
        train_labels.append(data[b"labels"])
    train_images = np.concatenate(train_images)
    train_labels = np.concatenate(train_labels)
    # 读取测试数据
    file = path + "/test_batch"
    data = unpickle(file)
    test_images = data[b"data"]
    test_labels = np.array(data[b"labels"])
    # 转换数据类型
    train_images = train_images.astype(np.float32)
    test_images = test_images.astype(np.float32)
    y_train = np.array(train_labels)
    y_test = np.array(test_labels)
    # 将像素值缩放到[0, 1]范围内
    x_train = train_images/255.0
    x_test = test_images/255.0
    
    # 将标签数据转换为one-hot编码
#     train_labels = tf.keras.utils.to_categorical(train_labels, num_classes=10)
#     test_labels = tf.keras.utils.to_categorical(test_labels, num_classes=10)
    
    return (x_train, y_train), (x_test, y_test)


# 加载数据集
(train_images, train_labels), (test_images, test_labels) = load_data("../cifar_data/cifar-10-batches-py")
train_images = train_images.reshape(50000, 32, 32, 3)
test_images = test_images.reshape(10000, 32, 32, 3)

当然还有更简单的方法那就是使用TensorFlow内部模块下载数据集,如下

# 下载数据集
cifar10=tf.keras.datasets.cifar10

(x_train,y_train),(x_test,y_test)=cifar10.load_data()

x_train[0][0][0]
# 对图像images进行数字标准化
x_train=x_train.astype('float32')/255.0 
x_test = x_test.astype('float32')/ 255.0

第四步:数据集本来的标签是数字,我们可以将它转化成对应的类型名

label_dict={0:"airplane",1:"automobile",2:"bird",3:"cat",4:"deer",5:"dog", 6:"frog", 7:"horse", 8:"ship", 9:"truck"}

第五步:开始构建神经网络模型,这里我就简单构建一个类似AlexNet的卷积神网络模型

# 建立卷积神经网络CNN模型AlexNet
#建立Sequential线性堆叠模型
'''
Conv2D(filters=,kernel_size=,strides=,padding=,activation=,input_shape=,)
filters:卷积核数量,即输出的特征图数量。
kernel_size:卷积核大小,可以是一个整数或者一个元组,例如(3, 3)。
strides:卷积步长,可以是一个整数或者一个元组,例如(1, 1)。
padding:填充方式,可以是'same'或'valid'。'same'表示在输入图像四周填充0,保证输出特征图大小与输入图像大小相同;
        'valid'表示不填充,直接进行卷积运算。
activation:激活函数,可以是一个字符串、一个函数或者一个可调用对象。
input_shape:输入图像的形状
'''

'''
MaxPooling2D(pool_size=,strides=,padding=,)
pool_size:池化窗口大小,可以是一个整数或者一个元组,例如(2, 2)表示2x2的池化窗口。
'''


#this is a noe model,you just have to choose one or the other
def creatAlexNet():
    model = tf.keras.models.Sequential()#第1个卷积层
    model.add(tf.keras.layers.Conv2D(filters=32,
                                     kernel_size=(3,3), 
                                     input_shape=(32,32,3),
                                     activation='relu', padding='same'))
    # 防止过拟合
    model.add(tf.keras.layers.Dropout(rate=0.3))
    #第1个池化层
    model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2)))
    #第2个卷积层
    model.add(tf.keras.layers.Conv2D(filters = 64,kernel_size=(3,3), activation='relu', padding ='same'))
    # 防止过拟合
    model.add(tf.keras.layers.Dropout(rate=0.3))#第2个池化层
    model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2)))# 平坦层

    #第3个卷积层
    model.add(tf.keras.layers.Conv2D(filters = 128,kernel_size=(3,3), activation='relu', padding ='same'))
    # 防止过拟合
    model.add(tf.keras.layers.Dropout(rate=0.3))#第3个池化层
    model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2)))# 平坦层

    model.add(tf.keras.layers.Flatten())# 添加输出层
    model.add(tf.keras.layers.Dense(10,activation='softmax'))
    return model

第六步:开始加载模型

执行模型函数

model = creatAlexNet()

输出摘要

model.summary()

摘要结果如下: 

TensorFlow2进行CIFAR-10数据集动物识别,保存模型并且进行外部下载图片测试

 超参数定义及模型训练

'''
model.compile(optimizer =,loss=,metrics=)
optimizer:指定优化器,可以传入字符串标识符(如'rmsprop'、'adam'等),也可以传入Optimizer类的实例。
loss:指定损失函数,可以传入字符串标识符(如'mse'、'categorical_crossentropy'等),也可以传入自定义的损失函数。
metrics:指定评估指标,可以传入字符串标识符(如'accuracy'、'mae'等),也可以传入自定义的评估函数或函数列表
'''

'''
model.fit(x=,y=,batch_size=,epochs=,verbose=,validation_data=,validation_split=,shuffle=,callbacks=)
x:训练数据,通常为一个形状为(样本数, 特征数)的numpy数组,也可以是一个包含多个numpy数组的列表。

y:标签,也是一个numpy数组或列表,长度应与x的第一维相同。

batch_size:批量大小,表示每次迭代训练的样本数,通常选择2的幂次方,比如32、64、128等。

epochs:训练轮数,一个轮数表示使用所有训练数据进行了一次前向传播和反向传播,通常需要根据实际情况调整。

verbose:输出详细信息,0表示不输出,1表示输出进度条,2表示每个epoch输出一次。

validation_data:验证数据,通常为一个形状与x相同的numpy数组,也可以是一个包含多个numpy数组的列表。

validation_split:切分验证集,将训练数据的一部分用作验证数据,取值范围在0到1之间,表示将训练数据的一部分划分为验证数据的比例。

shuffle:是否打乱训练数据,True表示每个epoch之前打乱数据,False表示不打乱数据。

callbacks:回调函数,用于在训练过程中定期保存模型、调整学习率等操作,
常用的回调函数包括ModelCheckpoint、EarlyStopping、ReduceLROnPlateau等。
'''

# 设置训练参数
train_epochs=10#训练轮数
batch_size=100#单次训练样本数(批次大小)

# 定义训练模式
model.compile(optimizer ='adam',#优化器
loss='sparse_categorical_crossentropy',#损失函数
              metrics=['accuracy'])#评估模型的方式
#训练模型
train_history = model.fit(x_train,y_train,validation_split = 0.2, epochs = train_epochs, 
                          batch_size = batch_size)

训练过程如下:

TensorFlow2进行CIFAR-10数据集动物识别,保存模型并且进行外部下载图片测试

第七步:训练的损失率和成功率的可视化图

# 定义训练过程可视化函数
def visu_train_history(train_history,train_metric,validation_metric):
    plt.plot(train_history.history[train_metric])
    plt.plot(train_history.history[validation_metric])
    plt.title('Train History')
    plt.ylabel(train_metric)
    plt.xlabel('epoch')
    plt.legend(['train','validation'],loc='upper left')
    plt.show()

 损失率可视化

visu_train_history(train_history,'loss','val_loss')

 TensorFlow2进行CIFAR-10数据集动物识别,保存模型并且进行外部下载图片测试

成功率可视化 

visu_train_history(train_history,'accuracy','val_accuracy')

 TensorFlow2进行CIFAR-10数据集动物识别,保存模型并且进行外部下载图片测试

第八步:模型测试及评估

用测试集评估模型

# 评估模型
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print('Test accuracy:', test_acc)

 模型测试,可视化测试

#model test
preds = model.predict(x_test)

可视化函数

# 定义显示图像数据及其对应标签的函数
# 图像列表
def plot_images_labels_prediction(images,# 标签列表
                                  labels,
                                  preds,#预测值列表
                                  index,#从第index个开始显示
                                  num = 5):  # 缺省一次显示5幅
    fig=plt.gcf()#获取当前图表,Get Current Figure 
    fig.set_size_inches(12,6)#1英寸等于2.54cm 
    if num > 10:#最多显示10个子图
        num = 10
    for i in range(0, num):
        ax = plt.subplot(2,5,i+1)#获取当前要处理的子图
        plt.tight_layout()
        ax.imshow(images[index])
        title=str(i)+','+label_dict[labels[index][0]]#构建该图上要显示的title信息
        if len(preds)>0:
            title +='=>' + label_dict[np.argmax(preds[index])]
        ax.set_title(title,fontsize=10)#显示图上的title信息
        index += 1 
    plt.show()

执行可视化函数

plot_images_labels_prediction(x_test,y_test, preds,15,30)

 结果如下:

TensorFlow2进行CIFAR-10数据集动物识别,保存模型并且进行外部下载图片测试

第九步:模型保存及模型使用,测试外部图片

保存模型

# 保存模型
model_filename ='models/cifarCNNModel.h5'
model.save(model_filename)

加载模型,测试模型

方法一:使用TensorFlow内部模块加载图片,将dog.jpg路径换成你的图片路径

# 加载模型
loaded_model = tf.keras.models.load_model('models/cifarCNNModel.h5')

type = ("airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck")
label_dict={0:"airplane",1:"automobile",2:"bird",3:"cat",4:"deer",5:"dog", 6:"frog", 7:"horse", 8:"ship", 9:"truck"}

# 加载外来图片
img = tf.keras.preprocessing.image.load_img(
    'dog.jpg', target_size=(32, 32)
)

# 转化为numpy数组
img_array = tf.keras.preprocessing.image.img_to_array(img)

# 归一化数据
img_array = img_array / 255.0

# 维度扩展
img_array = np.expand_dims(img_array, axis=0)

# 预测类别
predictions = loaded_model.predict(img_array)
pre_label = np.argmax(predictions)
plt.title("type:{}, pre_label:{}".format(label_dict[pre_label],pre_label))
plt.imshow(img, cmap=plt.get_cmap('gray'))

 结果如下,预测结果是正确的,我这里在浏览器下载的确实是一张狗的图片 

TensorFlow2进行CIFAR-10数据集动物识别,保存模型并且进行外部下载图片测试

方法二:使用PIL的库加载图片进行预测 

from PIL import Image
import numpy as np

img = Image.open('./cat.jpg')
img = img.resize((32, 32))
img_arr = np.array(img) / 255.0
img_arr = img_arr.reshape(1, 32, 32, 3)
pred = model.predict(img_arr)
class_idx = np.argmax(pred)
plt.title("type:{}, pre_label:{}".format(label_dict[class_idx],class_idx))
plt.imshow(img, cmap=plt.get_cmap('gray'))

结果如下,也是正确的,我这张图片确实是一张猫的图片

 TensorFlow2进行CIFAR-10数据集动物识别,保存模型并且进行外部下载图片测试

 方法三:从网络上加载图片进行预测,将下面的网址换成你想要预测的图片网址

# 加载模型
loaded_model = tf.keras.models.load_model('models/cifarCNNModel.h5')
# 使用模型预测浏览器上的一张图片
type = ("airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck")
label_dict={0:"airplane",1:"automobile",2:"bird",3:"cat",4:"deer",5:"dog", 6:"frog", 7:"horse", 8:"ship", 9:"truck"}

url = 'https://img1.baidu.com/it/u=1284172325,1569939558&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=580'
with urllib.request.urlopen(url) as url_response:
    img_array = np.asarray(bytearray(url_response.read()), dtype=np.uint8)
    img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
    img_array = cv2.resize(img, (32, 32))
    img_array = img_array / 255.0
    img_array = np.expand_dims(img_array, axis=0)
    
    predict_label = np.argmax(loaded_model.predict(img_array), axis=-1)[0]
    plt.imshow(img, cmap=plt.get_cmap('gray'))
    plt.title("Predict: {},Predict_label: {}".format(type[predict_label],predict_label))
    plt.xticks([])
    plt.yticks([])

结果如下, 这张就预测错了,明明是狗,预测成鸟(bird)去了

 TensorFlow2进行CIFAR-10数据集动物识别,保存模型并且进行外部下载图片测试

完整代码如下:

import tensorflow as tf
import numpy as np
import os
import matplotlib.pyplot as plt
import urllib
import cv2

# 下载数据集
cifar10=tf.keras.datasets.cifar10

(x_train,y_train),(x_test,y_test)=cifar10.load_data()

x_train[0][0][0]
# 对图像images进行数字标准化
x_train=x_train.astype('float32')/255.0 
x_test = x_test.astype('float32')/ 255.0

label_dict={0:"airplane",1:"automobile",2:"bird",3:"cat",4:"deer",5:"dog", 6:"frog", 7:"horse", 8:"ship", 9:"truck"}

# 建立卷积神经网络CNN模型AlexNet
#建立Sequential线性堆叠模型
'''
Conv2D(filters=,kernel_size=,strides=,padding=,activation=,input_shape=,)
filters:卷积核数量,即输出的特征图数量。
kernel_size:卷积核大小,可以是一个整数或者一个元组,例如(3, 3)。
strides:卷积步长,可以是一个整数或者一个元组,例如(1, 1)。
padding:填充方式,可以是'same'或'valid'。'same'表示在输入图像四周填充0,保证输出特征图大小与输入图像大小相同;
        'valid'表示不填充,直接进行卷积运算。
activation:激活函数,可以是一个字符串、一个函数或者一个可调用对象。
input_shape:输入图像的形状
'''

'''
MaxPooling2D(pool_size=,strides=,padding=,)
pool_size:池化窗口大小,可以是一个整数或者一个元组,例如(2, 2)表示2x2的池化窗口。
'''


#this is a noe model,you just have to choose one or the other
def creatAlexNet():
    model = tf.keras.models.Sequential()#第1个卷积层
    model.add(tf.keras.layers.Conv2D(filters=32,
                                     kernel_size=(3,3), 
                                     input_shape=(32,32,3),
                                     activation='relu', padding='same'))
    # 防止过拟合
    model.add(tf.keras.layers.Dropout(rate=0.3))
    #第1个池化层
    model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2)))
    #第2个卷积层
    model.add(tf.keras.layers.Conv2D(filters = 64,kernel_size=(3,3), activation='relu', padding ='same'))
    # 防止过拟合
    model.add(tf.keras.layers.Dropout(rate=0.3))#第2个池化层
    model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2)))# 平坦层

    #第3个卷积层
    model.add(tf.keras.layers.Conv2D(filters = 128,kernel_size=(3,3), activation='relu', padding ='same'))
    # 防止过拟合
    model.add(tf.keras.layers.Dropout(rate=0.3))#第3个池化层
    model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2)))# 平坦层

    model.add(tf.keras.layers.Flatten())# 添加输出层
    model.add(tf.keras.layers.Dense(10,activation='softmax'))
    return model

model = creatAlexNet()
model.summary()

'''
model.compile(optimizer =,loss=,metrics=)
optimizer:指定优化器,可以传入字符串标识符(如'rmsprop'、'adam'等),也可以传入Optimizer类的实例。
loss:指定损失函数,可以传入字符串标识符(如'mse'、'categorical_crossentropy'等),也可以传入自定义的损失函数。
metrics:指定评估指标,可以传入字符串标识符(如'accuracy'、'mae'等),也可以传入自定义的评估函数或函数列表
'''

'''
model.fit(x=,y=,batch_size=,epochs=,verbose=,validation_data=,validation_split=,shuffle=,callbacks=)
x:训练数据,通常为一个形状为(样本数, 特征数)的numpy数组,也可以是一个包含多个numpy数组的列表。

y:标签,也是一个numpy数组或列表,长度应与x的第一维相同。

batch_size:批量大小,表示每次迭代训练的样本数,通常选择2的幂次方,比如32、64、128等。

epochs:训练轮数,一个轮数表示使用所有训练数据进行了一次前向传播和反向传播,通常需要根据实际情况调整。

verbose:输出详细信息,0表示不输出,1表示输出进度条,2表示每个epoch输出一次。

validation_data:验证数据,通常为一个形状与x相同的numpy数组,也可以是一个包含多个numpy数组的列表。

validation_split:切分验证集,将训练数据的一部分用作验证数据,取值范围在0到1之间,表示将训练数据的一部分划分为验证数据的比例。

shuffle:是否打乱训练数据,True表示每个epoch之前打乱数据,False表示不打乱数据。

callbacks:回调函数,用于在训练过程中定期保存模型、调整学习率等操作,
常用的回调函数包括ModelCheckpoint、EarlyStopping、ReduceLROnPlateau等。
'''

# 设置训练参数
train_epochs=10#训练轮数
batch_size=100#单次训练样本数(批次大小)

# 定义训练模式
model.compile(optimizer ='adam',#优化器
loss='sparse_categorical_crossentropy',#损失函数
              metrics=['accuracy'])#评估模型的方式
#训练模型
train_history = model.fit(x_train,y_train,validation_split = 0.2, epochs = train_epochs, 
                          batch_size = batch_size)

# 定义训练过程可视化函数
def visu_train_history(train_history,train_metric,validation_metric):
    plt.plot(train_history.history[train_metric])
    plt.plot(train_history.history[validation_metric])
    plt.title('Train History')
    plt.ylabel(train_metric)
    plt.xlabel('epoch')
    plt.legend(['train','validation'],loc='upper left')
    plt.show()

visu_train_history(train_history,'accuracy','val_accuracy')

# 评估模型
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print('Test accuracy:', test_acc)

#model test
preds = model.predict(x_test)

np.argmax(preds[0])

# 定义显示图像数据及其对应标签的函数
# 图像列表
def plot_images_labels_prediction(images,# 标签列表
                                  labels,
                                  preds,#预测值列表
                                  index,#从第index个开始显示
                                  num = 5):  # 缺省一次显示5幅
    fig=plt.gcf()#获取当前图表,Get Current Figure 
    fig.set_size_inches(12,6)#1英寸等于2.54cm 
    if num > 10:#最多显示10个子图
        num = 10
    for i in range(0, num):
        ax = plt.subplot(2,5,i+1)#获取当前要处理的子图
        plt.tight_layout()
        ax.imshow(images[index])
        title=str(i)+','+label_dict[labels[index][0]]#构建该图上要显示的title信息
        if len(preds)>0:
            title +='=>' + label_dict[np.argmax(preds[index])]
        ax.set_title(title,fontsize=10)#显示图上的title信息
        index += 1 
    plt.show()

plot_images_labels_prediction(x_test,y_test, preds,15,30)

# 保存模型
model_filename ='models/cifarCNNModel.h5'
model.save(model_filename)

# 加载模型
loaded_model = tf.keras.models.load_model('models/cifarCNNModel.h5')

type = ("airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck")
label_dict={0:"airplane",1:"automobile",2:"bird",3:"cat",4:"deer",5:"dog", 6:"frog", 7:"horse", 8:"ship", 9:"truck"}

# 加载外来图片
img = tf.keras.preprocessing.image.load_img(
    'dog.jpg', target_size=(32, 32)
)

# 转化为numpy数组
img_array = tf.keras.preprocessing.image.img_to_array(img)

# 归一化数据
img_array = img_array / 255.0

# 维度扩展
img_array = np.expand_dims(img_array, axis=0)

# 预测类别
predictions = loaded_model.predict(img_array)
pre_label = np.argmax(predictions)
plt.title("type:{}, pre_label:{}".format(label_dict[pre_label],pre_label))
plt.imshow(img, cmap=plt.get_cmap('gray'))

#另一个加载图片方法
from PIL import Image
import numpy as np

img = Image.open('./cat.jpg')
img = img.resize((32, 32))
img_arr = np.array(img) / 255.0
img_arr = img_arr.reshape(1, 32, 32, 3)
pred = model.predict(img_arr)
class_idx = np.argmax(pred)
plt.title("type:{}, pre_label:{}".format(label_dict[class_idx],class_idx))
plt.imshow(img, cmap=plt.get_cmap('gray'))

# 加载模型
loaded_model = tf.keras.models.load_model('models/cifarCNNModel.h5')
# 使用模型预测浏览器上的一张图片
type = ("airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck")
label_dict={0:"airplane",1:"automobile",2:"bird",3:"cat",4:"deer",5:"dog", 6:"frog", 7:"horse", 8:"ship", 9:"truck"}

url = 'https://img1.baidu.com/it/u=1284172325,1569939558&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=580'
with urllib.request.urlopen(url) as url_response:
    img_array = np.asarray(bytearray(url_response.read()), dtype=np.uint8)
    img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
    img_array = cv2.resize(img, (32, 32))
    img_array = img_array / 255.0
    img_array = np.expand_dims(img_array, axis=0)
    
    predict_label = np.argmax(loaded_model.predict(img_array), axis=-1)[0]
    plt.imshow(img, cmap=plt.get_cmap('gray'))
    plt.title("Predict: {},Predict_label: {}".format(type[predict_label],predict_label))
    plt.xticks([])
    plt.yticks([])

那么本篇文章CIFAR10数据集分类模型训练就到此结束,感谢大家的继续支持!文章来源地址https://www.toymoban.com/news/detail-478981.html

到了这里,关于TensorFlow2进行CIFAR-10数据集动物识别,保存模型并且进行外部下载图片测试的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Tensorflow2.0笔记 - Tensor的数据索引和切片

            主要涉及的了基础下标索引\\\"[]\\\",逗号\\\",\\\",冒号\\\":\\\",省略号\\\"...\\\"操作,以及gather,gather_nd和boolean_mask的相关使用方法。 运行结果:   ....

    2024年01月23日
    浏览(35)
  • 【Python深度学习】Tensorflow+CNN进行人脸识别实战(附源码和数据集)

    需要源码和数据集请点赞关注收藏后评论区留言私信~~~ 下面利用tensorflow平台进行人脸识别实战,使用的是Olivetti Faces人脸图像 部分数据集展示如下  程序训练过程如下  接下来训练CNN模型 可以看到训练进度和损失值变化 接下来展示人脸识别结果   程序会根据一张图片自动

    2024年02月09日
    浏览(30)
  • Pytorch实现动物识别(含动物数据集和训练代码)

    目录 动物数据集+动物分类识别训练代码(Pytorch) 1. 前言 2. Animals-Dataset动物数据集说明 (1)Animals90动物数据集 (2)Animals10动物数据集 (3)自定义数据集 3. 动物分类识别模型训练 (1)项目安装 (2)准备Train和Test数据 (3)配置文件: config.yaml (4)开始训练 (5)可视化训

    2024年02月02日
    浏览(90)
  • [Pytorch] CIFAR-10数据集的训练和模型优化

    本篇文章借鉴了我的朋友Jc的报告,他是一个十分优秀的人。 本篇文章记录了第一次完整训练优化的过程 在CIFAR-10 dataset的介绍中,cifar-10数据集一共10类图片,每一类有6000张图片,加起来就是60000张图片,每张图片的尺寸是32x32,图片是彩色图,整个数据集被分为5个训练批次

    2023年04月14日
    浏览(31)
  • 【深度学习】pytorch——实现CIFAR-10数据集的分类

    笔记为自我总结整理的学习笔记,若有错误欢迎指出哟~ 往期文章: 【深度学习】pytorch——快速入门 CIFAR-10是一个常用的图像分类数据集,每张图片都是 3×32×32,3通道彩色图片,分辨率为 32×32。 它包含了10个不同类别,每个类别有6000张图像,其中5000张用于训练,1000张用于

    2024年02月06日
    浏览(39)
  • tensorflow2基础

    TensorFlow 包含以下特性: 训练流程 数据的处理  :使用 tf.data 和 TFRecord 可以高效地构建和预处理数据集,构建训练数据流。同时可以使用 TensorFlow Datasets 快速载入常用的公开数据集。 模型的建立与调试  :使用即时执行模式和著名的神经网络高层 API 框架 Keras,结合可视化

    2024年02月11日
    浏览(31)
  • TensorFlow案例学习:使用 YAMNet 进行迁移学习,对音频进行识别

    上一篇文章 TensorFlow案例学习:简单的音频识别 我们简单学习了音频识别。这次我们继续学习如何使用成熟的语音分类模型来进行迁移学习 官方教程: 使用 YAMNet 进行迁移学习,用于环境声音分类 模型下载地址(需要科学上网): https://tfhub.dev/google/yamnet/1 YAMNet简介 YAMNet(

    2024年02月03日
    浏览(33)
  • tensorflow2 模型建立与训练

    模型的构建:  tf.keras.Model  和  tf.keras.layers 模型的损失函数:  tf.keras.losses 模型的优化器:  tf.keras.optimizer 模型的评估:  tf.keras.metrics Keras 有两个重要的概念:  模型(Model)  和  层(Layer)  。层将各种计算流程和变量进行了封装(例如基本的全连接层,CNN 的卷积层

    2024年02月10日
    浏览(30)
  • tensorflow2模型保存和恢复

    有两种方法可以保存模型: ·使用检查点,一种简单的在硬盘上保存变量的方法 ·使用SavedModel,模型结构及检查点 检查点不包含任何关于模型自身的描述:它们只是一种简单的存储参数并能让开发者正确恢复它的方法。 SavedModel格式在保存参数值的基础上加上了计算过程的序

    2024年02月11日
    浏览(36)
  • 【Python机器学习】实验15 将Lenet5应用于Cifar10数据集

    CIFAR-10 数据集由10个类别的60000张32x32彩色图像组成,每类6000张图像。有50000张训练图像和10000张测试图像。数据集分为五个训练批次 和一个测试批次,每个批次有10000张图像。测试批次包含从每个类别中随机选择的1000张图像。训练批次包含随机顺序的剩余图像,但一些训练批

    2024年02月11日
    浏览(25)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包