AI Wiki中文/EN

U-Net: recover location without throwing away context

U-Net

Trace valid-convolution sizes and crop connections, derive boundary-weighted loss, and run a complete small U-Net forward and backward pass.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The gap between two cells is part of the answer

Imagine two bright cells separated by a thin dark gap. A classifier with little context may confuse a dim cell edge with background. A network that repeatedly pools the image sees more context, but can lose the narrow gap. Simply making its final output larger does not restore the missing local information.

U-Net carries fine-resolution features from its contracting path across to its expanding path. At each matching scale, the decoder combines those features with upsampled context and learns further convolutions. The U shape describes this flow of spatial scales, not a special loss function or a guarantee of accurate boundaries. Original architecture, figure 1 and §2

Olaf Ronneberger, Philipp Fischer and Thomas Brox submitted the first preprint on 18 May 2015. The authors’ page identifies the MICCAI 2015 publication and a later packaged implementation. We study the original valid-convolution architecture, then implement a smaller version with explicit differences. Submission history, author publication and release page

The original paper also gives extra loss weight to separating cell boundaries. These are two distinct ideas: skip connections improve what information the model can use; spatial weights change which mistakes cost more. Neither converts a foreground/background output into a complete set of cell identities. The underlying task and basic evaluation are introduced in semantic segmentation.

Count the pixels through every operation

The original U-Net is not a same-size input/output model

A valid convolution does not pad the input. With a 3×3 kernel and stride one, each spatial side loses two pixels. Two such convolutions lose four. A 2×2 max pool with stride two then halves an even side. In our selected up-convolution, a 2×2 transposed kernel with stride two doubles it:

ntwo valid convs=n−4,npool=n2  (n even),nup=2n.n_{\text{two valid convs}}=n-4,\qquad n_{\text{pool}}=\frac n2\;(n\text{ even}),\qquad n_{\text{up}}=2n.

The paper’s example begins at 572×572 and ends at 388×388. At each contracting stage it applies two valid convolutions with ReLU, saves their output for a skip connection, then pools. Channels grow from 64 through 128, 256 and 512 to a 1024-channel bottleneck. On the way back up, channels decrease while the saved features are concatenated with upsampled features. The final 1×1 convolution maps 64 features to class logits. This architecture has 23 convolutional layers when the four up-convolutions and final class projection are counted. Paper §2 and figure 1

StageAfter two valid convolutionsAfter pooling or up-convolution
Contract 1568284
Contract 2280140
Contract 313668
Contract 46432
Bottleneck28Up to 56
Expand 452Up to 104
Expand 3100Up to 200
Expand 2196Up to 392
Expand 1388Class head keeps 388

These numbers describe one spatial side. At the first expansive stage, the saved feature map has side 64 while the upsampled map has side 56. Crop four pixels from each side of the skip feature map before concatenation. The next skip crops are 16, 40 and 88 pixels per side: (136−104)/2, (280−200)/2 and (568−392)/2. Concatenation increases the channel count; it does not add the maps element by element.

The final label map must align with the output. A centered crop from 572 to 388 removes 92 pixels from each side of the original target map. That is different from the final skip-feature crop of 88. One acts on the original annotation; the other acts on a feature map already reduced by valid convolutions. Confusing them shifts supervision even if every tensor shape passes a check.

A transposed convolution is a transpose, not an inverse

For a transposed convolution, let s be stride, p padding, d dilation, k kernel size and o output padding. Along one axis,

nout=(nin−1)s−2p+d(k−1)+o+1.n_{\text{out}}=(n_{\text{in}}-1)s-2p+d(k-1)+o+1.

Choosing s=2, k=2, p=0, d=1 and o=0 gives exactly twice the input size. We use this explicit operator for the small model’s up-convolutions. A nearest-neighbor resize followed by an unpadded 2×2 ordinary convolution would instead lose a pixel and is not interchangeable without further alignment choices. Fixed PyTorch 2.2 documentation explains the transpose interpretation and notes that output padding resolves shape ambiguity; it is not literal zero padding appended to the computed output. ConvTranspose2d definition

Flatten an ordinary linear convolution into a matrix A. Its input-gradient operator is the transpose:

y=Ax,∂L∂x=A⊤∂L∂y,⟨A⊤u,v⟩=⟨u,Av⟩.y=Ax,\qquad \frac{\partial L}{\partial x}=A^\top\frac{\partial L}{\partial y},\qquad \langle A^\top u,v\rangle=\langle u,Av\rangle.

There is no general requirement that A⊤AA^\top A be the identity. Pooling may have already removed information as well. Our test explicitly builds the matrix of the corresponding stride-two convolution and compares its transpose with the up-convolution implementation; a separate inner-product check verifies the same relation.

In the single-channel case, input [5] and a 2×2 kernel [[1,2],[3,4]] produce [[5,10],[15,20]]. With a kernel of all ones, each input value is copied into a 2×2 block. With arbitrary learned weights, the four spatial phases can differ. This stride/kernel pair has no overlap between the output blocks, but that alone does not guarantee artifact-free predictions.

Why a crop connection helps learning

An expansive block receives two kinds of information: an upsampled representation with broader context and a cropped contracting feature map with finer detail. It concatenates them along channels, then applies two convolutions. The following kernels decide how to combine the two; concatenation does not assume that corresponding channels have the same meaning.

This skip is also a gradient path. Let E be a saved encoder feature, C the linear center-crop operator, and J the decoder’s channel concatenation. During backpropagation, split the gradient of J into the skip and upsampled channel groups. Scatter the cropped skip gradient back into the matching part of E, filling the removed border with zeros. Add that contribution to the gradient returning through pooling:

∂L∂E=gthrough pooling+C⊤gcropped skip.\frac{\partial L}{\partial E}=g_{\text{through pooling}}+C^\top g_{\text{cropped skip}}.

The addition happens because E was used along two paths. Overwriting one contribution with the other would lose a valid part of the derivative. Max-pool backpropagation routes each output gradient to its selected maximum; our implementation chooses the first maximum in a tie. ReLU uses derivative zero at zero. Finite-difference tests use smooth cases away from these switching boundaries.

Make the narrow separation expensive to erase

The paper constructs a spatial weight map from a class-balancing term wc(x)w_c(x) and distances to the boundaries of the nearest and second-nearest different cells, d1(x)d_1(x) and d2(x)d_2(x):

w(x)=wc(x)+w0exp⁡ ⁣(−(d1(x)+d2(x))22σ2).w(x)=w_c(x)+w_0\exp\!\left(-\frac{(d_1(x)+d_2(x))^2}{2\sigma^2}\right).

The reported settings are w0=10w_0=10 and σ≈5 pixels. When two cell boundaries are nearby, the distance sum is small and the additional weight is large. This makes an error in that region cost more. The formula is a spatial weight map, not a rule that only background pixels can receive extra weight. Paper §3, equation 2 and figure 3

The two distances must not be the distances to two neighboring points on the same cell. Our original grid implementation uses positive instance IDs, identifies each cell’s inner four-neighbor boundary pixels, and measures Euclidean distance to their pixel centers. The image exterior is treated as outside the cell for this boundary definition. These discretization choices are explicit teaching conventions; the paper does not specify all of them in its short morphological description.

Compute one nearest-boundary distance map per distinct instance, then keep the smallest two maps at each pixel. In a small example, a pixel lies two grid units from each of two cell boundaries. With base weight one, its weight is 1+10exp(−16/50). On the first cell’s boundary, the nearest distance is zero and the other cell can still be four units away. Choosing a neighboring point of the first cell as “second nearest” would give the wrong weight.

If fewer than two instances exist, our second distance stays infinite and the additional term becomes zero. The result is just the base map. This is a declared local convention, not an undocumented claim about the authors’ software. Instance IDs are used to construct supervision; the network in this chapter still predicts only background and foreground.

Choose the sign and reduction of the objective explicitly

Let pℓ(x)(x)p_{\ell(x)}(x) be the probability of the true semantic class at output pixel x. A minimized weighted cross-entropy is

Lsum=−∑x∈Ωw(x)log⁡pℓ(x)(x),Lmean=Lsum∑x∈Ωw(x).L_{\text{sum}}=-\sum_{x\in\Omega}w(x)\log p_{\ell(x)}(x),\qquad L_{\text{mean}}=\frac{L_{\text{sum}}}{\sum_{x\in\Omega}w(x)}.

The original PDF’s equation 1 prints a positive weighted log-probability sum. The page image confirms that this is not an OCR omission. For minimization, the negative sign above matters: log(0.2) is smaller than log(0.8), so minimizing positive log probability would reward a lower probability for the correct class. One could maximize the positive sum instead. We state the minimized objective explicitly rather than infer the authors’ executable training code from a printed sign. Paper equation 1

The program supports both reductions. Its default sum corresponds to the negated printed expression; the demonstration takes a step using a weight-sum mean to keep its step size manageable. Multiplying all weights by seven multiplies the sum loss and gradient by seven, while leaving this mean unchanged. These are different scaling conventions, even though both prioritize the same locations at fixed weights.

For fixed targets and weights, the class-logit derivative is

∂L∂zk(x)=w(x)D[pk(x)−1{k=ℓ(x)}],D=1 for sum,D=∑x∈Ωw(x) for mean.\frac{\partial L}{\partial z_k(x)}=\frac{w(x)}{D}\left[p_k(x)-\mathbf1\{k=\ell(x)\}\right],\qquad D=1\text{ for sum},\quad D=\sum_{x\in\Omega}w(x)\text{ for mean}.

The weights come from annotations and are held fixed, not recomputed from the current predictions. We construct them on the full annotation map before cropping them and the semantic targets to the output window. Cropping the instance map first can remove a cell or change which pixels count as its boundary, producing a different supervision map.

Run a full small U-Net training step

Save the standalone code as unet.py and run python unet.py with Python 3.12 and NumPy 1.26.4. The default is a two-level U-Net with channels 2, 4 and 8, thirteen convolutional layers and 1,886 parameters. It accepts a 64×64 image and outputs 24×24 logits for two classes. Its target crop is rows and columns 20 through 43 inclusive. The two synthetic rectangles give 252 foreground pixels within that window.

The model uses valid convolutions, ReLU, max pooling, learned 2×2 transposed convolutions, crop-and-concatenate skips and a 1×1 class head. The program computes gradients for all parameter arrays and for the input, including both routes through every encoder feature. It then takes one step of size 0.02 on all parameter arrays. It uses base pixel weights of one, so it does not apply an additional class-frequency correction in this example.

This is a reduced training demonstration, not an original checkpoint or a microscopy benchmark. It omits the paper’s dropout, data augmentation, high-momentum optimizer and overlap-tile inference implementation. Spatial convolutions use a Gaussian initialization scaled by their fan-in; the up-convolutions use a separately stated random scale. The exact original packaged Caffe implementation is not being executed.

Spatial trace of the executed two-level model. Dashed arrows carry saved encoder features; crops remove 4 and 16 pixels per side before concatenation. The original target map instead loses 20 pixels per side.
Spatial trace of the executed two-level model. Dashed arrows carry saved encoder features; crops remove 4 and 16 pixels per side before concatenation. The original target map instead loses 20 pixels per side.
"""Original reduced valid-convolution U-Net, boundary weights and full backward pass."""
import numpy as np


def image_array(value):
    x=np.asarray(value,float)
    if x.ndim!=3 or min(x.shape)<1 or not np.isfinite(x).all():
        raise ValueError('finite nonempty HWC array required')
    return x


def conv_valid(image,kernel,bias=None,stride=1):
    x=image_array(image);k=np.asarray(kernel,float)
    if k.ndim!=4 or min(k.shape)<1 or k.shape[2]!=x.shape[2] or not np.isfinite(k).all():
        raise ValueError('finite kh,kw,input,output kernel required')
    if type(stride) is not int or stride<1 or x.shape[0]<k.shape[0] or x.shape[1]<k.shape[1]:
        raise ValueError('positive stride and sufficient input required')
    b=np.zeros(k.shape[3]) if bias is None else np.asarray(bias,float)
    if b.shape!=(k.shape[3],) or not np.isfinite(b).all():raise ValueError('output-channel bias required')
    h=(x.shape[0]-k.shape[0])//stride+1;w=(x.shape[1]-k.shape[1])//stride+1
    result=np.broadcast_to(b,(h,w,len(b))).copy()
    for dy in range(k.shape[0]):
        for dx in range(k.shape[1]):result+=x[dy:dy+h*stride:stride,dx:dx+w*stride:stride] @ k[dy,dx]
    return result


def pool2(image):
    return pool_forward(image)[0]


def pool_forward(image):
    x=image_array(image);h,w,c=x.shape
    if h%2 or w%2:raise ValueError('even spatial sizes required before pooling')
    patches=x.reshape(h//2,2,w//2,2,c).transpose(0,2,4,1,3).reshape(h//2,w//2,c,4)
    chosen=patches.argmax(axis=-1)
    return np.take_along_axis(patches,chosen[...,None],axis=-1)[...,0],(x.shape,chosen)


def pool_backward(gradient,cache):
    shape,chosen=cache;g=image_array(gradient)
    if g.shape!=chosen.shape:raise ValueError('pooled gradient shape mismatch')
    result=np.zeros(shape)
    for dy in range(2):
        for dx in range(2):result[dy::2,dx::2]=g*(chosen==2*dy+dx)
    return result


def upconv2(image,kernel,bias=None):
    """2x2 kernel, stride2, zero padding: scatter input channels to output channels."""
    x=image_array(image);k=np.asarray(kernel,float)
    if k.ndim!=4 or k.shape[:3]!=(2,2,x.shape[2]) or k.shape[3]<1 or not np.isfinite(k).all():
        raise ValueError('finite2x2,input,output kernel required')
    b=np.zeros(k.shape[3]) if bias is None else np.asarray(bias,float)
    if b.shape!=(k.shape[3],) or not np.isfinite(b).all():raise ValueError('output-channel bias required')
    out=np.broadcast_to(b,(2*x.shape[0],2*x.shape[1],len(b))).copy()
    for dy in range(2):
        for dx in range(2):out[dy::2,dx::2]+=x @ k[dy,dx]
    return out


def crop_to(image,shape):
    x=image_array(image)
    if len(shape)!=2 or any(type(n) is not int or n<1 for n in shape):raise ValueError('positive target height/width required')
    difference=[x.shape[i]-shape[i] for i in range(2)]
    if any(d<0 or d%2 for d in difference):raise ValueError('symmetric integer center crop required')
    y,z=(d//2 for d in difference)
    return x[y:y+shape[0],z:z+shape[1]]


def conv_backward(image,kernel,gradient):
    """Valid stride1 convolution gradients; the model uses this stride in its blocks."""
    x=image_array(image);g=image_array(gradient);k=np.asarray(kernel,float)
    if g.shape!=(x.shape[0]-k.shape[0]+1,x.shape[1]-k.shape[1]+1,k.shape[3]):
        raise ValueError('valid convolution gradient shape mismatch')
    h,w=g.shape[:2];dx=np.zeros_like(x);dk=np.zeros_like(k)
    for iy in range(k.shape[0]):
        for ix in range(k.shape[1]):
            patch=x[iy:iy+h,ix:ix+w]
            dk[iy,ix]=np.einsum('hwc,hwf->cf',patch,g)
            dx[iy:iy+h,ix:ix+w]+=g @ k[iy,ix].T
    return dx,(dk,g.sum(axis=(0,1)))


def upconv_backward(image,kernel,gradient):
    x=image_array(image);g=image_array(gradient);k=np.asarray(kernel,float)
    if k.shape[:3]!=(2,2,x.shape[2]) or g.shape!=(2*x.shape[0],2*x.shape[1],k.shape[3]):
        raise ValueError('up-convolution gradient shape mismatch')
    dx=np.zeros_like(x);dk=np.zeros_like(k)
    for iy in range(2):
        for ix in range(2):
            part=g[iy::2,ix::2]
            dx+=part @ k[iy,ix].T
            dk[iy,ix]=np.einsum('hwc,hwf->cf',x,part)
    return dx,(dk,g.sum(axis=(0,1)))


def pair_forward(value,layers):
    cache=[]
    for kernel,bias in layers:
        activation=conv_valid(value,kernel,bias)
        cache.append((value,activation));value=np.maximum(activation,0)
    return value,cache


def pair_backward(gradient,layers,cache):
    grads=[None]*len(layers)
    for i in reversed(range(len(layers))):
        x,activation=cache[i]
        gradient,grads[i]=conv_backward(x,layers[i][0],gradient*(activation>0))
    return gradient,grads


def make_parameters(channels=1,base=2,levels=2,classes=2,seed=7):
    if any(type(n) is not int or n<1 for n in [channels,base,levels,classes]) or classes<2:
        raise ValueError('positive widths/levels and at least two classes required')
    rng=np.random.default_rng(seed)
    def layer(a,b,size=3):return rng.normal(0,np.sqrt(2/(size*size*a)),(size,size,a,b)),np.zeros(b)
    def pair(a,b):return [layer(a,b),layer(b,b)]
    down=[];width=channels
    for level in range(levels):
        next_width=base*2**level;down.append(pair(width,next_width));width=next_width
    bottleneck=pair(width,2*width);width*=2
    up=[]
    for level in reversed(range(levels)):
        next_width=base*2**level
        up.append({'up':(rng.normal(0,1/np.sqrt(width),(2,2,width,next_width)),np.zeros(next_width)),
                   'pair':pair(2*next_width,next_width)})
        width=next_width
    return {'down':down,'bottleneck':bottleneck,'up':up,'head':layer(width,classes,1)}


def forward(image,parameters):
    x=image_array(image);skips=[];trace=[];cache={'down':[],'up':[]}
    for layers in parameters['down']:
        x,block_cache=pair_forward(x,layers);skips.append(x);trace.append(('skip',list(x.shape)))
        x,pool_cache=pool_forward(x);cache['down'].append((block_cache,pool_cache))
    x,cache['bottleneck']=pair_forward(x,parameters['bottleneck']);trace.append(('bottleneck',list(x.shape)))
    if len(parameters['up'])!=len(skips):raise ValueError('one expansive stage per skip required')
    for stage,skip in zip(parameters['up'],reversed(skips)):
        up_input=x;x=upconv2(x,*stage['up']);cropped=crop_to(skip,list(x.shape[:2]))
        trace.append(('upsampled',list(x.shape)));trace.append(('cropped',list(cropped.shape)))
        x,block_cache=pair_forward(np.concatenate([cropped,x],axis=-1),stage['pair'])
        cache['up'].append((up_input,skip.shape,cropped.shape,block_cache));trace.append(('decoded',list(x.shape)))
    cache['head_input']=x
    logits=conv_valid(x,*parameters['head']);trace.append(('logits',list(logits.shape)))
    return logits,trace,cache


def backward(parameters,cache,logit_gradient):
    gradient,head=conv_backward(cache['head_input'],parameters['head'][0],logit_gradient)
    stages=len(parameters['up']);up_grads=[None]*stages;skip_grads=[None]*stages
    for i in reversed(range(stages)):
        stage=parameters['up'][i];up_input,skip_shape,crop_shape,block_cache=cache['up'][i]
        gradient,pair_grad=pair_backward(gradient,stage['pair'],block_cache)
        cut=crop_shape[2];crop_gradient=gradient[...,:cut]
        skip_gradient=np.zeros(skip_shape)
        y=(skip_shape[0]-crop_shape[0])//2;x=(skip_shape[1]-crop_shape[1])//2
        skip_gradient[y:y+crop_shape[0],x:x+crop_shape[1]]=crop_gradient
        skip_grads[stages-1-i]=skip_gradient
        gradient,up_grad=upconv_backward(up_input,stage['up'][0],gradient[...,cut:])
        up_grads[i]={'up':up_grad,'pair':pair_grad}
    gradient,bottleneck=pair_backward(gradient,parameters['bottleneck'],cache['bottleneck'])
    down_grads=[None]*stages
    for i in reversed(range(stages)):
        block_cache,pool_cache=cache['down'][i]
        gradient=pool_backward(gradient,pool_cache)+skip_grads[i]
        gradient,down_grads[i]=pair_backward(gradient,parameters['down'][i],block_cache)
    return {'down':down_grads,'bottleneck':bottleneck,'up':up_grads,'head':head},gradient


def parameter_items(tree,prefix=''):
    if isinstance(tree,np.ndarray):return {prefix:tree}
    pairs=tree.items() if isinstance(tree,dict) else enumerate(tree)
    result={}
    for key,value in pairs:result.update(parameter_items(value,prefix+'/'+str(key)))
    return result


def boundary_weights(instances,base=None,w0=10.,sigma=5.):
    """Distances to different instances' inner four-neighbor boundary pixel centers."""
    ids=np.asarray(instances)
    if ids.ndim!=2 or min(ids.shape)<1 or ids.dtype.kind not in 'iu' or (ids<0).any():
        raise ValueError('nonempty HW nonnegative integer instance IDs required')
    wc=np.ones(ids.shape) if base is None else np.asarray(base,float)
    if wc.shape!=ids.shape or not np.isfinite(wc).all() or (wc<=0).any():
        raise ValueError('positive finite HW base weights required')
    if not np.isfinite(w0) or w0<0 or not np.isfinite(sigma) or sigma<=0:
        raise ValueError('nonnegative w0 and positive sigma required')
    yy,xx=np.indices(ids.shape);first=np.full(ids.shape,np.inf);second=first.copy()
    for label in np.unique(ids[ids>0]):
        mask=ids==label;padded=np.pad(mask,1,constant_values=False)
        interior=mask&padded[:-2,1:-1]&padded[2:,1:-1]&padded[1:-1,:-2]&padded[1:-1,2:]
        distance2=np.full(ids.shape,np.inf)
        for y,x in np.argwhere(mask&~interior):distance2=np.minimum(distance2,(yy-y)**2+(xx-x)**2)
        distance=np.sqrt(distance2)
        second=np.where(distance<first,first,np.minimum(second,distance));first=np.minimum(first,distance)
    # Fewer than two instances: second remains infinity, so the extra term is zero.
    return wc+w0*np.exp(-.5*((first+second)/sigma)**2),first,second


def weighted_ce(logits,labels,weights,reduction='sum'):
    """Minimize negative weighted log likelihood; optional weight-sum mean is local."""
    z=image_array(logits);y=np.asarray(labels);w=np.asarray(weights,float)
    if z.shape[2]<2 or y.shape!=z.shape[:2] or y.dtype.kind not in 'iu' or (y<0).any() or (y>=z.shape[2]).any():
        raise ValueError('valid HW integer class labels required')
    if w.shape!=y.shape or not np.isfinite(w).all() or (w<=0).any():raise ValueError('positive finite pixel weights required')
    if reduction not in ['sum','mean']:raise ValueError('choose sum or mean reduction')
    shifted=z-z.max(axis=-1,keepdims=True);logp=shifted-np.log(np.exp(shifted).sum(axis=-1,keepdims=True))
    probability=np.exp(logp);flat_y=y.ravel().astype(int)
    loss=-np.sum(w.ravel()*logp.reshape(-1,z.shape[2])[np.arange(y.size),flat_y])
    gradient=probability.copy().reshape(-1,z.shape[2]);gradient[np.arange(y.size),flat_y]-=1
    gradient=gradient.reshape(z.shape)*w[...,None]
    denominator=w.sum() if reduction=='mean' else 1.
    return float(loss/denominator),gradient/denominator


if __name__=='__main__':
    instances=np.zeros((64,64),dtype=int);instances[24:38,21:30]=1;instances[24:38,32:41]=2
    image=(.1+.8*(instances>0)+np.random.default_rng(3).normal(0,.05,instances.shape))[...,None]
    parameters=make_parameters();logits,trace,cache=forward(image,parameters)
    weights,_,_=boundary_weights(instances)
    target=crop_to((instances>0)[...,None],list(logits.shape[:2]))[...,0].astype(int)
    local_weights=crop_to(weights[...,None],list(logits.shape[:2]))[...,0]
    summed,_=weighted_ce(logits,target,local_weights)
    before,dz=weighted_ce(logits,target,local_weights,'mean')
    gradients,_=backward(parameters,cache,dz);gradient_items=parameter_items(gradients)
    for name,value in parameter_items(parameters).items():value-=.02*gradient_items[name]
    after=weighted_ce(forward(image,parameters)[0],target,local_weights,'mean')[0]
    for name,shape in trace:print(name,shape)
    print('parameters:',sum(v.size for v in parameter_items(parameters).values()))
    print('target crop:',target.shape,'foreground pixels:',int(target.sum()))
    print('gap weight:',round(float(weights[30,30]),6))
    print('weighted sum loss:',round(summed,6))
    print('weighted mean step:',round(before,6),'->',round(after,6))

Actual output:

skip [60, 60, 2]
skip [26, 26, 4]
bottleneck [9, 9, 8]
upsampled [18, 18, 4]
cropped [18, 18, 4]
decoded [14, 14, 4]
upsampled [28, 28, 2]
cropped [28, 28, 2]
decoded [24, 24, 2]
logits [24, 24, 2]
parameters: 1886
target crop: (24, 24) foreground pixels: 252
gap weight: 9.352702
weighted sum loss: 1361.797915
weighted mean step: 0.692955 -> 0.692813

At pixel (30,30) in the full annotation map, the closest two boundaries are one and two pixels away, so the gap weight is 1+10exp(−9/50)=9.352702. The output window and weights are cropped together. The weighted sum loss is 1361.797915, while the weight-sum mean starts at 0.692955 and falls to 0.692813 after the complete parameter step. The different magnitudes are normalization, not different predictions. A small decrease on one synthetic image does not establish segmentation accuracy.

Sixteen numerical tests check operator values, explicit transpose matrices, pooling and crop behavior, all parameters and all input coordinates of a one-level network, a joint directional derivative through two levels, weight-map distances against independent boundary-point enumeration, both loss reductions and a complete training step. A four-level forward with reduced channels also actually runs the original 572→388 spatial topology. It checks the spatial design without allocating the original full channel widths or claiming to reproduce its learned weights.

Architecture is only part of the original method

The original training recipe favored large tiles and a batch size of one, with momentum 0.99. It used shifts, rotations, gray-value variation and elastic deformation. The described elastic fields came from Gaussian displacements with standard deviation 10 pixels on a coarse 3×3 grid, then bicubic interpolation; dropout at the end of the contracting path provided further variation. Those details belong to the reported training setup, not a guarantee that they suit every image domain. Our program does not reproduce them. Paper §3 and §3.1

Valid convolutions need surrounding image context. The paper describes overlap-tile prediction and mirroring of missing context at image borders. This is a memory strategy and a boundary assumption. Different padding, interpolation, pooling alignment or preprocessing can change the values near tile edges, so an implementation should test overlap consistency rather than promise identical results for arbitrary tilings. Paper figure 2 and surrounding discussion

Skip features cost memory: they must remain available until the corresponding expanding block, and training also stores information needed for gradients. A convolutional layer’s arithmetic is proportional to output height×width×kernel area×input channels×output channels. Increasing channel width and image size can therefore become expensive even though the diagram still looks like a simple U. Our brute-force boundary-distance routine costs O(PB), where P is the number of full-image pixels and B is the total number of boundary pixels across instances; it uses O(P) distance workspace. It is a transparent reference for small examples, not an efficient large-image distance transform.

U-Net predicts class maps; it does not by itself assign persistent identities across frames. The authors’ downloadable package also contains a greedy tracking algorithm, which is a separate part of a larger pipeline. Do not attribute every operation in that release to the neural architecture. Author release contents

For an easier starting point with explicit baselines and IoU, use semantic segmentation. For object identities, continue to instance segmentation. A U-shaped model can be useful outside the original application, but changing dimensionality, conditioning or output targets creates a new model profile that needs its own explanation and checks.

Trace the information and the supervision

1. Understanding: add or concatenate?

A decoder has an 18×18×4 upsampled map and a 26×26×4 encoder skip. What is the input to its next convolution after the selected crop connection?

Answer: Crop four pixels from each side of the skip to obtain 18×18×4, then concatenate along channels to obtain 18×18×8. Elementwise addition would keep four channels and is a different operation. The following two valid 3×3 convolutions reduce the side to 14.

2. Calculation: two different crop sizes

The original example has input side 572, final output side 388, and a last skip of side 568 paired with an upsampled side 392. Compute the target crop and the skip crop per side.

Answer: The original target loses (572−388)/2=92 pixels on each side. The skip loses (568−392)/2=88. They refer to different coordinate grids. Using the skip crop for the original annotation would misalign supervision.

3. Boundary: what is the second-nearest boundary?

A point lies on cell A’s boundary. Another boundary pixel of A is one unit away, while the nearest boundary of cell B is four units away. Which distances enter the extra weight? What if only A exists?

Answer: The distances are 0 and 4 because they refer to different cells, not two points of A. With base one, w0=10 and σ=5, the weight is 1+10exp(−16/50). With only one cell, this program uses an infinite second distance and returns the base weight. That fallback is an explicit local choice.

4. Transfer: a falling objective with the wrong sign

A program minimizes the printed positive weighted log-probability sum. Its objective falls as the probability of the correct class changes from 0.8 to 0.2. Is that evidence of successful training? Does multiplying all pixel weights by seven leave the learning step unchanged?

Answer: No: positive log probability gets smaller when the correct class becomes less probable. Minimize negative log probability or maximize the positive sum. Scaling all weights scales the sum objective and gradient by seven, so a fixed learning-rate step changes; under the stated weight-sum mean, both numerator and denominator scale and the gradient stays the same. Check the objective and reduction before interpreting a learning curve.

What was checked, and what remains a different experiment

The U-Net v1 reading covers physical pages 2–6: the architecture figure, valid-convolution and overlap-tile design, weighted loss, class/boundary weights, initialization and augmentation description. Pages 2, 4 and 5 were visually checked. The experiment opening on page 6 was read for its setup, but its benchmark scores are not used here. The fixed PyTorch 2.2 ConvTranspose2d documentation provides an explicit transpose/shape contract, not evidence of which framework the 2015 experiments used.

The authors’ page identifies the publication and packaged release; the package itself was not executed or audited. The program and numeric examples here are original. Independent finite differences and matrix identities support the stated calculation, while the original model’s reported application results remain evidence from its authors, not results reproduced by this encyclopedia.

Make a prediction, then check

A 26×26×4 skip is paired with an 18×18×4 upsampled map. What enters the next convolution after center cropping and channel concatenation?

Choose one answer

Learning objectives

  • Trace original and reduced U-Net spatial sizes, distinguishing target crops from skip-feature crops.
  • Implement transposed convolution, crop/concatenate skips and complete parameter/input backpropagation.
  • Construct weights from different cell boundaries and distinguish weighted sum, mean and objective sign.

Prerequisites & connections

Explore related knowledge →

References

  1. U-Net: Convolutional Networks for Biomedical Image Segmentation — v1 architecture and training
    Olaf Ronneberger; Philipp Fischer; Thomas Brox · 2015
  2. PyTorch v2.2.0 ConvTranspose2d — transpose and output-shape contract
    PyTorch contributors
  3. U-Net arXiv first-submission record
    Olaf Ronneberger; Philipp Fischer; Thomas Brox · 2015
  4. U-Net author page — publication and packaged release
    Olaf Ronneberger and University of Freiburg LMB · 2015

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: original U-Net method and fixed transpose contract, exact spatial traces, full-model finite differences, independently enumerated boundary distances, loss sign/reduction and complete bilingual comparison. Not independent human review or original biomedical benchmark reproduction.

  • Sixteen numerical checks: explicit transposed matrix and adjoint identity; pooling/crop values, tie routing, all upconv parameter/input derivatives; every parameter/input coordinate in a one-level full model, two-level joint directional derivative, full four-level spatial topology, distinct-instance boundary distances versus enumeration, sum/mean loss/logit gradients and complete weight step. Formal tests extract article code and verify diagram data.
  • Compared all bilingual sections, seven displayed equations, full code/output, four reference scopes and four explained answers. Distinguished original valid geometry from the reduced profile, printed positive log likelihood from the minimized loss, annotation-based weights from instance predictions, and full small backpropagation from original training reproduction.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.