Reputation: 55
I am trying to achieve a high Precision score on the MNIST dataset using Tensorflow and Keras. My code is working if I set the metric to accuracy but when I set it to precision, it gives the following error:
ValueError: Shapes (32, 10) and (32, 1) are incompatible
Here is my code:
import tensorflow as tf
import keras
from tensorflow.keras.datasets import mnist
def bulid_model(n = 1, neuron=30,lr = 3e-3,input_shape=(784,)):
model = keras.models.Sequential()
model.add(keras.layers.InputLayer(input_shape=input_shape))
for layer in range(n):
model.add(keras.layers.Dense(neuron, activation = 'relu'))
model.add(keras.layers.Dense(10,activation='softmax'))
optimizer = keras.optimizers.Adam(lr = lr)
model.compile(loss = 'sparse_categorical_crossentropy',optimizer=optimizer,metrics = [keras.metrics.Precision()])
return model
if __name__ == "__main__":
(X_train,Y_train),(X_test,Y_test) = mnist.load_data()
X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
model = bulid_model(3,20,0.0156)
history = model.fit(X_train,Y_train,epochs=50)
Can anyone help me with this?
Upvotes: 1
Views: 276
Reputation: 4970
Precision, is a metric for binary classification. It computes true_positives
and false_positives
then simply divides true_positives
by the sum of true_positives
and false_positives
.
But Accuracy
metric can be used for multi-class classification like MNIST, because it calculates how often predictions equal labels.
Upvotes: 1