0 运行环境:Colab tensorflow 2.1
1 代码
%tensorflow_version 2.x
import tensorflow as tf
print(tf.__version__)
import os
import pandas as pd
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation,GlobalMaxPooling2D,GlobalAveragePooling2D
from tensorflow.keras import applications
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras import optimizers
from tensorflow.keras.applications import *
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img
from tensorflow.keras.utils import to_categorical
from sklearn.model_selection import train_test_split
!pip install PyDrive googledrivedownloader
from google_drive_downloader import GoogleDriveDownloader
GoogleDriveDownloader.download_file_from_google_drive(file_id='1K1X9-ori8zj0TdOem6dJZs2qvuiOjBVx',dest_path='./content',unzip=True)
BATCH_SIZE = 128
IMAGE_SIZE = 224
EPOCHS = 50
INPUT_SHAPE = (IMAGE_SIZE, IMAGE_SIZE, 3)
import matplotlib.pyplot as plt
with tf.device('/gpu:0'):
import numpy as np
np.random.seed(2345)
import pandas as pd
df_raw = pd.read_csv("./train.csv")
df = df_raw.sample(frac=1)
df["category"] = df["label"].replace({
0: 'Audi', 2: 'benz', 1: 'BMW'})
df = df.drop(columns="label")
total_df = df.shape[0]
with tf.device('/gpu:0'):
train_df, validate_df = train_test_split(df, test_size=0.1)
train_df = train_df.reset_index(drop=True)
validate_df = validate_df.reset_index(drop=True)
total_train = train_df.shape[0]
total_validate = validate_df.shape[0]
train_datagen = ImageDataGenerator(
rotation_range=15,
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest',
width_shift_range=0.1,
height_shift_range=0.1
)
train_generator = train_datagen.flow_from_dataframe(
train_df,
"./train",
x_col = 'filename',
y_col = 'category',
class_mode='categorical',
target_size=(IMAGE_SIZE, IMAGE_SIZE),
batch_size