Skip to content

Instantly share code, notes, and snippets.

@lundquist-ecology-lab
Last active January 17, 2023 04:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lundquist-ecology-lab/ac05320f7049eff2c9bd92c5705f575a to your computer and use it in GitHub Desktop.
Save lundquist-ecology-lab/ac05320f7049eff2c9bd92c5705f575a to your computer and use it in GitHub Desktop.
Example using TensorFlow in Python
#Let's say we have a dataset of images of cats and dogs, and we want to train a
# model to classify them correctly. We will be using the tf.keras module, which
# provides a high-level API for building and training neural networks.
import tensorflow as tf
from tensorflow import keras
# load dataset
(x_train, y_train), (x_val, y_val) = keras.datasets.cifar10.load_data()
# normalize data
x_train = x_train / 255.0
x_val = x_val / 255.0
# define the model
model = keras.Sequential([
keras.layers.Conv2D(32, (3, 3), padding='same', input_shape=(32, 32, 3), activation='relu'),
keras.layers.MaxPooling2D((2, 2)),
keras.layers.Conv2D(64, (3, 3), padding='same', activation='relu'),
keras.layers.MaxPooling2D((2, 2)),
keras.layers.Flatten(),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
# compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# train the model
model.fit(x_train, y_train, batch_size=32, epochs=10, validation_data=(x_val, y_val))
# In this example, we first load the CIFAR-10 dataset using the keras.datasets
# module and normalize the data. Then we define a convolutional neural network
# model using the tf.keras.Sequential API, which consists of a sequence of layers.
#b We then compile the model by specifying the optimizer, loss function, and
# evaluation metric. Finally, we train the model using the fit method,
# where we specify the training data, batch size, and number of epochs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment