基于Keras实现多变量预测:利用情感值预测价格
Hey there! Let's walk through how to build your Price prediction model with Keras using your sentiment-dependent dataset.
Dataset Overview
You’ve got a 3-column dataset where Price movement is directly tied to Sentiment (positive sentiment pushes prices up, negative sentiment pulls them down):
| Date | Price | Sentiment |
|---|---|---|
| Date 1 | Price 1 | S1 |
| Date 2 | Price 2 | S2 |
| Date 3 | Price 3 | S3 |
Step 1: Data Preprocessing
First, we need to get the data ready for Keras. Here’s what to tackle:
- Convert categorical
Sentimentvalues to numerical format (e.g., map "positive" to 1, "negative" to -1, "neutral" to 0). - Split your data into training and test sets (standard 80-20 split works well).
- Reshape inputs to fit Keras’ expected 2D array format:
(number_of_samples, number_of_features).
Sample preprocessing code:
import pandas as pd from sklearn.model_selection import train_test_split # Load your dataset df = pd.read_csv("your_dataset.csv") # Encode sentiment (adjust mapping to match your actual sentiment labels) sentiment_mapping = {"positive": 1, "negative": -1, "neutral": 0} df["Sentiment"] = df["Sentiment"].map(sentiment_mapping) # Define input features (X) and target variable (y) X = df[["Sentiment"]].values y = df["Price"].values # Split into training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
Step 2: Build the Keras Model
Since Price depends directly on Sentiment, a simple feedforward neural network is a great starting point. We’ll use dense layers to capture the relationship:
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense # Initialize the sequential model model = Sequential() # Input layer + first hidden layer (1 input feature = Sentiment) model.add(Dense(16, activation='relu', input_shape=(1,))) # Second hidden layer to capture complex patterns model.add(Dense(8, activation='relu')) # Output layer (predicting continuous Price, so no activation function) model.add(Dense(1)) # Compile the model: use Adam optimizer and MSE loss for regression tasks model.compile(optimizer='adam', loss='mean_squared_error')
Step 3: Train the Model
Now let’s train the model on our preprocessed data:
# Train the model with validation split to monitor overfitting history = model.fit( X_train, y_train, epochs=50, batch_size=4, validation_split=0.1 )
Step 4: Evaluate and Predict
After training, check performance on the test set and generate predictions:
# Evaluate model on test data test_loss = model.evaluate(X_test, y_test) print(f"Test Set MSE Loss: {test_loss}") # Generate price predictions for test data predictions = model.predict(X_test)
Quick Tips to Boost Performance
- If your Sentiment values are already continuous (not categorical), skip the encoding step and use raw values directly.
- Add temporal features from the
Datecolumn (e.g., day of week, month) if price has time-based patterns. - Adjust the number of neurons/layers or try different activation functions if the model is underfitting/overfitting.
内容的提问来源于stack exchange,提问作者Nidhin Radh

