Exemplo n.º 1
0
    preprocessors=[simple_preprocessor, image_to_array_preprocessor])
data, labels = simple_dataset_loader.load(image_paths, verbose=500)
data = data.astype('float') / 255.0

X_train, X_test, y_train, y_test = train_test_split(data,
                                                    labels,
                                                    test_size=.25,
                                                    random_state=42)

y_train = LabelBinarizer().fit_transform(y_train)
y_test = LabelBinarizer().fit_transform(y_test)

print('[INFO] Compiling model...')
optimizer = SGD(lr=.005)

model = ShallowNet.build(width=32, height=32, depth=3, classes=3)
model.compile(loss='categorical_crossentropy',
              optimizer=optimizer,
              metrics=['accuracy'])

print('[INFO] Training network...')
H = model.fit(X_train,
              y_train,
              validation_data=(X_test, y_test),
              batch_size=64,
              epochs=100,
              verbose=1)

print('[INFO] Serializing network...')
model.save(arguments['model'])
def main():
    args = option()

    # load training data and testing data
    trainX, trainY = load_data_train(args["dataset"])
    testX, testY = load_data_test(args["dataset"])

    # reshape data matrix
    if K.image_data_format() == "channels_first":
        trainX = trainX.reshape(trainX.shape[0], 3, 32, 32)
        testX = testX.reshape(testX.shape[0], 3, 32, 32)
    else:
        trainX = trainX.reshape(trainX.shape[0], 32, 32, 3)
        testX = testX.reshape(testX.shape[0], 32, 32, 3)

    # scale trainX, testX into range [0,1]
    trainX = trainX.astype("float") / 255.0
    testX = testX.astype("float") / 255.0

    # convert labels as vector
    lb = LabelBinarizer()
    trainY = lb.fit_transform(trainY)
    testY = lb.fit_transform(testY)

    # initialize the label names for the CIFAR-10 dataset
    labelNames = [
        "airplane", "automobile", "bird", "cat", "deer", "dog", "frog",
        "horse", "ship", "truck"
    ]

    # initialize the optimizer and model
    print("[INFO] compiling model...")
    opt = SGD(lr=0.01)
    model = ShallowNet.build(width=32, height=32, depth=3, classes=10)
    model.compile(loss="categorical_crossentropy",
                  optimizer=opt,
                  metrics=["accuracy"])

    # train the network
    print("[INFO] training network...")
    H = model.fit(trainX,
                  trainY,
                  validation_data=(testX, testY),
                  batch_size=32,
                  epochs=40,
                  verbose=1)

    # evaluate network
    print("[INFO] evaluating network...")
    preds = model.predict(testX)
    print(
        classification_report(testY.argmax(axis=1),
                              preds.argmax(axis=1),
                              target_names=labelNames))

    # plot training loss and accuracy
    plt.style.use("ggplot")
    plt.figure()
    plt.plot(np.arange(0, 40), H.history["loss"], label="train_loss")
    plt.plot(np.arange(0, 40), H.history["val_loss"], label="val_loss")
    plt.plot(np.arange(0, 40), H.history["accuracy"], label="train_acc")
    plt.plot(np.arange(0, 40), H.history["val_accuracy"], label="val_acc")
    plt.title("Training Loss and Accuracy")
    plt.xlabel("Epoch")
    plt.ylabel("Loss/Accuracy")
    plt.legend()
    plt.savefig(args["output"])
Exemplo n.º 3
0
(trainX, trainY), (testX, testY) = cifar10.load_data()
trainX = trainX.astype("float") / 255.0
testX = testX.astype("float") / 255.0

lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.fit_transform(testY)

# record label names of CIFAR10
labelNames = ["airplane","automobile","bird","cat","deer","dog","frog",\
        "horse","ship","truck"]

## initialize models
print("[INFO] compiling models...")
sgd = SGD(lr=0.01)
model = ShallowNet.build(height=32, width=32, depth=3, classes=10)
model.compile(loss="categorical_crossentropy",
              optimizer=sgd,
              metrics=["accuracy"])

print("[INFO] training...")
H = model.fit(trainX,
              trainY,
              validation_data=(testX, testY),
              batch_size=32,
              epochs=args["epochs"],
              verbose=1)

print("[INFO] testing...")
predictions = model.predict(testX, batch_size=32)
print(
Exemplo n.º 4
0
def main():
    args = option()

    # grab list of images
    print("[INFO] loading images...")
    imagePaths = list(paths.list_images(args["dataset"]))

    # initialize the image preprocessors
    sp = SimplePreprocessor(32, 32)
    iap = ImageToArrayPreprocessor()

    # load the dataset from disk
    sdl = SimpleDatasetLoader(preprocessors=[sp, iap])
    (data, labels) = sdl.load(imagePaths, verbose=500)

    # scale the raw pixel intensities to the range [0, 1]
    data = data.astype("float") / 255.0

    # split training: 75%, testing: 25%
    (trainX, testX, trainY, testY) = train_test_split(data,
                                                      labels,
                                                      test_size=0.25,
                                                      random_state=42)

    # convert labels as vector
    lb = LabelBinarizer()
    trainY = lb.fit_transform(trainY)
    testY = lb.fit_transform(testY)

    # initialize the optimizer and model
    print("[INFO] compiling model...")
    opt = SGD(lr=0.005)
    model = ShallowNet.build(width=32, height=32, depth=3, classes=3)
    model.compile(loss="categorical_crossentropy",
                  optimizer=opt,
                  metrics=["accuracy"])

    # train the network
    print("[INFO]training network ...")
    H = model.fit(trainX,
                  trainY,
                  validation_data=(testX, testY),
                  batch_size=32,
                  epochs=100,
                  verbose=1)

    # evaluate the network
    print("[INFO] evaluating network...")
    preds = model.predict(testX)
    print(
        classification_report(testY.argmax(axis=1),
                              preds.argmax(axis=1),
                              target_names=["cat", "dog", "panda"]))

    # plot the training loss and accuracy
    plt.style.use("ggplot")
    plt.figure()
    plt.plot(np.arange(0, 100), H.history["loss"], label="train_loss")
    plt.plot(np.arange(0, 100), H.history["val_loss"], label="val_loss")
    plt.plot(np.arange(0, 100), H.history["accuracy"], label="train_acc")
    plt.plot(np.arange(0, 100), H.history["val_accuracy"], label="val_acc")
    plt.title("Training Loss and Accuracy")
    plt.xlabel("Epoch #")
    plt.ylabel("Loss/Accuracy")
    plt.legend()
    plt.savefig(args["output"])
def main():
    args = option()

    class_name = [
        'Apple', 'Avocado', 'Banana', 'Coconut', 'Custard_apple',
        'Dragon_fruit', 'Guava', 'Mango', 'Orange', 'Plum', 'Start_fruit',
        'Watermelon'
    ]

    in_data = 'H5PY/train/train_normal.h5'
    in_label = 'H5PY/train/labels_train.h5'

    # import the feature vector and trained labels
    h5f_data = h5py.File(in_data, 'r')
    h5f_label = h5py.File(in_label, 'r')

    data = h5f_data['dataset']
    labels = h5f_label['dataset']

    data = np.array(data)
    labels = np.array(labels)

    # reshape data matrix
    if K.image_data_format() == "channels_first":
        data = data.reshape(data.shape[0], 3, 32, 32)
    else:
        data = data.reshape(data.shape[0], 32, 32, 3)

    # split training: 80%, testing: 20%
    (trainX, testX, trainY, testY) = train_test_split(data,
                                                      labels,
                                                      test_size=0.2,
                                                      random_state=42)

    # convert labels as vector
    lb = LabelBinarizer()
    trainY = lb.fit_transform(trainY)
    testY = lb.fit_transform(testY)

    # initialize the optimizer and model
    print("[INFO] compiling model...")
    opt = SGD(lr=0.05)
    model = ShallowNet.build(width=32, height=32, depth=3, classes=12)
    model.compile(loss="categorical_crossentropy",
                  optimizer=opt,
                  metrics=["accuracy"])

    # train the network
    print("[INFO]training network ...")
    H = model.fit(trainX,
                  trainY,
                  validation_data=(testX, testY),
                  batch_size=32,
                  epochs=40,
                  verbose=1)

    # save the network to disk
    print("[INFO] serializing network ...")
    model.save(args["model"])

    # evaluate the network
    print("[INFO] evaluating network...")
    preds = model.predict(testX)
    print(
        classification_report(testY.argmax(axis=1),
                              preds.argmax(axis=1),
                              target_names=class_name))

    # plot the training loss and accuracy
    plt.style.use("ggplot")
    plt.figure()
    plt.plot(np.arange(0, 40), H.history["loss"], label="train_loss")
    plt.plot(np.arange(0, 40), H.history["val_loss"], label="val_loss")
    plt.plot(np.arange(0, 40), H.history["accuracy"], label="train_acc")
    plt.plot(np.arange(0, 40), H.history["val_accuracy"], label="val_acc")
    plt.title("Training Loss and Accuracy")
    plt.xlabel("Epoch #")
    plt.ylabel("Loss/Accuracy")
    plt.legend()
    plt.savefig(args["output"])