Module contents
Lesson 15 of 33Core 110 min

Point clouds: registration, ICP and learning on sets

LiDAR and depth cameras produce unordered point sets rather than grids. Learn backprojection, voxel downsampling, local PCA normals, Kabsch alignment, point-to-point and point-to-plane ICP, PointNet and PointNet++.

After this lesson you can

  • Backproject a depth map into a point cloud and estimate normals using local PCA.
  • Derive Kabsch's optimal rigid alignment using SVD, including reflection correction.
  • Implement point-to-point and point-to-plane ICP and compare convergence and attraction basins.
  • Explain PointNet's permutation invariance and limitations for local structure.
  • Train PointNet and PointNet++ for classification and segmentation on a local GPU.

Before you start

A surface without a grid

Two scans of a room do not match point by point. LiDAR observes different surfaces from each position, and density depends on distance and occlusion. Combining them requires estimating a transformation between coordinate frames, rather than sorting points and subtracting rows.

A depth camera returns Z(u,v)Z(u,v) along the optical axis. With the pinhole model, without distortion and with zero skew, pixel p~=(u,v,1)⊤\tilde{\vb{p}}=(u,v,1)\T gives X=ZK−1p~\vb{X}=Z\mat{K}\inv\tilde{\vb{p}}. If the sensor returns Euclidean distance to the center instead of axial depth, first normalize the ray. Discard invalid depths. For example, fx=fy=500f_x=f_y=500, (cx,cy)=(320,240)(c_x,c_y)=(320,240) and Z=2Z=2 at (400,300)(400,300) yield (0.32,0.24,2)(0.32,0.24,2) meters.

To make a cloud manageable, a voxel of side length hh groups points with the same key ⌊p/h⌋\lfloor\vb{p}/h\rfloor and is represented by their centroid. Changing hh changes geometric detail and the weighting of dense regions. Statistical outlier removal based on distance to neighbors can also remove real, sparsely sampled details; inspect the distribution and do not treat an arbitrary threshold as ground truth.

Local normals

Normal estimation by local PCA fits a plane to a neighborhood. Center neighbors qj\vb{q}_j at their mean qˉ\bar{\vb{q}} and compute C=1k∑j(qj−qˉ)(qj−qˉ)⊤\mat{C}=\frac1k\sum_j(\vb{q}_j-\bar{\vb{q}})(\vb{q}_j-\bar{\vb{q}})\T. The eigenvector corresponding to the smallest eigenvalue minimizes the sum of squared distances to the plane with a unit normal. This is principal component analysis applied locally.

The normal’s sign is ambiguous: n\vb{n} and −n-\vb{n} define the same plane. If the sensor origin o\vb{o} is known, choose the sign using n⊤(o−p)≥0\vb{n}\T(\vb{o}-\vb{p})\ge0. This orients it toward that sensor, not necessarily consistently across the scene. A very small neighborhood is sensitive to noise; a large one mixes faces at edges. For linear surfaces or nearly isotropic neighborhoods the normal is poorly defined.

Known correspondences: Kabsch

Kabsch alignment solves min⁡R∈SO(3),t∑i∥Rpi+t−qi∥2\min_{\mat{R}\in SO(3),\vb{t}}\sum_i\norm{\mat{R}\vb{p}_i+\vb{t}-\vb{q}_i}^2 for known pairs. Centering both clouds removes the translation: t=qˉ−Rpˉ\vb{t}=\bar{\vb{q}}-\mat{R}\bar{\vb{p}}. If H=∑i(pi−pˉ)(qi−qˉ)⊤=UΣV⊤\mat{H}=\sum_i(\vb{p}_i-\bar{\vb{p}})(\vb{q}_i-\bar{\vb{q}})\T=\mat{U}\mat{\Sigma}\mat{V}\T, one solution is

R=Vdiag⁡(1,1,det⁡(VU⊤))U⊤.\mat{R}=\mat{V}\diag(1,1,\det(\mat{V}\mat{U}\T))\mat{U}\T.

The proof expands the centered error: the norm terms do not depend on R\mat{R}, and we maximize tr⁡(RH)\tr(\mat{R}\mat{H}). Write Q=V⊤RU\mat{Q}=\mat{V}\T\mat{R}\mat{U}. Then maximize tr⁡(QΣ)\tr(\mat{Q}\mat{\Sigma}) over orthogonal matrices with the determinant imposed by R∈SO(3)\mat{R}\in SO(3). Singular values are ordered from largest to smallest; if a sign change is needed to avoid a reflection, sacrifice the smallest. The SVD gives U,Σ,V\mat{U},\mat{\Sigma},\mat{V}, and the positive determinant ensures a proper rotation. The solution may not be unique in degenerate configurations.

Proof

To complete the argument, write S=(Q+Q⊤)/2\mat{S}=(\mat{Q}+\mat{Q}\T)/2. Since Q\mat{Q} is orthogonal, its eigenvalues have unit modulus and I−S\mat{I}-\mat{S} is positive semidefinite. Also, tr⁡(QΣ)=tr⁡(SΣ)\tr(\mat{Q}\mat{\Sigma})=\tr(\mat{S}\mat{\Sigma}). If det⁡Q=1\det\mat{Q}=1, each diagonal entry of Q\mat{Q} is at most one, and the trace does not exceed σ1+σ2+σ3\sigma_1+\sigma_2+\sigma_3; Q=I\mat{Q}=\mat{I} attains the bound.

If det⁡Q=−1\det\mat{Q}=-1, a real orthogonal matrix of odd dimension has a unit eigenvector v\vb{v} with eigenvalue −1-1. The matrix I−S\mat{I}-\mat{S} has eigenvalue 2 along v\vb{v} and its other eigenvalues are nonnegative. Thus,

tr⁡(Σ(I−S))≥2v⊤Σv≥2σ3.\tr\big(\mat{\Sigma}(\mat{I}-\mat{S})\big)\ge 2\vb{v}\T\mat{\Sigma}\vb{v}\ge 2\sigma_3.

Hence tr⁡(QΣ)≤σ1+σ2−σ3\tr(\mat{Q}\mat{\Sigma})\le\sigma_1+\sigma_2-\sigma_3, a bound attained by Q=diag⁡(1,1,−1)\mat{Q}=\diag(1,1,-1). Substituting R=VQU⊤\mat{R}=\mat{V}\mat{Q}\mat{U}\T gives the determinant formula. If some singular values repeat or vanish, other solutions may attain the same bound.

∎
InteractiveThe fit that creates a mirror image
  • Target
  • Fitted points
  • Residual
0.08
Constraint
Determinant1.00
RMS error per pair0.1788
The target is a synthetic reflection of nearly planar points plus a translation, with known correspondences. Compare the unconstrained orthogonal solution with the best proper rotation. Increase the thickness: the reflection fits, but it is not an allowed rigid motion in SO(3). The values were computed with the described model's SVD.

ICP: unknown correspondences

Point-to-point ICP (iterative closest point) alternates between assigning each transformed point its nearest neighbor in the target cloud and fitting a rigid transformation to those pairs. The assignment depends on the current pose. Without rejection or resampling, each exact step does not increase the nearest-neighbor objective, but this only guarantees descent toward a local optimum, not physical correspondence or the global minimum. The paper by Besl and McKay proposes ICP for shape registration.

Point-to-plane ICP minimizes residuals ri=ni⊤(Rpi+t−qi)r_i=\vb{n}_i\T(\mat{R}\vb{p}_i+\vb{t}-\vb{q}_i) using target normals. For a small left-applied increment, δω×xi+δv\delta\vb{\omega}\times\vb{x}_i+\delta\vb{v}, the Jacobian row is [(xi×ni)⊤ ni⊤][(\vb{x}_i\times\vb{n}_i)\T\ \vb{n}_i\T]. Solve least squares for the increment and compose in SE(3)SE(3), as in the retraction. With a single infinite plane, tangential displacements and rotation around the normal are unobservable: fast residual convergence does not mean recovering the whole pose. The Open3D documentation compares both objectives.

InteractiveAn attraction basin for each objective
  • Target
  • Transformed source
  • Assigned neighbor
60
Objective
iteration 0
Residual angle60.0°
Neighbor RMS0.184
The target cloud is a sample of 120 points from the Open3D Bunny mesh, with seed 42, centered and scaled to a maximum radius of one. The source is the same sample rotated around Y and translated; fitting uses nearest neighbors and 15 iterations. Change the initialization and objective: results are from that specific run, not a universal ICP threshold.

Reject pairs that are too far apart or whose normals are incompatible, and initialize with global registration or a prior pose. Rejection changes the effective objective, so the simple monotonicity above is no longer guaranteed. Partial overlap, symmetries, and uneven density produce misleading minima. Evaluate the transformation against known ground truth when available and record coverage and residuals, not just a final number.

The difference between the objectives is visible on a smooth surface: the nearest neighbor can slide tangentially when the pose changes. Point-to-point penalizes that sliding for a particular sample; point-to-plane first estimates normal displacement of the surface and can approach the solution faster when initialization is good. But a plane does not contain information for every degree of freedom. Small singular values of the linear system’s normal matrix reveal this problem: even a tiny residual can coexist with an uncertain pose. Use geometry in several orientations or add another measurement to constrain it.

Learning on sets

PointNet applies the same MLP hh to each point and aggregates with a maximum per channel. If π\pi permutes the indices, max⁡ih(xπ(i))=max⁡ih(xi)\max_i h(\vb{x}_{\pi(i)})=\max_i h(\vb{x}_i), so any subsequent head γ\gamma preserves invariance. For segmentation, it concatenates per-point features with the global description and predicts a label for each: permuting the input permutes the per-point output in the same way, a property called equivariance.

In PointNet, points attaining any maximum are critical to that cloud’s representation. Removing a point that attains no maximum leaves the global vector intact if there are no operations between points before the maximum. This does not guarantee robustness to removing critical points, moving points, or introducing new maxima. The approximation theorem considers sets of exactly nn points in [0,1]m[0,1]^m and scalar functions continuous with respect to Hausdorff distance: for every positive tolerance, continuous functions and a sufficiently wide channelwise maximum exist that uniformly approximate the function. This is an existence statement under those assumptions, not a guarantee that a particular finite network learns any function from finite data.

InteractiveWhich points support the maximum
  • Critical
  • Noncritical retained
0
Critical points26
Points retained256
Predicted classbed
The cloud comes from the ModelNet10 test set. A compact PointNet trained for three epochs on the training set produced the displayed class and 26 points that win at least one channel. Remove only the others: the output remains because the maxima do not change. This does not imply robustness to removing critical points.

For that cloud, evaluating the model before and after removing all noncritical points produced a maximum logit difference of 2.38×10−72.38\times10^{-7}, consistent with floating-point precision. The figure uses the first correctly classified example among the first 64 test examples; this is not a random performance sample. The data come from that run, not an invented rule for coloring points. The training and test subsets are those published for ModelNet10.

PointNet++ hierarchically applies set modules to neighborhoods in a metric space. It samples centers, groups neighbors, and extracts a local feature aggregated at the next scale. Grouping introduces local structure that an isolated global maximum does not explicitly represent. Radius, density, and maximum neighbor count matter; PointNet++ also addresses varying densities. Normalize training and test using the same rule, without joint statistics that leak information from the test set.

Farthest point sampling successively chooses the point whose distance to the set of chosen centers is greatest. It covers space better than taking the first rows, but has a cost and depends on the first center and tie breaking. A fixed radius captures a defined geometric scale, whereas the kk nearest neighbors guarantee a number of points but change spatial extent as density changes. The compact variant below uses kk neighbors; do not attribute every property of the original hierarchical architecture to it.

For context, table 1 of the PointNet paper reports 89.2% overall accuracy on ModelNet40, with 1024 points sampled per surface and augmentation during training. That published number is not our lab result: we use ModelNet10, 256 points, a smaller architecture, and three epochs. The paper also uses ShapeNetPart for segmentation with 16 categories and 50 part labels and evaluates instance mIoU; the per-point accuracy calculated below answers a different question.

Implementing registration

The following functions use rows for points and column vectors in the equations. Matrix R acts as P @ R.T + t. For exact correspondences, Kabsch is checked with a known rotation; the next step uses nearby neighbors.

[ ]Backprojection, voxels, and normalsBrowser
import numpy as np
from scipy.spatial import cKDTree

def backproject(depth, fx, fy, cx, cy):
    v, u = np.indices(depth.shape)
    mask = np.isfinite(depth) & (depth > 0)
    z = depth[mask]
    return np.column_stack(((u[mask]-cx)*z/fx, (v[mask]-cy)*z/fy, z))

def voxel_mean(points, size):
    if size <= 0: raise ValueError('El lado del vóxel debe ser positivo')
    key = np.floor(points / size).astype(np.int64)
    _, inv, count = np.unique(key, axis=0, return_inverse=True, return_counts=True)
    sums = np.zeros((len(count), 3))
    np.add.at(sums, inv, points)
    return sums / count[:,None]

def normals(points, k=12, origin=None):
    _, ids = cKDTree(points).query(points, k=k)
    result = []
    for p, neighbors in zip(points, ids):
        q = points[neighbors]
        q = q - q.mean(axis=0)
        _, V = np.linalg.eigh(q.T @ q)
        n = V[:,0]
        if origin is not None and n @ (origin-p) < 0: n = -n
        result.append(n)
    return np.array(result)

def kabsch(P, Q):
    p, q = P.mean(axis=0), Q.mean(axis=0)
    U, _, Vt = np.linalg.svd((P-p).T @ (Q-q))
    D = np.diag([1., 1., np.linalg.det(Vt.T @ U.T)])
    R = Vt.T @ D @ U.T
    return R, q - R @ p

depth = np.zeros((301,401))
depth[300,400] = 2
print('punto retroproyectado:', backproject(depth,500,500,320,240)[0])
rng = np.random.default_rng(42)
P = rng.normal(size=(60,3))
a = 0.3
R_true = np.array([[np.cos(a),-np.sin(a),0],[np.sin(a),np.cos(a),0],[0,0,1]])
t_true = np.array([0.2,-0.1,0.3])
Q = P @ R_true.T + t_true
R_fit, t_fit = kabsch(P,Q)
print('error de R:', np.linalg.norm(R_fit-R_true), 'error de t:', np.linalg.norm(t_fit-t_true))
grid = np.array([[x,y,0.] for x in np.linspace(-1,1,9) for y in np.linspace(-1,1,9)])
estimated = normals(grid,k=12,origin=np.array([0.,0.,2.]))
print('mínimo producto con normal verdadera:', round(float(estimated[:,2].min()), 6))
print('puntos tras vóxeles de lado 0.5:', len(voxel_mean(grid,0.5)))

The following algorithm reassociates neighbors after each transformation. The point-to-plane solution linearizes rotation: to apply a finite increment it uses Rodrigues rather than treating I+[δω]×\mat{I}+[\delta\vb{\omega}]_\times as an exact rotation. The matrix may be rank deficient, so least squares is used and its rank is reported. This educational version does not include robust rejection or global registration.

[ ]Point-to-point and point-to-plane ICPBrowser
def rodrigues(w):
    a = np.linalg.norm(w)
    W = np.array([[0.,-w[2],w[1]],[w[2],0.,-w[0]],[-w[1],w[0],0.]])
    if a < 1e-12: return np.eye(3)+W
    return np.eye(3) + np.sin(a)/a*W + (1-np.cos(a))/(a*a)*(W@W)

def icp(P, Q, R0, t0, iterations=20, normal_dest=None):
    R, t = R0.copy(), t0.copy()
    tree = cKDTree(Q)
    history = []
    for _ in range(iterations):
        X = P @ R.T + t
        dist, ix = tree.query(X)
        target = Q[ix]
        if normal_dest is None:
            dR, dt = kabsch(X, target)
            rank = None
        else:
            n = normal_dest[ix]
            A = np.column_stack((np.cross(X,n), n))
            residual = np.sum(n*(X-target), axis=1)
            step, _, rank, _ = np.linalg.lstsq(A, -residual, rcond=None)
            dR, dt = rodrigues(step[:3]), step[3:]
        R, t = dR @ R, dR @ t + dt
        history.append((float(np.mean(dist**2)), rank))
    return R, t, history

def rotation_error(R, truth):
    c = np.clip((np.trace(R @ truth.T)-1)/2, -1, 1)
    return np.degrees(np.arccos(c))

g = np.random.default_rng(7)
x, y = g.uniform(-1,1,(2,400))
P = np.column_stack((x, y, 0.3*x*x+0.15*y*y+0.1*x*y))
a = 0.08
R_true = np.array([[np.cos(a),-np.sin(a),0],[np.sin(a),np.cos(a),0],[0,0,1]])
t_true = np.array([0.04,-0.03,0.02])
Q = P @ R_true.T + t_true
N = normals(Q, k=20, origin=np.array([0.,0.,3.]))
for method, normal in [('punto a punto', None), ('punto a plano', N)]:
    R_est, t_est, hist = icp(P,Q,np.eye(3),np.zeros(3),30,normal)
    print(method, 'error angular (grados):', round(rotation_error(R_est,R_true),4),
          'error de traslación:', round(float(np.linalg.norm(t_est-t_true)),6), 'rango:', hist[-1][1])
[ ]Sensitivity to initial poseBrowser
for initial_deg in (0, 15, 30, 60):
    angle = np.radians(initial_deg)
    R0 = np.array([[np.cos(angle),-np.sin(angle),0],[np.sin(angle),np.cos(angle),0],[0,0,1]])
    for method, normal in [('punto',None),('plano',N)]:
        r, t, history = icp(P,Q,R0,np.zeros(3),30,normal)
        print(initial_deg, method, 'error angular:',round(rotation_error(r,R_true),2),
              'error traslación:',round(float(np.linalg.norm(t-t_true)),3))

These errors use the synthetic scene’s true pose, which is unknown in an unfamiliar scan. Comparing only distance to the neighbor can hide incorrect registration. The attraction basin depends on shape, overlap, point distribution, threshold, and method; there is no universal maximum angle.

For this surface and 30 iterations, initialization at 60 degrees leaves a 70.57-degree angular error for point-to-point, while point-to-plane reaches an error rounded to 0.00 degrees. With initializations of 0, 15 and 30 degrees, both reach an error rounded to 0.00 degrees here. This is one noiseless example with full overlap, not evidence that point-to-plane always wins. The bunny sequence uses different geometry and mesh normals, so the same basin should not be expected.

The library version below runs the same test from scratch in local Python. Unlike the educational implementation above, Open3D uses a distance threshold to reject pairs and estimates normals in the target cloud. Compare transformations and coverage rather than expecting an exact match at every iteration.

[ ]Registration and preprocessing with Open3DLocal GPU
import numpy as np
import open3d as o3d
g = np.random.default_rng(7)
x, y = g.uniform(-1,1,(2,400))
P_local = np.column_stack((x,y,0.3*x*x+0.15*y*y+0.1*x*y))
a = 0.08
R_true_local = np.array([[np.cos(a),-np.sin(a),0],[np.sin(a),np.cos(a),0],[0,0,1]])
t_true_local = np.array([0.04,-0.03,0.02])
Q_local = P_local @ R_true_local.T + t_true_local
src, dst = o3d.geometry.PointCloud(), o3d.geometry.PointCloud()
src.points = o3d.utility.Vector3dVector(P_local)
dst.points = o3d.utility.Vector3dVector(Q_local)
dst.estimate_normals(o3d.geometry.KDTreeSearchParamKNN(knn=20))
print('vóxeles del destino:', len(dst.voxel_down_sample(0.1).points))
for name, est in [('punto a punto',o3d.pipelines.registration.TransformationEstimationPointToPoint()),
                  ('punto a plano',o3d.pipelines.registration.TransformationEstimationPointToPlane())]:
    result = o3d.pipelines.registration.registration_icp(src,dst,0.5,np.eye(4),est,
        o3d.pipelines.registration.ICPConvergenceCriteria(max_iteration=30))
    R = result.transformation[:3,:3]; t = result.transformation[:3,3]
    angle = np.degrees(np.arccos(np.clip((np.trace(R@R_true_local.T)-1)/2,-1,1)))
    print(name,'error angular:',round(float(angle),4),'error de traslación:',round(float(np.linalg.norm(t-t_true_local)),6),'cobertura:',round(result.fitness,3))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local lab: classification with ModelNet10

ModelNet10 includes CAD meshes, category labels, and training and test splits, not part labels. It is therefore useful here for classification; it cannot evaluate supervised segmentation without another annotated dataset. Download the official archive and extract it into a local ModelNet10 folder. You need Open3D, NumPy, and PyTorch, with an optional GPU. Preparation processes the complete meshes and may take time: it is excluded from automatic execution because it requires downloaded data. Each mesh is sampled on its surface, centered, and divided by its maximum radius using the same rule in both splits. The seed makes sampling reproducible in the Open3D version used.

[ ]Preparing ModelNet10 cloudsLocal GPU
from pathlib import Path
import numpy as np
import open3d as o3d

root = Path('ModelNet10')
classes = sorted(p.name for p in root.iterdir() if p.is_dir())
if len(classes) != 10:
    raise ValueError('Se esperaba la carpeta ModelNet10 con diez categorías')
o3d.utility.random.seed(42)
for split in ('train','test'):
    clouds, labels, failed = [], [], []
    for label, name in enumerate(classes):
        for path in sorted((root/name/split).glob('*.off')):
            mesh = o3d.io.read_triangle_mesh(str(path))
            if len(mesh.triangles) == 0:
                failed.append(str(path)); continue
            p = np.asarray(mesh.sample_points_uniformly(number_of_points=256).points,dtype=np.float32)
            p -= p.mean(axis=0)
            scale = np.linalg.norm(p,axis=1).max()
            if scale == 0:
                failed.append(str(path)); continue
            clouds.append(p/scale); labels.append(label)
    np.savez_compressed(f'modelnet10_{split}.npz',x=np.array(clouds),y=np.array(labels),classes=np.array(classes))
    print(split,len(clouds),'mallas descartadas',len(failed))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The first model is a compact PointNet without a learned transformation network. The second uses centers selected by farthest point sampling, 16 neighbors, and a shared MLP over offsets and center coordinates, followed by local and global maxima. It is a small version of the PointNet++ idea, not the reference architecture or an attempt to reproduce its benchmark. The test uses a common permutation, retains the first 128 points, and adds Gaussian noise with standard deviation 0.02 in normalized coordinates. Record any full training run separately from this short test.

[ ]Training and evaluating both networksLocal GPU
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

torch.manual_seed(42)
torch.cuda.manual_seed_all(42)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train = np.load('modelnet10_train.npz')
test = np.load('modelnet10_test.npz')
train_ds = TensorDataset(torch.from_numpy(train['x']),torch.from_numpy(train['y']).long())
test_x = torch.from_numpy(test['x']).to(device)
test_y = torch.from_numpy(test['y']).long().to(device)

class PointNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.feat=nn.Sequential(nn.Conv1d(3,64,1),nn.ReLU(),nn.Conv1d(64,128,1),nn.ReLU(),nn.Conv1d(128,256,1),nn.ReLU())
        self.head=nn.Sequential(nn.Linear(256,128),nn.ReLU(),nn.Linear(128,10))
    def forward(self,x):
        h=self.feat(x.transpose(1,2))
        pooled,idx=h.max(dim=2)
        return self.head(pooled),idx

def fps(x,m):
    b,n,_=x.shape
    inds=torch.empty((b,m),dtype=torch.long,device=x.device)
    dist=torch.full((b,n),float('inf'),device=x.device)
    first=((x-x.mean(dim=1,keepdim=True))**2).sum(-1).argmax(-1)
    rows=torch.arange(b,device=x.device)
    for j in range(m):
        inds[:,j]=first
        d=((x-x[rows,first][:,None,:])**2).sum(-1)
        dist=torch.minimum(dist,d)
        first=dist.argmax(-1)
    return inds

class PointNetPlusPlus(nn.Module):
    def __init__(self):
        super().__init__()
        self.local=nn.Sequential(nn.Conv2d(6,64,1),nn.ReLU(),nn.Conv2d(64,128,1),nn.ReLU())
        self.head=nn.Sequential(nn.Linear(128,128),nn.ReLU(),nn.Linear(128,10))
    def forward(self,x):
        b,n,_=x.shape
        m=min(32,n); k=min(16,n)
        ix=fps(x,m)
        rows=torch.arange(b,device=x.device)[:,None]
        centers=x[rows,ix]
        nearest=torch.cdist(centers,x).topk(k,largest=False).indices
        offsets=x[rows[:,:,None],nearest]-centers[:,:,None,:]
        groups=torch.cat((offsets,centers[:,:,None,:].expand(-1,-1,k,-1)),dim=-1)
        h=self.local(groups.permute(0,3,1,2)).max(dim=3).values.max(dim=2).values
        return self.head(h),None

def evaluate(model,x,y):
    model.eval()
    with torch.no_grad():
        predictions=torch.cat([model(a)[0] for a in x.split(64)]).argmax(1)
    return float((predictions==y).float().mean())

epochs = 3  # ejecución corta de validación; aumenta para investigar
for cls in (PointNet,PointNetPlusPlus):
    model=cls().to(device)
    optimizer=torch.optim.Adam(model.parameters(),lr=0.001)
    loader=DataLoader(train_ds,batch_size=32,shuffle=True,generator=torch.Generator().manual_seed(42))
    for epoch in range(epochs):
        model.train(); total=0
        for x,y in loader:
            x,y=x.to(device),y.to(device)
            optimizer.zero_grad(); logits,_=model(x); loss=nn.functional.cross_entropy(logits,y)
            loss.backward(); optimizer.step(); total+=float(loss.detach())*len(x)
        print(cls.__name__,'época',epoch+1,'pérdida',total/len(train_ds))
    torch.save(model.state_dict(),f'{cls.__name__}.pt')
    perm=torch.randperm(test_x.shape[1],device=device)
    gen=torch.Generator(device=device).manual_seed(27)
    noise=torch.randn(test_x.shape,device=device,generator=gen)*0.02
    print(cls.__name__,'test',evaluate(model,test_x,test_y),
          'permutado',evaluate(model,test_x[:,perm],test_y),
          '128 puntos',evaluate(model,test_x[:,:128],test_y),
          'ruido',evaluate(model,test_x+noise,test_y))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In one local three-epoch run with all 3,991 training meshes and 908 test meshes, PointNet achieved accuracy 0.725 on the original cloud, 0.725 after permutation, 0.718 with 128 points, and 0.731 with noise. The local variant achieved 0.702, 0.702, 0.705, and 0.700 respectively. These are one short run with one seed, not results from the paper or a conclusive comparison of architectures. Farthest point sampling starts at the point farthest from the centroid; exact ties may depend on order. For a statistical comparison, repeat seeds, reserve validation for decisions, and evaluate the test set once with the protocol fixed.

During development, the test of a first local variant using only relative offsets was observed to achieve 0.207 accuracy; the center position was added and the variant above was run. That intervention after looking at test results makes these figures exploratory. A formal study must make that choice using validation and reserve an unseen test set for the final result.

Segmentation needs per-point labels

For part segmentation, use ShapeNetPart, not ModelNet10 category labels. The HDF5 files from the original PointNet code contain data, label, and pid: coordinates, category, and per-point part label. The public ShapeNetPart mirror uses seg for the last key; its files have not been verified byte-identical to the original archive. The next cell accepts both names, expects *train*.h5 and *test*.h5 files in ShapeNetPart/hdf5_data, and requires h5py. First run the architecture cell, which defines fps; because of the download and training, this cell is excluded from automatic tests.

[ ]Part segmentation with annotated dataLocal GPU
from pathlib import Path
import h5py
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

def load_parts(split):
    files = sorted(Path('ShapeNetPart/hdf5_data').glob(f'*{split}*.h5'))
    if not files:
        raise RuntimeError('Faltan los HDF5 de ShapeNetPart para ' + split)
    xs, ys = [], []
    for path in files:
        with h5py.File(path,'r') as f:
            xs.append(f['data'][:,:256,:].astype(np.float32))
            key = 'pid' if 'pid' in f else 'seg'
            ys.append(f[key][:,:256].astype(np.int64))
    return torch.from_numpy(np.concatenate(xs)), torch.from_numpy(np.concatenate(ys))

class PointNetParts(nn.Module):
    def __init__(self):
        super().__init__()
        self.local=nn.Sequential(nn.Conv1d(3,64,1),nn.ReLU())
        self.global_net=nn.Sequential(nn.Conv1d(64,128,1),nn.ReLU(),nn.Conv1d(128,256,1),nn.ReLU())
        self.head=nn.Sequential(nn.Conv1d(320,128,1),nn.ReLU(),nn.Conv1d(128,50,1))
    def forward(self,x):
        h=self.local(x.transpose(1,2))
        g=self.global_net(h).max(dim=2,keepdim=True).values.expand(-1,-1,x.shape[1])
        return self.head(torch.cat((h,g),dim=1)).transpose(1,2)

class PointNetPlusParts(nn.Module):
    def __init__(self):
        super().__init__()
        self.local=nn.Sequential(nn.Conv2d(6,64,1),nn.ReLU(),nn.Conv2d(64,128,1),nn.ReLU())
        self.head=nn.Sequential(nn.Conv1d(259,128,1),nn.ReLU(),nn.Conv1d(128,50,1))
    def forward(self,x):
        b,n,_=x.shape; m=min(32,n); k=min(16,n)
        rows=torch.arange(b,device=x.device)[:,None]
        centers=x[rows,fps(x,m)]
        nearest=torch.cdist(centers,x).topk(k,largest=False).indices
        offsets=x[rows[:,:,None],nearest]-centers[:,:,None,:]
        groups=torch.cat((offsets,centers[:,:,None,:].expand(-1,-1,k,-1)),dim=-1)
        h=self.local(groups.permute(0,3,1,2)).max(dim=3).values.transpose(1,2)
        nearest_center=torch.cdist(x,centers).argmin(dim=2)
        local=h[rows,nearest_center]
        global_feature=h.max(dim=1,keepdim=True).values.expand(-1,n,-1)
        return self.head(torch.cat((x,local,global_feature),dim=2).transpose(1,2)).transpose(1,2)

torch.manual_seed(42)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
x_train,y_train=load_parts('train')
x_test,y_test=load_parts('test')
for cls in (PointNetParts,PointNetPlusParts):
    model=cls().to(device)
    opt=torch.optim.Adam(model.parameters(),lr=0.001)
    loader=DataLoader(TensorDataset(x_train,y_train),batch_size=16,shuffle=True)
    for epoch in range(3):
        model.train()
        for x,y in loader:
            x,y=x.to(device),y.to(device)
            opt.zero_grad(); logits=model(x)
            loss=nn.functional.cross_entropy(logits.reshape(-1,50),y.reshape(-1))
            loss.backward(); opt.step()
        print(cls.__name__,'época',epoch+1,'última pérdida',float(loss.detach()))
    torch.save(model.state_dict(),f'{cls.__name__}.pt')
    model.eval(); correct=0; total=0
    with torch.no_grad():
        for x,y in DataLoader(TensorDataset(x_test,y_test),batch_size=16):
            pred=model(x.to(device)).argmax(-1).cpu()
            correct+=int((pred==y).sum()); total+=y.numel()
    print(cls.__name__,'precisión por punto:',correct/total)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Per-point accuracy is not instance mIoU and does not reproduce the paper’s protocol: it does not restrict predictions to valid parts for the category and weights objects by their number of points. For a benchmark, retain the category, calculate IoU per part and instance according to the protocol, and separate validation from test.

In a short run on the indicated mirror, the splits contained 12,137 training and 2,874 test shapes. With 256 points per shape and three epochs, test per-point accuracy was 0.842 for the global network and 0.830 for the local variant. These are two single-seed runs with a simplified protocol and no category mask: they are neither mIoU nor published PointNet figures. The mirror’s validation split was not used in this workflow test.

Exercises

ProofCorrecting reflections
Prove: Derive the optimal Kabsch rotation for known correspondences.
0
The clouds are centered and H=∑ipiqi⊤=UΣV⊤\mat{H}=\sum_i\vb{p}_i\vb{q}_i\T=\mat{U}\mat{\Sigma}\mat{V}\T, with singular values in descending order.

Step 1 of 3. Which part of the error depends on rotation?

ProofSymmetry of the maximum
Prove: Prove that f({xi})=γ(max⁡ih(xi))f(\{\vb{x}_i\})=\gamma(\max_i h(\vb{x}_i)) does not depend on point order.
0
The maximum is componentwise and h is applied with the same parameters to each point.

Step 1 of 2. What happens when the input is permuted?

Quiz
Two clouds sample an ideal infinite plane with exact normals. What does a near-zero point-to-plane residual reveal?
CodeRigid alignment with SVD
Implement kabsch(P, Q) with points in rows. Return R and t such that P @ R.T + t aligns with Q, enforcing det(R) = +1.
import numpy as np
def kabsch(P, Q):
  pass
Shift+Enter to run
Numeric
With axial depth 2 m at pixel (400, 300), focal lengths of 500 px and center (320, 240), what is the X coordinate in meters?
Key idea
A cloud is a set: its rows are not correspondences. Registration needs initialization, an association rule, and a measure of uncertainty; learning over sets must respect permutations.