LLoyd relation¶
Na criação de mapas aleatórios, o algoritmo de Lloyd é usado para dar um aspect melhor ao criar o diagrama de voronoi. Também pode ser usado para evitar a sibreposição de pontos.
In [12]:
Copied!
# Criando uma série de pontos
import numpy as np
from scipy.spatial import Voronoi, voronoi_plot_2d
import matplotlib.pyplot as plt
rng = np.random.default_rng(12345) # forma mais moderna de fazer random e seed 12345
points = 256*rng.random((100,2)) # retorna um array de 100 pares de valores. tamanho dos pontos vai até 256
# print(points)
plt.figure(figsize=(9, 5))
plt.plot(points[:, 0], points[:, 1], 'bo')
plt.show()
# Criando uma série de pontos
import numpy as np
from scipy.spatial import Voronoi, voronoi_plot_2d
import matplotlib.pyplot as plt
rng = np.random.default_rng(12345) # forma mais moderna de fazer random e seed 12345
points = 256*rng.random((100,2)) # retorna um array de 100 pares de valores. tamanho dos pontos vai até 256
# print(points)
plt.figure(figsize=(9, 5))
plt.plot(points[:, 0], points[:, 1], 'bo')
plt.show()
In [15]:
Copied!
# Se plotarmos o driagrama de Voronoi teremos o seguinte resultado
vor = Voronoi(points)
fig = voronoi_plot_2d(
vor
, show_vertices=False
, show_points=False
# , line_colors='orange'
# , line_width=2
# , point_size=5
)
fig.set_size_inches(9, 5)
plt.show()
# Se plotarmos o driagrama de Voronoi teremos o seguinte resultado
vor = Voronoi(points)
fig = voronoi_plot_2d(
vor
, show_vertices=False
, show_points=False
# , line_colors='orange'
# , line_width=2
# , point_size=5
)
fig.set_size_inches(9, 5)
plt.show()
In [16]:
Copied!
from lloyd import Field
# build a model we can use to run lloyd relaxation on the data points
field = Field(points)
# plot the initial voronoi map
voronoi_plot_2d(field.voronoi, show_vertices=False, show_points=False)
# run lloyd relaxation several times and plot the result of each iteration
for i in range(5):
# the .relax() method performs lloyd relaxation, which spaces the points apart
field.relax()
# plot the updated points and voronoi map
# if i%2==0:
p = voronoi_plot_2d(field.voronoi, show_vertices=False, show_points=False)
from lloyd import Field
# build a model we can use to run lloyd relaxation on the data points
field = Field(points)
# plot the initial voronoi map
voronoi_plot_2d(field.voronoi, show_vertices=False, show_points=False)
# run lloyd relaxation several times and plot the result of each iteration
for i in range(5):
# the .relax() method performs lloyd relaxation, which spaces the points apart
field.relax()
# plot the updated points and voronoi map
# if i%2==0:
p = voronoi_plot_2d(field.voronoi, show_vertices=False, show_points=False)
Além dos pontos de pontos aleatórios pode ser uma estratégia criar clusters aleatórios que criariam um aspecto mais diferenciado.
In [17]:
Copied!
# Ou usando a a função make_blobs do scikit learn
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
X, y = make_blobs(centers=5, cluster_std=0.8, random_state=1234)
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.title("Three normally-distributed clusters")
plt.show()
# print(X)
# print(y)
# Ou usando a a função make_blobs do scikit learn
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
X, y = make_blobs(centers=5, cluster_std=0.8, random_state=1234)
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.title("Three normally-distributed clusters")
plt.show()
# print(X)
# print(y)
In [18]:
Copied!
vor = Voronoi(X)
fig = voronoi_plot_2d(vor, show_vertices=False, show_points=False)
fig.set_size_inches(10, 5.5)
plt.show()
vor = Voronoi(X)
fig = voronoi_plot_2d(vor, show_vertices=False, show_points=False)
fig.set_size_inches(10, 5.5)
plt.show()
E caso necessário, utilizar o algoritmo de LLoyd para espalhar um pouco mais os clusters.
In [24]:
Copied!
from lloyd import Field
# build a model we can use to run lloyd relaxation on the data points
field = Field(X)
# plot the initial voronoi map
v = field.voronoi
p = voronoi_plot_2d(field.voronoi, show_vertices=False, show_points=False)
# run lloyd relaxation several times and plot the result of each iteration
for i in range(5):
# the .relax() method performs lloyd relaxation, which spaces the points apart
field.relax()
# plot the updated points and voronoi map
if i==0 or i%5==0:
v = field.voronoi
p = voronoi_plot_2d(field.voronoi)
from lloyd import Field
# build a model we can use to run lloyd relaxation on the data points
field = Field(X)
# plot the initial voronoi map
v = field.voronoi
p = voronoi_plot_2d(field.voronoi, show_vertices=False, show_points=False)
# run lloyd relaxation several times and plot the result of each iteration
for i in range(5):
# the .relax() method performs lloyd relaxation, which spaces the points apart
field.relax()
# plot the updated points and voronoi map
if i==0 or i%5==0:
v = field.voronoi
p = voronoi_plot_2d(field.voronoi)
In [26]:
Copied!
# imprimindo os novos pontos
points_ = v.points
plt.figure(figsize=(9.5, 5.5))
plt.plot(points_[:, 0], points_[:, 1], 'bo')
# plt.axis('off')
plt.show()
# imprimindo os novos pontos
points_ = v.points
plt.figure(figsize=(9.5, 5.5))
plt.plot(points_[:, 0], points_[:, 1], 'bo')
# plt.axis('off')
plt.show()
In [27]:
Copied!
from scipy.spatial import ConvexHull, convex_hull_plot_2d
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
fig2, ax2 = plt.subplots(figsize=(9, 5), layout='constrained')
# Create a scatter plot of the original data points
ax2.scatter(points[:, 0], points[:, 1], c=y, cmap='viridis')
ax2.set_title("Convex Hull for Each Cluster")
patches = []
# Find and plot the convex hull for each cluster
for i in range(len(points_)):
# Select the points belonging to the current cluster
points = points_[y == i]
# Ensure there are at least 3 points to form a hull
if len(points) >= 3:
# Compute the convex hull
hull = ConvexHull(points)
# print(hull)
# ax2.plot(points[:, 0], points[:, 1], 'bo')
# for simplex in hull.simplices:
# ax2.plot(points[simplex, 0], points[simplex, 1], 'k-')
# Get the vertices of the hull
hull_vertices = points[hull.vertices]
# To close the polygon, append the first vertex to the end
closed_hull_vertices = np.vstack([hull_vertices, hull_vertices[0]])
# print(closed_hull_vertices)
polygon = Polygon(closed_hull_vertices, closed=True)
patches.append(polygon)
print(polygon)
# Plot the convex hull lines
ax2.plot(closed_hull_vertices[:, 0], closed_hull_vertices[:, 1], 'k-', lw=2)
# Display the plot
plt.show()
from scipy.spatial import ConvexHull, convex_hull_plot_2d
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
fig2, ax2 = plt.subplots(figsize=(9, 5), layout='constrained')
# Create a scatter plot of the original data points
ax2.scatter(points[:, 0], points[:, 1], c=y, cmap='viridis')
ax2.set_title("Convex Hull for Each Cluster")
patches = []
# Find and plot the convex hull for each cluster
for i in range(len(points_)):
# Select the points belonging to the current cluster
points = points_[y == i]
# Ensure there are at least 3 points to form a hull
if len(points) >= 3:
# Compute the convex hull
hull = ConvexHull(points)
# print(hull)
# ax2.plot(points[:, 0], points[:, 1], 'bo')
# for simplex in hull.simplices:
# ax2.plot(points[simplex, 0], points[simplex, 1], 'k-')
# Get the vertices of the hull
hull_vertices = points[hull.vertices]
# To close the polygon, append the first vertex to the end
closed_hull_vertices = np.vstack([hull_vertices, hull_vertices[0]])
# print(closed_hull_vertices)
polygon = Polygon(closed_hull_vertices, closed=True)
patches.append(polygon)
print(polygon)
# Plot the convex hull lines
ax2.plot(closed_hull_vertices[:, 0], closed_hull_vertices[:, 1], 'k-', lw=2)
# Display the plot
plt.show()
Polygon9((-6.48788, -2.23806) ...) Polygon7((-2.53049, 5.36958) ...) Polygon8((4.16828e-10, 4.44023e-10) ...) Polygon6((2.09907, 8.65704) ...) Polygon9((6.7452, 8.3226) ...)
In [35]:
Copied!
print(f"qtd: {len(patches)}")
print(patches[0].get_xy())
print(f"qtd: {len(patches)}")
print(patches[0].get_xy())
qtd: 5 [[-6.48788317 -2.23806443] [-6.48788317 -6.00294709] [-3.54799872 -2.31560696] [-3.3950119 0.41941103] [-4.31072665 3.27721551] [-5.44454074 4.38888743] [-6.15292969 3.66641719] [-6.43420681 1.76750641] [-6.48788317 -2.23806443]]
In [37]:
Copied!
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
def round_polygon_corners(polygon, radius, resolution=20):
"""
Rounds the corners of a matplotlib.patches.Polygon by replacing each
vertex with a circular arc.
Args:
polygon (matplotlib.patches.Polygon): The input polygon.
radius (float): The radius of the rounding arc.
resolution (int): The number of points to use for each arc to control smoothness.
Returns:
np.ndarray: A new array of vertices for the rounded polygon.
"""
vertices = polygon.get_xy()
rounded_vertices = []
num_vertices = len(vertices)
# Ensure the polygon is closed
if not np.array_equal(vertices[0], vertices[-1]):
vertices = np.vstack([vertices, vertices[0]])
for i in range(num_vertices):
# Current vertex and its neighbors
p_prev = vertices[i - 1]
p_current = vertices[i]
p_next = vertices[i + 1]
# Vectors for the incoming and outgoing edges
v_in = p_current - p_prev
v_out = p_next - p_current
# Calculate the distance from the vertex to the arc's center
# This uses the angle between the two edges
v_in_norm = v_in / np.linalg.norm(v_in)
v_out_norm = v_out / np.linalg.norm(v_out)
# Angle between the vectors
dot_product = np.dot(v_in_norm, v_out_norm)
# Clamp value to avoid errors from floating point inaccuracies
angle = np.arccos(np.clip(dot_product, -1.0, 1.0))
# Distance from vertex to arc start/end points
corner_dist = radius / np.tan(angle / 2)
# Check if the corner distance is larger than the edge length
# If so, scale the radius down to prevent overlap
edge_len_prev = np.linalg.norm(v_in)
edge_len_next = np.linalg.norm(v_out)
if corner_dist > edge_len_prev / 2 or corner_dist > edge_len_next / 2:
corner_dist = min(edge_len_prev, edge_len_next) / 2
radius = corner_dist * np.tan(angle / 2)
# Points where the arc begins and ends on the edges
arc_start_point = p_current - v_in_norm * corner_dist
arc_end_point = p_current + v_out_norm * corner_dist
# Add the start point of the arc
rounded_vertices.append(arc_start_point)
# Calculate the center of the arc
angle_bisector = (v_in_norm + v_out_norm) / np.linalg.norm(v_in_norm + v_out_norm)
arc_center = p_current + angle_bisector * (radius / np.sin(angle / 2))
# Calculate the start and end angles of the arc
start_angle = np.arctan2(arc_start_point[1] - arc_center[1], arc_start_point[0] - arc_center[0])
end_angle = np.arctan2(arc_end_point[1] - arc_center[1], arc_end_point[0] - arc_center[0])
# Handle the angle direction for the arc
if start_angle > end_angle:
start_angle -= 2 * np.pi
# Generate points along the arc
angles = np.linspace(start_angle, end_angle, resolution)
arc_points = np.vstack([arc_center[0] + radius * np.cos(angles),
arc_center[1] + radius * np.sin(angles)]).T
# Add the arc points
rounded_vertices.extend(arc_points)
return np.array(rounded_vertices)
# 1. Create a simple polygon (e.g., a square)
original_vertices = np.array([
[0, 0], [1, 0], [1, 1], [0, 1]
])
original_vertices = patches[0].get_xy()
original_polygon = Polygon(original_vertices, closed=True)
# 2. Round the corners of the polygon
# You can adjust the radius to control the rounding amount
new_vertices = round_polygon_corners(original_polygon, radius=0.1)
rounded_polygon = Polygon(new_vertices, closed=True)
# 3. Plot both the original and rounded polygons for comparison
fig, ax = plt.subplots(figsize=(8, 8))
# Plot original polygon (dashed outline)
ax.add_patch(original_polygon)
original_polygon.set_facecolor('none')
original_polygon.set_edgecolor('blue')
original_polygon.set_linestyle('--')
original_polygon.set_label("Original Polygon")
# Plot rounded polygon (solid filled)
ax.add_patch(rounded_polygon)
rounded_polygon.set_facecolor('lightblue')
rounded_polygon.set_edgecolor('blue')
rounded_polygon.set_label("Rounded Polygon")
ax.set_aspect('equal', adjustable='box')
ax.set_title("Polygon with Rounded Corners")
ax.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
def round_polygon_corners(polygon, radius, resolution=20):
"""
Rounds the corners of a matplotlib.patches.Polygon by replacing each
vertex with a circular arc.
Args:
polygon (matplotlib.patches.Polygon): The input polygon.
radius (float): The radius of the rounding arc.
resolution (int): The number of points to use for each arc to control smoothness.
Returns:
np.ndarray: A new array of vertices for the rounded polygon.
"""
vertices = polygon.get_xy()
rounded_vertices = []
num_vertices = len(vertices)
# Ensure the polygon is closed
if not np.array_equal(vertices[0], vertices[-1]):
vertices = np.vstack([vertices, vertices[0]])
for i in range(num_vertices):
# Current vertex and its neighbors
p_prev = vertices[i - 1]
p_current = vertices[i]
p_next = vertices[i + 1]
# Vectors for the incoming and outgoing edges
v_in = p_current - p_prev
v_out = p_next - p_current
# Calculate the distance from the vertex to the arc's center
# This uses the angle between the two edges
v_in_norm = v_in / np.linalg.norm(v_in)
v_out_norm = v_out / np.linalg.norm(v_out)
# Angle between the vectors
dot_product = np.dot(v_in_norm, v_out_norm)
# Clamp value to avoid errors from floating point inaccuracies
angle = np.arccos(np.clip(dot_product, -1.0, 1.0))
# Distance from vertex to arc start/end points
corner_dist = radius / np.tan(angle / 2)
# Check if the corner distance is larger than the edge length
# If so, scale the radius down to prevent overlap
edge_len_prev = np.linalg.norm(v_in)
edge_len_next = np.linalg.norm(v_out)
if corner_dist > edge_len_prev / 2 or corner_dist > edge_len_next / 2:
corner_dist = min(edge_len_prev, edge_len_next) / 2
radius = corner_dist * np.tan(angle / 2)
# Points where the arc begins and ends on the edges
arc_start_point = p_current - v_in_norm * corner_dist
arc_end_point = p_current + v_out_norm * corner_dist
# Add the start point of the arc
rounded_vertices.append(arc_start_point)
# Calculate the center of the arc
angle_bisector = (v_in_norm + v_out_norm) / np.linalg.norm(v_in_norm + v_out_norm)
arc_center = p_current + angle_bisector * (radius / np.sin(angle / 2))
# Calculate the start and end angles of the arc
start_angle = np.arctan2(arc_start_point[1] - arc_center[1], arc_start_point[0] - arc_center[0])
end_angle = np.arctan2(arc_end_point[1] - arc_center[1], arc_end_point[0] - arc_center[0])
# Handle the angle direction for the arc
if start_angle > end_angle:
start_angle -= 2 * np.pi
# Generate points along the arc
angles = np.linspace(start_angle, end_angle, resolution)
arc_points = np.vstack([arc_center[0] + radius * np.cos(angles),
arc_center[1] + radius * np.sin(angles)]).T
# Add the arc points
rounded_vertices.extend(arc_points)
return np.array(rounded_vertices)
# 1. Create a simple polygon (e.g., a square)
original_vertices = np.array([
[0, 0], [1, 0], [1, 1], [0, 1]
])
original_vertices = patches[0].get_xy()
original_polygon = Polygon(original_vertices, closed=True)
# 2. Round the corners of the polygon
# You can adjust the radius to control the rounding amount
new_vertices = round_polygon_corners(original_polygon, radius=0.1)
rounded_polygon = Polygon(new_vertices, closed=True)
# 3. Plot both the original and rounded polygons for comparison
fig, ax = plt.subplots(figsize=(8, 8))
# Plot original polygon (dashed outline)
ax.add_patch(original_polygon)
original_polygon.set_facecolor('none')
original_polygon.set_edgecolor('blue')
original_polygon.set_linestyle('--')
original_polygon.set_label("Original Polygon")
# Plot rounded polygon (solid filled)
ax.add_patch(rounded_polygon)
rounded_polygon.set_facecolor('lightblue')
rounded_polygon.set_edgecolor('blue')
rounded_polygon.set_label("Rounded Polygon")
ax.set_aspect('equal', adjustable='box')
ax.set_title("Polygon with Rounded Corners")
ax.legend()
plt.show()
C:\Users\ulima\AppData\Local\Temp\ipykernel_14528\2282911382.py:39: RuntimeWarning: invalid value encountered in divide v_in_norm = v_in / np.linalg.norm(v_in)
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[37], line 98 94 original_polygon = Polygon(original_vertices, closed=True) 96 # 2. Round the corners of the polygon 97 # You can adjust the radius to control the rounding amount ---> 98 new_vertices = round_polygon_corners(original_polygon, radius=0.1) 99 rounded_polygon = Polygon(new_vertices, closed=True) 101 # 3. Plot both the original and rounded polygons for comparison Cell In[37], line 31, in round_polygon_corners(polygon, radius, resolution) 29 p_prev = vertices[i - 1] 30 p_current = vertices[i] ---> 31 p_next = vertices[i + 1] 33 # Vectors for the incoming and outgoing edges 34 v_in = p_current - p_prev IndexError: index 9 is out of bounds for axis 0 with size 9
In [7]:
Copied!
grupos = y
dados = X
dicionario_agrupado = {}
for i, grupo in enumerate(grupos):
if grupo not in dicionario_agrupado:
dicionario_agrupado[grupo] = []
dicionario_agrupado[grupo].append(dados[i].tolist())
print(dicionario_agrupado)
grupos = y
dados = X
dicionario_agrupado = {}
for i, grupo in enumerate(grupos):
if grupo not in dicionario_agrupado:
dicionario_agrupado[grupo] = []
dicionario_agrupado[grupo].append(dados[i].tolist())
print(dicionario_agrupado)
{np.int64(0): [[-6.014873891245867, 2.8849265495620307], [-5.845248263166001, 2.6734489735806655], [-5.115089749078044, 2.0667311930319174], [-6.436872885068631, 2.4438701125434266], [-6.069840629407581, 2.1839395763100007], [-5.629167724324249, 0.9885536395244798], [-6.487883174982147, 2.712125543687815], [-5.478637159074283, 2.344502160918498], [-6.108651322152364, 1.9890186764246718], [-6.140697443074895, 0.7821933402446137], [-5.496271222025241, 4.354943833167064], [-5.112684438718645, 1.204650978213245], [-6.279046859031232, 2.456806773876013], [-6.157053894730611, 0.6480274574483129], [-5.406951689932209, 0.8251715646406608], [-5.9713772326233165, 1.7244499932448782], [-6.3317280521254995, 1.91739994548549], [-5.2495824126462995, 3.2357322386707796], [-5.331548134107976, 3.2789260252987695], [-6.316097824565353, 3.2893507708535576]], np.int64(2): [[5.23890407986705, -3.948816849611915], [6.144040965881235, -6.002947086660459], [6.002389569665032, -4.319911346521682], [4.974631935475756, -4.922562027417156], [5.216056959515671, -4.787360928720031], [5.816184841437512, -3.4345589395900413], [5.400770518871392, -5.04231321274478], [5.053208965216602, -4.199141810874433], [5.323703350972354, -4.125517378109252], [4.777235715430544, -5.015922463355798], [5.436369869495069, -4.693888223679754], [5.986946652575869, -3.4573626844062506], [5.637173470636638, -4.232272526885404], [6.252791303614343, -4.613705535808499], [4.744325135591963, -4.957652941648619], [6.579175646477009, -5.573034514462401], [6.299896565795529, -5.9167201535707905], [5.663390012782973, -4.868119558904385], [4.237105943085479, -4.2331794150362345], [5.83248045017052, -4.094920937264309]], np.int64(3): [[-5.85899399671438, 7.005750514623996], [-4.041287837215866, 5.4423792563514235], [-3.832766561595767, 5.733594923462482], [-6.138927410834154, 7.581640964672845], [-3.529264937054123, 5.61797466859442], [-3.9676942359074308, 6.186639029718844], [-5.180090379126368, 6.304801895419591], [-6.16961109641241, 5.770641598353786], [-3.8178131104500332, 7.552271124777345], [-4.279070101134948, 6.158424854135944], [-3.9099887124055823, 6.824794007278317], [-5.158449537123459, 6.218231940087389], [-4.849931609238614, 5.992086977507641], [-4.07380055613999, 6.6747194440323465], [-3.959008686583104, 5.267820485176231], [-4.7268780029307695, 5.304484461687152], [-3.9154322669950545, 6.5803472896682695], [-3.3844770906524193, 5.393576571367022], [-4.568097624071522, 7.930058453772416], [-3.9086651179367857, 5.357166533376293]], np.int64(4): [[8.831183198848352, 6.378016908091476], [8.41226498239962, 6.52739544476606], [10.008893620237794, 6.885461647259586], [9.274533692899139, 7.340237509335913], [9.033877547078855, 8.229978690100193], [10.861740584548945, 7.616471442248957], [10.18070313651107, 6.358999407751184], [7.444503043559215, 6.440626684075689], [9.330302903702842, 7.044343891770754], [8.035241681735888, 8.657041457059687], [8.743085196931327, 7.576155126338189], [9.924769749761401, 8.309162760916541], [8.206368080340527, 7.045162316324094], [7.984293942901585, 6.801388202600397], [9.104700422503962, 7.078170355991158], [9.393488551846316, 6.677421544785863], [8.907137953801918, 7.022658224664932], [9.453638719119422, 7.506851005398218], [10.046268329562354, 7.173413082429057], [9.288385774831454, 7.061488413978062]], np.int64(1): [[-0.4184046338133114, 3.7868087672255477], [-0.6820626394879713, 6.125978048590432], [0.379037676813329, 4.793066643057173], [-2.367023845058386, 5.6264371143162535], [-0.6315502312557816, 6.495107547803302], [-0.7928545750076348, 6.943698717975831], [-1.9864486706818916, 7.313446034897785], [-0.9990701356848835, 5.540372663790681], [-1.6840391792071947, 5.591476067579877], [-0.6411140339392025, 5.879386539050939], [-1.8737933892682683, 6.076819464005023], [-0.7398616632104072, 5.738781823630078], [-1.07593851043555, 6.270948173729072], [-0.572638183912598, 4.55052361263994], [-0.873931359816994, 2.8563583457755963], [-0.9622289540983204, 5.678761254052873], [-2.024834286871563, 5.6508957725921025], [-1.0638751863609945, 4.785044386874622], [-0.18856072748154618, 5.829276116039012], [-1.1138215855117921, 5.363095121574195]]}
In [8]:
Copied!
dados_2 = dicionario_agrupado[0]
eixo_x = [i[0] for i in dados_2]
eixo_y = [i[1] for i in dados_2]
plt.figure(figsize=(9, 5))
plt.plot(eixo_x, eixo_y, 'bo')
plt.show
dados_2 = dicionario_agrupado[0]
eixo_x = [i[0] for i in dados_2]
eixo_y = [i[1] for i in dados_2]
plt.figure(figsize=(9, 5))
plt.plot(eixo_x, eixo_y, 'bo')
plt.show
Out[8]:
<function matplotlib.pyplot.show(close=None, block=None)>
In [9]:
Copied!
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from scipy.spatial import ConvexHull
import numpy as np
# Generate the data with 5 clusters
X, y = make_blobs(centers=5, cluster_std=0.8, random_state=1234)
# Create a scatter plot of the original data points
plt.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis')
plt.title("Convex Hull for Each Cluster")
# Find and plot the convex hull for each cluster
for i in range(5):
# Select the points belonging to the current cluster
points = X[y == i]
# Ensure there are at least 3 points to form a hull
if len(points) >= 3:
# Compute the convex hull
hull = ConvexHull(points)
# Get the vertices of the hull
hull_vertices = points[hull.vertices]
# To close the polygon, append the first vertex to the end
closed_hull_vertices = np.vstack([hull_vertices, hull_vertices[0]])
# Plot the convex hull lines
plt.plot(closed_hull_vertices[:, 0], closed_hull_vertices[:, 1], 'k-', lw=2)
# Display the plot
plt.show()
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from scipy.spatial import ConvexHull
import numpy as np
# Generate the data with 5 clusters
X, y = make_blobs(centers=5, cluster_std=0.8, random_state=1234)
# Create a scatter plot of the original data points
plt.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis')
plt.title("Convex Hull for Each Cluster")
# Find and plot the convex hull for each cluster
for i in range(5):
# Select the points belonging to the current cluster
points = X[y == i]
# Ensure there are at least 3 points to form a hull
if len(points) >= 3:
# Compute the convex hull
hull = ConvexHull(points)
# Get the vertices of the hull
hull_vertices = points[hull.vertices]
# To close the polygon, append the first vertex to the end
closed_hull_vertices = np.vstack([hull_vertices, hull_vertices[0]])
# Plot the convex hull lines
plt.plot(closed_hull_vertices[:, 0], closed_hull_vertices[:, 1], 'k-', lw=2)
# Display the plot
plt.show()
In [10]:
Copied!
dados = dicionario_agrupado[0]
plt.scatter(dados[:, 0], dados[:, 1])
plt.title("Three normally-distributed clusters")
plt.show()
dados = dicionario_agrupado[0]
plt.scatter(dados[:, 0], dados[:, 1])
plt.title("Three normally-distributed clusters")
plt.show()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[10], line 2 1 dados = dicionario_agrupado[0] ----> 2 plt.scatter(dados[:, 0], dados[:, 1]) 3 plt.title("Three normally-distributed clusters") 4 plt.show() TypeError: list indices must be integers or slices, not tuple