Tensorflow 模型在特定范围内正确,但在休息时错误

问题描述 投票:0回答:1

我正在使用

tensorflow.keras
来创建一个简单的神经网络来预测
sin
函数。但模型在 -15 到 15 范围内是正确的,但在其余部分是错误的。

这是我的脚本:

import tensorflow as tf
from matplotlib import pyplot as plt
import numpy as np

# Define the number of neurons in each layer
input_layer = 1
hidden_layer_1 = 25
hidden_layer_2 = 50
output_layer = 1

# Create the model using Sequential API
model = 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 model
model.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 model
model.fit(X, y, epochs=100, batch_size=35)

# Once trained, you can use the model for predictions
test_input = np.array([[0.5]])  # Example test input
predicted_output = model.predict(test_input)
print("Predicted output:", predicted_output)

# Test the model with new data points
test_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 model
plt.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()

我确信这不是一个训练问题,因为这个问题在多次尝试中始终会发生。

第一次尝试:

第二次尝试:

python numpy tensorflow keras neural-network
1个回答
1
投票

这可能是因为训练数据的性质,尝试使用统一的训练数据网格。

© www.soinside.com 2019 - 2024. All rights reserved.