如何按正负评分可视化Word2Vec的t-SNE降维结果?
How to Plot t-SNE Results Colored by Review Sentiment
Got it, let's fix this up and get your scatter plot sorted! First, a quick note: your current code runs t-SNE on word vectors from your Word2Vec model, but you need to run it on the average Word2Vec vectors of each review (since you want to visualize individual reviews, not words). Let's walk through the full process step by step:
Step 1: Prepare Your Data
First, make sure you have two core pieces of data ready:
avg_w2v_reviews: A list (or numpy array) where each element is the 50-dimensional average Word2Vec vector for one review (you mentioned this is inlist_of_sent—we'll convert it to a numpy array for easier handling)scores: A list/array where each element is the sentiment label for the corresponding review (e.g., 0 for negative, 1 for positive, or strings like "negative"/"positive")
Step 2: Run t-SNE on Review Vectors
Replace your existing t-SNE code with this (targeting review vectors instead of word vectors):
import numpy as np from sklearn.manifold import TSNE # Convert your list of average review vectors to a numpy array avg_w2v_array = np.array(list_of_sent) # Run t-SNE to reduce to 2 dimensions tsne = TSNE(n_components=2, perplexity=30, random_state=42) # Add random_state for reproducibility tsne_data = tsne.fit_transform(avg_w2v_array)
Step 3: Plot the Colored Scatter Plot
We'll use matplotlib for this—super straightforward. We'll map positive reviews to blue and negative to red, then add labels and a legend:
import matplotlib.pyplot as plt # Split t-SNE results by sentiment # Assuming scores are 0 (negative) and 1 (positive) negative_mask = scores == 0 positive_mask = scores == 1 # Plot negative reviews in red, positive in blue plt.figure(figsize=(10, 8)) plt.scatter(tsne_data[negative_mask, 0], tsne_data[negative_mask, 1], c='red', label='Negative Reviews', alpha=0.6) plt.scatter(tsne_data[positive_mask, 0], tsne_data[positive_mask, 1], c='blue', label='Positive Reviews', alpha=0.6) # Add plot details plt.title('t-SNE Visualization of Review Average Word2Vec Vectors') plt.xlabel('t-SNE Component 1') plt.ylabel('t-SNE Component 2') plt.legend() plt.show()
If your scores are strings (e.g., "negative"/"positive")
Adjust the mask lines to:
negative_mask = scores == "negative" positive_mask = scores == "positive"
Quick Notes
- The
alpha=0.6makes points semi-transparent, which helps with overlapping points (common in t-SNE plots) - Adding
random_state=42to TSNE ensures your plot looks the same every time you run the code (reproducibility is key!) - If you haven't already converted your
scorescolumn to a numpy array, you can do that withscores = np.array(your_score_list)
内容的提问来源于stack exchange,提问作者kunwarvikrant
相关产品推荐
相关产品推荐

