Beispiel #1
0
def train(tagged):
    """
    Trains an SVM classifier based on the training data passed.

    Mostly based on http://dlib.net/svm_binary_classifier.py.html.

    :param tagged: list of TaggedFace to train on
    :return: dlib.svm
    """
    x = dlib.vectors()  # will carry the facial encodings
    y = dlib.array()  # will carry the gender label
    print("Preparing dataset...")
    total = len(tagged)
    for i, t in enumerate(tagged):
        print(f"\rEncoding {t.path} ({i + 1}/{total})...", end="")
        faces = encode(t.img)
        x.append(dlib.vector(faces[0]))
        y.append(t.tag)
        img = t.img
        for _ in range(5):
            faces = encode(img)
            if not faces:
                break
            x.append(dlib.vector(faces[0]))
            y.append(t.tag)
            img = cv2.resize(img, None, fx=0.7, fy=0.7)

    print("Training SVM...")
    trainer = dlib.svm_c_trainer_radial_basis()
    #trainer.be_verbose()
    trainer.set_c(10)
    model = trainer.train(x, y)
    with open(PATH_SVMFILE, "wb") as filehandle:
        pickle.dump(model, filehandle)
    return None
Beispiel #2
0
def test_array_extend():
    a = array()
    a.extend([0, 1, 2, 3, 4])
    assert len(a) == 5
    for idx, val in enumerate(a):
        assert idx == val
        assert type(val) == FloatType
Beispiel #3
0
def test_array_resize():
    a = array(10)
    a.resize(100)
    assert len(a) == 100

    for i in range(100):
        assert a[i] == 0
Beispiel #4
0
def test_array_serialization_empty():
    a = array()
    # cPickle with protocol 2 required for Python 2.7
    # see http://pybind11.readthedocs.io/en/stable/advanced/classes.html#custom-constructors
    ser = pickle.dumps(a, 2)
    deser = pickle.loads(ser)
    assert a == deser
Beispiel #5
0
def test_array_extend():
    a = array()
    a.extend([0, 1, 2, 3, 4])
    assert len(a) == 5
    for idx, val in enumerate(a):
        assert idx == val
        assert type(val) == FloatType
Beispiel #6
0
def test_array_serialization_empty():
    a = array()
    # cPickle with protocol 2 required for Python 2.7
    # see http://pybind11.readthedocs.io/en/stable/advanced/classes.html#custom-constructors
    ser = pickle.dumps(a, 2)
    deser = pickle.loads(ser)
    assert a == deser
Beispiel #7
0
def test_array_resize():
    a = array(10)
    a.resize(100)
    assert len(a) == 100

    for i in range(100):
        assert a[i] == 0
Beispiel #8
0
def training_data():
    r = Random(0)
    predictors = vectors()
    sparse_predictors = sparse_vectors()
    response = array()
    for i in range(30):
        for c in [-1, 1]:
            response.append(c)
            values = [r.random() + c * 0.5 for _ in range(3)]
            predictors.append(vector(values))
            sp = sparse_vector()
            for i, v in enumerate(values):
                sp.append(pair(i, v))
            sparse_predictors.append(sp)
    return predictors, sparse_predictors, response
Beispiel #9
0
def training_data():
    r = Random(0)
    predictors = vectors()
    sparse_predictors = sparse_vectors()
    response = array()
    for i in range(30):
        for c in [-1, 1]:
            response.append(c)
            values = [r.random() + c * 0.5 for _ in range(3)]
            predictors.append(vector(values))
            sp = sparse_vector()
            for i, v in enumerate(values):
                sp.append(pair(i, v))
            sparse_predictors.append(sp)
    return predictors, sparse_predictors, response
Beispiel #10
0
def test_array_init_with_list():
    a = array([0, 1, 2, 3, 4])
    assert len(a) == 5
    for idx, val in enumerate(a):
        assert idx == val
        assert type(val) == FloatType
Beispiel #11
0
def test_array_init_with_zero():
    a = array(0)
    assert len(a) == 0
Beispiel #12
0
def test_array_serialization():
    a = array([0, 1, 2, 3, 4])
    ser = pickle.dumps(a, 2)
    deser = pickle.loads(ser)
    assert a == deser
Beispiel #13
0
def test_array_clear():
    a = array(10)
    a.clear()
    assert len(a) == 0
Beispiel #14
0
def test_array_string_representations_empty():
    a = array()
    assert str(a) == ""
    assert repr(a) == "array[]"
Beispiel #15
0
def test_array_serialization():
    a = array([0, 1, 2, 3, 4])
    ser = pickle.dumps(a, 2)
    deser = pickle.loads(ser)
    assert a == deser
Beispiel #16
0
def test_array_init_with_tuple():
    a = array((0, 1, 2, 3, 4))
    for idx, val in enumerate(a):
        assert idx == val
        assert type(val) == FloatType
Beispiel #17
0
#   things run faster.  
#
#   Compiling dlib should work on any operating system so long as you have
#   CMake and boost-python installed.  On Ubuntu, this can be done easily by
#   running the command:
#       sudo apt-get install libboost-python-dev cmake
#

import dlib
try:
    import cPickle as pickle
except ImportError:
    import pickle

x = dlib.vectors()
y = dlib.array()

# Make a training dataset.  Here we have just two training examples.  Normally
# you would use a much larger training dataset, but for the purpose of example
# this is plenty.  For binary classification, the y labels should all be either +1 or -1.
x.append(dlib.vector([1, 2, 3, -1, -2, -3]))
y.append(+1)

x.append(dlib.vector([-1, -2, -3, 1, 2, 3]))
y.append(-1)


# Now make a training object.  This object is responsible for turning a
# training dataset into a prediction model.  This one here is a SVM trainer
# that uses a linear kernel.  If you wanted to use a RBF kernel or histogram
# intersection kernel you could change it to one of these lines:
Beispiel #18
0
def test_array_init_with_empty_list():
    a = array([])
    assert len(a) == 0
Beispiel #19
0
def test_array_clear():
    a = array(10)
    a.clear()
    assert len(a) == 0
Beispiel #20
0
def test_array_string_representations():
    a = array([1, 2, 3])
    assert str(a) == "1\n2\n3"
    assert repr(a) == "array[1, 2, 3]"
Beispiel #21
0
def test_array_string_representations_empty():
    a = array()
    assert str(a) == ""
    assert repr(a) == "array[]"
Beispiel #22
0
def test_array_init_without_argument():
    a = array()
    assert len(a) == 0
Beispiel #23
0
def test_array_init_with_empty_list():
    a = array([])
    assert len(a) == 0
Beispiel #24
0
def test_array_init_without_argument():
    a = array()
    assert len(a) == 0
Beispiel #25
0
def test_array_init_with_list():
    a = array([0, 1, 2, 3, 4])
    assert len(a) == 5
    for idx, val in enumerate(a):
        assert idx == val
        assert type(val) == FloatType
Beispiel #26
0
def test_array_init_with_zero():
    a = array(0)
    assert len(a) == 0
Beispiel #27
0
def test_array_init_with_number():
    a = array(5)
    assert len(a) == 5
    for i in range(5):
        assert a[i] == 0
        assert type(a[i]) == FloatType
Beispiel #28
0
def test_array_init_with_negative_number():
    with raises(Exception):
        array(-5)
Beispiel #29
0
def test_array_init_with_negative_number():
    with raises(Exception):
        array(-5)
Beispiel #30
0
def test_array_string_representations():
    a = array([1, 2, 3])
    assert str(a) == "1\n2\n3"
    assert repr(a) == "array[1, 2, 3]"
Beispiel #31
0
def test_array_init_with_negative_number():
    with raises(MemoryError):
        array(-5)
Beispiel #32
0
def test_array_init_with_number():
    a = array(5)
    assert len(a) == 5
    for i in range(5):
        assert a[i] == 0
        assert type(a[i]) == FloatType
Beispiel #33
0
def test_array_init_with_tuple():
    a = array((0, 1, 2, 3, 4))
    for idx, val in enumerate(a):
        assert idx == val
        assert type(val) == FloatType
Beispiel #34
0
#       python setup.py install
#
#   Compiling dlib should work on any operating system so long as you have
#   CMake installed.  On Ubuntu, this can be done easily by running the
#   command:
#       sudo apt-get install cmake
#

import dlib
try:
    import cPickle as pickle
except ImportError:
    import pickle

x = dlib.vectors()
y = dlib.array()

# Make a training dataset.  Here we have just two training examples.  Normally
# you would use a much larger training dataset, but for the purpose of example
# this is plenty.  For binary classification, the y labels should all be either +1 or -1.
x.append(dlib.vector([1, 2, 3, -1, -2, -3]))
y.append(+1)

x.append(dlib.vector([-1, -2, -3, 1, 2, 3]))
y.append(-1)

# Now make a training object.  This object is responsible for turning a
# training dataset into a prediction model.  This one here is a SVM trainer
# that uses a linear kernel.  If you wanted to use a RBF kernel or histogram
# intersection kernel you could change it to one of these lines:
#  svm = dlib.svm_c_trainer_histogram_intersection()
Beispiel #35
0
male_label = +1
female_label = -1

print "Retrieving males images ..."
males = glob.glob("./imdb-datasets/images/males/*.jpg")
print "Retrieved {} faces !".format(len(males))

print "Retrieving females images ..."
females = glob.glob("./imdb-datasets/images/females/*.jpg")
print "Retrieved {} faces !".format(len(females))

females = females[:max_size]
males = males[:max_size]

vectors = dlib.vectors()
labels = dlib.array()

print "Reading males images ..."
for i, male in enumerate(males):
    print "Reading {} of {}\r".format(i, len(males))
    face_vectors = face_vector(read_image(male))
    if face_vectors is None:
        continue
    vectors.append(dlib.vector(face_vectors))
    labels.append(male_label)

print "Reading females images ..."
for i, female in enumerate(females):
    print "Reading {} of {}\r".format(i, len(females))
    face_vectors = face_vector(read_image(female))
    if face_vectors is None: