本文主要是介绍cifar10在resnet50上精度达95%以上,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、tensorflow环境
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import timeimport tensorflow as tf
from tensorflow import keras
from tensorflow.keras.utils import to_categorical(x_train, y_train), (x_test, y_test) =tf.keras.datasets.cifar10.load_data()
y_train = to_categorical(y_train,num_classes=10)
y_test = to_categorical(y_test,num_classes=10)def preprocess(image,lable):resize_image = tf.image.resize(image,[224,224])resize_image = tf.image.random_flip_left_right(resize_image)resize_image = tf.cast(resize_image, tf.float32)/255.mean = [0.5, 0.45, 0.4]std = [0.23, 0.22, 0.21]resize_image = (resize_image - mean)/stdreturn resize_image,labledef preprocess_dataset(x, y, batch_size, seed=42):dataset = tf.data.Dataset.from_tensor_slices((x, y))dataset = dataset.shuffle(buffer_size=batch_size,seed=seed)dataset = dataset.map(preprocess).batch(batch_size)dataset = dataset.prefetch(1)return datasettrain_set = preprocess_dataset(x_train,y_train,16)
test_set = preprocess_dataset(x_test, y_test,4)base_model = tf.keras.applications.ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
base_model.trainable = Truemodel = keras.models.Sequential([base_model,keras.layers.GlobalAveragePooling2D(),keras.layers.Dense(10, activation='softmax')
])optimizer = tf.keras.optimizers.SGD(learning_rate=0.001, momentum=0.9)
loss_function = tf.keras.losses.CategoricalCrossentropy()
model.compile(optimizer=optimizer, loss=loss_function, metrics=['accuracy'])history = model.fit(train_set, epochs=5)model.evaluate(test_set)
结果如下:
2、pytorch环境
import torch
import torchvision
from torch import nn
from torchvision import transforms
from torch import optimmytrans = transforms.Compose([transforms.Resize((224, 224)),transforms.RandomHorizontalFlip(p=0.5),transforms.ToTensor(),transforms.Normalize((0.5, 0.45, 0.4), (0.23, 0.22, 0.21))])train_set = torchvision.datasets.CIFAR10(root='./cifar-10-python/', train=True, download=True, transform=mytrans)
train_set = torch.utils.data.DataLoader(train_set, batch_size=16, shuffle=True, num_workers=0)test_set = torchvision.datasets.CIFAR10(root='./cifar-10-python/', train=False, download=True, transform=mytrans)
test_set = torch.utils.data.DataLoader(test_set, batch_size=16, shuffle=True, num_workers=0)model = torchvision.models.resnet50(weights=True)
nums = model.fc.in_features
model.fc = nn.Linear(nums, 10)device = torch.device("cuda:0")
# device = torch.device("cpu")
model = model.to(device)myoptim = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
myloss = nn.CrossEntropyLoss()n_epoch = 10
for epoch in range(1,n_epoch+1):print("epoch {}/{}".format(epoch,n_epoch))for step,test_data in enumerate(train_set):image, label = test_data[0].to(device), test_data[1].to(device)predict_label = model.forward(image) loss = myloss(predict_label, label)myoptim.zero_grad()loss.backward()myoptim.step()end = "" if step != len(train_set)-1 else "\n"print("\rtrain iteration {}/{} - training loss: {:.3f}".format(step+1, len(train_set), loss.item()), end=end)model.eval()total = 0correct = 0for step,test_data in enumerate(test_set):image = test_data[0].to(device)label = test_data[1].to(device)outputs = model(image)_, pred = torch.max(outputs.data,1)total += label.size(0)correct += (pred==label).sum().item()end = "" if step != len(test_set)-1 else "\n"print('\rtest iteration {}/{} - testing accuracy: {:.3f}%'.format(step+1, len(test_set), 100*correct/total), end=end)
结果如下:
这篇关于cifar10在resnet50上精度达95%以上的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!