Skip to content

Instantly share code, notes, and snippets.

@lgeiger
Created February 28, 2018 23:09
Show Gist options
  • Save lgeiger/f4cba03c87f8f036d6a1c11f2ae962ba to your computer and use it in GitHub Desktop.
Save lgeiger/f4cba03c87f8f036d6a1c11f2ae962ba to your computer and use it in GitHub Desktop.
CIFAR 10 using group equivariant convolutions with tf.keras
import tensorflow as tf
from groupy.gconv.gconv_tensorflow.keras.layers import P4ConvZ2, P4ConvP4
batch_size = 32
num_classes = 10
epochs = 25
num_predictions = 20
# The data, split between train and test sets:
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# Convert class vectors to binary class matrices.
y_train = tf.keras.utils.to_categorical(y_train, num_classes)
y_test = tf.keras.utils.to_categorical(y_test, num_classes)
model = tf.keras.models.Sequential()
# model.add(tf.keras.layers.Conv2D(32, 3, padding='same', activation='relu', input_shape=x_train.shape[1:]))
# model.add(tf.keras.layers.Conv2D(32, 3, strides=(2, 2), activation='relu'))
model.add(P4ConvZ2(32 // 2, 3, padding='same', activation='relu', input_shape=x_train.shape[1:]))
model.add(P4ConvP4(32 // 2, 3, strides=(2, 2), activation='relu'))
model.add(tf.keras.layers.Dropout(0.25))
# model.add(tf.keras.layers.Conv2D(64, 3, padding='same', activation='relu'))
# model.add(tf.keras.layers.Conv2D(64, 3, strides=(2, 2), activation='relu'))
model.add(P4ConvP4(64 // 2, 3, padding='same', activation='relu'))
model.add(P4ConvP4(64 // 2, 3, strides=(2, 2), activation='relu'))
model.add(tf.keras.layers.Dropout(0.25))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(512, activation='relu'))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer=tf.keras.optimizers.Adam(lr=0.001),
metrics=['accuracy'])
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255.
x_test /= 255.
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
validation_data=(x_test, y_test),
shuffle=True)
scores = model.evaluate(x_test, y_test, verbose=1)
print('Test loss:', scores[0])
print('Test accuracy:', scores[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment