python code RNN for NLP
时间: 2023-11-04 19:22:49 浏览: 51
Sure! Here's an example of Python code for a simple Recurrent Neural Network (RNN) used for Natural Language Processing (NLP):
```python
import numpy as np
import tensorflow as tf
# Preprocessing
# Assuming you have already preprocessed your text data and converted it to numerical representation
# Define your input data
num_samples = 1000
input_length = 10
vocab_size = 1000
# Generate dummy input data
input_data = np.random.randint(0, vocab_size, size=(num_samples, input_length))
# Define your RNN model
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, 64, input_length=input_length),
tf.keras.layers.SimpleRNN(64),
tf.keras.layers.Dense(1, activation='sigmoid')
])
# Compile and train the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(input_data, labels, epochs=10, batch_size=32)
```
This code demonstrates how to build a simple RNN model using TensorFlow's Keras API. It includes an embedding layer to convert the input sequence into dense vectors, followed by a SimpleRNN layer for sequence processing. Finally, a dense layer with a sigmoid activation function is added for binary classification.
Please note that this is a basic example and you may need to modify it based on your specific NLP task and dataset.