approximate sin function with neural net in python

To approximate the sin function using a neural network in Python, you can follow these steps:

  1. Import the necessary libraries: numpy for numerical operations and tensorflow for building and training the neural network.
main.py
import numpy as np
import tensorflow as tf
43 chars
3 lines
  1. Generate a set of input-output pairs for training the network. In this case, we'll use the sin function as our target function.
main.py
x_train = np.arange(0, 2 * np.pi, 0.1)
y_train = np.sin(x_train)
65 chars
3 lines
  1. Build the neural network model. Here, we'll use a simple feedforward network with one hidden layer.
main.py
model = tf.keras.Sequential([
    tf.keras.layers.Dense(16, activation='relu', input_shape=(1,)),
    tf.keras.layers.Dense(1)
])
130 chars
5 lines
  1. Compile the model by specifying the optimizer and loss function.
main.py
model.compile(optimizer='adam', loss='mse')
44 chars
2 lines
  1. Train the model on the training data.
main.py
model.fit(x_train, y_train, epochs=1000, verbose=0)
52 chars
2 lines
  1. Use the trained model to approximate the sin function for new inputs.
main.py
x_test = np.arange(0, 2 * np.pi, 0.01)
y_test = model.predict(x_test)
70 chars
3 lines

You can adjust the number of hidden layers, the number of neurons per layer, and the training parameters (e.g., learning rate, number of epochs) to improve the approximation accuracy. Additionally, you can evaluate the performance of the model using metrics such as mean squared error (MSE) or plot the results to visualize the approximation.

Note that neural networks can handle a wide range of functions, including complex ones like sin, and can achieve good approximation with sufficient training and appropriate architecture.

gistlibby LogSnag