-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjax_cifar10_cnn_classification.py
167 lines (134 loc) · 5.15 KB
/
jax_cifar10_cnn_classification.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File name: jax_cifar10_cnn_classification.py
import jax
import jax.numpy as jnp
import numpy as np
import tensorflow_datasets as tfds
# Define the CNN model architecture
def jax_cnn_model(inputs):
"""
Define a simple CNN model for CIFAR-10 classification.
Parameters:
inputs (jax.numpy.DeviceArray): Input data
Returns:
jax.numpy.DeviceArray: Output logits for each class
"""
# Convolutional layer 1
x = jax.lax.conv_general_dilated(inputs, jax.random.normal(jax.random.PRNGKey(0), (3, 3, 3, 32)), (1, 1), 'SAME')
x = jax.nn.relu(x)
x = jax.lax.avg_pool(x, (2, 2), (2, 2), 'VALID')
# Convolutional layer 2
x = jax.lax.conv_general_dilated(x, jax.random.normal(jax.random.PRNGKey(1), (3, 3, 32, 64)), (1, 1), 'SAME')
x = jax.nn.relu(x)
x = jax.lax.avg_pool(x, (2, 2), (2, 2), 'VALID')
# Flatten the feature maps
x = x.reshape((x.shape[0], -1))
# Fully connected layer
x = jax.nn.relu(jax.lax.dot_general(x, jax.random.normal(jax.random.PRNGKey(2), (x.shape[-1], 256)), (((1,), (0,)), ((), ()))))
# Output layer
x = jax.lax.dot_general(x, jax.random.normal(jax.random.PRNGKey(3), (256, 10)), (((1,), (0,)), ((), ())))
return x
# Define the loss function
def jax_loss_fn(params, inputs, labels):
"""
Compute the loss for the CNN model.
Parameters:
params (dict): Model parameters
inputs (jax.numpy.DeviceArray): Input data
labels (jax.numpy.DeviceArray): True labels
Returns:
jax.numpy.DeviceArray: Computed loss
"""
logits = jax_cnn_model(inputs)
one_hot_labels = jax.nn.one_hot(labels, num_classes=10)
loss = jnp.mean(jax.nn.softmax_cross_entropy_with_logits(logits, one_hot_labels))
return loss
# Define the accuracy metric
def jax_accuracy(params, inputs, labels):
"""
Compute the accuracy of the CNN model.
Parameters:
params (dict): Model parameters
inputs (jax.numpy.DeviceArray): Input data
labels (jax.numpy.DeviceArray): True labels
Returns:
float: Computed accuracy
"""
logits = jax_cnn_model(inputs)
predictions = jnp.argmax(logits, axis=-1)
return jnp.mean(predictions == labels)
# Load and preprocess the CIFAR-10 dataset
def jax_load_data():
"""
Load and preprocess the CIFAR-10 dataset.
Returns:
tuple: Preprocessed training and test datasets
"""
ds_train, ds_test = tfds.load('cifar10', split=['train', 'test'], as_supervised=True)
ds_train = ds_train.map(lambda x, y: (x / 255.0, y)).batch(32).prefetch(1)
ds_test = ds_test.map(lambda x, y: (x / 255.0, y)).batch(32).prefetch(1)
return ds_train, ds_test
# Train the model
def jax_train(params, optimizer, ds_train, num_epochs):
"""
Train the CNN model.
Parameters:
params (dict): Model parameters
optimizer (jax.experimental.optimizers.Optimizer): Optimizer for training
ds_train (tf.data.Dataset): Training dataset
num_epochs (int): Number of epochs to train
Returns:
dict: Trained model parameters
"""
for epoch in range(num_epochs):
for batch in ds_train:
inputs, labels = batch
loss_value, grads = jax.value_and_grad(jax_loss_fn)(params, inputs, labels)
params = optimizer.update(grads, params)
print(f"Epoch {epoch + 1}, Loss: {loss_value:.4f}")
return params
# Evaluate the model
def jax_evaluate(params, ds_test):
"""
Evaluate the CNN model.
Parameters:
params (dict): Model parameters
ds_test (tf.data.Dataset): Test dataset
Returns:
float: Computed test accuracy
"""
accuracies = []
for batch in ds_test:
inputs, labels = batch
acc = jax_accuracy(params, inputs, labels)
accuracies.append(acc)
return jnp.mean(jnp.array(accuracies))
# Main function
def main():
"""
Main function to run the training and evaluation of the CNN model.
"""
# Initialize model parameters
rng = jax.random.PRNGKey(0)
params = jax.random.normal(rng, (3, 32, 32, 32))
# Initialize optimizer
optimizer = jax.optim.Adam(learning_rate=0.001)
# Load and preprocess data
ds_train, ds_test = jax_load_data()
# Train the model
params = jax_train(params, optimizer, ds_train, num_epochs=10)
# Evaluate the model
accuracy = jax_evaluate(params, ds_test)
print(f"Test Accuracy: {accuracy:.4f}")
if __name__ == "__main__":
main()
# Possible Errors and Solutions:
# 1. ImportError: No module named 'tensorflow_datasets'.
# Solution: Ensure you have TensorFlow Datasets installed. Use `pip install tensorflow-datasets`.
# 2. AttributeError: module 'jax' has no attribute 'lax'.
# Solution: Ensure you have the correct version of JAX installed. Use `pip install --upgrade jax jaxlib`.
# 3. RuntimeError: CUDA out of memory.
# Solution: Reduce the batch size or the model size to fit the available GPU memory.
# 4. TypeError: 'float' object is not iterable.
# Solution: Check the data pipeline and ensure that the input data is batched correctly.
# 5. ValueError: operands could not be broadcast together with shapes.
# Solution: Ensure that the shapes of the arrays involved in operations are compatible.