I am making a simple neural network using tensorflow.keras
to predict the sin
function. But the model is correct from -15 to 15, but is wrong on the rest.
This is my script:
import tensorflow as tffrom matplotlib import pyplot as pltimport numpy as np# Define the number of neurons in each layerinput_layer = 1hidden_layer_1 = 25hidden_layer_2 = 50output_layer = 1# Create the model using Sequential APImodel = tf.keras.Sequential([ tf.keras.layers.Dense(hidden_layer_1, activation='relu', input_shape=(input_layer,)), tf.keras.layers.Dense(hidden_layer_2, activation='relu'), tf.keras.layers.Dense(hidden_layer_2, activation='relu'), tf.keras.layers.Dense(hidden_layer_1, activation='relu'), tf.keras.layers.Dense(output_layer, activation='linear') # Linear activation for single output])# Compile the modelmodel.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])# Generate some sample data (input and output)np.random.seed(562)X = np.random.uniform(low=-200, high=200, size=(10000, input_layer))y = np.sin(X)# Train the modelmodel.fit(X, y, epochs=100, batch_size=35)# Once trained, you can use the model for predictionstest_input = np.array([[0.5]]) # Example test inputpredicted_output = model.predict(test_input)print("Predicted output:", predicted_output)# Test the model with new data pointstest_points = np.linspace(-30, 30, 200)[:, np.newaxis]predicted_values = model.predict(test_points)# Plot the original sin(x) and the predicted values by the modelplt.figure(figsize=(8, 6))plt.plot(test_points, predicted_values, label='Predicted Values', color='red')plt.plot(test_points, np.sin(test_points), label='Actual Values', color='blue')plt.xlabel('X')plt.ylabel('sin(X)')plt.legend()plt.show()
I sure that this is not a training problem, because this issue consistently happens over multiple tries.
First try:
Image may be NSFW.
Clik here to view.
Second try: