Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
debakarr
GitHub Repository: debakarr/machinelearning
Path: blob/master/Part 8 - Deep Learning/Convolutional Neural Networks/cnn.py
1009 views
1
# Convolutional Neural Network
2
3
# Installing Theano
4
# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
5
6
# Installing Tensorflow
7
# Install Tensorflow from the website: https://www.tensorflow.org/versions/r0.12/get_started/os_setup.html
8
9
# Installing Keras
10
# pip install --upgrade keras
11
12
# Part 1 - Building the CNN
13
14
# Importing the Keras libraries and packages
15
from keras.models import Sequential
16
from keras.layers import Conv2D
17
from keras.layers import MaxPooling2D
18
from keras.layers import Flatten
19
from keras.layers import Dense
20
21
# Initialising the CNN
22
classifier = Sequential()
23
24
# Step 1 - Convolution
25
classifier.add(Conv2D(32, (3, 3), input_shape=(64, 64, 3), activation="relu"))
26
27
# Step 2 - Pooling
28
classifier.add(MaxPooling2D(pool_size = (2, 2)))
29
30
# Adding a second convolutional layer
31
classifier.add(Conv2D(32, (3, 3), activation="relu"))
32
classifier.add(MaxPooling2D(pool_size = (2, 2)))
33
34
# Step 3 - Flattening
35
classifier.add(Flatten())
36
37
# Step 4 - Full connection
38
classifier.add(Dense(activation="relu", units=128))
39
classifier.add(Dense(activation="sigmoid", units=1))
40
41
# Compiling the CNN
42
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
43
44
# Part 2 - Fitting the CNN to the images
45
46
from keras.preprocessing.image import ImageDataGenerator
47
48
train_datagen = ImageDataGenerator(rescale = 1./255,
49
shear_range = 0.2,
50
zoom_range = 0.2,
51
horizontal_flip = True)
52
53
test_datagen = ImageDataGenerator(rescale = 1./255)
54
training_set = train_datagen.flow_from_directory('dataset/training_set',
55
target_size = (64, 64),
56
batch_size = 32,
57
class_mode = 'binary')
58
59
test_set = test_datagen.flow_from_directory('dataset/test_set',
60
target_size = (64, 64),
61
batch_size = 32,
62
class_mode = 'binary')
63
classifier.fit_generator(training_set,
64
epochs = 25,
65
validation_data = test_set,
66
validation_steps = 2000,
67
steps_per_epoch=250)
68