Skip to content

Instantly share code, notes, and snippets.

View rafalpronko's full-sized avatar

Rafal Pronko rafalpronko

View GitHub Profile
# for Pytorch
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
# for tensorflow
import tensorflow as tf
from tensorflow import keras
modeltf = keras.Sequential([
keras.layers.Conv2D(input_shape=(28,28,1), filters=16, kernel_size=5, strides=1, padding="same", activation=tf.nn.relu),
keras.layers.BatchNormalization(),
keras.layers.MaxPooling2D(pool_size=2, strides=2),
keras.layers.Conv2D(32, kernel_size=5, strides=1, padding="same", activation=tf.nn.relu),
keras.layers.BatchNormalization(),
keras.layers.MaxPooling2D(pool_size=2, strides=2),
keras.layers.Flatten(),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
modelpy = NeuralNet(10)
criterion = nn.CrossEntropyLoss()
optim = torch.optim.Adam(modelpy.parameters())
modelpy
modeltf.compile(optimizer=keras.optimizers.Adam(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
modeltf.summary()
train_images_tf = train_images_tf.reshape(train_images_tf.shape[0],
train_images_tf.shape[1],
train_images_tf.shape[2], 1)
%%time
modeltf.fit(train_images_tf, train_labels_tf, epochs=10, batch_size=32)
correct = 0
total = 0
modelpy.eval()
for images, labels in test_loader:
outputs = modelpy(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
print('Test Accuracy of the model on the {} test images: {}%'.format(total, 100 * correct / total))
test_images_tf = test_images_tf.reshape(test_images_tf.shape[0],
test_images_tf.shape[1],
test_images_tf.shape[2], 1)
predictions = modeltf.predict(test_images_tf)
correct = 0
for i, pred in enumerate(predictions):
if np.argmax(pred) == test_labels_tf[i]:
correct += 1
print('Test Accuracy of the model on the {} test images: {}%'.format(test_images_tf.shape[0],
100 * correct/test_images_tf.shape[0]))
test_loss, test_acc = modeltf.evaluate(test_images_tf, test_labels_tf)
print('Test accuracy:', test_acc)
torch.save(modelpy, "/content/drive/My Drive/article/model.pt")
model_load_py = torch.load("/content/drive/My Drive/article/model.pt")
model_load_py