{"version":2,"relationshipURLBase":"https://codingai-lec03.pages.dev/course/notebook-blocks/26c6c8535ba248998b17337eae768d44.html","relationshipResolution":"Resolve relative relationship URLs against relationshipURLBase; complete records and absolute URLs are in blocks.","title":"参数更新和三个单条件比较 · 实现代码","url":"https://codingai-lec03.pages.dev/course/notebook-blocks/26c6c8535ba248998b17337eae768d44.html","markdown":"https://codingai-lec03.pages.dev/course/notebook-blocks/26c6c8535ba248998b17337eae768d44.md","pages":[{"id":"reading-opening","title":"参数更新和三个单条件比较 · 实现代码","unit":"参数更新和三个单条件比较 · 实现代码","unitId":"notebook-blocks/26c6c8535ba248998b17337eae768d44","chapter":"course","number":1}],"aliases":[{"oldId":"b-437e38778468458f863df87d","targetId":"b-437e38778468458f863df87d","page":"reading-opening","operation":"move","beforeSHA256":"f6dfd09a50caab375f02e0abcc3ff7a454ea579ed8eef0c35b95c95b0619c304","afterSHA256":"f6dfd09a50caab375f02e0abcc3ff7a454ea579ed8eef0c35b95c95b0619c304","reason":"Same source body in authored semantic page"},{"oldId":"b-dd0dab3c70b4dbcc7715158e","targetId":"b-dd0dab3c70b4dbcc7715158e","page":"reading-opening","operation":"move","beforeSHA256":"9fab536815fa25e7ec4f4cdfff09b63be580a962ee0c201d9a517a56d3344371","afterSHA256":"9fab536815fa25e7ec4f4cdfff09b63be580a962ee0c201d9a517a56d3344371","reason":"Same source body in authored semantic page"},{"oldId":"b-82bbe9be4fa50d5f5005dc0a","targetId":"b-82bbe9be4fa50d5f5005dc0a","page":"reading-opening","operation":"move","beforeSHA256":"e91f24e4e4ca40e2099a0d81d30db6568f4bf2074b499eeee6e3959617bd97ac","afterSHA256":"e91f24e4e4ca40e2099a0d81d30db6568f4bf2074b499eeee6e3959617bd97ac","reason":"Same source body in authored semantic page"},{"oldId":"b-be7bb5eb54ec3067d09c1c90","targetId":"b-be7bb5eb54ec3067d09c1c90","page":"reading-opening","operation":"move","beforeSHA256":"6f0b115c3c32032428a4c0d5ec4791e16d6b63aa3d643457bed758bf6af2b765","afterSHA256":"6f0b115c3c32032428a4c0d5ec4791e16d6b63aa3d643457bed758bf6af2b765","reason":"Same source body in authored semantic page"},{"oldId":"b-b5bcde49457bd7b8560a49d4","targetId":"b-b5bcde49457bd7b8560a49d4","page":"reading-opening","operation":"move","beforeSHA256":"cbf83d8e6014f82b705eda9f4ac45b1f5aa1fc34316744b66ad8e4d20f7d7705","afterSHA256":"cbf83d8e6014f82b705eda9f4ac45b1f5aa1fc34316744b66ad8e4d20f7d7705","reason":"Same source body in authored semantic page"}],"blocks":[{"id":"b-437e38778468458f863df87d","type":"p","scope":"document","url":"https://codingai-lec03.pages.dev/course/notebook-blocks/26c6c8535ba248998b17337eae768d44.html#b-437e38778468458f863df87d","content":"[LAB 11 · 从 RGB 到像素：读出、FCN 与边界](/course/notebooks/9e268706471944e3a59e6f568f9ce9a3.html)","sha256":"f6dfd09a50caab375f02e0abcc3ff7a454ea579ed8eef0c35b95c95b0619c304","chapter":{"id":"course","title":"参数更新和三个单条件比较 · 实现代码"},"unit":{"id":"notebook-blocks/26c6c8535ba248998b17337eae768d44","title":"参数更新和三个单条件比较 · 实现代码"},"page":{"id":"reading-opening","title":"参数更新和三个单条件比较 · 实现代码","number":1},"sectionTitle":"参数更新和三个单条件比较 · 实现代码","currentQuestion":"参数更新和三个单条件比较 · 实现代码","sourceSlides":[],"knowledgeBlock":null,"formulas":[],"previousBlock":null,"nextBlock":"b-dd0dab3c70b4dbcc7715158e","prerequisites":[],"relatedBlocks":[]},{"id":"b-dd0dab3c70b4dbcc7715158e","type":"h1","scope":"document","url":"https://codingai-lec03.pages.dev/course/notebook-blocks/26c6c8535ba248998b17337eae768d44.html#b-dd0dab3c70b4dbcc7715158e","content":"# 参数更新和三个单条件比较 · 实现代码","sha256":"9fab536815fa25e7ec4f4cdfff09b63be580a962ee0c201d9a517a56d3344371","chapter":{"id":"course","title":"参数更新和三个单条件比较 · 实现代码"},"unit":{"id":"notebook-blocks/26c6c8535ba248998b17337eae768d44","title":"参数更新和三个单条件比较 · 实现代码"},"page":{"id":"reading-opening","title":"参数更新和三个单条件比较 · 实现代码","number":1},"sectionTitle":"参数更新和三个单条件比较 · 实现代码","currentQuestion":"参数更新和三个单条件比较 · 实现代码","sourceSlides":[],"knowledgeBlock":null,"formulas":[],"previousBlock":"b-437e38778468458f863df87d","nextBlock":"b-82bbe9be4fa50d5f5005dc0a","prerequisites":[{"id":"b-437e38778468458f863df87d","url":"#b-437e38778468458f863df87d","role":"problem-context"}],"relatedBlocks":[]},{"id":"b-82bbe9be4fa50d5f5005dc0a","type":"p","scope":"document","url":"https://codingai-lec03.pages.dev/course/notebook-blocks/26c6c8535ba248998b17337eae768d44.html#b-82bbe9be4fa50d5f5005dc0a","content":"按问题继续","sha256":"e91f24e4e4ca40e2099a0d81d30db6568f4bf2074b499eeee6e3959617bd97ac","chapter":{"id":"course","title":"参数更新和三个单条件比较 · 实现代码"},"unit":{"id":"notebook-blocks/26c6c8535ba248998b17337eae768d44","title":"参数更新和三个单条件比较 · 实现代码"},"page":{"id":"reading-opening","title":"参数更新和三个单条件比较 · 实现代码","number":1},"sectionTitle":"参数更新和三个单条件比较 · 实现代码","currentQuestion":"参数更新和三个单条件比较 · 实现代码","sourceSlides":[],"knowledgeBlock":null,"formulas":[],"previousBlock":"b-dd0dab3c70b4dbcc7715158e","nextBlock":"b-be7bb5eb54ec3067d09c1c90","prerequisites":[{"id":"b-dd0dab3c70b4dbcc7715158e","url":"#b-dd0dab3c70b4dbcc7715158e","role":"section-title"},{"id":"b-437e38778468458f863df87d","url":"#b-437e38778468458f863df87d","role":"problem-context"}],"relatedBlocks":[]},{"id":"b-be7bb5eb54ec3067d09c1c90","type":"p","scope":"document","url":"https://codingai-lec03.pages.dev/course/notebook-blocks/26c6c8535ba248998b17337eae768d44.html#b-be7bb5eb54ec3067d09c1c90","content":"前景/背景/mIoU口径、RGB到mask训练、FCN与1×1读出及边界","sha256":"6f0b115c3c32032428a4c0d5ec4791e16d6b63aa3d643457bed758bf6af2b765","chapter":{"id":"course","title":"参数更新和三个单条件比较 · 实现代码"},"unit":{"id":"notebook-blocks/26c6c8535ba248998b17337eae768d44","title":"参数更新和三个单条件比较 · 实现代码"},"page":{"id":"reading-opening","title":"参数更新和三个单条件比较 · 实现代码","number":1},"sectionTitle":"参数更新和三个单条件比较 · 实现代码","currentQuestion":"参数更新和三个单条件比较 · 实现代码","sourceSlides":[],"knowledgeBlock":null,"formulas":[],"previousBlock":"b-82bbe9be4fa50d5f5005dc0a","nextBlock":"b-b5bcde49457bd7b8560a49d4","prerequisites":[{"id":"b-dd0dab3c70b4dbcc7715158e","url":"#b-dd0dab3c70b4dbcc7715158e","role":"section-title"},{"id":"b-437e38778468458f863df87d","url":"#b-437e38778468458f863df87d","role":"problem-context"}],"relatedBlocks":[]},{"id":"b-b5bcde49457bd7b8560a49d4","type":"pre","scope":"document","url":"https://codingai-lec03.pages.dev/course/notebook-blocks/26c6c8535ba248998b17337eae768d44.html#b-b5bcde49457bd7b8560a49d4","content":"```\n%%writefile -a lab11_segmentation.py\ndef run(out='lab11-results',epochs=20):\n    started=datetime.now(timezone.utc).isoformat();start=time.time();out=Path(out);out.mkdir(exist_ok=True,parents=True);seed_all(19)\n    warmup=sampling_warmup(out)\n    train,_,raw_train=make_scenes(384,7101);test,_,raw_test=make_scenes(128,7901)\n    small,_,raw_small=make_scenes(128,7901,scale=.45)\n    target=with_ignore(raw_train);test_target=with_ignore(raw_test);small_target=with_ignore(raw_small)\n    readout=PixelReadout();pixel_history=train_model(readout,train,target,epochs=25,lr=.03)\n    fcn=SmallFCN();random_pred=predict(fcn,test);history=train_model(fcn,train,target,epochs=epochs,lr=.003)\n    pred=predict(fcn,test);nearest_pred=predict(fcn,test,mode='nearest');small_pred=predict(fcn,small)\n    # Same image/target, blur changes RGB only, preserving geometry and label.\n    blurred=F.avg_pool2d(F.pad(test,(2,2,2,2),mode='reflect'),5,stride=1);blur_pred=predict(fcn,blurred)\n    # ignore_index check: arbitrarily changing predictions only at ignored pixels leaves metrics identical.\n    altered=pred.clone();altered[test_target==255]=(altered[test_target==255]+1)%3\n    assert segmentation_metrics(pred,test_target)==segmentation_metrics(altered,test_target)\n    # Synchronized flip can be undone on both image and categorical target.\n    assert torch.equal(train.flip(-1).flip(-1),train) and torch.equal(target.flip(-1).flip(-1),target)\n    results={'provenance':provenance(__file__,started),'config':{'image_shape':[3,48,48],'logits_shape':['B',3,48,48],'target_shape':['B',48,48],\n            'target_dtype':'int64','classes':{'0':'background','1':'red rectangle','2':'blue ellipse'},'ignore_label':255,\n            'train_count':384,'heldout_count':128,'split_seeds':[7101,7901],'seed':19,'FCN_epochs':epochs,'readout_epochs':25,\n            'loss':'cross_entropy on valid pixels, ignore_index=255','optimizer':'Adam FCN lr=.003; pixel readout lr=.03',\n            'FCN_parameters':sum(p.numel() for p in fcn.parameters()),'readout_parameters':sum(p.numel() for p in readout.parameters()),\n            'upsampling':'12x12 coarse logits ->48x48 bilinear align_corners=False + fine skip logits','augmentation':'paired horizontal flip',\n            'data_identity':'generated scenes with color/shape correlated; heldout original scene seeds; no pretrained weights'},\n            'sampling_warmup':warmup,'random_FCN':segmentation_metrics(random_pred,test_target),\n            'learned_pixel_readout':segmentation_metrics(predict(readout,test),test_target),'trained_FCN':segmentation_metrics(pred,test_target),\n            'condition_nearest_logits':segmentation_metrics(nearest_pred,test_target),'condition_scale_045':segmentation_metrics(small_pred,small_target),\n            'condition_RGB_blur5':segmentation_metrics(blur_pred,test_target),'readout_RGB_blur5':segmentation_metrics(predict(readout,blurred),test_target),'readout_scale_045':segmentation_metrics(predict(readout,small),small_target),'history_FCN':history,'history_pixel_readout':pixel_history,\n            'ignore_metric_invariance_test':'passed','paired_flip_involution_test':'passed','sampling_known_values_tests':'passed','seconds':time.time()-start}\n    counts=((pred!=test_target)&(test_target!=255)).flatten(1).sum(1);worst=counts.argsort(descending=True)[:4].tolist()\n    results['failure_examples']=[{'sample_index':i,'wrong_valid_pixels':int(counts[i])} for i in worst]\n    torch.save({'state_dict':fcn.state_dict(),'config':results['config']},out/'fcn.pt');torch.save(readout.state_dict(),out/'pixel-readout.pt')\n    np.savez_compressed(out/'heldout-input-target-predictions.npz',images=test.numpy(),target=test_target.numpy(),prediction=pred.numpy(),\n                       half_scale_images=small.numpy(),half_scale_target=small_target.numpy(),half_scale_prediction=small_pred.numpy(),blur_images=blurred.numpy(),blur_prediction=blur_pred.numpy())\n    plot_predictions(test,test_target,pred,out/'heldout-segmentation.png','FCN heldout image-to-mask predictions')\n    plot_predictions(test,test_target,pred,out/'failure-segmentation.png','Four largest valid-pixel error counts',worst)\n    plot_predictions(small,small_target,small_pred,out/'small-object-segmentation.png','Same latent scenes: object dimensions x0.45')\n    plot_predictions(blurred,test_target,blur_pred,out/'blur-segmentation.png','Same geometry, RGB blurred with 5x5 average')\n    fig,ax=plt.subplots(figsize=(7,4));ax.plot(history,label='FCN');ax.plot(pixel_history,label='pixel softmax readout');ax.set(xlabel='epoch (zero based)',ylabel='valid-pixel CE');ax.legend();fig.tight_layout();fig.savefig(out/'training-curve.png',dpi=150);plt.close(fig)\n    save_json(out/'run.json',results);print(json.dumps({k:results[k]['mIoU_3_classes'] for k in ['random_FCN','learned_pixel_readout','trained_FCN','condition_scale_045','condition_RGB_blur5']},indent=2),flush=True)\n    return results\n\nif __name__=='__main__':\n    p=argparse.ArgumentParser();p.add_argument('--out',default='lab11-results');p.add_argument('--epochs',type=int,default=20);a=p.parse_args();run(a.out,a.epochs)\n\n```","sha256":"cbf83d8e6014f82b705eda9f4ac45b1f5aa1fc34316744b66ad8e4d20f7d7705","chapter":{"id":"course","title":"参数更新和三个单条件比较 · 实现代码"},"unit":{"id":"notebook-blocks/26c6c8535ba248998b17337eae768d44","title":"参数更新和三个单条件比较 · 实现代码"},"page":{"id":"reading-opening","title":"参数更新和三个单条件比较 · 实现代码","number":1},"sectionTitle":"参数更新和三个单条件比较 · 实现代码","currentQuestion":"参数更新和三个单条件比较 · 实现代码","sourceSlides":[],"knowledgeBlock":null,"formulas":[],"previousBlock":"b-be7bb5eb54ec3067d09c1c90","nextBlock":null,"prerequisites":[{"id":"b-dd0dab3c70b4dbcc7715158e","url":"#b-dd0dab3c70b4dbcc7715158e","role":"section-title"},{"id":"b-437e38778468458f863df87d","url":"#b-437e38778468458f863df87d","role":"problem-context"}],"relatedBlocks":[]}]}
