Solutions to Problem 5.1:

  1. 1-D Visualization:
from sklearn.manifold import TSNE
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt

# Load the Iris dataset
iris = load_iris()
X = iris.data
y = iris.target

# Create a t-SNE object with 1 component
tsne = TSNE(n_components=1, random_state=42)

# Fit and transform the data
X_tsne = tsne.fit_transform(X)

# Plot the t-SNE 1D visualization
plt.figure(figsize=(8, 6))
colors = ['red', 'green', 'blue']
for i in range(3):
    plt.scatter(X_tsne[y == i], [0] * sum(y == i), color=colors[i], label=iris.target_names[i])
plt.xlabel('t-SNE Component 1')
plt.yticks([])  # Hide the y-axis
plt.title('t-SNE 1D Visualization of Iris Dataset')
plt.legend()
plt.show()
  1. 3-D Visualization:
from sklearn.manifold import TSNE
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Load the Iris dataset
iris = load_iris()
X = iris.data
y = iris.target

# Create a t-SNE object with 3 components
tsne = TSNE(n_components=3, random_state=42)

# Fit and transform the data
X_tsne = tsne.fit_transform(X)

# Plot the t-SNE 3D visualization
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
colors = ['red', 'green', 'blue']
for i in range(3):
    ax.scatter(X_tsne[y == i, 0], X_tsne[y == i, 1], X_tsne[y == i, 2],
               color=colors[i], label=iris.target_names[i])
ax.set_xlabel('t-SNE Component 1')
ax.set_ylabel('t-SNE Component 2')
ax.set_zlabel('t-SNE Component 3')
ax.set_title('t-SNE 3D Visualization of Iris Dataset')
ax.legend()
plt.show()