Datasets:
Formats:
json
Languages:
English
Size:
< 1K
ArXiv:
Tags:
mathematics
optimization
gradient-descent
convex-optimization
learning-theory
recursive-self-improvement
Download research/code/make_figures.py from PureOne/Nhoryun-Omega-III: direct link, hf CLI and curl.
- Browser
- Download file 6.2 kB
-
https://huggingface.co/datasets/PureOne/Nhoryun-Omega-III/resolve/main/research/code/make_figures.py
- Command line
-
hf download hf://datasets/PureOne/Nhoryun-Omega-III/research/code/make_figures.py
-
curl -L -o make_figures.py https://huggingface.co/datasets/PureOne/Nhoryun-Omega-III/resolve/main/research/code/make_figures.py
6.2 kB
| #!/usr/bin/env python3 | |
| """Recreate mathematical illustrations; decimal plot data are not proofs.""" | |
| from __future__ import annotations | |
| import csv | |
| import math | |
| from pathlib import Path | |
| import numpy as np | |
| import matplotlib | |
| matplotlib.use('Agg') | |
| import matplotlib.pyplot as plt | |
| from verify_witness import actual_trajectory | |
| ROOT=Path(__file__).resolve().parents[1] | |
| FIG=ROOT/'figures' | |
| DATA=ROOT/'data' | |
| FIG.mkdir(exist_ok=True);DATA.mkdir(exist_ok=True) | |
| plt.rcParams.update({ | |
| 'font.family':'DejaVu Sans','font.size':9,'axes.spines.top':False, | |
| 'axes.spines.right':False,'axes.labelcolor':'#193449','text.color':'#193449', | |
| 'axes.edgecolor':'#84949E','axes.titlesize':10,'figure.titlesize':12, | |
| 'pdf.fonttype':42}) | |
| TEAL='#006978';PLUM='#72476E';GREEN='#397D5A';GREY='#8899A6' | |
| def save(fig,name): | |
| fig.savefig(FIG/(name+'.pdf'),bbox_inches='tight') | |
| fig.savefig(FIG/(name+'.png'),dpi=210,bbox_inches='tight') | |
| plt.close(fig) | |
| def witness(): | |
| m=32;M=m+1 | |
| a,mu,h,states,values=actual_trajectory(m) | |
| vals=np.array([float(x) for x in values]) | |
| dec=np.array([float(values[i]-values[i+1]) for i in range(M)]) | |
| curv=np.array([float(values[i]-2*values[i+1]+values[i+2]) for i in range(m)]) | |
| fig,ax=plt.subplots(1,3,figsize=(8.4,2.65),layout='constrained') | |
| ax[0].plot(vals,color=TEAL,lw=2);ax[0].set(title='Loss decreases',xlabel='Iteration k',ylabel=r'$H_a(x_k)$') | |
| ax[1].plot(dec*1e3,color=PLUM,lw=2);ax[1].set(title='Improvements increase',xlabel='Step k',ylabel=r'$10^3 D_k$') | |
| ax[2].plot(curv*1e5,color=TEAL,lw=2,label='Exact rational trajectory') | |
| ax[2].axhline(-float(a*a)*885/512*1e5,color=PLUM,ls='--',label='Proved upper bound') | |
| ax[2].set(title='Strict negative curvature',xlabel='Index k',ylabel=r'$10^5\kappa_k$') | |
| ax[2].legend(fontsize=6.8,loc='center',bbox_to_anchor=(.50,.59)) | |
| for q in ax:q.grid(axis='y',alpha=.17) | |
| fig.suptitle(f'm = 32; condition number = {128*M:,}; normalized step = {float(h):.8f}') | |
| save(fig,'witness_m32') | |
| with (DATA/'witness_m32_plot_data.csv').open('w',newline='') as f: | |
| w=csv.writer(f);w.writerow(['k','loss_decimal_approx','decrement_decimal_approx','second_difference_decimal_approx']) | |
| for k,v in enumerate(vals):w.writerow([k,v,dec[k] if k<len(dec) else '',curv[k] if k<len(curv) else '']) | |
| def information(): | |
| mu=.25;L=1.;b=.5;v=1.;eta=.5;t=5 | |
| x=np.linspace(-4.5,4.5,700) | |
| f=lambda x,a: np.where(x<0,v*x+a*x*x/2,v*x+b*x*x/2) | |
| fig,ax=plt.subplots(1,2,figsize=(8.2,3.0),layout='constrained') | |
| ax[0].plot(x,f(x,mu),color=TEAL,lw=2,label='Hidden curvature 1/4') | |
| ax[0].plot(x,f(x,L),color=PLUM,lw=2,ls='--',label='Hidden curvature 1') | |
| ax[0].axvspan(0,4.5,color='#E8EEF0',zorder=-1) | |
| ax[0].axvline(0,color=GREY,lw=.8) | |
| ax[0].set(title='Identical observed half-line',xlabel='Parameter x',ylabel='Objective value') | |
| ax[0].text(1.0,5.8,'Same values\nand gradients',fontsize=8) | |
| ax[0].legend(fontsize=7,loc='upper left') | |
| n=np.arange(0,21) | |
| for a,col,lab in [(mu,TEAL,'Remaining gap = 2'),(L,PLUM,'Remaining gap = 1/2')]: | |
| gain=v*v/(2*a)*(1-(1-eta*a)**(2*n)) | |
| ax[1].plot(n,gain,color=col,lw=2,label=lab) | |
| ax[1].set(title='Different future improvement',xlabel='Additional gradient steps',ylabel='Cumulative improvement') | |
| ax[1].legend(fontsize=8,loc='lower right') | |
| for q in ax:q.grid(alpha=.14) | |
| save(fig,'information_barrier') | |
| def smoothing(): | |
| m=np.array([1,2,4,8,16,32,64,128,256,512]) | |
| M=m+1.;a=1/(8*M) | |
| sigma=a/(2*np.sqrt(2*np.log(64/a**2))) | |
| fig,ax=plt.subplots(1,2,figsize=(8.1,3),layout='constrained') | |
| ax[0].loglog(M,sigma,'o-',color=TEAL,label='Quadratic-chamber theorem') | |
| ax[0].set(xlabel='M = m + 1',ylabel='Gaussian standard deviation',title='Certified analytic smoothing width') | |
| ax[1].loglog(M,128*M,'o-',color=PLUM) | |
| ax[1].set(xlabel='M = m + 1',ylabel='Exact condition number',title='Linear conditioning for long runs') | |
| for q in ax:q.grid(which='both',alpha=.15) | |
| save(fig,'analytic_scales') | |
| def boundaries(): | |
| hc=1.75;hi=(19-math.sqrt(17))/8;hs=1.863425364363717532 | |
| fig,ax=plt.subplots(1,2,figsize=(8.4,3.2),layout='constrained', | |
| gridspec_kw={'width_ratios':[1.35,1]}) | |
| names=['Every curvature nonnegative','Two-step compensation', | |
| 'No adjacent negative curvatures','Stable objective descent'] | |
| values=[hc,hi,hs,2.] | |
| colors=[TEAL,PLUM,GREEN,GREY] | |
| for i,(name,v,col) in enumerate(zip(names,values,colors)): | |
| y=3-i | |
| ax[0].barh(y,v-1.65,left=1.65,color=col,height=.28,alpha=.85) | |
| ax[0].text(1.653,y+.24,name,fontsize=7.8,va='bottom') | |
| ax[0].text(v+.004,y,f'{v:.6f}' if i in (1,2) else f'{v:g}', | |
| fontsize=7.1,va='center') | |
| ax[0].set(xlim=(1.65,2.065),ylim=(-.45,3.7),yticks=[], | |
| xlabel=r'Normalized step $h=\eta L$',title='Different universal guarantees') | |
| ax[0].set_xticks([1.7,1.8,1.9,2.]) | |
| for spine in ['left','top','right']:ax[0].spines[spine].set_visible(False) | |
| ax[1].axvspan(1.855,hi,color=PLUM,alpha=.15) | |
| ax[1].axvspan(hi,hs,color=GREEN,alpha=.18) | |
| ax[1].axvspan(hs,1.868,color=GREY,alpha=.2) | |
| ax[1].axvline(hi,color=PLUM,lw=1.5);ax[1].axvline(hs,color=GREEN,lw=1.5) | |
| ax[1].text((1.855+hi)/2,.63,'Compensation\nguaranteed',ha='center',fontsize=8) | |
| ax[1].text((hi+hs)/2,.30,'Compensation\nmay fail;\nadjacent negative\npairs still excluded',ha='center',fontsize=7.3) | |
| ax[1].text((hs+1.868)/2,.63,'Adjacent\nnegatives\npossible',ha='center',fontsize=8) | |
| ax[1].text(hi,.98,r'$h_{\mathrm{iso}}$',ha='center',va='top',color=PLUM) | |
| ax[1].text(hs,.98,r'$h_*$',ha='center',va='top',color=GREEN) | |
| ax[1].set(xlim=(1.855,1.868),ylim=(0,1),yticks=[],xlabel=r'Normalized step $h$', | |
| title='The two nearby boundaries') | |
| ax[1].set_xticks([1.856,1.860,1.864,1.868]) | |
| ax[1].tick_params(axis='x',labelsize=7.8) | |
| for spine in ['left','top','right']:ax[1].spines[spine].set_visible(False) | |
| save(fig,'phase_boundaries') | |
| if __name__=='__main__': | |
| witness();information();smoothing();boundaries() | |
| print('Created witness_m32, information_barrier, analytic_scales, phase_boundaries (PDF and PNG).') | |