In the Python programming language, first read from a CSV file containing three columns:
ID
title
content
then read a list of sentences from the 'content' column, and use the small Chinese model in the SpaCy toolkit to process that list, and return the following:
Tokenized sentences
POS tags of each token
dependency trees
NER
Vectors
Display the results as a dataframe using the display() function, and perform PCA on the average vector for each sentence. Use the first two dimensions as axes of a scatter plot.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To accomplish this task, you'll need to install the required libraries (pandas, spaCy, sklearn, and matplotlib) if you haven't already. You can do this by running:
import pandas as pd
import spacy
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
from collections import defaultdict
import numpy as np
# For running in a Jupyter Notebook
from IPython.display import display
Load the Chinese model and create a function to process sentences:
python
# Load the SpaCy Chinese language model ("zh_core_web_sm")
nlp = spacy.load("zh_core_web_sm")
# Processes a single sentence using the SpaCy NLP pipeline.
def process_sentence(sentence):
# Use SpaCy to process input
doc = nlp(sentence)
# Tokenize the sentence into words or characters
tokenized_sentence = [token.text for token in doc]
# Extract part-of-speech tags for each token
pos_tags = [token.pos_ for token in doc]
# Build dependency tree as a list of tuples
dependency_trees = [(token.head.text, token.dep_, token.text) for token in doc]
# Extract named entities with their labels
ner = [(ent.text, ent.label_) for ent in doc.ents]
# Ensure reliability by replacing missing vectors with zero vectors to avoid calculation errors
vectors = [token.vector if token.has_vector else np.zeros(nlp.vocab.vectors_length) for token in doc]
return tokenized_sentence, pos_tags, dependency_trees, ner, vectors
Read the CSV file and process the 'content' column as a list of sentences:
python
df = pd.read_csv("your_file.csv")
# Extract the "content" column from the DataFrame as a list of sentences.
sentences = df["content"].tolist()
Process the sentences and store the results in a new DataFrame:
python
# Process each sentence and collect the results
results = []
for sentence in sentences:
# Use the process_sentence function to analyze the sentence
tokenized_sentence, pos_tags, dependency_trees, ner, vectors = process_sentence(sentence)
results.append({
"Tokenized Sentence": tokenized_sentence,
"POS Tags": pos_tags,
"Dependency Trees": dependency_trees,
"NER": ner,
"Vectors": vectors
})
# Convert the results into a DataFrame
result_df = pd.DataFrame(results)
Perform PCA on the average vector for each sentence to reduce the dimensionality of the sentence embeddings, and create a scatter plot. PCA helps reduce the dimensionality of the sentence-level vectors. PCA simplifies complex data by identifying the main patterns (principal components) that capture most information. This makes visualizing relationships and clusters between sentences in a two-dimensional scatter plot easier.
python
# Perform PCA
average_vectors = np.array([np.mean(row["Vectors"], axis=0) for _, row in result_df.iterrows()])
# Apply PCA to reduce the dimensionality to 2 components
pca = PCA(n_components=2)
pca_result = pca.fit_transform(average_vectors)
# Plot the PCA results to visualize the distribution of sentence embeddings
plt.figure(figsize=(8, 6))
plt.scatter(pca_result[:, 0], pca_result[:, 1])
plt.xlabel("First Principal Component")
plt.ylabel("Second Principal Component")
plt.show()
Display the results:
python
# DataFrame with all the processed results
display(result_df)