Here's a Python script that extracts 10 numerical features for each feedstock, making it as comprehensive as possible. The features include text-based statistics, part-of-speech counts, and principal components from both word embeddings and TF-IDF vectors.
# Import necessary libraries
import pandas as pd
import numpy as np
import gensim.downloader as api
from sklearn.decomposition import PCA
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.tokenize import word_tokenize
from nltk import pos_tag
import nltk
# Download NLTK data files (only need to do this once)
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
# Step 1: Load the Feedstock Data from the Excel File
# Update the file_path with the actual path to your Excel file
file_path = 'Prices.xlsx' # Update with your file path
# Load data from the 'Feedstocks' sheet
feedstocks_df = pd.read_excel(file_path, sheet_name='Feedstocks', header=None)
# Splitting data columns using a special character as a delimiter (EM SPACE)
feedstocks_df = feedstocks_df[0].str.split(" ", expand=True)
# Renaming the columns for easier handling
feedstocks_df.columns = ['Feedstock Name', 'Estimated Price per Ton (£)']
# Dropping rows with NaN and cleaning up data further
feedstocks_df = feedstocks_df.dropna()
# Convert the 'Estimated Price per Ton (£)' column to numeric
feedstocks_df['Estimated Price per Ton (£)'] = pd.to_numeric(
feedstocks_df['Estimated Price per Ton (£)'], errors='coerce'
)
# Display the first few rows
print("Feedstock Data:")
print(feedstocks_df.head())
# Step 2: Text Preprocessing and Feature Extraction
def extract_text_features(text):
"""
Extracts various text features from the feedstock name.
Returns a dictionary of features.
"""
# Tokenize the text
tokens = word_tokenize(text.lower())
num_words = len(tokens)
avg_word_length = np.mean([len(token) for token in tokens]) if tokens else 0
# Part-of-speech tagging
pos_tags = pos_tag(tokens)
num_nouns = sum(1 for word, pos in pos_tags if pos.startswith('NN'))
num_verbs = sum(1 for word, pos in pos_tags if pos.startswith('VB'))
num_adjectives = sum(1 for word, pos in pos_tags if pos.startswith('JJ'))
num_adverbs = sum(1 for word, pos in pos_tags if pos.startswith('RB'))
features = {
'Num_Words': num_words,
'Avg_Word_Length': avg_word_length,
'Num_Nouns': num_nouns,
'Num_Verbs': num_verbs,
'Num_Adjectives': num_adjectives,
'Num_Adverbs': num_adverbs
}
return features
# Apply the text feature extraction to each feedstock name
print("\nExtracting text-based features...")
text_features = feedstocks_df['Feedstock Name'].apply(extract_text_features)
text_features_df = pd.DataFrame(list(text_features))
# Step 3: Load Pre-trained Word Embeddings
print("\nLoading pre-trained word embeddings...")
# Load GloVe embeddings
glove_model = api.load('glove-wiki-gigaword-300')
# Step 4: Compute Embeddings for Each Feedstock
def get_feedstock_embedding(feedstock_name, model):
"""
Compute the embedding for a feedstock name by averaging the embeddings of its constituent words.
"""
words = feedstock_name.lower().split()
embeddings = []
for word in words:
try:
embeddings.append(model[word])
except KeyError:
# If the word is not in the vocabulary, skip it
pass
if embeddings:
feedstock_embedding = np.mean(embeddings, axis=0)
else:
# If all words are out-of-vocabulary, use a zero vector
feedstock_embedding = np.zeros(model.vector_size)
return feedstock_embedding
# Compute embeddings for all feedstocks
print("\nComputing embeddings for each feedstock...")
embeddings = []
for name in feedstocks_df['Feedstock Name']:
embedding = get_feedstock_embedding(name, glove_model)
embeddings.append(embedding)
# Convert the list of embeddings to a NumPy array
embedding_matrix = np.array(embeddings)
# Step 5: Apply PCA to Reduce Dimensionality of Embeddings
print("\nApplying PCA to reduce dimensionality of embeddings...")
embedding_pca = PCA(n_components=5)
embedding_pca_scores = embedding_pca.fit_transform(embedding_matrix)
embedding_pcs_df = pd.DataFrame(
embedding_pca_scores, columns=[f'Embedding_PC{i+1}' for i in range(5)]
)
# Step 6: TF-IDF Features
print("\nComputing TF-IDF features...")
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(feedstocks_df['Feedstock Name'])
# Apply PCA to TF-IDF features to reduce to 5 components
tfidf_pca = PCA(n_components=5)
tfidf_pca_scores = tfidf_pca.fit_transform(tfidf_matrix.toarray())
tfidf_pcs_df = pd.DataFrame(
tfidf_pca_scores, columns=[f'TFIDF_PC{i+1}' for i in range(5)]
)
# Step 7: Combine All Features
print("\nCombining all features...")
# Concatenate all features into a single DataFrame
features_df = pd.concat(
[feedstocks_df.reset_index(drop=True), text_features_df, embedding_pcs_df, tfidf_pcs_df],
axis=1
)
# Select only the required features (10 numerical features)
numerical_features = [
'Num_Words',
'Avg_Word_Length',
'Num_Nouns',
'Num_Verbs',
'Num_Adjectives',
'Num_Adverbs',
'Embedding_PC1',
'Embedding_PC2',
'TFIDF_PC1',
'TFIDF_PC2'
]
# Final DataFrame with selected features
final_df = features_df[['Feedstock Name', 'Estimated Price per Ton (£)'] + numerical_features]
# Display the final DataFrame
print("\nFinal Data with Extracted Features:")
print(final_df.head())
# Save the DataFrame to a CSV file (optional)
final_df.to_csv('feedstock_with_numerical_features.csv', index=False)
Explanation of the Features Extracted:
- Num_Words: The number of words in the feedstock name.
- Avg_Word_Length: The average length of the words in the feedstock name.
- Num_Nouns: The number of nouns identified in the feedstock name.
- Num_Verbs: The number of verbs identified in the feedstock name.
- Num_Adjectives: The number of adjectives identified in the feedstock name.
- Num_Adverbs: The number of adverbs identified in the feedstock name.
- Embedding_PC1 & Embedding_PC2: The first two principal components from PCA applied to the GloVe word embeddings of the feedstock names.
- TFIDF_PC1 & TFIDF_PC2: The first two principal components from PCA applied to the TF-IDF vectors of the feedstock names.
Steps Overview:
- Data Loading: Reads the feedstock names and their estimated prices from an Excel file.
- Text Feature Extraction: Uses NLTK to tokenize the feedstock names and extract linguistic features.
- Word Embeddings: Loads pre-trained GloVe embeddings and computes the average embedding for each feedstock name.
- Dimensionality Reduction: Applies PCA to both the word embeddings and TF-IDF features to reduce their dimensionality.
- Feature Combination: Combines all extracted features into a single DataFrame, selecting the top 10 numerical features.
- Output: Displays the final DataFrame and optionally saves it to a CSV file.
Additional Notes:
- NLTK Data Download: The script downloads the necessary NLTK data files for tokenization and POS tagging. This only needs to be done once.
- Pre-trained Embeddings: The GloVe embeddings are used instead of FastText in this example for variety. You can switch back to FastText or use another model if preferred.
- PCA Components: The number of components for PCA is set to 5 for embeddings and TF-IDF features to capture more variance. We then select the first two components from each for our feature set.
Requirements:
Ensure you have the following Python packages installed:
- pandas
- numpy
- gensim
- scikit-learn
- nltk
You can install any missing packages using pip:
pip install pandas numpy gensim scikit-learn nltk
Running the Script:
- Update the
file_path variable with the path to your 'Prices.xlsx' Excel file.
- Run the script in an environment where you have the necessary permissions to download data and install packages.
- The script will print progress messages and display the first few rows of the final DataFrame.
- The final DataFrame is also saved as 'feedstock_with_numerical_features.csv' in the current directory.
Example Output:
Feedstock Data:
Feedstock Name Estimated Price per Ton (£)
0 Straw Bales 40
1 Woodchip 80
2 Miscanthus Pellets 60
3 Agricultural Residues 50
4 Switchgrass 55
Extracting text-based features...
Loading pre-trained word embeddings...
Computing embeddings for each feedstock...
Applying PCA to reduce dimensionality of embeddings...
Computing TF-IDF features...
Combining all features...
Final Data with Extracted Features:
Feedstock Name ... TFIDF_PC2
0 Straw Bales ... 0.083176
1 Woodchip ... -0.049669
2 Miscanthus Pellets ... -0.037964
3 Agricultural Residues ... -0.068895
4 Switchgrass ... 0.073351
[5 rows x 12 columns]
This script provides a comprehensive extraction of numerical features from feedstock names, combining linguistic analysis with advanced vector representations.