0

I try to learn a network with keras to learn y=x**2 but acuuracy is 0; I write this code by reading documentation.

import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras import layers
inputs=keras.Input(shape=(1,))
x= layers.Dense(64, activation="relu")(inputs)
x2 = layers.Dense(64, activation="relu")(x)
outputs = layers.Dense(1,)(x2)
model = keras.Model(inputs=inputs, outputs=outputs, name="first_model")
x_train=np.random.rand(1,5000)
y_train=np.zeros((1,5000))
for j in range(0,np.size(x_train[0])):
    y_train[0,j]=x_train[0,j]**2
    
model.compile(
    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer=keras.optimizers.RMSprop(),
    metrics=["accuracy"],
)

history = model.fit(x_train[0], y_train[0], batch_size=10,epochs=1, )
x_test=np.random.rand(1,50000)
y_test=np.zeros((1,50000))
for j in range(0,np.size(x_test[0])):
    y_test[0,j]=x_test[0,j]**2
test_scores = model.evaluate(x_test[0], y_test[0], verbose=2)
print("Test loss:", test_scores[0])
print("Test accuracy:", test_scores[1])

1 Answers1

0

You have the wrong loss function – SparseCategoricalCrossentropy is used when you have categories which you want to predict. In your case, you could use for example MeanSquaredError

model.compile(
    loss='mse',
    optimizer=keras.optimizers.RMSprop(),
    metrics=["mse"],
)
AndrzejO
  • 1,502
  • 1
  • 9
  • 12