code
stringlengths
38
801k
repo_path
stringlengths
6
263
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="GqOP27Nw7Ah0" colab_type="text" # ## Python Numbers # Python has several built-in types for general programming. It also supports custom types known as Classes. Not all classes are technically Types as in Type Theory, but it is a good way to start thinking about them. A true Pythonista can create their own type and define what math means for that type. Basically, we can invent math. More on this in the classes module. # # In this section we will focus on the three most common types of numbers in Python: # # - Integer `int`: Python supports big integers - this is a colossal understatement. Python can handle an integer so big it takes all of your available RAM. # # - Float `float`: Python supports 64bit floating point approximation of real numbers. # # - Complex `complex`: Python supports Complex Numbers, like in most engineering fields the letter j is used in Python to distinguish values on the complex plane. # # ```python # my_int: int = 42 # my_float: float = 3.14159265359 # my_complex: complex = 2 + 3j # # print(my_int) # print(my_float) # print(my_complex) # ``` # # ``` # 42 # 3.14159265359 # (2+3j) # ``` # # In the above example the colon and type name are optional, Python does not enforce these types! The type hints are for human readers, not Python. Future versions of Python may support strict typing. # # The code below is effectively the same as above. # # ```python # my_int = 42 # my_float = 3.14159265359 # my_complex = 2 + 3j # # print(my_int) # print(my_float) # print(my_complex) # ``` # # ``` # 42 # 3.14159265359 # (2+3j) # ``` # # + id="TQSJgQ1yKGPR" colab_type="code" colab={}
WEEKS/CD_Sata-Structures/_RESOURCES/python-prac/Intro_to_Python/02_numbers.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Bit serial computation - Dot product # # The notebook illustrates that bit-serial computation of a dot product of a an operand `A` by an operand `B`, where the `A` operand is a set of values viewed at the bit level. This computation can be viewed as tensor computation where the bit-level representation of `A` is achieved with a rank-2 tensor where the lower rank is a set of sparse fibers with a 1 at those coordinates that match the bit-positions with a 1 in the binary representation of the value. The operand `B` is simply represented as a rank-1 tensor of values. As a result this computation can be represented with the following Einsum: # # $$ # Z = A_{i,j} \times B_i \times 2^j # $$ # # This representation of the calculation allows us to consider different dataflows and parallelism options, which are illustrated below. # ## Setup # # The first step is to set up the environment and create some tensors # + # Run boilerplate code to set up environment # %run ../prelude.py --style=tree --animation=movie # - # ## Configure some tensors # + # Default value for the number of elements in the dot product I = 4 # Default value for the number of bits in each elemnt of the `A` tensor J = 8 tm = TensorMaker("dot product inputs") tm.addTensor("A_IJ", rank_ids=["I", "J"], shape=[I, J], density=0.6, interval=1, seed=0, color="blue") tm.addTensor("B_I", rank_ids=["I"], shape=[I], density=1, seed=1, color="green") tm.displayControls() # - # ## Create and display the tensors # + A_IJ = tm.makeTensor("A_IJ") A_JI = A_IJ.swapRanks().setName("A_JI") B_I = tm.makeTensor("B_I") # # Calculate binary value of A from bit-wise represenation # a_values = [] for i, a_j in A_IJ: a_value = 0 for j, _ in a_j: a_value += 2**j a_values.append(a_value) print(f"A_IJ (with values {a_values})") displayTensor(A_IJ) print("A_JI") displayTensor(A_JI) print("B") displayTensor(B_I) # - # ## Create power array # # Although the original Einsum notation includes a multiplication by a value that is a function only of an index value (`2^j`), this code will express that as a multiplicaton by a value from a constant rank-1 tensor (`pow2`). In reality, this would probably be implemented directly in hardware (in this case as a **shift**). # + pow2 = Tensor(rank_ids=["J"], shape=[J], name="Pow2", color="lightblue") pow2_j = pow2.getRoot() for j, pow2_ref in pow2_j.iterShapeRef(): pow2_ref <<= 2 ** j displayTensor(pow2) # - # ## Serial execution # # Observations: # # - Since both `a_i` and `b_i` are dense they can be uncompressed and their intersection in trivial # - Since `a_j` is compressed and `pow2` can be uncompressed their intersection can be leader-follower # - Elapsed time is proportional to the total occupancy of all the fibers in the `J` rank of `A_IJ`. # + z = Tensor(rank_ids=[], name="Dot Prod") a_i = A_IJ.getRoot() b_i = B_I.getRoot() pow2_j = pow2.getRoot() z_ref = z.getRoot() canvas = createCanvas(A_IJ, B_I, pow2, z) for i, (a_j, b_val) in a_i & b_i: for j, (a_val, pow2_val) in a_j & pow2_j: z_ref += (a_val * b_val) * pow2_val canvas.addFrame((i,j),(i,),(j,), (0,)) displayTensor(z) displayCanvas(canvas) # - # ## Parallel across B's # # Observations: # # - Time is equal to the occupancy of the longest fiber in the `J` rank of `A` # + z = Tensor(rank_ids=[], name="Dot Prod") a_i = A_IJ.getRoot() b_i = B_I.getRoot() pow2_j = pow2.getRoot() z_ref = z.getRoot() canvas = createCanvas(A_IJ, B_I, pow2, z) for i, (a_j, b_val) in a_i & b_i: for n_j, (j, (a_val, pow2_val)) in enumerate(a_j & pow2_j): z_ref += (a_val * b_val) * pow2_val canvas.addActivity((i,j),(i,),(j,), (0,), spacetime=(i, n_j)) displayTensor(z) displayCanvas(canvas) # - # ## Parallel across bits # # Observations: # # - Lantency is the occupancy of the longest fibers in the `I` of the `A_JI` tensor # + z = Tensor(rank_ids=[], name="Dot Prod") a_j = A_JI.getRoot() b_i = B_I.getRoot() pow2_j = pow2.getRoot() z_ref = z.getRoot() canvas = createCanvas(A_IJ, A_JI, B_I, pow2, z) for j, (a_i, pow2_val) in a_j & pow2_j: for n_i, (i, (a_val, b_val)) in enumerate(a_i & b_i): z_ref += (a_val * b_val) * pow2_val canvas.addActivity((i,j),(j,i),(i,),(j,), (0,), spacetime=(j, n_i)) displayTensor(z) displayCanvas(canvas) # - # ## Parallel across bits (limited parallelism) # # But limit parallelism to `I` to make fair comparison to `B` parallel. In this design, there is a barrier between the processing of each group of `I` bits, i.e., between the processing of each fiber of the `j0` rank of the split `A_JI` tensor. # # Observations: # # - Latency is the sum of the largest occupancies of the `I` rank for each of the fibers in the `j0` rank of the split `A_JI` tensor # + A_JI_split = A_JI.splitUniform(I) displayTensor(A_JI_split) # + z = Tensor(rank_ids=[], name="Dot Prod") a_j1 = A_JI_split.getRoot() b_i = B_I.getRoot() pow2_j = pow2.getRoot() z_ref = z.getRoot() canvas = createCanvas(A_IJ, A_JI_split, B_I, pow2, z) for n_j1, (j1, a_j0) in enumerate(a_j1): for j, (a_i, pow2_val) in a_j0 & pow2_j: for n_i, (i, (a_val, b_val)) in enumerate(a_i & b_i): z_ref += (a_val * b_val) * pow2_val canvas.addActivity((i,j),(j1,j,i),(i,),(j,), (0,), spacetime=(j-j1, (n_j1,n_i))) displayTensor(z) displayCanvas(canvas) # - # ## ## Parallel across bits (limited parallelism) # # Allowing slip between groups of bits, i.e., relaxes bit-level barrier. However, each PE works on a fixed position in each fiber in `a_j0`. # # Observation: # # - Each PE is busy for the sum of the occupancies of the `a_i` fibers at that PE's position in the `a_j0` fibers # - Latency is equal long pole PE. # + z = Tensor(rank_ids=[], name="Dot Prod") a_j1 = A_JI_split.getRoot() b_i = B_I.getRoot() pow2_j = pow2.getRoot() z_ref = z.getRoot() cycles = I*[0] canvas = createCanvas(A_IJ, A_JI_split, B_I, pow2, z) for n_j1, (j1, a_j0) in enumerate(a_j1): for j, (a_i, pow2_val) in a_j0 & pow2_j: for n_i, (i, (a_val, b_val)) in enumerate(a_i & b_i): z_ref += (a_val * b_val) * pow2_val pe = j-j1 canvas.addActivity((i,j),(j1,j,i),(i,),(j,), (0,), spacetime=(pe, cycles[pe])) cycles[pe] += 1 displayTensor(z) displayCanvas(canvas) # -
notebooks/bit-serial/bit-serial-dot-product.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- # ## Pool characteristics for tracers in BARKLEY run # # Lin # Sal # Nit # Oxy # Sil # Pho # NOx # Met # Alk # DIC import cmocean as cmo from netCDF4 import Dataset import matplotlib.pyplot as plt # %matplotlib inline import numpy as np import seaborn as sns import xarray as xr import canyon_tools.readout_tools as rout import canyon_tools.savitzky_golay as sg sns.set_context('talk') sns.set_style('whitegrid') # + # Grid, state and tracers datasets of base case grid_file = '/data/kramosmu/results/TracerExperiments/BARKLEY_II/run01/gridGlob.nc' state_file = '/data/kramosmu/results/TracerExperiments/BARKLEY_II/run01/stateGlob.nc' ptracers_file = '/data/kramosmu/results/TracerExperiments/BARKLEY_II/run01/ptracersGlob.nc' ptracers_fileNoC = '/data/kramosmu/results/TracerExperiments/BARKLEY_II/run02/ptracersGlob.nc' # + with Dataset(grid_file, 'r') as nbl: Z = nbl.variables['RC'][:] X = nbl.variables['X'][:] Y = nbl.variables['Y'][:] hFacC = nbl.variables['HFacC'][:] rA = nbl.variables['rA'][:] Depth = nbl.variables['Depth'][:] with Dataset(state_file, 'r') as nbl: iters = nbl.variables['iter'][:] # + labels = ['Linear','Salinty','Oxygen','Nitrate','Silicate','Phosphate','Nitrous-oxide','Methane', 'Alkalinity', 'DIC'] colours = ['purple','blue','green','gold','orange','red','orchid','teal', 'magenta', 'olive'] tracer_names = ['Tr01','Tr02','Tr03','Tr04','Tr05','Tr06','Tr07','Tr08', 'Tr09', 'Tr10'] fig,ax = plt.subplots(1,1,figsize=(6,8)) with Dataset(ptracers_file, 'r') as nbl: for trac, lab, col in zip(tracer_names, labels, colours): profile = nbl.variables[trac][0,0:50,50,180] C0 = profile[29] ax.plot(profile/C0,Z[0:50],color=col,label=lab) ax.set_xlabel(r'$C/C_{SB}$ (t=0)') ax.set_ylabel('Depth (m)') ax.set_title('Initial profiles') ax.legend(loc=0) # + def mask2DCanyon(bathy, sbdepth=-152.5): '''Mask out the canyon from the shelf. bathy : depths 2D array from the grid file sbdepth: shelf depth, always negative float Returns mask''' bathyMasked = np.ma.masked_less(-bathy, -152.5) return(bathyMasked.mask) def ConcAreaFunc(Tr, hfac, ra, bathy, sbdepth=-152.5): '''Tr: Tracer field (nt,nz,ny,nx) hfac: fraction of open cell at center (nz,ny,nx) ra: array of cell horizontal areas (ny,nx) bathy : depths 2D array from the grid file (ny,nx) sbdepth: shelf break depth (negative value) RETURNS: ConcArea = concentration at cell closest to bottom times its area (nt,ny,nx) Conc = cocnetration near bottom (nt,ny,nx)''' ConcArea = np.empty((360,616)) Conc = np.empty((360,616)) ConcFiltered = np.empty((360,616)) Area = np.empty((360,616)) BottomInd = np.argmax(hfac[::-1,:,:]>0.0,axis=0) # start looking for first no-land cell from the bottom up. BottomInd = np.ones(np.shape(BottomInd))*89 - BottomInd # Get index of unreversed z axis for j in range(616): for i in range(360): TrBottom = Tr[BottomInd[i,j],i,j] if TrBottom > 0.0: ConcArea[i,j] = TrBottom*ra[i,j] Conc[i,j] = TrBottom Area[i,j] = ra[i,j] else: ConcArea[i,j] = np.NaN Conc[i,j] = np.NaN Area[i,j] = np.NaN # Filter step noise ConcFiltered[:,j] = sg.savitzky_golay(Conc[:,j], 7,3) maskShelf = mask2DCanyon(bathy, sbdepth) maskShelf = np.expand_dims(maskShelf,0) # expand along time dimension maskShelf = maskShelf + np.zeros(Conc.shape) return (ConcArea, np.ma.masked_array(ConcFiltered, mask=maskShelf), Area, ) def PlotBAC(ax,ConcFilt,xslice,yslice,cmap=cmo.cm.tempo, maxCM=9999, minCM=9999): BAC = ConcFilt[yslice,xslice] if maxCM == 9999: maxCM = np.nanmax(ConcFilt[yslice,xslice]) minCM = np.nanmin(ConcFilt[yslice,xslice]) mesh = ax.contourf(X[xslice]/1000,Y[yslice]/1000,BAC,21, vmax=maxCM, vmin=minCM, cmap=cmap) #cbar_ax = fig.add_axes([0.9, 0.327, 0.015, 0.252]) #cb=fig.colorbar(mesh, cax=cbar_ax,ticks=[5.2,6.2,7.2,8.2,9.2,10.2],format='%.1f') #cb.ax.yaxis.set_tick_params(pad=1) fig.colorbar(mesh,ax=ax) #ax.set_axis_bgcolor((205/255.0, 201/255.0, 201/255.0)) SB = ax.contour(X[xslice]/1000,Y[yslice]/1000, Depth[yslice,xslice], [150.0], colors='0.1',linewidths=[0.75] ) ax.tick_params(axis='x', pad=1) ax.tick_params(axis='y', pad=1) # + ConcFilt1 = np.ma.empty((3,360,616)) # saving 3 time outputs, nx,ny ConcFilt2 = np.ma.empty((3,360,616)) ConcFilt3 = np.ma.empty((3,360,616)) ConcFilt4 = np.ma.empty((3,360,616)) ConcFilt5 = np.ma.empty((3,360,616)) ConcFilt6 = np.ma.empty((3,360,616)) ConcFilt7 = np.ma.empty((3,360,616)) ConcFilt8 = np.ma.empty((3,360,616)) ConcFilt9 = np.ma.empty((3,360,616)) ConcFilt10 = np.ma.empty((3,360,616)) concList = [ConcFilt1,ConcFilt2,ConcFilt3,ConcFilt4,ConcFilt5,ConcFilt6,ConcFilt7,ConcFilt8, ConcFilt9, ConcFilt10] for trac,conc in zip(tracer_names, concList): with Dataset(ptracers_file, 'r') as nbl: ConcArea, conc[0,:,:], Area = ConcAreaFunc(nbl.variables[trac][0,:,:,:],hFacC,rA,Depth) ConcArea, conc[1,:,:], Area = ConcAreaFunc(nbl.variables[trac][7,:,:,:],hFacC,rA,Depth) ConcArea, conc[2,:,:], Area = ConcAreaFunc(nbl.variables[trac][14,:,:,:],hFacC,rA,Depth) print('done with tracer %s' %trac ) # + # General input nx = 616 ny = 360 nz = 90 nt = 19 # t dimension size yslice = slice(225,360) xslice = slice(0,616) # + fig, ax = plt.subplots(10,4,figsize=(16,20)) timesInd = [0,7,14] # days I saved above for ii,tt in zip(range(0,3),timesInd): PlotBAC(ax[0,ii],ConcFilt1[ii,:,:],xslice,yslice) PlotBAC(ax[1,ii],ConcFilt2[ii,:,:],xslice,yslice) PlotBAC(ax[2,ii],ConcFilt3[ii,:,:],xslice,yslice) PlotBAC(ax[3,ii],ConcFilt4[ii,:,:],xslice,yslice) PlotBAC(ax[4,ii],ConcFilt5[ii,:,:],xslice,yslice) PlotBAC(ax[5,ii],ConcFilt6[ii,:,:],xslice,yslice) PlotBAC(ax[6,ii],ConcFilt7[ii,:,:],xslice,yslice) PlotBAC(ax[7,ii],ConcFilt8[ii,:,:],xslice,yslice) PlotBAC(ax[8,ii],ConcFilt9[ii,:,:],xslice,yslice) PlotBAC(ax[9,ii],ConcFilt10[ii,:,:],xslice,yslice) ax[0,ii].set_title('%1.1f days' % ((iters[tt]*40)/(3600*24))) with Dataset(ptracers_file, 'r') as nbl: for trac, ii in zip(tracer_names, range(len(tracer_names))): profile = nbl.variables[trac][0,0:50,50,180] C0 = profile[29] ax[ii,3].plot(profile/C0,Z[0:50],color='green') ax[ii,3].yaxis.tick_right() ax[ii,3].yaxis.set_label_position("right") ax[ii,3].set_ylabel('Depth (m)') ax[ii,0].set_ylabel('CS distance (km)',labelpad=0.3) ax[7,3].set_xlabel(r'Concentration ($\mu$M)') ax[0,2].text(0.6,0.8,'ABC ($\mu$M)',transform=ax[0,2].transAxes) ax[7,0].set_xlabel('Alongshore distance (km)',labelpad=0.3) ax[7,1].set_xlabel('Alongshore distance (km)',labelpad=0.3) ax[7,2].set_xlabel('Alongshore distance (km)',labelpad=0.3) # + ConcFilt1NoC = np.ma.empty((3,360,616)) # saving 3 time outputs, nx,ny ConcFilt2NoC = np.ma.empty((3,360,616)) ConcFilt3NoC = np.ma.empty((3,360,616)) ConcFilt4NoC = np.ma.empty((3,360,616)) ConcFilt5NoC = np.ma.empty((3,360,616)) ConcFilt6NoC = np.ma.empty((3,360,616)) ConcFilt7NoC = np.ma.empty((3,360,616)) ConcFilt8NoC = np.ma.empty((3,360,616)) ConcFilt9NoC = np.ma.empty((3,360,616)) ConcFilt10NoC = np.ma.empty((3,360,616)) concList = [ConcFilt1NoC,ConcFilt2NoC,ConcFilt3NoC,ConcFilt4NoC,ConcFilt5NoC, ConcFilt6NoC,ConcFilt7NoC,ConcFilt8NoC,ConcFilt9NoC,ConcFilt10NoC] for trac,conc in zip(tracer_names, concList): with Dataset(ptracers_fileNoC, 'r') as nbl: ConcArea, conc[0,:,:], Area = ConcAreaFunc(nbl.variables[trac][0,:,:,:],hFacC,rA,Depth) ConcArea, conc[1,:,:], Area = ConcAreaFunc(nbl.variables[trac][7,:,:,:],hFacC,rA,Depth) ConcArea, conc[2,:,:], Area = ConcAreaFunc(nbl.variables[trac][14,:,:,:],hFacC,rA,Depth) print('done with tracer %s' %trac ) # + fig, ax = plt.subplots(10,4,figsize=(14,20)) timesInd = [0,7,14] # days I saved above for ii,tt in zip(range(0,3),timesInd): maxCM = np.nanmax((ConcFilt1-ConcFilt1NoC)[:,yslice,xslice]) minCM = - maxCM PlotBAC(ax[0,ii],ConcFilt1[ii,:,:]-ConcFilt1NoC[ii,:,:],xslice,yslice,cmap=cmo.cm.curl,maxCM=maxCM,minCM=minCM) maxCM = np.nanmax((ConcFilt2-ConcFilt2NoC)[:,yslice,xslice]) minCM = - maxCM PlotBAC(ax[1,ii],ConcFilt2[ii,:,:]-ConcFilt2NoC[ii,:,:],xslice,yslice,cmap=cmo.cm.curl,maxCM=maxCM,minCM=minCM) maxCM = np.nanmax((ConcFilt3-ConcFilt3NoC)[:,yslice,xslice]) minCM = - maxCM PlotBAC(ax[2,ii],ConcFilt3[ii,:,:]-ConcFilt3NoC[ii,:,:],xslice,yslice,cmap=cmo.cm.curl,maxCM=maxCM,minCM=minCM) maxCM = np.nanmax((ConcFilt4-ConcFilt4NoC)[:,yslice,xslice]) minCM = - maxCM PlotBAC(ax[3,ii],ConcFilt4[ii,:,:]-ConcFilt4NoC[ii,:,:],xslice,yslice,cmap=cmo.cm.curl,maxCM=maxCM,minCM=minCM) maxCM = np.nanmax((ConcFilt5-ConcFilt5NoC)[:,yslice,xslice]) minCM = - maxCM PlotBAC(ax[4,ii],ConcFilt5[ii,:,:]-ConcFilt5NoC[ii,:,:],xslice,yslice,cmap=cmo.cm.curl,maxCM=maxCM,minCM=minCM) maxCM = np.nanmax((ConcFilt6-ConcFilt6NoC)[:,yslice,xslice]) minCM = - maxCM PlotBAC(ax[5,ii],ConcFilt6[ii,:,:]-ConcFilt6NoC[ii,:,:],xslice,yslice,cmap=cmo.cm.curl,maxCM=maxCM,minCM=minCM) maxCM = np.nanmax((ConcFilt7-ConcFilt7NoC)[:,yslice,xslice]) minCM = - maxCM PlotBAC(ax[6,ii],ConcFilt7[ii,:,:]-ConcFilt7NoC[ii,:,:],xslice,yslice,cmap=cmo.cm.curl,maxCM=maxCM,minCM=minCM) maxCM = np.nanmax((ConcFilt8-ConcFilt8NoC)[:,yslice,xslice]) minCM = - maxCM PlotBAC(ax[7,ii],ConcFilt8[ii,:,:]-ConcFilt8NoC[ii,:,:],xslice,yslice,cmap=cmo.cm.curl,maxCM=maxCM,minCM=minCM) maxCM = np.nanmax((ConcFilt9-ConcFilt9NoC)[:,yslice,xslice]) minCM = - maxCM PlotBAC(ax[8,ii],ConcFilt9[ii,:,:]-ConcFilt9NoC[ii,:,:],xslice,yslice,cmap=cmo.cm.curl,maxCM=maxCM,minCM=minCM) maxCM = np.nanmax((ConcFilt10-ConcFilt10NoC)[:,yslice,xslice]) minCM = - maxCM PlotBAC(ax[9,ii],ConcFilt10[ii,:,:]-ConcFilt10NoC[ii,:,:],xslice,yslice,cmap=cmo.cm.curl,maxCM=maxCM,minCM=minCM) ax[0,ii].set_title('%1.1f days' % ((iters[tt]*40)/(3600*24))) with Dataset(ptracers_file, 'r') as nbl: for trac, ii in zip(tracer_names, range(len(tracer_names))): profile = nbl.variables[trac][0,0:50,50,180] C0 = profile[29] ax[ii,3].plot(profile/C0,Z[0:50],color='green') ax[ii,3].yaxis.tick_right() ax[ii,3].yaxis.set_label_position("right") ax[ii,3].set_ylabel('Depth (m)') ax[ii,0].set_ylabel('CS distance (km)',labelpad=0.3) ax[9,3].set_xlabel(r'Concentration ($\mu$M)') ax[0,2].text(0.6,0.8,'ABCA ($\mu$M)',transform=ax[0,2].transAxes) ax[9,0].set_xlabel('Alongshore distance (km)',labelpad=0.3) ax[9,1].set_xlabel('Alongshore distance (km)',labelpad=0.3) ax[9,2].set_xlabel('Alongshore distance (km)',labelpad=0.3) # - # ## Plot for OSM 2018 talk (now with DIC and ALK) # + sns.set_context('talk') tracer_names = ['Tr01','Tr02','Tr03','Tr04','Tr05','Tr06','Tr07','Tr08','Tr09','Tr10'] colours = ['dark lavender','ocean blue','kelly green','cherry red', 'tangerine','golden yellow','medium pink','turquoise', 'tan','olive'] labels = ['linear','salinty','oxygen','nitrate','silicate','phosphate','nitrous-oxide','methane', 'alkalinity', 'DIC'] fig,ax = plt.subplots(1,1,figsize=(4,6)) with Dataset('/data/kramosmu/results/TracerExperiments/CNTDIFF_STEP/run38/ptracersGlob.nc', 'r') as nbl: profile = nbl.variables['Tr1'][0,0:50,50,180] C0 = profile[29] ax.plot(profile/C0,Z[0:50],color=sns.xkcd_rgb['black'],label='base case') with Dataset(ptracers_file, 'r') as nbl: for trac, lab, col in zip(tracer_names, labels, colours): profile = nbl.variables[trac][0,0:50,50,180] C0 = profile[29] ax.plot(profile/C0,Z[0:50],color=sns.xkcd_rgb[col],label=lab) ax.set_xlabel(r'$C/C_{sb}$') ax.set_ylabel('Depth (m)') ax.set_title('Initial profiles') ax.legend(bbox_to_anchor=(1.3,-0.15), ncol = 3, frameon=True) plt.savefig('Barkley_ini_profiles.eps', format='eps', bbox_inches='tight', transparent=True) # + sns.set_context('talk') tracer_names = ['Tr03','Tr04','Tr08'] colours = ['kelly green','cherry red','turquoise'] labels = ['oxygen','nitrate','methane'] fig,ax = plt.subplots(1,1,figsize=(4,6)) with Dataset('/data/kramosmu/results/TracerExperiments/CNTDIFF_STEP/run38/ptracersGlob.nc', 'r') as nbl: profile = nbl.variables['Tr1'][0,0:50,50,180] C0 = profile[29] ax.plot(profile/C0,Z[0:50],color=sns.xkcd_rgb['black'],label='base case') with Dataset(ptracers_file, 'r') as nbl: for trac, lab, col in zip(tracer_names, labels, colours): profile = nbl.variables[trac][0,0:50,50,180] C0 = profile[29] ax.plot(profile/C0,Z[0:50],color=sns.xkcd_rgb[col],label=lab) ax.set_xlabel(r'$C/C_{sb}$') ax.set_ylabel('Depth (m)') ax.set_title('Initial profiles') ax.legend(bbox_to_anchor=(1.5,1)) plt.savefig('O2_Nit_Met_ini_profiles.eps', format='eps',bbox_inches='tight') # -
NutrientProfiles/Pool/pool_Barkley.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Primerjava pristopov za luščenje ključnih besed na povzetkih člankov s ključno besedo "Longevity" # # V tem zvezku predstavljamo primerjavo pristopov za luščenje ključnih besed iz nabora povzetkov člankov s ključno besedo "Longevity" v zbirki PubMed. # # Predstavili bomo objektivno primerjavo pristopov za luščenje besed. Primerjali bomo izluščene besede s ključnimi besedami, ki so jih označili avtorji člankov. Za vsako metodo bomo prikazali povprečno preciznost (precision), priklic (recall) in mero F1. # + import string import ast import pandas as pd import nltk from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from lemmagen.lemmatizer import Lemmatizer from lemmagen import DICTIONARY_ENGLISH from matplotlib import pyplot as plt import yake import rake from textsemantics import specific_words from utils.scores import ( precision, recall, average_precision, average_recall, average_f_score, take_n, score_in_len_range ) # - # Naložimo metapodatke in dokumente iz zbirke in dokumente preprocesiramo in izluščimo posamezne besede. # + nltk.download('stopwords', quiet=True) lemmatizer = Lemmatizer(dictionary=DICTIONARY_ENGLISH) stop_words = set(stopwords.words('english')) def preprocess(corpus): tokenizer = RegexpTokenizer("\w+") preprocessed = list() for text in corpus: text = text.translate(text.maketrans('', '', string.punctuation)) tokens = tokenizer.tokenize(text.lower()) tokens = [lemmatizer.lemmatize(token) for token in tokens if token not in stop_words and len(token) > 2 and not token.isnumeric()] # lematizer in rare cases produce empty strings - removing them tokens = list(filter(lambda a: a != '', tokens)) preprocessed.append(tokens) return preprocessed df = pd.read_pickle("data/pubmed_longevity.pkl") len_before = len(df) # izpusti članke brez ključnih besed df = df[~df["keywords"].isnull()] # ne lematiziramo, ker so izhodiščne besede že korenjene (<NAME>) df["Keywords_one_word"] = df["keywords"].apply( lambda ph: [w.strip('][ )') for p in ph if p is not None for w in p.split()] ) tokens_list = preprocess(df["abstract"]) print(f"Število dokumentov: {len(df)}/{len_before}") # - # Poglejmo si podatkte in izseke prvih 5 dokumentov df.head() # Sedaj bomo pridobili ključne besede z vsako od primerjanih metod: # - [TF-IDF](https://github.com/biolab/text-semantics/blob/main/examples/04_03_specific_words_with_tfidf.ipynb) # - [Metoda z vložitvami:](https://github.com/biolab/text-semantics/blob/main/examples/04_01_specific_words_with_embeddings.ipynb) samo na besedah v dokumentih # - [RAKE](https://onlinelibrary.wiley.com/doi/abs/10.1002/9780470689646.ch1) # - [Yake!](https://onlinelibrary.wiley.com/doi/abs/10.1002/9780470689646.ch1) # - [TextRank](https://web.eecs.umich.edu/~mihalcea/papers/mihalcea.emnlp04.pdf) # %%time tfidf_keywords = specific_words.tfidf_keywords(tokens=tokens_list) tfidf_keywords = [[x for x, _ in wds] for wds in tfidf_keywords] # %%time emb_doc_keywords = specific_words.embedding_document_keywords( tokens=tokens_list, language="english" ) emb_doc_keywords = [[x for x, _ in wds] for wds in emb_doc_keywords] # + # %%time stop_path = "utils/english-stopwords.txt" rake_object = rake.Rake(stop_path, max_words_length=1) def rake_method(text): kw = rake_object.run(text) # rake works on unormalized texts so normalize them afterwards return [lemmatizer.lemmatize(x) for x, _ in kw if x not in stop_words] rake_keywords = [rake_method(txt) for txt in df["abstract"]] # + # %%time custom_kw_extractor = yake.KeywordExtractor(lan="en", n=1) def yake_method(text): kw = custom_kw_extractor.extract_keywords(text) return [lemmatizer.lemmatize(x) for x, _ in kw if x not in stop_words] yake_keywords = [yake_method(txt) for txt in df["abstract"]] # - # %%time text_rank_keywords = specific_words.text_rank_keywords(tokens=tokens_list, num_words=20) text_rank_keywords = [[w for w, _ in kws] for kws in text_rank_keywords] methods = [ ("Emb - document", emb_doc_keywords), ("TFIDF", tfidf_keywords), ("RAKE", rake_keywords), ("YAKE", yake_keywords), ("TextRank", text_rank_keywords), ] # Ko imamo pridobljene ključne besede, si izpišemo povprečno število ključnih besed in najmanjše število ključnih besed, ki jih vsaka od metod vrne. Te statitike nam služijo zgolj, da vidimo ali je bila izluščitev besed uspešna. Nekatere metode omogočajo nastavljanje števila najbolj pomembnih ključnih besed zato imamo tam tipično manj ključnih besed na besedilo. for name, kw in methods: print( f"{name} - Povprečno število besed:", f"{sum(len(x) for x in kw) / len(kw):.1f}", "Minimalno število specifičnih besed:", min(len(x) for x in kw) ) # Izračunajmo natančnosti s pripravljenimi merami in jih izrišimo. Izračunamo povprečno preciznost, priklic in mero F1 za različno število izbranih najbolj pomembnih ključnih besed. Z vsako metodo smo pridobili seznam ključnih besed, ki je razvrščen po pomembnosti. Za namen izrisa grafov smo se odločili, da izračunamo vse tri mere za število ključnih besed v intervalu med 1 in 20. Na ta način vidimo kako uspešna je metoda glede na izbrano število ključnih besed. # # Izrišemo po en graf za vsako od mer - graf, ki prikazuje vrednost mere v odvisnosti od števila izbranih najboljših ključnih besed. Četrti graf prikazuje preciznost in priklic na enem grafu. V tem grafu ima metoda krivuljo iz večih točk. Vsaka od točk predstavlja preciznost in priklic za različno število izbranih ključnih besede. Metoda katere krivulja je bližje zgornjemu desnemu kotu, je boljša. # # + kw = df['Keywords_one_word'].tolist() kw = [[lemmatizer.lemmatize(t.lower()) for t in k] for k in kw] precisions = [score_in_len_range(pred, kw, average_precision) for _, pred in methods] recalls = [score_in_len_range(pred, kw, average_recall) for _, pred in methods] f_scores = [score_in_len_range(pred, kw, average_f_score) for _, pred in methods] # + CB_color_cycle = ['#377eb8', '#ff7f00', '#4daf4a', '#f781bf', '#a65628', '#984ea3', '#999999', '#e41a1c', '#dede00'] plt.style.use('ggplot') fig = plt.figure(figsize=(12,8)) fig.patch.set_facecolor('white') scores = ( ("Precision", precisions), ("Recall", recalls), ("F1 Score", f_scores), ) for i, (title, sc) in enumerate(scores): plt.subplot(2, 2, i + 1) for p, (l, _), c in zip(sc, methods, CB_color_cycle): plt.plot(range(1, 21), p, label=l, color=c) if i == 0: plt.legend() plt.xlabel("# keywords") plt.ylabel(title) plt.subplot(2, 2, 4) for p, r, (l, _), c in zip(precisions, recalls, methods, CB_color_cycle): plt.plot(p, r, label=l, color=c) plt.xlabel("Precision") plt.ylabel("Recall") plt.tight_layout() # - # Iz grafov lahko sklepamo, da se na primeru člankov najbolje obnese metoda YAKE!. Sledita TF-IDF in Text Rank. Razlika med YAKE in TF-IDF je na tem korpusu večja kot pri korpusu Schutz2008. # ## Most common words # + import matplotlib.pyplot as plt # %matplotlib inline from wordcloud import WordCloud wordcloud = WordCloud( width=4000, height=3000, random_state=0, background_color="white" ).generate(" ".join([t for ts in tokens_list for t in ts])) plt.figure(figsize=(15, 15)) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off"); # -
examples/04_10_specific_words_comparison_longevity_lematizer.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Getting started # # This example uses a custom class and custom function. See [custom steps](./writing-custom-steps.ipynb) for more details. # # **In this section** # - [Steps](#steps) # - [Create a function](#create-a-function) # - [Build the graph](#build-the-graph) # - [Visualize the graph](#visualize-the-graph) # - [Test the function](#test-the-function) # - [Deploy the function](#deploy-the-function) # - [Test the deployed function](#test-the-deployed-function) # ## Steps # # The following code defines basic steps that illustrate building a graph. These steps are: # # - **`inc`**: increments the value by 1. # - **`mul`**: multiplies the value by 2. # - **`WithState`**: class that increments an internal counter, prints an output, and adds the input value to the current counter. # + # mlrun: start-code def inc(x): return x + 1 def mul(x): return x * 2 class WithState: def __init__(self, name, context, init_val=0): self.name = name self.context = context self.counter = init_val def do(self, x): self.counter += 1 print(f"Echo: {self.name}, x: {x}, counter: {self.counter}") return x + self.counter # mlrun: end-code # - # ## Create a function # # Now take the code above and create an MLRun function called `serving-graph`. import mlrun fn = mlrun.code_to_function("simple-graph", kind="serving", image="mlrun/mlrun") graph = fn.set_topology("flow") # ## Build the graph # # Use `graph.to()` to chain steps. Use `.respond()` to mark that the output of that step is returned to the caller # (as an http response). By default the graph is async with no response. graph.to(name="+1", handler='inc')\ .to(name="*2", handler='mul')\ .to(name="(X+counter)", class_name='WithState').respond() # ## Visualize the graph # # Using the `plot` method, you can visualize the graph. graph.plot(rankdir='LR') # ## Test the function # # Create a mock server and test the graph locally. Since this graph accepts a numeric value as the input, that value is provided # in the `body` parameter. server = fn.to_mock_server() server.test(body=5) # Run the function again. This time, the counter should be 2 and the output should be 14. server.test(body=5) # ## Deploy the function # # Use the `deploy` method to deploy the function. fn.deploy(project='basic-graph-demo') # ## Test the deployed function # # Use the `invoke` method to call the function. fn.invoke('', body=5) fn.invoke('', body=5)
docs/serving/getting-started.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- a=list(range(1,11)) a=0 while a<10: a+=1 print(a) a=list(range(1,11)) for N in a: print(N) a=0 b=0 while a<10: a+=1 b+=a print(b) a=list(range(1,11)) b=0 for N in a: b+=N print (b) a=list(range(1,21)) for N in a: if N % 2 == 0: continue print(N, end=" ") a="kkklklkjkljlk ljkljfd lkjlkj fdljjlkj lkjfdlkjklj fdlfkj dfd" for N in a: if len(a)>=50: s=a[:50] break print(s) name=input("Name: ") print("hello, {}".format(name.title())) print("how old are you")
whileloop.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### Import Libraries import opstrat as op # ### Declare parameters # + K=200 #spot price St=208 #current stock price r=4 #4% risk free rate t=30 #time to expiry, 30 days v=20 #volatility type='c' #Option type call bsm=op.black_scholes(K=K, St=St, r=r, t=t, v=v, type='c') # - # ### Option values bsm['value'] # ### Option Greeks bsm['greeks']
examples/Black Scholes and Option Greeks.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # DCMIP test case 4 demo # ------- # # Here, the ability of the dynamical core to maintain a balanced state is # tested. The initial conditions are analytically derived to be a steady # state solution of the primitive equations on a sphere (Jablonowski and Williamson (2006)). # # Jablonowski's group provides a fortran file which generates the initial conditions # to test any dynamical core. We have written a Cython wrapper around it, and use it to # start the simulation. # + # %matplotlib notebook from climt.dynamics import dynamics from climt.dcmip import getBaroclinicWaveICs import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set_style('whitegrid',rc={'grid.linestyle':'dotted', 'grid.color':'0.0'}) # Dynamical core parameters kwargs = {} kwargs['dt'] = 1200 kwargs['nlon'] = 128 kwargs['nlat'] = 62 kwargs['MonitorFields'] = ['U','T'] # Display zonal velocity during simulation kwargs['MonitorFreq'] = 6.*3600 #6 hourly update #Init the dynamics Component dycore = dynamics(scheme='gfs', **kwargs) #Get the pressure and lat/lon values; this is needed #to generate the initial conditions pressure = dycore['p'] ps = dycore['ps'] full_latitudes = dycore.Extension.latitudes full_longitudes = dycore.Extension.longitudes #Get new initial conditions u,v,t, phis = getBaroclinicWaveICs(pressure, full_longitudes, full_latitudes) #Initialise model topography dycore.Extension.set_topography(phis) #Initialise winds, surface pressure and temperature dycore.Extension.initial_conditions(u,v,t,ps) #Run the code for 30 days. each time step is 1200 seconds = 1/3 hour num_steps = 30*24*3 #Store error between integrated and initial zonal mean zonal wind error = np.zeros(num_steps) u_init = np.average(u, axis=0) for i in range(num_steps): #Go ahead one time step dycore.step() #Get the new value of zonal mean zonal wind u_new = np.average(dycore['U'], axis=0) #Calculate the error error[i] = np.sqrt(np.mean((u-u_new)**2)) # Delete reference to deallocate fortran data del(dycore) # + plt.figure() plt.plot(np.arange(num_steps)/(24.*3), error) plt.title('Deviation from initial state') plt.xlabel('days') plt.ylabel('RMSE (m/s)') # -
lib/examples/CliMT -- Maintain Basic State Demo.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # The lineal path function # In the original version of the lineal path function described by Torquato, he proposes to insert lines of arbitrary length and orientation into the image, then count the fraction of these lines that lie wholly within a single phase. If the media is isotropic then it is not strictly necessary to use random orientations, since the length of the valid lines will be the same in all direction. On the other hand, if the material is anisotropic, then orientation does matter. Or, flipping this concept around, it becomes possible to detect anisotropy in an image by measuring the lineal-path function along a single direction, then repeating for perpedicular directions. Anisotropy is thus revealed by the disparity in the lineal-path results. # # PoreSpy favors this latter approach, and computes the lineal-path function along a single axis. PoreSpy includes the ``distance_transform_lin`` function with can compute a version of the distance transform that is limited to the linear distance along the specified axis. Applying this function to an image creates the input data for the lineal path function, which then computes the cumulative distribution function of the values in the image. The following example outlines the steps to compute the lineal-path function in two perpendicular directions for an anisotropic image. import porespy as ps import numpy as np import matplotlib.pyplot as plt ps.visualization.set_mpl_style() # First generate an anisotropic image using the ``blobs`` generator: im = ps.generators.blobs([400, 400], blobiness=[1, 2], porosity=0.6) ps.imshow(im); # Next apply the ``distance_transform_lin`` function along the 0 axis. paths = ps.filters.distance_transform_lin(im, mode='forward', axis=0) ps.imshow(paths); # The greyscale values of the above image are worth a comment. They indicated the length of a path that can be drawn from each voxel to the nearest solid voxel, in the specified direction. Or in terms of Torquato's definition, each greyscale value represents a random starting point (A) and moving along this line until solid is encountered represents the end of the line (B), providing the path length A $\rightarrow$ B. The 'counter associated with the distance between A and B is then incremented', which corresponds to the binning the greyscale values in the above image. In other words, the above representation includes ALL possible starting points on each path, so provides the largest possible data set. # With the image now computed, it can be passed to the ``lineal_path_distribution`` function, which computes the histogram. The bins were set to a specific range so that the line up with subsequent plot shown below: lpf = ps.metrics.lineal_path_distribution(paths, bins=range(1, 200, 10)) # Finally, plottings: fig, ax = plt.subplots(1, 1) ax.bar(x=lpf.L, height=lpf.cdf, width=lpf.bin_widths, edgecolor='k', alpha=0.8) ax.set_xlabel('Path length [voxels]') ax.set_ylabel('Fraction of voxels within stated distance to solid') # Since the image is anisotropic, the process will yeild a different result in the perpendicular direction, so repeating the above with ``axis=1`` instead of the default ``axis=0``. paths = ps.filters.distance_transform_lin(im, mode='forward', axis=1) ps.imshow(paths); # Overlaying this result wit the previous one: lpf = ps.metrics.lineal_path_distribution(paths, bins=range(1, 200, 10)) ax.bar(x=lpf.L, height=lpf.cdf, width=lpf.bin_widths, edgecolor='k', alpha=0.8); fig # The anisotropy of the image is clearly visible with the first axis possessing longer lineal-path values.
examples/metrics/tutorials/lineal_path_function.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import * from sklearn.model_selection import GridSearchCV np.random.seed(0) from sklearn.linear_model import SGDClassifier from sklearn.svm import SVC from sklearn.model_selection import cross_val_score from sklearn.naive_bayes import MultinomialNB from sklearn.naive_bayes import BernoulliNB from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.neural_network import MLPClassifier from lightgbm import LGBMClassifier from xgboost import XGBClassifier import sklearn import category_encoders as ce from catboost import CatBoostClassifier def scaler(scaler, data, test=None): scaler.fit(data) # Apply transform to both the training set and the test set. train_scale = scaler.transform(data) if test is not None: test_scale = scaler.fit_transform(test) return train_scale, test_scale, scaler def train_model(classifier, X_tr, y_tr, X_te, y_te): print('start training...') classifier.fit(X_tr, y_tr) print('evaluation...') y_p = classifier.predict(X_te) score = evaluate(y_te, y_p) print(f'score is {score}') return classifier, score def evaluate(y_true, y_pred): return f1_score(y_true, y_pred, average="macro") # + pycharm={"name": "#%%\n"} data = pd.read_table('data/dev.tsv') test = pd.read_table('data/eval.tsv') # + pycharm={"name": "#%%\n"} df = data.copy() # + pycharm={"name": "#%%\n"} eval = test.copy() # + pycharm={"name": "#%%\n"} from scipy import stats def happy_sad(x): if x>df['valence'].mean(): return 'happy' else: return 'sad' def popularity_cat(x): if x>= 7: return 'high' elif x >= 4 and x < 7: return 'med' else: return 'low' df['boringness'] = df['loudness'] + df['tempo'] + (df['energy']*100) + (df['danceability']*100) df['valence_happy_sad'] = df['valence'].apply(lambda x: happy_sad(x)) df['loudness_plus_60'] = df['loudness'].apply(lambda x: x+60) df['loudness_pos'] = df['loudness'].apply(lambda x: -1*x) df['loudness_pos'] = np.sqrt(df['loudness_pos']) df['boringness_plus_60'] = df['boringness'].apply(lambda x: x+60) df['duration_ms_box_cox_trans'] = stats.boxcox(df['duration_ms'])[0] df['acousticness_sqrt_trans'] = np.sqrt(df['acousticness']) df['liveness_sqrt_trans'] = np.sqrt(df['liveness']) df['popularity_sqrt_trans'] = np.sqrt(df['popularity']) df['popularity_sqrt_trans_cat'] = df['popularity_sqrt_trans'].apply(lambda x: popularity_cat(x)) df['speechiness_sqrt_trans'] = np.sqrt(df['speechiness']) # + pycharm={"name": "#%%\n"} # df = df.sort_values(by='mode') # mode0 = stats.boxcox(df[df['mode']==0]['duration_ms'])[0] # mode1 = stats.boxcox(df[df['mode']==1]['duration_ms'])[0] # # + pycharm={"name": "#%%\n"} # df.loc[df['mode']==0,['duration_ms_box_cox_trans_per_class']] = mode0 # df.loc[df['mode']==1,['duration_ms_box_cox_trans_per_class']] = mode1 # + pycharm={"name": "#%%\n"} df = df.fillna(value=0) # df.describe().T # + pycharm={"name": "#%%\n"} import seaborn as sns import matplotlib.pyplot as plt def dist_plot_box_cox_by_class(df,col): plt.figure(figsize=(16,6)) plt.title("Distribution of "+col+" box cox transformation") sns.distplot(df[df['mode']==0][col], color="green", kde=True,bins=120, label='mode 0') sns.distplot(df[df['mode']==1][col],color="red", kde=True,bins=120, label='mode 1') plt.legend() plt.show() def dist_plot_box_cox(df,col): plt.figure(figsize=(16,6)) plt.title("Distribution of "+col+" box cox transformation") sns.distplot(stats.boxcox(df[col])[0], color="green", kde=True,bins=120, label='mode 0') plt.legend() plt.show() # dist_plot_box_cox_by_class(df,'duration_ms_box_cox_trans_per_class') # + pycharm={"name": "#%%\n"} col = [ 'valence', 'year', # 'acousticness', 'artists', 'danceability', 'duration_ms', 'energy', 'explicit', # 'id', 'instrumentalness', 'key', 'liveness', # 'loudness', # 'popularity', # 'speechiness', 'tempo', # 'mode', # 'loudness_plus_60', 'loudness_pos', # 'boringness', # 'valence_happy_sad', # 'boringness_plus_60', # 'duration_ms_box_cox_trans', 'acousticness_sqrt_trans', # 'liveness_sqrt_trans', # 'popularity_sqrt_trans', 'speechiness_sqrt_trans', # 'duration_ms_box_cox_trans_per_class', # 'popularity_sqrt_trans_cat' ] # + pycharm={"name": "#%%\n"} df = sklearn.utils.shuffle(df) # + pycharm={"name": "#%%\n"} # print(f"{len(df.loc[(df['duration_ms_box_cox_trans']<12.5) | (df['duration_ms_box_cox_trans']>15)])}") # duration_df = df.loc[(df['duration_ms_box_cox_trans'] > 12.5) & (df['duration_ms_box_cox_trans']<15)] # sns.distplot(duration_df['duration_ms_box_cox_trans'], # color="green", kde=True,bins=120, label='mode 0') # + pycharm={"name": "#%%\n"} # sns.countplot(duration_df['mode'], palette='Set3') # + pycharm={"name": "#%%\n"} # sns.countplot(df.loc[(df['duration_ms_box_cox_trans']<12.5) | (df['duration_ms_box_cox_trans']>15)]['mode'], palette='Set3') # + pycharm={"name": "#%%\n"} X = df[col] y = df['mode'] # encoder = ce.OneHotEncoder(cols=['artists']) # X = encoder.fit_transform(X,y) # + pycharm={"name": "#%%\n"} X # + pycharm={"name": "#%%\n"} from imblearn.pipeline import Pipeline from imblearn.under_sampling import RandomUnderSampler,NearMiss,TomekLinks,ClusterCentroids from imblearn.over_sampling import SMOTE,SVMSMOTE,ADASYN from imblearn.combine import SMOTETomek # ous = RandomUnderSampler(random_state=42) # nm = NearMiss() # tl = TomekLinks() # cc = ClusterCentroids(random_state=42,n_jobs=-1)/ # smt = SMOTETomek(sampling_strategy='auto',n_jobs=-1) # over = SMOTE(sampling_strategy=0.1,random_state=42) # under = RandomUnderSampler(sampling_strategy=0.5,random_state=42) # # # steps = [('o', over), ('u', under)] # pipeline = Pipeline(steps=steps) # sm = SVMSMOTE() # X_spl, y_spl = nm.fit_resample(X, y) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0,shuffle=True) # # encoder = ce.(cols=['key']) # encoder.fit(X_train,y_train) # X_train = encoder.transform(X_train, y_train) # X_test = encoder.transform(X_test, y_test) # + pycharm={"name": "#%%\n"} # from sklearn.preprocessing import * # X_train_scal, X_test_scal, x_scaler = scaler(StandardScaler(), X_train, X_test) # + pycharm={"name": "#%%\n"} # + pycharm={"name": "#%%\n"} from sklearn.decomposition import PCA def dim_reduction(train, test=None): tsvd = PCA(n_components=4,random_state=42) tsvd.fit(train) print('strat transformation SVD') X_train_svd = tsvd.transform(train) X_test_svd = None if test is not None: X_test_svd = tsvd.transform(test) percentage = np.sum(tsvd.explained_variance_ratio_) * 100 print(f'{percentage:.2f}%') return X_train_svd, X_test_svd,tsvd # X_train_svd, X_test_svd , tsvd = dim_reduction(X_train_scal, X_test_scal) # + pycharm={"name": "#%%\n"} from collections import Counter counter = Counter(y) # estimate scale_pos_weight value estimate = counter[0]/counter[1] print('Estimate: %.3f' % estimate) print(counter,counter[0]) # + pycharm={"name": "#%%\n"} from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import VotingClassifier # clf = SVC(random_state=42) # clf = GaussianNB() # clf = MultinomialNB(alpha=10/100) # clf = BernoulliNB(alpha=10/100) # clf = LogisticRegression(penalty='l2',max_iter=10000,random_state=0) # clf = RandomForestClassifier(criterion = 'entropy',n_estimators=1500,max_depth=1,n_jobs=-1,random_state=0) # clf = GradientBoostingClassifier(n_estimators=1000, random_state=0) # clf = AdaBoostClassifier(n_estimators=100,random_state=0) # clf = SGDClassifier() # clf = KNeighborsClassifier(n_neighbors = 10) # clf = MLPClassifier(early_stopping=True,random_state=1,max_iter=500, verbose=True) # clf = LGBMClassifier(learning_rate=0.00001,n_jobs=-1,n_estimators=1000) # clf= XGBClassifier(learning_rate=0.65, scale_pos_weight=estimate,n_jobs=-1,random_state=0,) clf = CatBoostClassifier(auto_class_weights='SqrtBalanced',random_state=0,) # clf = VotingClassifier(estimators=[('RandomForestClassifier', RandomForestClassifier(n_estimators=1000,n_jobs=-1, random_state=0)), # ('XGBClassifier', XGBClassifier(learning_rate=0.1,n_jobs=-1,random_state=0)), # ('LGBMClassifier', LGBMClassifier(learning_rate=0.15,n_jobs=-1,n_estimators=1000))], # voting='soft', weights=[1, 2, 1]) print(f'start training... {clf}') X_train_val, X_val, y_train_val, y_val = train_test_split(X_train, y_train, test_size=0.1, random_state=0,shuffle=True) # eval_set = [(X_val, y_val)] # clf.fit(X_train_val, y_train_val,early_stopping_rounds=50,eval_metric="mae", eval_set=eval_set, verbose=True) clf.fit(X_train_val,y_train_val,cat_features=['artists','key'],eval_set=(X_val,y_val)) print('evaluation...') y_p = clf.predict(X_test) score = evaluate(y_test, y_p) print(f'score is {score}') # scores = cross_val_score(clf, X, y, cv=5,scoring='f1_macro') # print(f'mean score {np.mean(scores)}, max score {np.max(scores)}, min score {np.min(scores)}') # + pycharm={"name": "#%%\n"} print(f' score {score} {clf}') # + pycharm={"name": "#%%\n"} # from sklearn.neighbors import KNeighborsClassifier # # score = [] # for i in range(2,100,2): # knn = KNeighborsClassifier(n_neighbors = i) # knn.fit(X_train, y_train) # y_pred = knn.predict(X_test) # sco = evaluate(y_test, y_pred) # score.append(sco) # print(f'{i} {sco:.4f}') # + pycharm={"name": "#%%\n"} eval # + pycharm={"name": "#%%\n"} def WriteOnFile(name, y_eval): f = open(name, "w") f.write("Id,Predicted\n") for index, i in enumerate(y_eval): f.write(f"{index},{i}\n") f.close eval['boringness'] = eval['loudness'] + eval['tempo'] + (eval['energy']*100) + (eval['danceability']*100) eval['valence_happy_sad'] = eval['valence'].apply(lambda x: happy_sad(x)) eval['loudness_plus_60'] = eval['loudness'].apply(lambda x: x+60) eval['loudness_pos'] = eval['loudness'].apply(lambda x: -1*x) eval['loudness_pos'] = np.sqrt(eval['loudness_pos']) eval['boringness_plus_60'] = eval['boringness'].apply(lambda x: x+60) eval['duration_ms_box_cox_trans'] = stats.boxcox(eval['duration_ms'])[0] eval['acousticness_sqrt_trans'] = np.sqrt(eval['acousticness']) eval['liveness_sqrt_trans'] = np.sqrt(eval['liveness']) eval['popularity_sqrt_trans'] = np.sqrt(eval['popularity']) eval['speechiness_sqrt_trans'] = np.sqrt(eval['speechiness']) eval = eval.fillna(value=0) # + pycharm={"name": "#%%\n"} test = eval[col] # test = encoder.transform(test) # test_scal = x_scaler.transform(test) # test_svd = tsvd.transform(test_scal) y_pred = clf.predict(test) WriteOnFile('submission.csv',y_pred) # + pycharm={"name": "#%%\n"} test # + pycharm={"name": "#%%\n"} # cols = [ # 'valence', # 'year', # # 'acousticness', # # 'artists', # 'danceability', # # 'duration_ms', # 'energy', # 'explicit', # # 'id', # 'instrumentalness', # 'key', # 'liveness', # # 'loudness', # # 'popularity', # # 'speechiness', # 'tempo', # # 'mode', # # 'loudness_plus_60', # 'loudness_pos', # # 'boringness', # # 'valence_happy_sad', # # 'boringness_plus_60', # 'duration_ms_box_cox_trans', # 'acousticness_sqrt_trans', # # 'liveness_sqrt_trans', # # 'popularity_sqrt_trans', # 'speechiness_sqrt_trans', # # 'duration_ms_box_cox_trans_per_class' # ]
classification.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- #First we import the modules we are going to use import numpy as np import joblib import pandas as pd from sklearn.linear_model import LinearRegression #import linear regression model from sklearn.model_selection import train_test_split #to divide data # + #loading the dataset we are going to work with Powerdataset=pd.read_csv('Powerproduction dataset.csv', delimiter=',') x=Powerdataset['speed'] y=Powerdataset['power'] #plotting dataset to see its distribution Powerdataset.plot(kind='scatter', x= 'speed', y='power') plt.show() # + #Let's create our linear regression model #doing test train split X_train, X_test, y_train, y_test= train_test_split(Powerdataset.speed, Powerdataset.power) # + #Plotting the data spplit done in cell above. #Train data shows in green while test data is in red plt.scatter(X_train, y_train, label='Training Data', color='g', alpha=.7) plt.scatter(X_test, y_test, label='Test Data', color= 'r', alpha=.7) plt.legend() plt.title('Test train split') plt.show() # - #Model creation #naming model LR as Linear Regression LR=LinearRegression() LR.fit(X_train.values.reshape(-1,1), y_train.values)#Adding x_train and y_train values and reshaping X_train values as they need to be in #a 1d shape for this to work # + # Predicting power values using this model we created prediction=LR.predict(X_test.values.reshape(-1,1)) #Plotting X_test against prediction results in same plot plt.plot(X_test, prediction, label='Linear Regression', color='r') plt.scatter(X_test, y_test, label='Actual Test Data', color='b', alpha=.7) plt.legend() plt.show() # + #Making predictions for specific values #using command predict we enter a sample wind speed: print('This is the power generated considering your input: ') LR.predict(np.array([[25.00]]))[0] # + #score function to determine whether the model is accurate. Maximum punctuation is 1.0 . LR.score(X_test.values.reshape(-1,1),y_test.values) # + #Using joblib to save model joblib_file = "joblib_LR_Model.pkl" joblib.dump(LR, "joblib_LR_Model.pkl" ) # -
Jupyter_notebooks/LR Model.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 0.4.6 # language: julia # name: julia-0.4 # --- # + [markdown] nbpresent={"id": "356b3db5-699d-4c86-a408-c91b72158ffe"} slideshow={"slide_type": "slide"} # # Introduction to Julia for Pythonistas # # <img src="http://pearsonlab.github.io/images/plab_hex_icon_gray.png" width="150", align="left", style="float:left"> # <img src="http://www.duke.edu/~jmp33/assets/dibs-logo-small.png" width="350", align="left", style="float:right"> # # <br> # <NAME> # P[&lambda;]ab # Duke Institute for Brain Sciences # + [markdown] slideshow={"slide_type": "slide"} # # Following along # # <img src="https://cdn.meme.am/instances/500x/71711850.jpg"> # # ## If you have Julia... # Slides and other material available at https://github.com/jmxpearson/julia-for-pythonistas # + [markdown] slideshow={"slide_type": "slide"} # # About me # # <img src="http://pearsonlab.github.io/images/plab_logo_dark.svg" width="400"> # # - @jmxpearson on GitHub and (rarely) Twitter; [pearsonlab.github.io](http://pearsonlab.github.io) # - computational neuroscience lab at Duke # - using Julia for about 1.5 years # - member of JuliaStats organization # + [markdown] slideshow={"slide_type": "slide"} # # What is Julia? # # - new programming language (public since 2012) # - brought to you by MIT, Julia Computing # - focused on scientific computing applications # - aims to be a high-level prototyping language that is also fast enough for serious simulation # - as easy to learn and flexible as Python or R # - within 2x the speed of C, C++, or FORTRAN # - Currently (almost) 0.5, with very active developer community # + [markdown] slideshow={"slide_type": "slide"} # # Reasons to Consider Julia # # - you mostly write your own algorithms # - you need to write code that is very fast # - you’d like to prototype and optimize within the same language # - you want zero overhead boilerplate calls to C, Python (and soon C++) # - you need powerful metaprogramming/macros # - you want access to state-of-the-art automatic differentiation and optimization # - you want to use Greek letters in variable names # - you are interested in programming language design # - you want to get in on the ground floor # + [markdown] slideshow={"slide_type": "slide"} # # Reasons Julia may not be for you (yet) # # - you mostly use packages written by others # - you rely critically on several packages that aren't available # - you don’t have much need to optimize your code # - you perform mostly data analysis and model building, as opposed to algorithm development # - you prioritize long-term stability # - you don’t want to devote time to keeping up with changes # - you have zero background with compiled languages
0. Why Julia.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # EXERCÍCIOS ORIENTAÇÃO A OBJETOS # # [![Google Colab](https://img.shields.io/badge/launch-Exercicios-yellow.svg)](https://colab.research.google.com/github/python-joinville/workshops/blob/master/orientacao-a-objetos/2-exercicios.ipynb) [launch](https://colab.research.google.com/github/python-joinville/workshops/blob/master/orientacao-a-objetos/2-exercicios.ipynb) # # 1) Classe Retangulo: Crie uma classe que modele um retangulo: # # * **Atributos**: x, y (ou comprimento e largura) # * **Métodos**: # * Mudar valor dos lados # * Retornar valor dos lados # * calcular Área # * calcular Perímetro # # Utilize esta classe em uma função. Ela deve receber as medidas de uma sala e deve criar um objeto com as medidas e calcular a quantidade de pisos e de rodapés necessárias para a sala. # 2) Classe Bichinho Virtual: Crie uma classe que modele um Tamagushi (Bichinho Eletrônico): # # * **Atributos**: Nome, Fome, Saúde e Idade # * **Métodos**: Alterar Nome, Fome, Saúde e Idade; Retornar Nome, Fome, Saúde e Idade # # Existe mais uma informação que devemos levar em consideração, o Humor do nosso tamagushi, este humor é uma combinação entre os atributos Fome e Saúde, ou seja, um campo calculado, então não devemos criar um atributo para armazenar esta informação por que ela pode ser calculada a qualquer momento. # 3) Classe carro: Implemente uma classe chamada Carro com as seguintes propriedades: # # * Um veículo tem um certo consumo de combustível (medidos em km / litro) e uma certa quantidade de combustível no tanque. # * O consumo é especificado no construtor e o nível de combustível inicial é 0. # * Forneça um método andar( ) que simule o ato de dirigir o veículo por uma certa distância, reduzindo o nível de combustível no tanque de gasolina. # * Forneça um método obterGasolina( ), que retorna o nível atual de combustível. # * Forneça um método adicionarGasolina( ), para abastecer o tanque. Exemplo de uso: # # ```python # meuFusca = Carro(15); # 15 quilômetros por litro de combustível. # meuFusca.adicionarGasolina(20); # abastece com 20 litros de combustível. # meuFusca.andar(100); # anda 100 quilômetros. # meuFusca.obterGasolina() # Imprime o combustível que resta no tanque. # ``` # 4) Classe Bichinho Virtual++: Melhore o programa do bichinho virtual, permitindo que o usuário especifique quanto de comida ele fornece ao bichinho e por quanto tempo ele brinca com o bichinho. Faça com que estes valores afetem quão rapidamente os níveis de fome e tédio caem. # 5) Dado a classe `No`, implemente uma classe que representa uma `Fila`, uma classe que representa uma `Pilha` e uma classe que representa uma `Arvore` class No: def __init__(self, dado=None, proximo=None): self.dado = dado self.proximo = proximo def __str__(self): return str(self.dado) # ### Fila # # Uma Fila deve conter as operações `insere(elemento)`, `remove`, `testa_vazia` e `to_list`. # # * `insere(elemento)` deve inserir o elemento no final da lista # * `remove` deve remover o primeiro elemento da lista # * `testa_vazia` deve retornar True ou False indicando se a fila está vazia # * `to_list` deve retornar uma lista padrão Python que será usada nos testes implementados abaixo # # A Fila deve ter o atributo `tamanho`, que indica quantos elementos a fila possui. class Fila: pass ## IMPLEMENTE # + fila = Fila() fila.insere(1) assert [1] == fila.to_list() assert 1 == fila.tamanho # + fila.insere(2) assert [1, 2] == fila.to_list() assert 2 == fila.tamanho # + fila.insere(3) assert [1, 2, 3] == fila.to_list() assert 3 == fila.tamanho # + fila.remove() assert [2, 3] == fila.to_list() assert 2 == fila.tamanho # + fila.remove() assert [3] == fila.to_list() assert 1 == fila.tamanho # + fila.remove() assert [] == fila.to_list() assert fila.testa_vazia() # - # ### Pilha # # Uma Pilha deve conter as operações `empilha(elemento)`, `desempilha`, `testa_vazia` e `to_list`. # # * `empilha(elemento)` deve inserir o elemento no topo da pilha # * `desempilha` deve remover o elemento do topo da pilha # * `testa_vazia` deve retornar True ou False indicando se a pilha está vazia # * `to_list` deve retornar uma lista padrão Python que será usada nos testes implementados abaixo # # A Pilha deve ter o atributo `tamanho`, que indica quantos elementos a fila possui. class Pilha: pass ## IMPLEMENTE # + pilha = Pilha() pilha.empilha(1) assert [1] == pilha.to_list() assert 1 == pilha.tamanho # + pilha.empilha(2) assert [1, 2] == pilha.to_list() assert 2 == pilha.tamanho # + pilha.empilha(3) assert [1, 2, 3] == pilha.to_list() assert 3 == pilha.tamanho # - assert 3 == pilha.desempilha() assert [1, 2] == pilha.to_list() assert 2 == pilha.tamanho # + pilha.empilha(5) assert [1, 2, 5] == pilha.to_list() assert 3 == pilha.tamanho # - assert 5 == pilha.desempilha() assert [1, 2] == pilha.to_list() assert 2 == pilha.tamanho assert 2 == pilha.desempilha() assert [1] == pilha.to_list() assert 1 == pilha.tamanho # + pilha.empilha(9) assert [1, 9] == pilha.to_list() assert 2 == pilha.tamanho # - # ### Árvore # # Dado a classe `No` e os exemplos acima para `Fila` e `Pilha`, implemente o mesmo para uma árvore :)
orientacao-a-objetos/2-exercicios.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import os import sys module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) import pandas as pd import numpy as np import xgboost as xgb from joblib import dump from src.models import eval_model as evm from src.models import eval_baseline as evb from sklearn.utils import resample from hyperopt import Trials, STATUS_OK, tpe, hp, fmin from sklearn.metrics import accuracy_score, confusion_matrix,roc_curve, roc_auc_score, precision_score, recall_score, precision_recall_curve, f1_score, plot_confusion_matrix from sklearn.model_selection import cross_val_score , cross_validate # %load_ext autoreload # %autoreload 2 # - # # Case for Down Sample from sklearn.model_selection import train_test_split def read_and_split_data(file): df = pd.read_csv(file) x=df.drop(['TARGET_5Yrs','TARGET_5Yrs_Inv'],axis=1) y=df['TARGET_5Yrs_Inv'] x_data , x_test ,y_data, y_test = train_test_split(x, y, test_size=0.2, random_state = 8, stratify=y) x_train , x_val , y_train, y_val = train_test_split(x_data, y_data, test_size=0.2, random_state = 8, stratify=y_data) print('y',y.value_counts()) print('y_train',y_train.value_counts()) print('y_val', y_val.value_counts()) print('y_test',y_test.value_counts()) return x_train , x_val , y_train, y_val, x_test, y_test x_train , x_val , y_train, y_val, x_test, y_test = read_and_split_data("../data/processed/df_cleaned_downsampled_nba_prediction.csv") space = { 'max_depth': hp.choice('max_depth',range(1,100,1)), 'learning_rate' : hp.quniform('learning_rate', 0.01, 0.5, 0.05), 'min_child_weight' : hp.quniform('min_child_weight', 1, 100, 1), 'colsample_bytree' : hp.quniform('colsample_bytree', 0.1, 1.0, 0.05), 'subsample' : hp.quniform('subsample', 0.1, 1, 0.05), 'reg_lambda' : hp.quniform('reg_lambda', 0.1, 1, 0.05), 'reg_alpha' : hp.quniform('reg_alpha', 0.1, 1, 0.05) } space def objective(space): xgboost = xgb.XGBClassifier( random_state=8, max_depth = int(space['max_depth']), learning_rate = space['learning_rate'], min_child_weight = space['min_child_weight'], colsample_bytree = space['colsample_bytree'], subsample = space['subsample'], reg_lambda = space['reg_lambda'], reg_alpha = space['reg_alpha'], use_label_encoder=False ) acc = cross_val_score(xgboost, x_train, y_train, cv=10, scoring="accuracy").mean() return{'loss': 1-acc, 'status': STATUS_OK } best1 = fmin( fn=objective, space=space, algo=tpe.suggest, max_evals=5 ) print("Best: ", best1) xgboost1 = xgb.XGBClassifier( random_state=8, max_depth = int(best1['max_depth']), learning_rate = best1['learning_rate'], min_child_weight = best1['min_child_weight'], colsample_bytree = best1['colsample_bytree'], subsample = best1['subsample'], reg_lambda = best1['reg_lambda'], reg_alpha = best1['reg_alpha'], use_label_encoder=False ) evm.eval_model(xgboost1,x_train,y_train,x_val,y_val) def objective(space): xgboost = xgb.XGBClassifier( random_state=8, max_depth = int(space['max_depth']), learning_rate = space['learning_rate'], min_child_weight = space['min_child_weight'], colsample_bytree = space['colsample_bytree'], subsample = space['subsample'], reg_lambda = space['reg_lambda'], reg_alpha = space['reg_alpha'], use_label_encoder=False ) acc = cross_val_score(xgboost, x_train, y_train, cv=10, scoring="roc_auc").mean() return{'loss': 1-acc, 'status': STATUS_OK } best2 = fmin( fn=objective, space=space, algo=tpe.suggest, max_evals=5 ) print("Best: ", best2) xgboost2 = xgb.XGBClassifier( random_state=8, max_depth = int(best2['max_depth']), learning_rate = best2['learning_rate'], min_child_weight = best2['min_child_weight'], colsample_bytree = best2['colsample_bytree'], subsample = best2['subsample'], reg_lambda = best2['reg_lambda'], reg_alpha = best2['reg_alpha'], use_label_encoder=False, ) evm.eval_model(xgboost2,x_train,y_train,x_val,y_val) def objective(space): xgboost = xgb.XGBClassifier( random_state=8, max_depth = int(space['max_depth']), learning_rate = space['learning_rate'], min_child_weight = space['min_child_weight'], colsample_bytree = space['colsample_bytree'], subsample = space['subsample'], reg_lambda = space['reg_lambda'], reg_alpha = space['reg_alpha'], use_label_encoder=False, objective ='binary:logistic' ) acc = cross_val_score(xgboost, x_train, y_train, cv=10).mean() return{'loss': 1-acc, 'status': STATUS_OK } best3 = fmin( fn=objective, space=space, algo=tpe.suggest, max_evals=5 ) print("Best: ", best3) xgboost3 = xgb.XGBClassifier( random_state=8, max_depth = int(best3['max_depth']), learning_rate = best3['learning_rate'], min_child_weight = best3['min_child_weight'], colsample_bytree = best3['colsample_bytree'], subsample = best3['subsample'], reg_lambda = best3['reg_lambda'], reg_alpha = best3['reg_alpha'], use_label_encoder=False, objective ='binary:logistic' ) evm.eval_model(xgboost3,x_train,y_train,x_val,y_val) def objective(space): xgboost = xgb.XGBClassifier( random_state=8, max_depth = int(space['max_depth']), learning_rate = space['learning_rate'], min_child_weight = space['min_child_weight'], colsample_bytree = space['colsample_bytree'], subsample = space['subsample'], reg_lambda = space['reg_lambda'], reg_alpha = space['reg_alpha'], use_label_encoder=False, objective ='binary:logistic', eval_metric ='auc' ) acc = cross_val_score(xgboost, x_train, y_train, cv=10).mean() return{'loss': 1-acc, 'status': STATUS_OK } best4 = fmin( fn=objective, space=space, algo=tpe.suggest, max_evals=5 ) print("Best: ", best4) xgboost4 = xgb.XGBClassifier( random_state=8, max_depth = int(best4['max_depth']), learning_rate = best4['learning_rate'], min_child_weight = best4['min_child_weight'], colsample_bytree = best4['colsample_bytree'], subsample = best4['subsample'], reg_lambda = best4['reg_lambda'], reg_alpha = best4['reg_alpha'], use_label_encoder=False, objective ='binary:logistic', eval_metric ='auc' ) evm.eval_model(xgboost4,x_train,y_train,x_val,y_val) # # Validating the results evm.get_performance(xgboost1, x_test, y_test, "Test", True) evm.get_performance(xgboost2, x_test, y_test, "Test", True) evm.get_performance(xgboost3, x_test, y_test, "Test", True) evm.get_performance(xgboost4, x_test, y_test, "Test", True) def predict_extract_result(infile,mod,outfile): df = pd.read_csv(infile) df_cleaned = df.copy() print('Before Data Clean') for cols in df_cleaned.columns: chk_rows = df_cleaned[df_cleaned[cols]<0].shape[0] if chk_rows > 0 : print(f'Column Name {cols},\tRows with Negative Value {chk_rows},\tPercentage {chk_rows/len(df)*100}') df_cleaned[ df_cleaned<0 ] = 0 df_cleaned.loc[df_cleaned['3P Made'] <= 0, ['3P Made', '3PA', 'CALC3P%']] = 0, 0, 0 df_cleaned.loc[df_cleaned['FGM'] <= 0, ['FGM', 'FGA', 'CALCFG%']] = 0, 0, 0 df_cleaned.loc[df_cleaned['FTM'] <= 0, ['FTM', 'FTA', 'CALCFT%']] = 0, 0, 0 df_cleaned.loc[df_cleaned['3P Made'] > df_cleaned['3PA'], ['3P Made' , '3PA', 'CALC3P%']] = 0, 0, 0 df_cleaned.loc[df_cleaned['FGM'] > df_cleaned['FGA'], ['FGM', 'FGA', 'CALCFG%']] = 0, 0, 0 df_cleaned.loc[df_cleaned['FTM'] > df_cleaned['FTA'], ['FTM', 'FTA', 'CALCFT%']] = 0, 0, 0 df_cleaned.loc[df_cleaned['3P Made'] > 0, ['CALC3P%']] = df_cleaned['3P Made']/df_cleaned['3PA']*100 df_cleaned.loc[df_cleaned['FGM'] > 0, ['CALCFG%']] =df_cleaned['FGM']/df_cleaned['FGA']*100 df_cleaned.loc[df_cleaned['FTM'] > 0, ['CALCFT%']] = df_cleaned['FTM']/df_cleaned['FTA']*100 print(df_cleaned.head(5)) print('After Data Clean') for cols in df_cleaned.columns: chk_rows = df_cleaned[df_cleaned[cols]<0].shape[0] if chk_rows > 0 : print(f'Column Name {cols},\tRows with Negative Value {chk_rows},\tPercentage {chk_rows/len(df)*100}') x = df_cleaned.drop(['3P%','FT%','FG%','Id_old','Id'],axis=1) print(df_cleaned.columns) y_pred_proba=mod.predict_proba(x) y_pred=mod.predict(x) print(np.unique(y_pred,return_counts=True)) df_cleaned_result = df_cleaned.copy() df_cleaned_result['TARGET_5Yrs'] = y_pred_proba[:,0] print(df_cleaned_result['TARGET_5Yrs'].round().value_counts()) df_cleaned_result.to_csv(outfile,index=False,columns=['Id', 'TARGET_5Yrs']) predict_extract_result('../data/raw/test.csv',xgboost1,'../data/processed/TestResult_XG_DownSample.csv')
notebooks/Pitchandi_Sampath_Week2_03-02-train-XG-Downsample-iteration2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np # + #rhomis_data = pd.read_csv("/Users/anab/Documents/MS_UCDavis/STA208/project/RHoMIS_Full_Data.csv", engine = "python") #rhomis_data.head() # + class Functions: """ Conatins all cleaning function for this data """ # def __init__(self,df): def getNAs(self, df): colNames = [] percentNA = [] for i in df.columns: colNames.append(i) numNA = df[i].isna().sum() percent = (numNA/len(df))*100 percentNA.append(percent) colNames = pd.DataFrame(colNames) colNames = colNames.rename(columns={0: "label"}) percentNA = pd.DataFrame(percentNA) percentNA = percentNA.rename(columns={0: "numNA"}) self.data = pd.concat([colNames,percentNA], axis = 1).sort_values(by=['numNA'], ascending = False) return self.data def drop_columns(self, df, threshold_percent): '''drop columns by a threshold (percentage of na)''' global data ### double check... data = self.getNAs(df) column_names = data[data.numNA >= threshold_percent].label self.clean_data = df.drop(column_names, axis = 1) return self.clean_data def entry_to_lowercase(self, df): for i in df.columns: if (df[i].dtype == "O"): df[i] = df[i].str.lower() return df def id_data_types(self, df): names = pd.DataFrame() category = pd.DataFrame() data_type = pd.DataFrame() numUni = pd.DataFrame() for i in df.columns: names = names.append({"variable": i},ignore_index = True) category = category.append({"category": list(df[i].unique())}, ignore_index = True) numUni = numUni.append({"numUnique": len(df[i].unique())}, ignore_index = True) data_type = data_type.append({"data_type": df[i].dtype}, ignore_index = True) view_data = pd.concat([names, category, numUni,data_type],axis =1) return (view_data) def replace_na_with_NaN(self, df): """ Input: Full dataset Output: Full dataset where object strings have underscores and spaces removed EX:'No_School-> NoSchool, no school -> noschool' """ for i in df.columns: df[i] = df[i].replace(np.nan, 'na') return df # removes underscores and spaces from instances, def remove_underscores_spaces(self, df): """ Input: Full dataset Output: Full dataset where object strings have underscores and spaces removed EX:'No_School-> NoSchool, no school -> noschool' """ for i in df.columns: if (df[i].dtype == "O"): df[i] = df[i].str.replace('_', "") df[i] = df[i].str.replace(' ', "") return df def convert_to_categorical(self, df, variables): """ Input: dataframe, column names of variables to be transformed Output: dataframe with dtypes of indicated variables changed #NOTE: USE this function AFTER preprocessing functions above """ # convert these to categories #df[v1] = df[v1].astype(‘category’) for i in variables: df[i] = df[i].astype('category') return df def impute_data(self, Xtrain, Xtest): """ Input: XTraining set, XTesting Set Output: The inputs with NA numerical variabes imputed by column median, and categorical NA varaibles converted into a seperate category "Na" """ num_train = Xtrain.select_dtypes(include=['float64', 'int64']) num_test = Xtest.select_dtypes(include=['float64', 'int64']) cat_train = Xtrain.select_dtypes(include=['object', 'category']) cat_test = Xtest.select_dtypes(include=['object', 'category']) # imputes NA numerics with median for i in num_train.columns: Xtrain[i] = num_train.fillna(np.nanmedian(Xtrain[i])) for i in num_test.columns: Xtest[i] = num_test.fillna(np.nanmedian(num_test[i])) # categorical NA to "Na" level for i in cat_train.columns: Xtrain[i] = cat_train.replace(np.nan, "Na") for i in cat_test.columns: Xtest[i] = cat_test.replace(np.nan, "Na") return Xtrain, Xtest def drop_response_rows_with_NAs(self,df,y_variable): """ Input: dataframe, response variable column Output: dataframe rows with missing response varaibles are dropped entirely (we cannot use these to train or test) But these dropped rows are saved to be used later """ ## need to delete PPI_threshold since that is like our y2 which we won’t use df = df.drop("PPI_Threshold", axis=1) condition = df[y_variable] rows_to_delete = df[np.isnan(condition)].index #save all rows with y=NA. Will use this data to predict the y later. prediction_dataset = df.iloc[rows_to_delete,:] #create new data new_data = df.drop(labels=rows_to_delete, axis=0) return new_data, prediction_dataset # - dat = pd.read_csv("../data/clean.csv") from Functions import Cleaning_Functions fun = Cleaning_Functions() #fun.id_data_types(dat) #check if replaceNan function works with updated .py file b = fun.replace_na_with_NaN(dat) b.head() fun.replace_na_with_NaN(dat) fun.entry_to_lowercase(dat) fun.remove_underscores_spaces(dat) fun.convert_to_categorical(dat,["crop_harvest_1", "crop_intercrop_1", "YEAR", "HFIAS_status", "continent"]) dat, s = fun.drop_response_rows_with_NAs(dat, "Market_Orientation") # + from sklearn.model_selection import train_test_split X = dat.loc[:, dat.columns != 'Market_Orientation'] y = dat.loc[:, "Market_Orientation"] X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = .3) # - X_train, X_test= fun.impute_data(X_train, X_test) X_train
finalized_code/functions_class.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] colab_type="text" id="TA21Jo5d9SVq" # # # ![JohnSnowLabs](https://nlp.johnsnowlabs.com/assets/images/logo.png) # # [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/NER_NO.ipynb) # # # # + [markdown] colab_type="text" id="CzIdjHkAW8TB" # # **Detect entities in Norwegian text** # + [markdown] colab_type="text" id="wIeCOiJNW-88" # ## 1. Colab Setup # + colab={"base_uri": "https://localhost:8080/", "height": 228} colab_type="code" id="CGJktFHdHL1n" outputId="0f0f1a83-95ba-4f26-bc37-58ac4be82532" # Install Java # ! apt-get update -qq # ! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null # ! java -version # Install pyspark # ! pip install --ignore-installed -q pyspark==2.4.4 # Install SparkNLP # ! pip install --ignore-installed spark-nlp # + [markdown] colab_type="text" id="eCIT5VLxS3I1" # ## 2. Start the Spark session # + colab={} colab_type="code" id="sw-t1zxlHTB7" import os import json os.environ['JAVA_HOME'] = "/usr/lib/jvm/java-8-openjdk-amd64" import pandas as pd import numpy as np from pyspark.ml import Pipeline from pyspark.sql import SparkSession import pyspark.sql.functions as F from sparknlp.annotator import * from sparknlp.base import * import sparknlp from sparknlp.pretrained import PretrainedPipeline spark = sparknlp.start() # + [markdown] colab_type="text" id="9RgiqfX5XDqb" # ## 3. Select the DL model # + colab={} colab_type="code" id="LLuDz_t40be4" # If you change the model, re-run all the cells below. # Applicable models: norne_840B_300, norne_6B_300, norne_6B_100 MODEL_NAME = "norne_840B_300" # + [markdown] colab_type="text" id="2Y9GpdJhXIpD" # ## 4. Some sample examples # + colab={} colab_type="code" id="vBOKkB2THdGI" # Enter examples to be transformed as strings in this list text_list = [ """<NAME> III (født 28. oktober 1955) er en amerikansk forretningsmagnat, programvareutvikler, investor og filantrop. Han er mest kjent som medgründer av Microsoft Corporation. I løpet av sin karriere hos Microsoft hadde Gates stillingene som styreleder, administrerende direktør (CEO), president og sjef programvarearkitekt, samtidig som han var den største individuelle aksjonæren fram til mai 2014. Han er en av de mest kjente gründere og pionerene i mikrodatarevolusjon på 1970- og 1980-tallet. Han er født og oppvokst i Seattle, Washington, og grunnla Microsoft sammen med barndomsvennen <NAME> i 1975, i Albuquerque, New Mexico; det fortsatte å bli verdens største programvare for datamaskinprogramvare. Gates ledet selskapet som styreleder og administrerende direktør til han gikk av som konsernsjef i januar 2000, men han forble styreleder og ble sjef for programvarearkitekt. I løpet av slutten av 1990-tallet hadde Gates blitt kritisert for sin forretningstaktikk, som har blitt ansett som konkurransedyktig. Denne uttalelsen er opprettholdt av en rekke dommer. I juni 2006 kunngjorde Gates at han skulle gå over til en deltidsrolle hos Microsoft og på heltid ved Bill & <NAME>ates Foundation, den private veldedige stiftelsen som han og kona, <NAME>, opprettet i 2000. [ 9] Han overførte gradvis arbeidsoppgavene sine til <NAME> og <NAME>. Han trakk seg som styreleder for Microsoft i februar 2014 og tiltrådte et nytt verv som teknologirådgiver for å støtte den nyutnevnte administrerende direktøren Satya Nadella.""", """<NAME> er et oljemaleri fra 1500-tallet skapt av Leonardo. Det holdes på Louvre i Paris.""" ] # + [markdown] colab_type="text" id="XftYgju4XOw_" # ## 5. Define Spark NLP pipeline # + colab={"base_uri": "https://localhost:8080/", "height": 69} colab_type="code" id="lBggF5P8J1gc" outputId="fcf7c6cd-40b2-4fc5-dc78-2fc07f6a8f17" document_assembler = DocumentAssembler() \ .setInputCol('text') \ .setOutputCol('document') tokenizer = Tokenizer() \ .setInputCols(['document']) \ .setOutputCol('token') # The wikiner_840B_300 is trained with glove_840B_300, so the embeddings in the # pipeline should match. Same applies for the other available models. if MODEL_NAME == "wikiner_840B_300": embeddings = WordEmbeddingsModel.pretrained('glove_840B_300', lang='xx') \ .setInputCols(['document', 'token']) \ .setOutputCol('embeddings') elif MODEL_NAME == "wikiner_6B_300": embeddings = WordEmbeddingsModel.pretrained('glove_6B_300', lang='xx') \ .setInputCols(['document', 'token']) \ .setOutputCol('embeddings') elif MODEL_NAME == "wikiner_6B_100": embeddings = WordEmbeddingsModel.pretrained('glove_100d') \ .setInputCols(['document', 'token']) \ .setOutputCol('embeddings') ner_model = NerDLModel.pretrained(MODEL_NAME, 'no') \ .setInputCols(['document', 'token', 'embeddings']) \ .setOutputCol('ner') ner_converter = NerConverter() \ .setInputCols(['document', 'token', 'ner']) \ .setOutputCol('ner_chunk') nlp_pipeline = Pipeline(stages=[ document_assembler, tokenizer, embeddings, ner_model, ner_converter ]) # + [markdown] colab_type="text" id="mv0abcwhXWC-" # ## 6. Run the pipeline # + colab={} colab_type="code" id="EYf_9sXDXR4t" empty_df = spark.createDataFrame([['']]).toDF('text') pipeline_model = nlp_pipeline.fit(empty_df) df = spark.createDataFrame(pd.DataFrame({'text': text_list})) result = pipeline_model.transform(df) # + [markdown] colab_type="text" id="UQY8tAP6XZJL" # ## 7. Visualize results # + colab={"base_uri": "https://localhost:8080/", "height": 469} colab_type="code" id="Ar32BZu7J79X" outputId="8d28503a-ee82-4ee6-e959-36530081b872" result.select( F.explode( F.arrays_zip('ner_chunk.result', 'ner_chunk.metadata') ).alias("cols") ).select( F.expr("cols['0']").alias('chunk'), F.expr("cols['1']['entity']").alias('ner_label') ).show(truncate=False)
tutorials/streamlit_notebooks/NER_NO.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] slideshow={"slide_type": "slide"} # # Solution of a linear system <a class="tocSkip"> # # + [markdown] slideshow={"slide_type": "slide"} # https://drive.google.com/file/d/1hBZ4tsoCt9P2v3SLft-Cn9_dhTQ9ULbz/view # # + slideshow={"slide_type": "slide"} import sys import re import numpy as np #import parser as ps # + slideshow={"slide_type": "slide"} # %ls -l print() # %ls -l input/ # + slideshow={"slide_type": "slide"} # if len(sys.argv) > 1: # #print sys.argv[1] # f = open('input/'+sys.argv[1], 'r') # else: # f = open('input.txt', 'r') f = open('input.txt', 'r') # + slideshow={"slide_type": "slide"} # pattern = re.compile(r'(?P<a>(-?\d+/))x(?P<b>([+-]\d+/))y(?P<c>([+-]\d+/))(\=)(?P<r>[0-9]+)') pattern = re.compile(r'(?P<a>(-?\d+))x(?P<b>([+-]\d+))y(?P<c>([+-]\d+))(\=)(?P<r>[0-9]+)') # + slideshow={"slide_type": "skip"} _ = """ matrixA = np.array([]) matrixB = np.array([]) for line in f: #line = f.readline() #newLine = ps.expr(line).compile() #match = pattern.match(line) #or findall match = re.search(pattern, line)#.groups() print match, type(match) print pattern, type(pattern) if match: a = int(match.group('a')) b = int(match.group('b')) c = int(match.group('c')) newRow = [a, b, c] matrixA = np.concatenate(matrixA, newRow) r = int(match.group('r')) newRow = [r] matrixB = np.concatenate(matrixB, newRow) else: raise Exception('Pattern not matched') """ # + slideshow={"slide_type": "skip"} matrixA = np.array([[2, 3, 6], [0, 4, 2], [1, 3, 5]]) matrixB = np.array([[2], [3], [1]]) print('matrixA:\n %s\n' % matrixA) print('matrixB:\n %s' % matrixB) # + slideshow={"slide_type": "slide"} # %%time detA = np.linalg.det(matrixA) if detA == 0: print('Determinant is 0. Program will stop') quit() matrixAinv = np.linalg.inv(matrixA) # + slideshow={"slide_type": "slide"} print('---', 'Inverse matrix is: ') print(matrixAinv) checkInv = np.allclose(np.dot(matrixA, matrixAinv), np.eye(3)) print("\nIs matrixAinv ok ?", checkInv) #x = np.linalg.solve(a, b, c) #Check that the solution is correct: #np.allclose(np.dot(a, x), b) # + [markdown] slideshow={"slide_type": "skip"} # --- #
labs-neural-networks/hw-lab2/Refactor.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Import Libraries # + # # !pip install -qqq pytorch_lightning torchmetrics wandb tokenizers janome jieba # + # Import built-in Python libs import random import sys import heapq from pathlib import Path from typing import List from tqdm import tqdm # Import data science libs import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd # Import deep learning libs import pytorch_lightning as pl import torchmetrics import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim # Import weights & bias import wandb # Import data preprocessing libs from tokenizers import Tokenizer from torch.utils.data import DataLoader # %matplotlib inline # - import os os.environ["TOKENIZERS_PARALLELISM"] = "False" utils_path = Path.cwd().parent / "utils" sys.path.append(str(utils_path)) from custom_tokenizer import load_jieba_tokenizer, load_janome_tokenizer # # Job Selection # + job = 1 # 0 - sentencepiece, 1 - language specific job_name = ["rnn_sentencepiece_ch2jp", "rnn_language_specific_ch2jp"] tokenizer_job = ["sentencepiece", "language_specific"] ch_tokenizer_job = ["ch_tokenizer.json", "jieba_tokenizer.json"] jp_tokenizer_job = ["jp_tokenizer.json", "janome_tokenizer.json"] embedding_job = ["sentencepiece_embedding", "language_specific_embedding"] # + method = 1 method_name = ["semantic", "phonetic", "meta"] ch_embedding_method = [ "ch_embedding.npy", "chp_embedding.npy", "ch_meta_embedding.npy", ] jp_embedding_method = [ "jp_embedding.npy", "jpp_embedding.npy", "jp_meta_embedding.npy", ] # - # # Config and WandB config = { "enc_emb_dim": 300, "dec_emb_dim": 300, "enc_hid_dim": 512, "dec_hid_dim": 512, "enc_dropout": 0.1, "dec_dropout": 0.1, "lr": 7e-4, "batch_size": 32, "num_workers": 0, "precision": 16, } run = wandb.init( project="phonetic-translation", entity="windsuzu", group="experiments", job_type=job_name[job] + "-" + method_name[method], config=config, reinit=True, ) # # Download Datasets, Tokenizers, Embedding, DataModule # ## Raw Data # + train_data_art = run.use_artifact("sampled_train:latest") train_data_dir = train_data_art.download() dev_data_art = run.use_artifact("dev:latest") dev_data_dir = dev_data_art.download() test_data_art = run.use_artifact("test:latest") test_data_dir = test_data_art.download() data_dir = { "train": train_data_dir, "dev": dev_data_dir, "test": test_data_dir, } # - # ## Tokenizer # + tokenizer_art = run.use_artifact(f"{tokenizer_job[job]}:latest") tokenizer_dir = tokenizer_art.download() src_tokenizer_dir = Path(tokenizer_dir) / ch_tokenizer_job[job] trg_tokenizer_dir = Path(tokenizer_dir) / jp_tokenizer_job[job] # - # ## Pretrained Embedding # # How to load pretrained embedding ? # # > https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html#torch.nn.Embedding.from_pretrained # + embedding_art = run.use_artifact(f"{embedding_job[job]}:latest") embedding_dir = embedding_art.download() ch_embedding_dir = Path(embedding_dir) / ch_embedding_method[method] jp_embedding_dir = Path(embedding_dir) / jp_embedding_method[method] # + src_embedding = np.load(Path(ch_embedding_dir)) trg_embedding = np.load(Path(jp_embedding_dir)) src_embedding = torch.FloatTensor(src_embedding) trg_embedding = torch.FloatTensor(trg_embedding) # - print(src_embedding.shape) print(trg_embedding.shape) # ## DataModule # + jupyter={"source_hidden": true} tags=[] class SentencePieceDataModule(pl.LightningDataModule): def __init__( self, data_dir, src_tokenizer_dir, trg_tokenizer_dir, batch_size=128, num_workers=8, pin_memory=True, job=0, ): super().__init__() self.data_dir = data_dir self.src_tokenizer_dir = src_tokenizer_dir self.trg_tokenizer_dir = trg_tokenizer_dir self.batch_size = batch_size self.num_workers = num_workers self.pin_memory = pin_memory self.job = job def setup(self, stage=None): self.src_tokenizer = self._load_tokenizer(self.src_tokenizer_dir) self.trg_tokenizer = self._load_tokenizer(self.trg_tokenizer_dir) if stage == "fit": self.train_set = self._data_preprocess(self.data_dir["train"]) self.val_set = self._data_preprocess(self.data_dir["dev"]) if stage == "test": self.test_set = self._data_preprocess(self.data_dir["test"]) def train_dataloader(self): return DataLoader( self.train_set, self.batch_size, shuffle=True, num_workers=self.num_workers, pin_memory=self.pin_memory, collate_fn=self._data_batching_fn, ) def val_dataloader(self): return DataLoader( self.val_set, self.batch_size, shuffle=False, num_workers=self.num_workers, pin_memory=self.pin_memory, collate_fn=self._data_batching_fn, ) def test_dataloader(self): return DataLoader( self.test_set, self.batch_size, shuffle=False, num_workers=self.num_workers, pin_memory=self.pin_memory, collate_fn=self._data_batching_fn, ) def _read_data_array(self, data_dir): with open(data_dir, encoding="utf8") as f: arr = f.readlines() return arr def _load_tokenizer(self, tokenizer_dir, lang="ch"): if self.job == 0: return Tokenizer.from_file(str(tokenizer_dir)) else: return ( load_jieba_tokenizer(tokenizer_dir) if "jieba" in str(tokenizer_dir) else load_janome_tokenizer(tokenizer_dir) ) def _data_preprocess(self, data_dir): src_txt = self._read_data_array(Path(data_dir) / "ch.txt") trg_txt = self._read_data_array(Path(data_dir) / "jp.txt") parallel_txt = np.array(list(zip(src_txt, trg_txt))) return parallel_txt def _data_batching_fn(self, data_batch): data_batch = np.array(data_batch) # shape=(batch_size, 2=src+trg) src_batch = data_batch[:, 0] # shape=(batch_size, ) trg_batch = data_batch[:, 1] # shape=(batch_size, ) # src_batch=(batch_size, longest_sentence) # trg_batch=(batch_size, longest_sentence) src_batch = self.src_tokenizer.encode_batch(src_batch) trg_batch = self.trg_tokenizer.encode_batch(trg_batch) # We have to sort the batch by their non-padded lengths in descending order, # because the descending order can help in `nn.utils.rnn.pack_padded_sequence()`, # which it will help us ignoring the <pad> in training rnn. # https://meetonfriday.com/posts/4d6a906a src_batch, trg_batch = zip( *sorted( zip(src_batch, trg_batch), key=lambda x: sum(x[0].attention_mask), reverse=True, ) ) return src_batch, trg_batch # + tags=[] dm = SentencePieceDataModule( data_dir, src_tokenizer_dir, trg_tokenizer_dir, config["batch_size"], config["num_workers"], job=job, ) # - # ### Test DataModule # + tags=[] dm.setup("test") # + input_dim = dm.src_tokenizer.get_vocab_size() output_dim = dm.trg_tokenizer.get_vocab_size() print(input_dim, output_dim) src_pad_idx = dm.src_tokenizer.token_to_id("[PAD]") print(src_pad_idx) # - for src, trg in dm.test_dataloader(): print(len(src), src[0], src[0].tokens) print(len(trg), trg[0], trg[0].tokens) break # # Build Lightning Model # ## Encoder # + jupyter={"source_hidden": true} tags=[] class Encoder(nn.Module): def __init__(self, input_dim, emb_dim, enc_hid_dim, dec_hid_dim, dropout): super().__init__() self.embedding = nn.Embedding.from_pretrained(src_embedding) self.rnn = nn.GRU(emb_dim, enc_hid_dim, bidirectional=True, batch_first=True) self.fc = nn.Linear(enc_hid_dim * 2, dec_hid_dim) self.dropout = nn.Dropout(dropout) def forward(self, src, src_len): # src = [batch_size, src_len] # src_len = [batch_size] embedded = self.dropout(self.embedding(src)) # embedded = [batch_size, src_len, emb_dim] packed_embedded = nn.utils.rnn.pack_padded_sequence(embedded, src_len.to("cpu"), batch_first=True) packed_outputs, hidden = self.rnn(packed_embedded) # packed_outputs is a packed sequence containing all hidden states # hidden is now from the final non-padded element in the batch enc_outputs, _ = nn.utils.rnn.pad_packed_sequence(packed_outputs, batch_first=True) # enc_outputs is now a non-packed sequence # enc_outputs = [batch_size, src_len, enc_hid_dim*num_directions] # = [forward_n + backward_n] # = [last layer] # hidden = [n_layers*num_directions, batch_size, enc_hid_dim] # = [forward_1, backward_1, forward_2, backword_2, ...] # hidden[-2, :, : ] is the last of the forwards RNN # hidden[-1, :, : ] is the last of the backwards RNN last_hidden = torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1) init_dec_hidden = torch.tanh(self.fc(last_hidden)) # enc_outputs = [batch_size, src_len, enc_hid_dim*2] (we only have 1 layer) # init_dec_hidden = [batch_size, dec_hid_dim] return enc_outputs, init_dec_hidden # - # ## Attention # + jupyter={"source_hidden": true} tags=[] class Attention(nn.Module): def __init__(self, enc_hid_dim, dec_hid_dim): super().__init__() self.attn = nn.Linear((enc_hid_dim * 2) + dec_hid_dim, dec_hid_dim) self.v = nn.Linear(dec_hid_dim, 1, bias=False) def forward(self, hidden, encoder_outputs, mask): # hidden = [batch_size, dec_hid_dim] # encoder_outputs = [batch_size, src_len, enc_hid_dim * 2] src_len = encoder_outputs.shape[1] hidden = hidden.unsqueeze(1).repeat(1, src_len, 1) # hidden = [batch_size, 1, dec_hid_dim] (unsqueeze 1) # = [batch_size, src_len, dec_hid_dim] (repeat) stacked_hidden = torch.cat((hidden, encoder_outputs), dim=2) # stacked_hidden = [batch_size, src_len, dec_hid_dim + enc_hid_dim * 2] energy = torch.tanh(self.attn(stacked_hidden)) # energy = [batch_size, src_len, dec_hid_dim] attention = self.v(energy).squeeze(2) # attention = [batch_size, src_len, 1] (v) # = [batch_size, src_len] (squeeze) attention = attention.masked_fill(mask == 0, -(2**15)) return F.softmax(attention, dim=1) # - # ## Decoder # + jupyter={"source_hidden": true} tags=[] class Decoder(nn.Module): def __init__( self, output_dim, emb_dim, enc_hid_dim, dec_hid_dim, dropout, attention ): super().__init__() self.attention = attention self.embedding = nn.Embedding.from_pretrained(trg_embedding) self.rnn = nn.GRU((enc_hid_dim * 2) + emb_dim, dec_hid_dim, batch_first=True) self.fc_out = nn.Linear((enc_hid_dim * 2) + dec_hid_dim + emb_dim, output_dim) self.dropout = nn.Dropout(dropout) def forward(self, inp, hidden, encoder_outputs, mask): # encoder_outputs = [batch_size, src_len, enc_hid_dim*2] # hidden = [batch_size, dec_hid_dim] inp = inp.unsqueeze(1) # inp = [batch_size] # = [batch_size, 1] (unsqueeze 1) # embedded = [batch_size, 1, emb_dim] embedded = self.dropout(self.embedding(inp)) # a = [batch_size, src_len] # = [batch_size, 1, src_len] (unsqueeze 1) a = self.attention(hidden, encoder_outputs, mask) a = a.unsqueeze(1) # weighted = [batch_size, 1, enc_hid_dim*2] weighted = torch.bmm(a, encoder_outputs) # rnn_input = [batch_size, 1, emb_dim + enc_hid_dim*2] rnn_input = torch.cat((embedded, weighted), dim=2) # hidden = [1, batch_size, dec_hid_dim] (unsqueeze 0) hidden = hidden.unsqueeze(0) # output = [batch_size, 1, dec_hid_dim] # hidden = [1, batch_size, dec_hid_dim] output, hidden = self.rnn(rnn_input, hidden) # embedded = [batch_size, emb_dim] (squeeze 0) # output = [batch_size, dec_hid_dim] (squeeze 0) # weighted = [batch_size, enc_hid_dim*2] (squeeze 0) # hidden = [batch_size, dec_hid_dim] (squeeze 0) embedded = embedded.squeeze(1) output = output.squeeze(1) weighted = weighted.squeeze(1) hidden = hidden.squeeze(0) assert (output == hidden).all() predict_input = torch.cat((output, weighted, embedded), dim=1) # prediction = [batch_size, output_dim] prediction = self.fc_out(predict_input) # a = [batch_size, src_len] (squeeze 1) a = a.squeeze(1) return prediction, hidden, a # - # ## Full Seq2Seq Model # + jupyter={"source_hidden": true} tags=[] class Seq2SeqModel(pl.LightningModule): def __init__(self, input_dim, output_dim, trg_tokenizer, config): super().__init__() self.trg_tokenizer = trg_tokenizer self.input_dim = input_dim self.output_dim = output_dim self.encoder = Encoder( input_dim, config["enc_emb_dim"], config["enc_hid_dim"], config["dec_hid_dim"], config["enc_dropout"], ) attn = Attention(config["enc_hid_dim"], config["dec_hid_dim"]) self.decoder = Decoder( output_dim, config["dec_emb_dim"], config["enc_hid_dim"], config["dec_hid_dim"], config["dec_dropout"], attn, ) self.lr = config["lr"] self.apply(self.init_weights) def init_weights(self, m): for name, param in m.named_parameters(): if 'weight' in name: nn.init.normal_(param.data, mean=0, std=0.01) else: nn.init.constant_(param.data, 0) # Training # Use only when training and validation def _forward(self, src, trg, teacher_forcing_ratio=0.5): # teacher_forcing_ratio is probability to use teacher forcing # e.g., if teacher_forcing_ratio is 0.5 we use teacher forcing 50% of the time # src = list of Encoding([ids, type_ids, tokens, offsets, attention_mask, special_tokens_mask, overflowing]) # trg = list of Encoding([ids, type_ids, tokens, offsets, attention_mask, special_tokens_mask, overflowing]) # src_batch = [batch_size, src_len] # src_mask = [batch_size, src_len] # src_len = [batch_size] src_batch = torch.tensor([e.ids for e in src], device=self.device) src_mask = torch.tensor([e.attention_mask for e in src], device=self.device) src_len = torch.sum(src_mask, axis=1) # trg_batch = [batch_size, trg_len] trg_batch = torch.tensor([e.ids for e in trg], device=self.device) batch_size = src_batch.shape[0] trg_len = trg_batch.shape[1] trg_vocab_size = self.output_dim # create a tensor for storing all decoder outputs preds = torch.zeros(batch_size, trg_len, trg_vocab_size, device=self.device) # encoder_outputs is all hidden states of the input sequence, back and forwards # hidden is the final forward and backward hidden states, passed through a linear layer encoder_outputs, hidden = self.encoder(src_batch, src_len) # first input to the decoder = [BOS] tokens # inp = [batch_size] inp = trg_batch[:, 0] for t in range(1, trg_len): # pred = [batch_size, output_dim] # hidden = [batch_size, dec_hid_dim] pred, hidden, _ = self.decoder(inp, hidden, encoder_outputs, src_mask) # store predictions in a tensor holding predictions for each token preds[:, t, :] = pred # decide if we are going to use teacher forcing or not teacher_force = random.random() < teacher_forcing_ratio # top1 = [batch_size] # get the highest predicted token from our predictions top1 = pred.argmax(1) # inp = [batch_size] # if teacher forcing, use actual next token as next input # if not, use predicted token inp = trg_batch[:, t] if teacher_force else top1 return preds # Inference # * Let you use the pl model as a pytorch model. # * # * pl_model.eval() # * pl_model(X) # * def forward(self, src, max_len=200): src_batch = torch.tensor([e.ids for e in src], device=self.device) src_mask = torch.tensor([e.attention_mask for e in src], device=self.device) src_len = torch.sum(src_mask, axis=1) # actual src_len without [PAD] batch_size = src_batch.shape[0] src_size = src_batch.shape[1] # src_len with [PAD] trg_len = max_len trg_vocab_size = self.output_dim preds = torch.zeros(batch_size, trg_len, trg_vocab_size, device=self.device) encoder_outputs, hidden = self.encoder(src_batch, src_len) # create a tensor for storing all attention matrices attns = torch.zeros(batch_size, trg_len, src_size, device=self.device) # first input to the decoder = [BOS] tokens # inp = [batch_size] inp = torch.tensor([self.trg_tokenizer.token_to_id("[BOS]")], device=self.device).repeat(batch_size) for t in range(1, trg_len): # attn = [batch_size, src_len] pred, hidden, attn = self.decoder(inp, hidden, encoder_outputs, src_mask) preds[:, t, :] = pred top1 = pred.argmax(1) inp = top1 # store attention sequences in a tensor holding attention value for each token attns[:, t, :] = attn return preds, attns, src_len def training_step(self, batch, batch_idx): # both are lists of encodings src, trg = batch # y = [batch_size, trg_len] # pred = [batch_size, trg_len, output_dim] y = torch.tensor([e.ids for e in trg], device=self.device) preds = self._forward(src, trg) output_dim = preds.shape[-1] # y = [batch_size * (trg_len-1)] # pred = [batch_size * (trg_len-1), output_dim] y = y[:, 1:].reshape(-1) preds = preds[:, 1:, :].reshape(-1, output_dim) loss = F.cross_entropy(preds, y, ignore_index=self.trg_tokenizer.token_to_id("[PAD]")) self.log("train_loss", loss) perplexity = torch.exp(loss) self.log("train_ppl", perplexity) if self.global_step % 50 == 0: torch.cuda.empty_cache() return loss def validation_step(self, batch, batch_idx): src, trg = batch y = torch.tensor([e.ids for e in trg], device=self.device) preds = self._forward(src, trg) output_dim = preds.shape[-1] y = y[:, 1:].reshape(-1) preds = preds[:, 1:, :].reshape(-1, output_dim) loss = F.cross_entropy(preds, y, ignore_index=self.trg_tokenizer.token_to_id("[PAD]")) self.log("valid_loss", loss, sync_dist=True) perplexity = torch.exp(loss) self.log("valid_ppl", perplexity, sync_dist=True) def test_step(self, batch, batch_idx): src, trg = batch preds, attn_matrix, real_src_len = self(src) # attn_matrix = [batch_size, trg_len, src_len] # preds = [batch_size, trg_len, output_dim] # = [batch_size, trg_len] (argmax 2) preds = preds.argmax(2) # convert `preds` tensor to list of real sentences (tokens) # meaning to cut the sentence by [EOS] and remove the [PAD] tokens # eos_pos = dict(sentence_idx: first_pad_position) # # e.g., {0: 32, 2: 55} # Meaning that we have 32 tokens (include [EOS]) in the first predicted sentence # and `max_len` tokens (no [EOS]) in the second predicted setence # and 55 tokens (include [EOS]) in the third predicted sentence eos_pos = dict(reversed((preds == self.trg_tokenizer.token_to_id("[EOS]")).nonzero().tolist())) pred_sentences, attn_matrices = [], [] for idx, (sentence, attention, src_len) in enumerate(zip(preds, attn_matrix, real_src_len)): # sentence = [trg_len_with_pad] # = [real_trg_len] pred_sentences.append(sentence[:eos_pos.get(idx)+1 if eos_pos.get(idx) else None]) # attention = [trg_len_with_pad, src_len_with_pad] # = [real_trg_len, real_src_len] attn_matrices.append(attention[:eos_pos.get(idx)+1 if eos_pos.get(idx) else None, :src_len]) # source sentences for displaying attention matrix src = [[token for token in e.tokens if token != "[PAD]"] for e in src] # target sentences for calculating BLEU scores trg = [[token for token in e.tokens if token != "[PAD]"] for e in trg] return pred_sentences, attn_matrices, src, trg def test_epoch_end(self, test_outputs): outputs = [] for (pred_sent_list, attn_list, src_list, trg_list) in test_outputs: for pred_sent, attn, src, trg in list(zip(pred_sent_list, attn_list, src_list, trg_list)): pred_sent = list(map(self.trg_tokenizer.id_to_token, pred_sent)) outputs.append((pred_sent, attn, src, trg)) # outputs = list of predictions of testsets, each has a tuple of (pred_sentence, attn_matrix, src_sentence, trg_sentence) # pred_sentence = [trg_len] # attn_matrix = [trg_len, src_len] # src_sentence = [src_len] # trg_sentence = [trg_len] self.test_outputs = outputs def configure_optimizers(self): return torch.optim.Adam(filter(lambda p: p.requires_grad, self.parameters()), lr=self.lr) def optimizer_zero_grad(self, epoch, batch_idx, optimizer, optimizer_idx): optimizer.zero_grad(set_to_none=True) # + class EmbeddingFineTuning(pl.callbacks.BaseFinetuning): def __init__(self, unfreeze_at_epoch=2): super().__init__() self._unfreeze_at_epoch = unfreeze_at_epoch def freeze_before_training(self, pl_module): # freeze any module you want self.freeze(pl_module.encoder.embedding) self.freeze(pl_module.decoder.embedding) def finetune_function(self, pl_module, current_epoch, optimizer, optimizer_idx): # When `current_epoch` is hit, embedding will start training. if current_epoch == self._unfreeze_at_epoch: self.unfreeze_and_add_param_group( modules=[ pl_module.encoder.embedding, pl_module.decoder.embedding, ], optimizer=optimizer, ) embedding_finetune = EmbeddingFineTuning(unfreeze_at_epoch=3) # + wandb_logger = pl.loggers.WandbLogger() model = Seq2SeqModel( input_dim, output_dim, dm.trg_tokenizer, config, ) # + def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) print(f'The model has {count_parameters(model):,} trainable parameters') model # - # # Training ckpt_dir = Path("checkpoints") checkpoint = pl.callbacks.ModelCheckpoint(dirpath=ckpt_dir, # path for saving checkpoints filename=f"{job_name[job]}-{method_name[method]}-" + "{epoch}-{valid_loss:.3f}", monitor="valid_loss", mode="min", save_weights_only=True, save_top_k=20, ) # + tags=[] trainer = pl.Trainer( fast_dev_run=False, logger=wandb_logger, gpus=1, max_epochs=15, gradient_clip_val=1, precision=config["precision"], callbacks=[checkpoint, embedding_finetune], ) # - trainer.fit(model, datamodule=dm) # # Testing (BLEU Scores) def calculate_corpus_bleu(preds: List[str], refs: List[List[str]], n_gram=4): # arg example: # preds: ["机器人行业在环境问题上的措施", "松下生产科技公司也以环境先进企业为目标"] # refs: [["机器人在环境上的改变", "對於机器人在环境上的措施"], ["松下科技公司的首要目标是解决环境问题"]] preds = list(map(list, preds)) refs = [[list(sen) for sen in ref] for ref in refs] return torchmetrics.functional.nlp.bleu_score(preds, refs, n_gram=n_gram) # + test_ckpt = [ "rnn_language_specific_ch2jp-meta-epoch=7-valid_loss=4.437.ckpt", "rnn_language_specific_ch2jp-meta-epoch=8-valid_loss=4.327.ckpt", "rnn_language_specific_ch2jp-meta-epoch=9-valid_loss=4.426.ckpt", "rnn_language_specific_ch2jp-meta-epoch=10-valid_loss=4.425.ckpt", "rnn_language_specific_ch2jp-meta-epoch=11-valid_loss=4.480.ckpt", "rnn_language_specific_ch2jp-meta-epoch=12-valid_loss=4.507.ckpt", "rnn_language_specific_ch2jp-meta-epoch=13-valid_loss=4.579.ckpt", "rnn_language_specific_ch2jp-meta-epoch=14-valid_loss=4.662.ckpt", ] for ckpt in test_ckpt: model.load_state_dict(torch.load(ckpt_dir / ckpt)["state_dict"]) trainer.test(model, datamodule=dm) preds = [ dm.trg_tokenizer.decode(list(map(dm.trg_tokenizer.token_to_id, output[0]))) for output in model.test_outputs ] refs = [ [dm.trg_tokenizer.decode(list(map(dm.trg_tokenizer.token_to_id, output[3])))] for output in model.test_outputs ] bleu_score = calculate_corpus_bleu(preds, refs, n_gram=4) print(ckpt) print(bleu_score) # - wandb.log({"bleu_score": 26.42}) run.finish() # # Case Study and Attention Matrix # + plt.rcParams['font.sans-serif'] = ['Noto Sans CJK TC'] plt.rcParams['axes.unicode_minus'] = False def sentence_bleu(pred_token, trg_token): trg = dm.trg_tokenizer.decode(list(map(dm.trg_tokenizer.token_to_id, trg_token))) pred = dm.trg_tokenizer.decode(list(map(dm.trg_tokenizer.token_to_id, pred_token))) return calculate_corpus_bleu([trg], [[pred]]) def case_study(pred_token, src_token, trg_token, attn_matrix): src = dm.src_tokenizer.decode(list(map(dm.src_tokenizer.token_to_id, src_token))) trg = dm.trg_tokenizer.decode(list(map(dm.trg_tokenizer.token_to_id, trg_token))) pred = dm.trg_tokenizer.decode(list(map(dm.trg_tokenizer.token_to_id, pred_token))) bleu = calculate_corpus_bleu([trg], [[pred]]) print(f"SOURCE: \n{src}\n {'-'*100}") print(f"TARGET: \n{trg}\n {'-'*100}") print(f"PREDICTION: \n{pred}\n {'-'*100}") print(f"BLEU SCORE: {bleu}") plt.figure(figsize=(30, 30)) for i in range(6): plt.subplot(3, 2, i+1) ax = sns.heatmap(attn_matrix[i], xticklabels=src_token, yticklabels=pred_token) ax.xaxis.set_ticks_position('top') # + scores = [] for i in tqdm(range(len(model.test_outputs))): bleu = sentence_bleu( model.test_outputs[i][0], model.test_outputs[i][3], ) scores.append(bleu) # - heapq.nlargest(50, range(len(scores)), np.array(scores).take)[10:20] i=1975 case_study(model.test_outputs[i][0], model.test_outputs[i][2], model.test_outputs[i][3], model.test_outputs[i][1].cpu().numpy())
experiments/main/nmt_task/rnn_embedding.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 0.7.0-beta2 # language: julia # name: julia-0.7 # --- # # Unique things # # Many of the features and commands in Symata will be familiar from other programs. This notebook presents a few things that may be unfamiliar and not documented elsewhere. Also note that many of the "unique" features appear in other tutorial notebooks. using Symata # enter Symata mode # ### Version information # Version information of main components. VersionInfo() # ### OutputStyle # # `OutputStyle` selects the appearance of printed (or rendered) Symata expressions. See the notebook "InteractingWithSymata" for more details. ? OutputStyle # ### Timing evaluation # Use `Time(True)` and `Time(False)` to toggle timing and allocation information after evaluation of each input line. Use `Timing(expr)` to time the evaluation of `expr` only. # # Suppress the output when using `Timing` like this # + Timing(Range(10^5), Null) # jit compile Timing(Range(10^5), Null) # - # ## Help # # `?` prints help on the `Help` function. # # `Help(topic)`, `Help("topic")`, or `? topic` prints documentation for `topic`. # # `h"words"` does a case insensitive search of the contents of help documents. # # Syamta uses the python package *SymPy* extensivley. `Help` prints relevant SymPy documentation along with Symata documentation. Type `ShowSymPyDocs(False)` to disable printing SymPy documentation. # ## Big integers # # By default, Symata converts input integers to the Julia type `Int`. But, you may want bigger numbers: 2^100 # overflow ? BigIntInput BigIntInput(True); 2^100 # Note that this only applies to input integers (at the moment) Head(Cos(Pi)) Head(BI(Cos(Pi))) # Convert explicitly to BigInt # Another way to parse a single number as a `BigInt` BigIntInput(False) big"2"^100 # ## Passing data between Julia and Symata # Symata's host language is Julia. There are several ways to interact with Julia in a Symata session. # # Julia and Symata keep separate lists of symbols. For instance, `x` may be defined in Julia, but not Symata, and vice versa. # # Use `SetJ` to bind (i.e. set) a Julia symbol to a Symata expression. ? SetJ expr = x + y # Bind the Julia variable `z` to the result of evaluating `expr`. SetJ(z , expr) # Execute Julia code, by enclosing it in `J( )`. We ask for the value of `z`. J(Main.z) # We can also leave Symata and return to Julia Julia() # begin interpreting expressions as Julia code. ; z # Now in Julia # The unexported Julia function symval returns the Symata binding of a symbol. ? Symata.symval Symata.symval(:expr) # We can do the reverse, set a Symata variable to the value of a Julia variable. # # Set a variable in Jula. a = 1 # Set a Julia symbol (bind an identifier to a value) isymata() # Enter Symata mode again expr2 = J( Main.a ) expr2 # Symata symbol `expr2` is now set to `1`. # ## SymPy # # Symata uses the python package *SymPy* extensively. Most of the interaction with SymPy is transparent to the user. But there are several commands for controlling this interaction. # Use Symata's help search feature to find commands related to SymPy. h"sympy" ? SymPyError # For debugging, you can disable converting SymPy objects to Symata. ? ReturnSymPy ? ToSymata ? ToSymPy # Use `ToSymPy` and `ToSymata` to convert between the languages. OutputStyle(InputForm) pyobj = ToSymPy(Integrate(f(x),x)) OutputStyle(JupyterForm) [Head(pyobj), PyHead(pyobj)] # Recover the Symata expression. ToSymata(pyobj) # ### Version and date VersionInfo() InputForm(Now())
TutorialNotebooks/Unique To Symata.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="udM33upN_ZXP" # %tensorflow_version 2.x import pandas as pd import numpy as np import ktrain from ktrain import text from sklearn.model_selection import train_test_split # + id="5sKgMiulbHry" # temp = {'25 words':17315,'50 words':22773, '75 words':26065, '100 words:'28572} # + id="bJpG3YxDKajc" temp = pd.read_excel('/content/drive/My Drive/Colab Notebooks/Datasets/final_dataset_25.xlsx') del temp['Unnamed: 0'] train, test = train_test_split(temp, test_size=0.2, stratify = temp['Emotion'], random_state = 42) num_classes = 6 embed_num_dims = 300 max_seq_len = 50 x_train = train.Text.tolist() x_test = test.Text.tolist() y_train = train.Emotion.tolist() y_test = test.Emotion.tolist() # data = data_train.append(data_test, ignore_index=True) class_names = ['happy', 'angry', 'sad', 'disgust', 'surprise','fear'] # + id="6VnA4Z_8KbnC" encoding = { 'happy': 0, 'angry': 1, 'sad': 2, 'disgust': 3, 'surprise': 4, 'fear': 5 } y_train = [encoding[i] for i in y_train] y_test = [encoding[i] for i in y_test] # + colab={"base_uri": "https://localhost:8080/", "height": 163} id="XdfEOSk9Ln4O" outputId="9423937c-a42d-41db-eb24-c628c454ef46" (x_train, y_train), (x_test, y_test), preproc = text.texts_from_array(x_train=x_train, y_train=y_train, x_test=x_test, y_test=y_test, class_names=class_names, preprocess_mode='bert', maxlen=50, max_features=26065) # + colab={"base_uri": "https://localhost:8080/"} id="V1uXHaXtMX2L" outputId="5b1f35ab-b6b2-4694-c609-e81a3bf86fbe" model = text.text_classifier('bert', train_data=(x_train, y_train), preproc=preproc) # + id="_QcmGvpTXJ_r" learner = ktrain.get_learner(model, train_data=(x_train, y_train), val_data=(x_test, y_test), batch_size=64) # + id="dM2HId2tXOb3" colab={"base_uri": "https://localhost:8080/"} outputId="a32630fc-55eb-4695-c94f-d82013c4ddeb" hist = learner.fit_onecycle(2e-5, 10)
Bangla Dataset Explorations/75_percent_mBERT.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Upcoming topics # The following topics are currently being developed for addition to the textbook. # 1. Shor's Algorithm # 2. Overview of Quantum Algorithms for NISQ Hardware # 3. Mapping the Ising Model onto a Superconducting Quantum Computer # 4. Solving Combinatorial Optimization Problems using QAOA # 5. Solving Linear Systems of Equations using HHL # 6. Securing Communications using BB84 # 7. Decoherence and Energy Relaxation: Measuring T2 and T1 # 8. Optimizing Microwave Pulses for High-Fidelity Qubit Operations # 9. State and Process Tomography
content/ch-upcoming/0.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: conda_python3 # language: python # name: conda_python3 # --- # + # #!pip install eli5 # + # #!pip install category_encoders # - pwd # + import pandas as pd import numpy as np import random import pickle import gc #import psycopg2 from matplotlib import pyplot as plt from sklearn.preprocessing import RobustScaler from sklearn.pipeline import make_pipeline from sklearn.metrics import accuracy_score, f1_score, r2_score, roc_auc_score from sklearn.model_selection import train_test_split, RandomizedSearchCV, GridSearchCV from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier pd.set_option('display.max_columns', 500) pd.set_option('display.max_rows', 500) import eli5 from eli5.sklearn import PermutationImportance #import category_encoders as ce #from catboost import CatBoostClassifier # + #pitcher = 'Greinke' #pitcher = 'Scherzer' #pitcher = 'deGrom' pitcher = 'Bauer' path = '/home/ec2-user/SageMaker/RC-v1.2-Predictive-Modelling/pitcher_df_pickles/' + pitcher + '_df.pkl' df = pd.read_pickle(path, compression='zip').reset_index() #make binary fastball/not-fastball target feature: df['fastball_target'] = (df['pitch_cat'] == 'fastball') * 1 # - # ## 1-hot encoding def one_hot_encode(df): cat_cols = df.select_dtypes('category').columns.tolist() cat_cols.remove('at_bat_number') cat_cols.remove('pitch_count') cat_cols.remove('pitch_cat') cat_cols.remove('player_name') df = pd.get_dummies(df, columns=cat_cols) return df # + # df = one_hot_encode(df) # - # ## Strategic Ordinal Encoding def custom_ordinal_ecode(df): df = df.copy() #description cols: desc_map = {'called_strike':1, 'swinging_strike':2, 'foul_tip':3, 'foul':4, 'swinging_strike_blocked':5, 'foul_bunt':6, 'missed_bunt':6, 'bunt_foul_tip':6, 'N/A':7, 'pitchout':7, 'hit_into_play':8, 'ball':9, 'blocked_ball':10, 'hit_by_pitch':11, 'hit_into_play_no_out':12, 'hit_into_play_score':13} desc_cols = ['L1_description', 'L2_description', 'L3_description'] df[desc_cols] = df[desc_cols].replace(desc_map).astype('int') #pitch_result cols pitch_result_map = {'S':1, 'N/A':2, 'X':3, 'B':4} result_cols = ['L1_pitch_result', 'L2_pitch_result'] df[result_cols] = df[result_cols].replace(pitch_result_map).astype('int') #pitch_type cols pitch_type_map = {'FA':1, 'FF':1, 'FT':2, 'FC':2, 'FS':2, 'SI':2, 'SF':2, 'N/A':2.5, 'SL':3, 'CB':4, 'CU':4, 'SC':5, 'KC':5, 'CH':6, 'KN':7, 'EP':8, 'FO':9, 'PO':9} pitch_type_cols = ['L1_pitch_type', 'L2_pitch_type', 'L3_pitch_type', 'pitch_type'] df[pitch_type_cols] = df[pitch_type_cols].replace(pitch_type_map).astype('float') #count_cat count_cat_map = {'ahead':1,'neutral':2, 'behind':3} df['count_cat'] = df['count_cat'].replace(count_cat_map).astype('int') #count _count_map = {'02':1, '12':2, '01':3, '22':4, '11':5, '00':6, '21':7, '32':8, '10':9, '20':10, '31':11, '30':12} df['_count'] = df['_count'].replace(_count_map).astype('int') #for swung and chased, make unknown (-1) set to 0, and 0 (didnt swing/chase) set to -1: swung_and_chased_cols = ['L1_batter_swung', 'L1_chased', 'L2_chased', 'L3_chased'] def swung_chase_edit(x): if x == 0: return -1 elif x == -1: return 0 else: return x for col in swung_and_chased_cols: df[col] = df[col].apply(swung_chase_edit) #fill remaining misc categories to numerics: misc_map = {'L':-1, 'R':2, 'Top':-1, 'Bot': 1, 'Standard':0, 'Infield shift': 1, 'Strategic':2, '4th outfielder':3} df = df.replace(misc_map) #clean up category dtypes to ints df['year'] = df['year'].cat.codes df['catcher_id'] = df['catcher_id'].cat.codes cat_cols = ['outs_when_up', 'inning', 'at_bat_number', 'pitch_number', 'balls', 'strikes', 'pitch_count', 'L1_pitch_zone', 'L1_batter_swung', 'L1_chased', 'L2_pitch_zone', 'L2_chased', 'L3_pitch_zone', 'L3_chased', 'batting_order_slot', 'month'] df[cat_cols] = df[cat_cols].astype('int') df[['stand', 'inning_topbot', 'if_fielding_alignment', 'of_fielding_alignment']] = df[['stand', 'inning_topbot', 'if_fielding_alignment', 'of_fielding_alignment']].astype('int') return df df = custom_ordinal_ecode(df) df.fastball_target.value_counts(normalize=True) # ## Split into Train/Test def train_test_split_by_date(df, train_fraction): train_idx = int(len(df) * train_fraction) train_end_date = df.loc[train_idx].game_date train = df[df['game_date'] < train_end_date] test = df[df['game_date'] >= train_end_date] print('train shape: ' + str(train.shape)) print('test shape: '+ str(test.shape)) return train, test train, test = train_test_split_by_date(df, .85) # + #target = 'pitch_cat' target = 'fastball_target' drop_cols = ['index', 'player_name', 'game_date', 'pitch_cat', 'pitcher', 'pitch_type', target] X = train.drop(columns=drop_cols) X_test = test.drop(columns=drop_cols) y = train[target] y_test = test[target] X.shape, X_test.shape, y.shape, y_test.shape # - # ## Scale the Float columns # + scale_cols = ['fastball_perc_faced', 'fastball_chase_perc', 'fastball_bip_swung_perc', 'fastball_taken_strike_perc', 'fastball_est_woba', 'fastball_babip', 'fastball_iso_value', 'breaking_perc_faced', 'breaking_chase_perc', 'breaking_bip_swung_perc', 'breaking_taken_strike_perc', 'breaking_est_woba', 'breaking_babip', 'breaking_iso_value', 'offspeed_perc_faced', 'offspeed_chase_perc', 'offspeed_bip_swung_perc', 'offspeed_taken_strike_perc', 'offspeed_est_woba', 'offspeed_babip', 'offspeed_iso_value', 'pitchout_perc_faced', 'overall_fastball_perc', 'count_cat_fastball_perc', 'overall_breaking_perc', 'count_cat_breaking_perc', 'overall_offspeed_perc', 'count_cat_offspeed_perc', 'L5_fastball_perc', 'L15_fastball_perc', 'L5_breaking_perc', 'L15_breaking_perc', 'L5_offspeed_perc', 'L15_offspeed_perc', 'L5_strike_perc', 'L15_strike_perc', 'PB_fastball', 'PB_breaking', 'PB_offspeed'] scaler = RobustScaler() X[scale_cols] = scaler.fit_transform(X[scale_cols].values) X_test[scale_cols] = scaler.transform(X_test[scale_cols].values) # - # ## Random Forest # + # %%time #with bootstrap: param_grid = { 'n_estimators': [25, 50, 75, 100, 125, 150, 200, 300], 'max_depth': [2, 4, 6, 8, 10, 15, 25], 'min_samples_split': [5, 8, 12, 18, 25], 'min_samples_leaf': [3, 5, 7, 10], 'max_features': ['auto', 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], 'class_weight': [None], 'warm_start': [False, True], 'oob_score': [False, True] } rfc_with_bootstrap = RandomForestClassifier(n_jobs=-1, random_state=42, criterion='gini', bootstrap=True) # search = GridSearchCV( # estimator = rfc, # param_grid=param_grid, # scoring='accuracy', # n_jobs=-1, # cv=4, # verbose=10, # return_train_score=True) rfc_with_bootstrap_search = RandomizedSearchCV(estimator=rfc_with_bootstrap, param_distributions=param_grid, n_iter=500, scoring='accuracy', n_jobs=-1, iid='warn', refit=True, cv=3, verbose=10, random_state=42, error_score='raise-deprecating', return_train_score=True) rfc_with_bootstrap_search.fit(X, y) rfc_bootstrap_search_results = pd.DataFrame(rfc_with_bootstrap_search.cv_results_).sort_values(by='rank_test_score') # - rfc_bootstrap_search_results.head() # + # %%time #w/o bootstrap: param_grid = { 'n_estimators': [25, 50, 75, 100, 125, 150, 200, 300], 'max_depth': [2, 4, 6, 8, 10, 15, 25], 'min_samples_split': [5, 8, 12, 18, 25], 'min_samples_leaf': [3, 5, 7, 10, 15, 25], 'max_features': ['auto', 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], 'class_weight': [None], 'warm_start': [False, True] } rfc_without_bootstrap = RandomForestClassifier(n_jobs=-1, random_state=42, criterion='gini', bootstrap=False) # search = GridSearchCV( # estimator = rfc, # param_grid=param_grid, # scoring='accuracy', # n_jobs=-1, # cv=2, # verbose=10, # return_train_score=True) rfc_without_bootstrap_search = RandomizedSearchCV(estimator=rfc_without_bootstrap, param_distributions=param_grid, n_iter=500, scoring='accuracy', n_jobs=-1, iid='warn', refit=True, cv=3, verbose=10, random_state=42, error_score='raise-deprecating', return_train_score=True) rfc_without_bootstrap_search.fit(X, y) rfc_without_bootstrap_search_results = pd.DataFrame(rfc_without_bootstrap_search.cv_results_).sort_values(by='rank_test_score') # - rfc_without_bootstrap_search_results.head() def get_top_n_models(search_results, model_type, n=10, k=100, accuracy_metric='accuracy'): results_list = [] for i in range(k): model_dict = {} params = search_results.iloc[i]['params'] if model_type == 'rfc_bootstrap': model = RandomForestClassifier(n_jobs=-1, random_state=42, criterion='gini', class_weight=params['class_weight'], max_depth=params['max_depth'], max_features=params['max_features'], min_samples_leaf=params['min_samples_leaf'], min_samples_split=params['min_samples_split'], n_estimators=params['n_estimators'], oob_score=params['oob_score'], warm_start=params['warm_start']) elif model_type == 'rfc_without_bootstrap': model = RandomForestClassifier(n_jobs=-1, random_state=42, criterion='gini', class_weight=params['class_weight'], max_depth=params['max_depth'], max_features=params['max_features'], min_samples_leaf=params['min_samples_leaf'], min_samples_split=params['min_samples_split'], n_estimators=params['n_estimators'], warm_start=params['warm_start']) elif model_type == 'gbc': model = GradientBoostingClassifier(random_state=42, loss=params['loss'], learning_rate=params['learning_rate'], n_estimators=params['n_estimators'], subsample=params['subsample'], min_samples_split=params['min_samples_split'], min_samples_leaf=params['min_samples_leaf'], max_depth=params['max_depth'], max_features=params['max_features'], tol=params['tol']) elif model_type == 'svm': model = SVC(random_state=42, degree=params['degree'], kernel=params['kernel'], tol=params['tol'], C=params['C'], shrinking=params['shrinking'], class_weight=params['class_weight'], max_iter=params['max_iter'], decision_function_shape=params['decision_function_shape'], gamma=params['gamma']) elif model_type == 'lin_SVC': model = LinearSVC(random_state=42, penalty=params['penalty'], loss=params['loss'], dual=params['dual'], tol=params['tol'], C=params['C'], class_weight=params['class_weight'], max_iter=params['max_iter'], fit_intercept=params['fit_intercept']) elif model_type == 'sgd': model = SGDClassifier(random_state=42, penalty=params['penalty'], alpha=params['alpha'], loss=params['loss'], tol=params['tol'], class_weight=params['class_weight'], max_iter=params['max_iter'], fit_intercept=params['fit_intercept'], warm_start=params['warm_start'], learning_rate=params['learning_rate'], shuffle=params['shuffle']) elif model_type == 'lda': model = lda = LinearDiscriminantAnalysis(solver=params['solver'], shrinkage=params['shrinkage'], tol=params['tol'], n_components=params['n_components']) model.fit(X, y) y_pred = model.predict(X_test) accuracy = accuracy_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) r2 = r2_score(y_test, y_pred) try: y_pred_proba = model.predict_proba(X_test)[:,1] roc_auc = roc_auc_score(y_test, y_pred_proba) except: roc_auc = 'N/A' model_dict['model'] = [model] model_dict['accuracy'] = accuracy model_dict['f1_score'] = f1 model_dict['r2_score'] = r2 model_dict['roc_auc_score'] = roc_auc #convert the dict to df and append to list results_list.append(pd.DataFrame(model_dict)) #return df with the top n highest accuracy models (on the test data) results_df = pd.concat(results_list, axis=0).sort_values(by=accuracy_metric, ascending=False).head(n) results_df['model_type'] = results_df['model'].astype(str).apply(lambda x: x.split('(')[0]).reset_index(drop=True) return results_df # %%time top10_rfc_bootstrap = get_top_n_models(rfc_bootstrap_search_results, 'rfc_bootstrap') # %%time top10_rfc_without_bootstrap = get_top_n_models(rfc_without_bootstrap_search_results, 'rfc_without_bootstrap') top10_rfc_bootstrap top10_rfc_without_bootstrap # + from sklearn.metrics import classification_report, confusion_matrix from matplotlib import pyplot as plt import seaborn as sns def con_matrix_analysis(model, X, X_test, y, y_test): model.fit(X, y) y_pred = model.predict(X_test) print(classification_report(y_test, y_pred, target_names=['Not Fastball', 'Fastball'])) con_matrix = pd.DataFrame(confusion_matrix(y_test, y_pred), columns=['Predicted Not Fastball', 'Predicted Fastball'], index=['Actual Not Fastball', 'Actual Fastball']) sns.heatmap(data=con_matrix, cmap='cool') plt.show(); return con_matrix # - # model = search.best_estimator_ model = top10_rfc_bootstrap.model.values[0] con_matrix_analysis(model, X, X_test, y, y_test) # model = search.best_estimator_ model = top10_rfc_without_bootstrap.model.values[0] con_matrix_analysis(model, X, X_test, y, y_test) # + import graphviz from sklearn.tree import export_graphviz feature_names = train.drop(columns=drop_cols).columns.tolist() model.fit(X, y) estimator = model.estimators_[5] dot_data = export_graphviz(estimator, out_file=None, #'tree.dot', feature_names = feature_names, class_names = ['Not Fastball', 'Fastball'], rounded = True, proportion = True, precision = 2, filled = True) graphviz.Source(dot_data) # - # ## Gradient Boosted Classifier # + param_grid = { 'loss' : ['deviance', 'exponential'], 'learning_rate': [0.03, 0.01, 0.005, 0.001, 0.0005, 0.0001], 'n_estimators': [50, 100, 200, 400, 500, 800, 1500], 'subsample': [0.5, 0.6, 0.7, 0.8, 0.9, 1.0], 'min_samples_split': [5, 8, 12, 18, 25], 'min_samples_leaf': [3, 5, 7, 10, 15, 25], 'max_depth': [2, 4, 6, 8, 10, 15, 25], 'max_features': ['auto','log2', 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], 'tol': [0.0001, 0.001] } gbc = GradientBoostingClassifier(random_state=42) # gbc_search = GridSearchCV( # estimator = gbc, # param_grid = param_grid, # scoring='accuracy', # n_jobs=-1, # cv=4, # verbose=10, # return_train_score=True # ) gbc_search = RandomizedSearchCV(estimator=gbc, param_distributions=param_grid, n_iter=400, scoring='accuracy', n_jobs=-1, iid='warn', refit=True, cv=3, verbose=10, random_state=42, error_score='raise-deprecating', return_train_score=True) gbc_search.fit(X, y) gbc_search_results = pd.DataFrame(gbc_search.cv_results_).sort_values(by='rank_test_score') # - gbc_search_results.head() # %%time top10_gbc = get_top_n_models(gbc_search_results, 'gbc', k=20) top10_gbc # model = search.best_estimator_ model = top10_gbc.model.values[0] con_matrix_analysis(model, X, X_test, y, y_test) # + #get_accuracy_metrics(model, X, y, X_test, y_test) # - # ## Support Vector Machine # + #1 hot encode instead of label encode: # + # sum = 0 # for col in cat_cols: # sum += df[col].nunique() # print(col + ': ' + str(df[col].nunique())) # print(sum) # + # one_hot_cols = set(cat_cols) - set(['index', 'player_name', 'game_date', 'pitch_cat', 'pitcher', 'pitch_type', 'fastball_target']) # one_hot_df = pd.get_dummies(df, prefix_sep='_',columns=one_hot_cols) # train, test = train_test_split_by_date(one_hot_df, .9) # #target = 'pitch_cat' # target = 'fastball_target' # drop_cols = ['index', 'player_name', 'game_date', 'pitch_cat', 'pitcher', 'pitch_type', target] # X = train.drop(columns=drop_cols) # X_test = test.drop(columns=drop_cols) # y = train[target] # y_test = test[target] # X.shape, X_test.shape, y.shape, y_test.shape # + # #scale the float cols: # scale_cols = ['fastball_perc_faced', 'fastball_chase_perc', 'fastball_bip_swung_perc', 'fastball_taken_strike_perc', # 'fastball_est_woba', 'fastball_babip', 'fastball_iso_value', 'breaking_perc_faced', 'breaking_chase_perc', # 'breaking_bip_swung_perc', 'breaking_taken_strike_perc', 'breaking_est_woba', 'breaking_babip', # 'breaking_iso_value', 'offspeed_perc_faced', 'offspeed_chase_perc', 'offspeed_bip_swung_perc', # 'offspeed_taken_strike_perc', 'offspeed_est_woba', 'offspeed_babip', 'offspeed_iso_value', # 'pitchout_perc_faced', 'overall_fastball_perc', 'count_cat_fastball_perc', 'overall_breaking_perc', # 'count_cat_breaking_perc', 'overall_offspeed_perc', 'count_cat_offspeed_perc', 'L5_fastball_perc', # 'L15_fastball_perc', 'L5_breaking_perc', 'L15_breaking_perc', 'L5_offspeed_perc', 'L15_offspeed_perc', # 'L5_strike_perc', 'L15_strike_perc', 'PB_fastball', 'PB_breaking', 'PB_offspeed'] # scaler = RobustScaler() # X[scale_cols] = scaler.fit_transform(X[scale_cols].values) # X_test[scale_cols] = scaler.transform(X_test[scale_cols].values) # + # %%time from sklearn.svm import SVC param_grid = { 'degree': [2,3,4], 'kernel': ['linear', 'poly', 'rbf', 'sigmoid'], 'tol': [0.0001, 0.00001], 'C': [0.2, 0.5, 1.0, 2.0, 3.5, 5.0], 'shrinking': [True, False], 'class_weight': [None], 'max_iter': [100, 250, 400, 700, 1200, 2000, 3500], 'decision_function_shape': ['ovo', 'ovr'], 'gamma': ['auto', 'scale'] } svm = SVC(random_state=42, verbose=50) # svm_search = GridSearchCV( # estimator = svm, # param_grid=param_grid, # scoring='accuracy', # n_jobs=-1, # cv=3, # verbose=10, # return_train_score=True # ) svm_search = RandomizedSearchCV(estimator=svm, param_distributions=param_grid, n_iter=400, scoring='accuracy', n_jobs=-1, iid='warn', refit=True, cv=3, verbose=10, random_state=42, error_score='raise-deprecating', return_train_score=True) svm_search.fit(X, y) svm_search_results = pd.DataFrame(svm_search.cv_results_).sort_values(by='rank_test_score') # - svm_search_results.head() # %%time top10_svm = get_top_n_models(svm_search_results, 'svm', k=30) # model = search.best_estimator_ model = top10_svm.model.values[0] con_matrix_analysis(model, X, X_test, y, y_test) # ## Linear SVC # + # %%time from sklearn.svm import LinearSVC #L1 Regularization param_grid = { 'penalty': ['l1'], 'loss': ['squared_hinge'], 'dual': [False], 'tol': [0.0001, 0.00005, 0.00001], 'C': [0.2, 0.5, 1.0, 2.0, 3.5, 5.0], 'class_weight': [None],# 'balanced' 'max_iter': [50, 100, 250, 400, 700, 1200, 2000], 'fit_intercept': [True, False] } l1_LinSVC = LinearSVC(random_state=42, verbose=50) l1_LinSVC_search = GridSearchCV( estimator = l1_LinSVC, param_grid=param_grid, scoring='accuracy', n_jobs=-1, cv=4, verbose=10, return_train_score=True ) # l1_LinSVC_search = RandomizedSearchCV(estimator=svm, param_distributions=param_grid, n_iter=500, # scoring='accuracy', n_jobs=-1, iid='warn', refit=True, cv=4, verbose=10, # random_state=42, error_score='raise-deprecating', return_train_score=True) l1_LinSVC_search.fit(X, y) l1_LinSVC_search_results = pd.DataFrame(l1_LinSVC_search.cv_results_).sort_values(by='rank_test_score') # - l1_LinSVC_search_results.head() # %%time top10_l1_LinSVC = get_top_n_models(l1_LinSVC_search_results, 'lin_SVC', k=50) # model = search.best_estimator_ model = top10_l1_LinSVC.model.values[0] con_matrix_analysis(model, X, X_test, y, y_test) # + # %%time from sklearn.svm import LinearSVC #L2 Regularization #The combination of penalty='l2' and loss='hinge' are not supported when dual=False, Parameters: penalty='l2', loss='hinge', dual=False param_grid = { 'penalty': ['l2'],#, 'l1'], 'loss': ['squared_hinge'],# 'hinge'], 'dual': [True, False], 'tol': [0.0001, 0.00005, 0.00001], 'C': [0.2, 0.5, 1.0, 2.0, 3.5, 5.0], 'class_weight': [None], # 'balanced' 'max_iter': [50, 100, 250, 400, 700, 1200], 'fit_intercept': [True, False] } l2_LinSVC = LinearSVC(random_state=42, verbose=50) l2_LinSVC_search_A = GridSearchCV( estimator = l2_LinSVC, param_grid=param_grid, scoring='accuracy', n_jobs=-1, cv=4, verbose=10, return_train_score=True ) l2_LinSVC_search_A.fit(X, y) l2_LinSVC_search_results_A = pd.DataFrame(l2_LinSVC_search_A.cv_results_).sort_values(by='rank_test_score') param_grid = { 'penalty': ['l2'], 'loss': ['hinge'], 'dual': [True], 'tol': [0.0001, 0.00005, 0.00001], 'C': [0.2, 0.5, 1.0, 2.0, 3.5, 5.0], 'class_weight': [None], # 'balanced' 'max_iter': [50, 100, 250, 400, 700, 1200], 'fit_intercept': [True, False] } l2_LinSVC_search_B = GridSearchCV( estimator = l2_LinSVC, param_grid=param_grid, scoring='accuracy', n_jobs=-1, cv=4, verbose=10, return_train_score=True ) l2_LinSVC_search_B.fit(X, y) l2_LinSVC_search_results_B = pd.DataFrame(l2_LinSVC_search_B.cv_results_).sort_values(by='rank_test_score') l2_LinSVC_search_results = pd.concat([l2_LinSVC_search_results_A, l2_LinSVC_search_results_B]).sort_values(by='rank_test_score') # - l2_LinSVC_search_results.head() # %%time top10_l2_LinSVC = get_top_n_models(l2_LinSVC_search_results, 'lin_SVC', k=50) # model = search.best_estimator_ model = top10_l2_LinSVC.model.values[0] con_matrix_analysis(model, X, X_test, y, y_test) # + #get_accuracy_metrics(model, X, y, X_test, y_test) # - # ## SGDClassifier # + # %%time from sklearn.linear_model import SGDClassifier param_grid = { 'penalty': ['l2', 'elasticnet'], 'alpha': [0.0001, 0.001, 0.01, 0.02, .05, 0.1], 'loss': ['squared_hinge', 'hinge', 'perceptron'], 'tol': [0.0001, 0.00005, 0.00001], #'multi_class': ['ovr'], 'class_weight': [None], 'max_iter': [1000, 3000, 5000, 10000, 20000, 40000, 100000, 200000], 'fit_intercept': [True, False], 'warm_start': [True, False], 'learning_rate': ['optimal'], 'shuffle':[True, False] } sgd = SGDClassifier(random_state=42, verbose=50) # search = GridSearchCV( # estimator = sgd, # param_grid=param_grid, # scoring='accuracy', # n_jobs=-1, # cv=4, # verbose=10, # return_train_score=True # ) sgd_search = RandomizedSearchCV(estimator=sgd, param_distributions=param_grid, n_iter=500, scoring='accuracy', n_jobs=-1, iid='warn', refit=True, cv=3, verbose=10, random_state=42, error_score='raise-deprecating', return_train_score=True) sgd_search.fit(X, y) sgd_search_results = pd.DataFrame(sgd_search.cv_results_).sort_values(by='rank_test_score') # - sgd_search_results.head() # %%time top10_sgd = get_top_n_models(sgd_search_results, 'sgd', k=100, accuracy_metric='accuracy') top10_sgd # model = search.best_estimator_ model = top10_sgd.model.values[0] con_matrix_analysis(model, X, X_test, y, y_test) # ## LDA # + from sklearn.discriminant_analysis import LinearDiscriminantAnalysis param_grid = { 'solver': ['lsqr'],#, 'eigen'], 'shrinkage': [None, 'auto', 0.1, 0.5], 'tol': [0.0001, 0.00005, 0.00001], 'n_components':[None, 25, 50, 75, 100], #'store_covariance': [True, False] } lda = LinearDiscriminantAnalysis() lda_search = GridSearchCV( estimator = lda, param_grid=param_grid, scoring='accuracy', n_jobs=-1, cv=8, verbose=10, return_train_score=True ) lda_search.fit(X, y) lda_search_results = pd.DataFrame(lda_search.cv_results_).sort_values(by='rank_test_score') # - lda_search_results.head() # %%time top10_lda = get_top_n_models(lda_search_results, 'lda', k=50) top10_lda model = top10_lda.model.values[0] con_matrix_analysis(model, X, X_test, y, y_test) # ## Save the work # + #combine all the top10s into one df and save to pickle file best_models = pd.concat([top10_rfc_bootstrap, top10_rfc_without_bootstrap, top10_gbc, top10_svm, top10_l1_LinSVC, top10_l2_LinSVC, top10_sgd, top10_lda]) # - best_models.to_pickle(path=(pitcher+'_best_models_v1.pkl'),compression='zip') # + # test = pd.read_pickle(pitcher+'_best_models_v1.pkl', compression='zip') # test.sort_values(by='accuracy', ascending=False).head(20)
modelling_noteboooks/Binary_Model_Hypertuning.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Reuired Libraries for Data Science # - Numpy # - Pandas # - Matplotlib # - Seaborn # # ## Pandas # # - Pandas is a one library # - It is used for Data Manipulation,Data Cleaning,Visualization,ML Models # - It is main power full library for Models for Data Analysis # - In Pandas Data Structures are two ways or data can use in Two ways # - Series # - DataFrame # ## Series # - It is similar to Numpy 1-D Array # - It is declare with **Series** # # ## DataFrame # - It is similar to table format # - It is declare **DataFrame** # - The default data structure in pandas is DataFrame import pandas as pd series = pd.Series([10,20,30,40]) series series[2] series[3] atted = pd.Series([45, 78, 65, 30, 69], pd.date_range(start = '03-08-2021', end = '03-12-2021')) atted pd.Series(pd.date_range('03-10-2021','03-12-2021',freq='6H')) # DataFrame datafr = pd.DataFrame([['ajay','vijay','tarun'],[25,36,45]]) datafr df2 = pd.DataFrame([['ajay','vijay','tarun'],[25,36,45]], columns = ['ece','eee','cse']) df2 df3=pd.DataFrame({'std_name':['pavan','ranga','anil','ayyappa'], 'marks':[100,200,300,400], 'grade':['d','c','a','b']}, index=['s1','s2','s3','s4']) df3 df3['marks'] df3['grade'] df3['s1':'s2'] df3.loc['s1'] df3.iloc[1,2] data = pd.read_csv('data.csv') data data.shape data.info() data.describe() imd = pd.read_csv("http://bit.ly/imdbratings") imd imd.head() # head is used to display first 5 rows imd.head(2) imd.tail() # It display the last 5 rows imd.info() imd.describe() imd.shape imd.columns imd.values imd.values[100] imd['star_rating']>9.5 imd[imd['star_rating']>9.5] imd[imd['star_rating']>8.0] imd[imd['star_rating']>8.0].count() imd['genre'].unique() imd['genre']=='Comedy' imd[imd['genre']=='Comedy'].count() imd[(imd['star_rating']>7.5) & (imd['genre']=='Action')] imd[(imd['star_rating']>7.5) & (imd['genre']=='Action')].count() h = ['Serial_num','Age','Gender','Designation','Salary'] movies = pd.read_table("http://bit.ly/movieusers",sep='|', header=None,names=h) movies movies.head(2) movies.Designation.unique() movies.isna() movies.isna().count() movies[movies.isna()] movies['Gender'].isnull().count() df4 = pd.read_csv('data.csv') df4 df4.isna() df4.isnull() df4[df4['Roll_No'].isna()] df4[df4['Percentage'].isnull()] df4['Percentage'].fillna(0) df4 df4['Percentage']=df4['Percentage'].fillna(0) df4 df4.columns df4['Roll_No'] = df4['Roll_No'].fillna(125) df4
12-03-2021.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import json import pandas as pd import numpy as np import matplotlib.pyplot as plt benchmark_json = json.load(open("../output_data/benchmark_f_se.json", "r")) benchmark_df = pd.DataFrame(benchmark_json).applymap(lambda x: x[0]) benchmark_df.columns = ["Upravená procedura", "Původní procedura"] benchmark_df.index = [f"$f_{x}$" for x in range(1, 8)] benchmark_df.plot.bar(log=True) plt.xlabel("f kritérium") plt.ylabel("Čas odhadu") print(benchmark_df.applymap(lambda x: round(x, 2))["Původní procedura"].to_latex(escape=False)) print(benchmark_df.applymap(lambda x: round(x, 2)).to_latex(escape=False))
jupyter_notebooks/plot_f_standard_error.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # + import logging reload(logging) logging.basicConfig( format='%(asctime)-9s %(levelname)-8s: %(message)s', datefmt='%I:%M:%S') # Enable logging at INFO level logging.getLogger().setLevel(logging.INFO) # Comment the follwing line to disable devlib debugging statements # logging.getLogger('ssh').setLevel(logging.DEBUG) # + # Generate plots inline # %pylab inline import json import os # - # # Test environment setup # + # Setup a target configuration my_target_conf = { # Define the kind of target platform to use for the experiments "platform" : 'linux', # Linux system, valid other options are: # android - access via ADB # linux - access via SSH # host - direct access # Preload settings for a specific target "board" : 'juno', # load JUNO specific settings, e.g. # - HWMON based energy sampling # - Juno energy model # valid options are: # - juno - JUNO Development Board # - tc2 - TC2 Development Board # - oak - Mediatek MT63xx based target # Define devlib module to load #"modules" : [ # 'bl', # enable big.LITTLE support # 'cpufreq' # enable CPUFreq support #], # Account to access the remote target "host" : '192.168.0.1', "username" : 'root', "password" : '', # Comment the following line to force rt-app calibration on your target "rtapp-calib" : { '0': 361, '1': 138, '2': 138, '3': 352, '4': 360, '5': 353 } } # Setup the required Test Environment supports my_tests_conf = { # Binary tools required to run this experiment # These tools must be present in the tools/ folder for the architecture #"tools" : ['rt-app', 'taskset', 'trace-cmd'], # FTrace events end buffer configuration "ftrace" : { "events" : [ "sched_switch", "cpu_frequency" ], "buffsize" : 10240 }, } # + # Support to access the remote target import devlib from env import TestEnv # Initialize a test environment using: # the provided target configuration (my_target_conf) # the provided test configuration (my_test_conf) te = TestEnv(target_conf=my_target_conf, test_conf=my_tests_conf) target = te.target # - # # Workload configuration # + # Support to configure and run RTApp based workloads from wlgen import RTA, Periodic, Ramp # Create a new RTApp workload generator using the calibration values # reported by the TestEnv module rtapp = RTA(target, 'simple', calibration=te.calibration()) # Configure this RTApp instance to: rtapp.conf( # 1. generate a "profile based" set of tasks kind='profile', # 2. define the "profile" of each task params={ # 3. PERIODIC task with 'task_p20': Periodic( period_ms=100, # period duty_cycle_pct=20, # duty cycle duration_s=5, # duration cpus='0' # pinned on CPU0 ).get(), # 4. RAMP task (i.e. increasing load) with 'task_r20_5-60': Ramp( start_pct=5, # intial load end_pct=65, # end load delta_pct=20, # load % increase... time_s=1, # ... every 1[s] # pinned on last CPU of the target cpus=str(len(target.core_names)-1) ).get(), }, # 4. use this folder for task logfiles run_dir=target.working_directory ); # - # # Workload execution # + logging.info('#### Setup FTrace') te.ftrace.start() logging.info('#### Start energy sampling') te.emeter.reset() logging.info('#### Start RTApp execution') rtapp.run(out_dir=te.res_dir, cgroup="") logging.info('#### Read energy consumption: %s/energy.json', te.res_dir) nrg_report = te.emeter.report(out_dir=te.res_dir) logging.info('#### Stop FTrace') te.ftrace.stop() trace_file = os.path.join(te.res_dir, 'trace.dat') logging.info('#### Save FTrace: %s', trace_file) te.ftrace.get_trace(trace_file) logging.info('#### Save platform description: %s/platform.json', te.res_dir) (plt, plt_file) = te.platform_dump(te.res_dir) # - # # Collected results # All data are produced in the output folder defined by the TestEnv module logging.info('Content of the output folder %s', te.res_dir) # !ls -la {te.res_dir} # Inspect the JSON file used to run the application with open('{}/simple_00.json'.format(te.res_dir), 'r') as fh: rtapp_json = json.load(fh, ) logging.info('Generated RTApp JSON file:') print json.dumps(rtapp_json, indent=4, sort_keys=True) # Dump the energy measured for the LITTLE and big clusters logging.info('Energy: %s', nrg_report.report_file) print json.dumps(nrg_report.channels, indent=4, sort_keys=True) # Dump the platform descriptor, which could be useful for further analysis # of the generated results logging.info('Platform description: %s', plt_file) print json.dumps(plt, indent=4, sort_keys=True) # # Trace inspection # + # Suport for FTrace events parsing and visualization import trappy # NOTE: The interactive trace visualization is available only if you run # the workload to generate a new trace-file trappy.plotter.plot_trace(te.res_dir) # - # # RTApp task performance plots # + # Support for performance analysis of RTApp workloads from perf_analysis import PerfAnalysis # Parse the RT-App generate log files to compute performance metrics pa = PerfAnalysis(te.res_dir) # For each task which has generated a logfile, plot its performance metrics for task in pa.tasks(): pa.plotPerf(task, "Performance plots for task [{}] ".format(task))
ipynb/wlgen/simple_rtapp.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # %matplotlib inline import numpy as np import matplotlib.pyplot as plt from os.path import expanduser import LSSToy2 # my toy LSST cadence model from appaloosa.aflare import aflare1 # my flare template # # Import Flare Data # This is from my previous *Kepler* study of the active M4 dwarf, GJ 1243 # Get the GJ 1243 flare data home = expanduser("~") flaredir = home + '/research/GJ1243-Flares/data/' lc = np.loadtxt(flaredir + 'gj1243_master_slc.dat', comments='#') fl = np.loadtxt(flaredir + 'gj1243_master_flares.tbl', comments='#') lc.shape # Columns (time, flux, error, detrended_flux) plt.plot(lc[:,0], lc[:,3]) plt.xlim(910,912) plt.ylim(265000, 285000) plt.xlabel('Time (days)') plt.ylabel('Flattened Flux') fl.shape # ----- Columns: ----- # index of flare start in "gj1243_master_slc.dat" # index of flare stop in "gj1243_master_slc.dat" # t_start # t_stop # t_peak # t_rise # t_decay # flux peak (in fractional flux units) # Equivalent Duration (ED) in units of per seconds # Equiv. Duration of rise (t_start to t_peak) # Equiv. Duration of decay (t_peak to t_stop) # Complex flag (1=classical, 2=complex) by humans # Number of people that identified flare event exists # Number of people that analyzed this month # Number of flare template components fit to event (1=classical >1=complex) # # Explore range of re-visit timescale # + # the start of the GJ 1243 light curve mintime = lc[:,0].min() dt_min = 2./60. # 5 minutes dt_max = 4. Nvisits = 500 Ntrials = 50 dt_range = np.logspace(np.log10(dt_min), np.log10(dt_max), num=Ntrials) # - # one example of what we simulate each time epoch = LSSToy2.generate_visits(Nvisits=Nvisits, tspan=2., stat=True, revisit=1., t0=mintime) # + e_rec_final = np.zeros_like(dt_range) e_err_final = np.zeros_like(dt_range) for k in range(Ntrials): epoch = LSSToy2.generate_visits(Nvisits=Nvisits, tspan=2., revisit=dt_range[k], t0=mintime) # down-sample the GJ 1243 light curve to the new epochs fdown = np.interp(epoch, lc[:,0], lc[:,3] / np.median(lc[:,3]) - 1.) e_rec = np.array([]) # scan thru every epoch, see if any known flares are intersected for j in range(0, len(epoch), 2): is_fl = np.where(((epoch[j] >= fl[:,2]) & (epoch[j] <= fl[:,3])) | ((epoch[j+1] >= fl[:,2]) & (epoch[j+1] <= fl[:,3]))) # if there IS a flare, grab the nearest epoch if len(is_fl[0]) > 0: tt = epoch[j:j+2] ff = fdown[j:j+2] e_true = fl[is_fl[0], 8] # equiv duration (in seconds) e_fit = np.trapz(ff, x=(tt-tt.min()*86400.)) e_rec = np.concatenate((e_rec, e_fit/e_true)) e_rec_final[k] = np.median(e_rec) e_err_final[k] = np.std(e_rec) # - plt.plot(dt_range*24., e_rec_final) plt.xscale('log') # Hm.... no good. Flare energies are not right at all
flare-figures.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Doc2Vec # + import sys, os, string, glob, gensim import pandas as pd import numpy as np from nltk.tokenize import word_tokenize, sent_tokenize import gensim.models.doc2vec assert gensim.models.doc2vec.FAST_VERSION > -1 # This will be painfully slow otherwise from gensim.models.doc2vec import Doc2Vec, TaggedDocument from gensim.utils import simple_preprocess # Import parser module. module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path + '//Scripts') from functions_xml_ET_parse import * # Declare absolute path. abs_dir = "/Users/quinn.wi/Documents/" # Define tokenizer. def fast_tokenize(text): # Get a list of punctuation marks punct = string.punctuation + '“' + '”' + '‘' + "’" lower_case = text.lower() lower_case = lower_case.replace('—', ' ').replace('\n', ' ') # Iterate through text removing punctuation characters no_punct = "".join([char for char in lower_case if char not in punct]) # Split text over whitespace into list of words tokens = no_punct.split() return tokens # - # ## Build Dataframe from XML # + # %%time """ Declare variables. """ # Declare regex to simplify file paths below regex = re.compile(r'.*/.*/(.*.xml)') # Declare document level of file. Requires root starting point ('.'). doc_as_xpath = './/ns:div/[@type="entry"]' # Declare date element of each document. date_path = './ns:bibl/ns:date/[@when]' # Declare person elements in each document. person_path = './/ns:p/ns:persRef/[@ref]' # Declare subject elements in each document. subject_path = './/ns:bibl//ns:subject' # Declare text level within each document. text_path = './ns:div/[@type="docbody"]/ns:p' """ Build dataframe. """ dataframe = [] for file in glob.glob(abs_dir + 'Data/PSC/JQA/*/*.xml'): reFile = str(regex.search(file).group(1)) # Call functions to create necessary variables and grab content. root = get_root(file) ns = get_namespace(root) for eachDoc in root.findall(doc_as_xpath, ns): # Call functions. entry = get_document_id(eachDoc, '{http://www.w3.org/XML/1998/namespace}id') date = get_date_from_attrValue(eachDoc, date_path, 'when', ns) people = get_peopleList_from_attrValue(eachDoc, person_path, 'ref', ns) subject = get_subject(eachDoc, subject_path, ns) text = get_textContent(eachDoc, text_path, ns) dataframe.append([reFile, entry, date, people, subject, text]) dataframe = pd.DataFrame(dataframe, columns = ['file', 'entry', 'date', 'people', 'subject', 'text']) # Split subject list and return "Multiple-Subject" or lone subject. dataframe['subject'] = dataframe['subject'].str.split(r',') def handle_subjects(subj_list): if len(subj_list) > 1: return 'Multiple-Subjects' else: return subj_list[0] dataframe['subject'] = dataframe['subject'].apply(handle_subjects) dataframe.head(4) # - # ## Build doc2vec Model # + # %%time # Create corpus. tagged_docs = dataframe \ .apply(lambda x: TaggedDocument(simple_preprocess(x.text), [f'{x.entry}'] # ['doc{}',format(x.entry)] ), axis = 1) training_corpus = tagged_docs.values # Training model = Doc2Vec(vector_size = 200, min_count = 4, epochs = 10) model.build_vocab(training_corpus) model.train(training_corpus, total_examples = model.corpus_count, epochs = model.epochs) # Store model. model.save(abs_dir + 'Data/Output/WordVectors/jqa-d2v.txt') # -
Jupyter_Notebooks/WordVectors/d2v_Build-Model.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # It's also possible to have a look around in the bedroom. The sample code contains an elif part that checks if room equals "bed". In that case, "looking around in the bedroom." is printed out. # # It's up to you now! Make a similar addition to the second control structure to further customize the messages for different values of area. # Define variables room = "bed" area = 14.0 # if-elif-else construct for room if room == "kit" : print("looking around in the kitchen.") elif room == "bed": print("looking around in the bedroom.") else : print("looking around elsewhere.") # ### Add an elif to the second control structure such that "medium size, nice!" is printed out if area is greater than 10. # + # if-elif-else construct for area if area > 15 : print("big place!") elif area > 10: print("medium size, nice!") else : print("pretty small.") # -
Intermediate Python for Data Science/Logic- Control Flow and Filtering/10-Customize further elif.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Model under development # # # WARNING # For plotly map rendering you must launch jupyter notebooks with a higher data limit: # <br> `jupyter notebook --NotebookApp.iopub_data_rate_limit=214748364` # # # TODO # - how to deal with missingness # # # %load_ext autoreload # %autoreload 2 import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from src.data.download_DHS import load_DHS_data df = load_DHS_data() df.shape df.head() df_wide = df.pivot(index='SurveyId', columns='IndicatorId', values='Value') df_wide.head() indicator_miss = df_wide.isna().mean().sort_values(ascending=False) indicator_miss.head() plt.plot(indicator_miss) survey_miss = df_wide.isna().mean(axis=1).sort_values(ascending=False) survey_miss.head() plt.plot(survey_miss) # # Subset to latest country survey df.head() latest_surveys = df.sort_values(['CountryName','SurveyYear'], ascending=False).drop_duplicates('CountryName')['SurveyId'] # df.sort_values(['CountryName', 'SurveyYear'], a).drop_duplicates() latest_surveys.head() df_latest = pd.merge(df, pd.DataFrame(latest_surveys)) print(len(df), len(df_latest)) df.sort_values(['CountryName', 'SurveyYear', 'IndicatorId']).head() df_wide = df_latest.pivot(index='SurveyId', columns='IndicatorId', values='Value') indicator_miss = df_wide.isna().mean().sort_values(ascending=False) indicator_miss.head() plt.plot(indicator_miss) survey_miss = df_wide.isna().mean(axis=1).sort_values(ascending=False) survey_miss.head() plt.plot(survey_miss) from sklearn.decomposition import PCA from sklearn.impute import SimpleImputer imputer = SimpleImputer() n_components = 10 pca = PCA(n_components=n_components) df_transformed = pd.DataFrame(imputer.fit_transform(df_wide), columns=df_wide.columns, index=df_wide.index) cols = [f'component_{i}' for i in range(0, n_components)] df_components = pd.DataFrame(pca.fit_transform(df_transformed), columns=cols, index=df_wide.index) df_components.head() df_all = pd.concat([df_components, df_transformed], axis=1) df_all.head() from src.data.download_DHS import IND_OTHER, IND_CHILD_RISKS inds = IND_CHILD_RISKS corr = df_all[cols + inds].corr() plt.figure(figsize=[12,10]) g = sns.heatmap(corr,annot=False, fmt = ".2f", cmap = "coolwarm", center=0) corr.head() from src.data.download_DHS import INDICATORS inds = [i for i in INDICATORS if i in df_all.columns] corr = df_all[cols + inds].corr().drop(cols, axis=0).drop(inds, axis=1) plt.figure(figsize=[10,20]) g = sns.heatmap(corr,annot=False, fmt = ".2f", cmap = "coolwarm", center=0) df_components.head() from sklearn.cluster import KMeans kmean = KMeans(n_clusters=8) kmean.fit(df_components) df_all['cluster'] = kmean.labels_ df_transformed['cluster'] = kmean.labels_ # pd.Series(kmean.labels_, dtype='str') # df_transformed['cluster'] = df_transformed['cluster'].astype(str) df_transformed.cluster.value_counts() df_transformed[['cluster']].head() sns.scatterplot('CN_NUTS_C_WH3', 'FE_FRTR_W_GFR', hue='cluster', data=df_transformed) sns.scatterplot('component_0', 'component_1', hue='cluster', data=df_all) sns.catplot("cluster", y="FE_FRTR_W_GFR", data=df_all) sns.catplot("cluster", y="component_0", data=df_all) sns.scatterplot('component_0', 'FE_FRTR_W_GFR', hue='cluster', data=df_all) inds = [i for i in INDICATORS if i in df_all.columns] data = df_all.groupby('cluster')[inds].mean().T data.head() # plt.figure(figsize=[10,20]) # g = sns.heatmap(data,annot=False, fmt = ".2f", cmap = "coolwarm", center=0) from sklearn.preprocessing import StandardScaler, MinMaxScaler scaler = MinMaxScaler() # StandardScaler() data = pd.DataFrame(scaler.fit_transform(df_all.drop('cluster', axis=1)), columns=df_all.drop('cluster', axis=1).columns, index=df_all.index) data['cluster'] = df_all['cluster'] data.head() data = data.groupby('cluster')[inds].mean().T data.head() # + # StandardScaler? # - plt.figure(figsize=[10,20]) g = sns.heatmap(data,annot=False, fmt = ".2f", cmap = "coolwarm", center=0.5) # # Map clusters from src.data.download_DHS import load_country_codebook codebook = load_country_codebook() dhs_country_codebook = pd.merge(codebook[['CountryName', 'ISO3_CountryCode']], df.drop_duplicates('SurveyId')[['SurveyId', 'CountryName']]) dhs_country_codebook.head() df_clusters = pd.merge(dhs_country_codebook, df_transformed.reset_index()) df_clusters.head() import plotly.plotly as py import plotly.graph_objs as go from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot # Connect Javascript to display the plots in the notebook init_notebook_mode(connected=True) # + # # Standard plotly imports # import plotly.plotly as py # import plotly.graph_objs as go # from plotly.offline import iplot # # Using cufflinks in offline mode # import cufflinks # cufflinks.go_offline() # - scale = [[0, 'rgb(166,206,227)'], [1, 'rgb(31,120,180)'], [2, 'rgb(178,223,138)'], [3, 'rgb(51,160,44)'], [4, 'rgb(251,154,153)'], [5, 'rgb(251,154,153)'], [6, 'rgb(251,154,153)'], [7, 'rgb(227,26,28)']] data = [dict(type='choropleth', locations=df_clusters['ISO3_CountryCode'], z = df_clusters['cluster'], text=df_clusters['CountryName'], colorscale='Blackbody', #scale, Rainbow autocolorscale = False, colorbar = {'title': 'Indicator'} )] layout = dict(title='My Title', geo=dict(showframe=False, projection={'type':'natural earth'})) fig = dict(data=data, layout=layout) iplot(fig)
notebooks/_archive/2019_01_25_first_clustering_model.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: DESI master # language: python # name: desi-master # --- import os import numpy as np from astropy.table import Table, vstack from desiutil.log import get_logger log = get_logger() # + #import tempfile #os.environ['MPLCONFIGDIR'] = tempfile.mkdtemp() import matplotlib.pyplot as plt import matplotlib.ticker as ticker import seaborn as sns sns.set(context='talk', style='ticks', font_scale=1.3)#, rc=rc) # %matplotlib inline # - # %env DESI_ROOT=/global/cfs/cdirs/desi # %env NYXGALAXY_DATA=/global/cfs/cdirs/desi/users/ioannis/nyxgalaxy nyxgalaxy_dir = os.getenv('NYXGALAXY_DATA') analysisdir = os.path.join(nyxgalaxy_dir, 'analysis') if not os.path.isdir(analysisdir): os.makedirs(analysisdir) def read_results(tilenight): nyxgalaxyfile = os.path.join(nyxgalaxy_dir, 'results', 'nyxgalaxy-{}.fits'.format(tilenight)) if not os.path.isfile(nyxgalaxyfile): log.info('Output file {} not found!'.format(nyxgalaxyfile)) return nyxgalaxy = Table.read(nyxgalaxyfile) return nyxgalaxy # + #'70500-20200303' tiletarg = { '67230-20200315': 'ELG', '67142-20200315': 'ELG', '68001-20200315': 'LRG', '68002-20200315': 'LRG', '66003-20200315': 'BGS', } res = [] for tilenight in tiletarg.keys(): res.append(read_results(tilenight=tilenight)) res = vstack(res) res = res[res['CONTINUUM_CHI2'] > 0] ngal = len(res) print(ngal) # - def zhist(): tilenight = np.array(['{}-{}'.format(tile, night) for tile, night in zip(res['TILE'], res['NIGHT'])]) indx = {'ELG': np.array([], np.int), 'BGS': np.array([], np.int), 'LRG': np.array([], np.int)} for tile in set(tilenight): targ = tiletarg[tile] these = np.where(tile == tilenight)[0] indx[targ] = np.hstack((indx[targ], these)) fig, ax = plt.subplots(figsize=(10, 7)) for targ in sorted(indx.keys()): these = indx[targ] print(targ, len(these)) _ = ax.hist(res['Z'][these], label='{} (N={})'.format(targ, len(these)), range=(-0.05, 1.7), bins=100, alpha=0.7) ax.xaxis.set_major_locator(ticker.MultipleLocator(0.5)) ax.yaxis.set_major_locator(ticker.MultipleLocator(50)) ax.legend(fontsize=18) ax.set_xlabel('Redshift') ax.set_ylabel('Number of Galaxies') pngfile = os.path.join(analysisdir, 'zhist.png') print('Writing {}'.format(pngfile)) fig.savefig(pngfile) zhist() fig, ax = plt.subplots(figsize=(10, 6)) ax.scatter(res['CONTINUUM_SNR'][:, 2], res['CONTINUUM_VDISP']) #ax.set_xscale('log') ax.set_xlim(0, 10) # + def oplot_class(ax, kewley=False, **kwargs): if kewley: niiha = np.linspace(-1.9, 0.4, 1000) oiiihb = 0.61 / (niiha-0.47) + 1.19 else: niiha = np.linspace(-1.9, -0.1, 1000) oiiihb = 0.61 / (niiha-0.05) + 1.3 ax.plot(niiha, oiiihb, **kwargs) def bpt(): good = np.where( (res['HALPHA_FLUX'] > 0) * (res['HBETA_FLUX'] > 0) * (res['NII_6584_FLUX'] > 0) * (res['OIII_5007_FLUX'] > 0) * (res['HALPHA_CHI2'] < 1e4) )[0] zz = res['Z'][good] niiha = np.log10(res['NII_6584_FLUX'][good] / res['HALPHA_FLUX'][good]) oiiihb = np.log10(res['OIII_5007_FLUX'][good] / res['HBETA_FLUX'][good]) ww = np.where((niiha > -0.05) * (niiha < 0.05) * (oiiihb < -0.5))[0] #print(res[good][ww]['HALPHA_FLUX', 'NII_6584_FLUX']) fig, ax = plt.subplots(figsize=(10, 7)) #for tile in set(res['TILE'][good]): # ax.scatter(niiha, oiiihb, label='{}'.format(tile), alpha=0.8, s=20) cb = ax.scatter(niiha, oiiihb, c=zz, cmap='viridis', vmin=0.0, vmax=0.5) oplot_class(ax, kewley=True, color='red', ls='--', lw=3, label='Kewley+01') oplot_class(ax, kewley=False, color='k', lw=3, label='Kauffmann+03') plt.colorbar(cb, label='Redshift') ax.set_xlim(-1.9, 0.7) ax.set_ylim(-1.2, 1.5) ax.set_xlabel(r'$\log_{10}$ ([NII] $\lambda6584$ / H$\alpha$)') ax.set_ylabel(r'$\log_{10}$ ([OIII] $\lambda5007$ / H$\beta$)') ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%.1f')) ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.1f')) ax.xaxis.set_major_locator(ticker.MultipleLocator(0.5)) ax.yaxis.set_major_locator(ticker.MultipleLocator(0.5)) ax.legend(fontsize=16, loc='lower left')#, ncol=2) plt.subplots_adjust(bottom=0.15, left=0.18, top=0.95, right=0.95) fig.savefig(os.path.join(analysisdir, 'bpt.png')) # - bpt() def d4000_ewhb(): good = np.where((res['D4000_IVAR'] > 0) * (res['HBETA_EW'] > 0))[0] d4000 = res['D4000_MODEL'][good].data ewhb = np.log10(res['HBETA_EW'][good].data) fig, ax = plt.subplots(figsize=(10, 8)) ax.scatter(d4000, ewhb, s=30) ax.set_xlim(0.75, 2.0) ax.set_ylim(-2, 3.5) ax.xaxis.set_major_locator(ticker.MultipleLocator(0.5)) ax.set_xlabel(r'$D_{n}(4000)$') ax.set_ylabel(r'$\log_{10}$ EW(H$\beta)$') #ax.legend(fontsize=18, loc='upper left') plt.subplots_adjust(bottom=0.15, left=0.18, top=0.95, right=0.95) fig.savefig(os.path.join(analysisdir, 'bpt.png')) d4000_ewhb() res.info() _ = plt.hist(res['LINEVSHIFT_BALMER'], bins=100)
2020/20201211-desidata-nyxgalaxy/nyxgalaxy.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.10.0 64-bit # language: python # name: python3 # --- # + import random import string import os with open(os.path.join(os.path.expanduser('~'), 'Desktop', 'duden.txt')) as f: words = f.read().splitlines() word_list = words #given following string anagram_scramble = 'Seife' def find_anagrams(anagram_scramble): anagram_list = [] for word in word_list: if sorted(anagram_scramble.lower()) == sorted(word.lower()): anagram_list.append(word) return anagram_list find_anagrams(anagram_scramble) # -
anagram_solver_german.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/humanpose1/MS-SVConv/blob/main/notebook/demo_MSSVConv.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="slKL_LEw6P3c" # # Demo of MS SVConv for point cloud registration # # The goal of this notebook is to quickly show how you can use MS-SVConv on your projects. # # # # # # + [markdown] id="fv1Ca0XF6pHz" # ## Installation # First we install necessary packages # + colab={"base_uri": "https://localhost:8080/"} id="vbPbVET4Bv15" outputId="ee214cd5-05ab-40e1-8aa5-434e38dbddd5" # !pip install torch==1.8.1 # !pip uninstall -y torch-scatter # !pip uninstall -y torch-sparse # !pip uninstall -y torch-cluster # !pip install torch-scatter -f https://data.pyg.org/whl/torch-1.8.1+cu102.html # !pip install torch-sparse -f https://data.pyg.org/whl/torch-1.8.1+cu102.html # !pip install torch-cluster -f https://data.pyg.org/whl/torch-1.8.1+cu102.html # !pip install torch-spline-conv -f https://data.pyg.org/whl/torch-1.8.1+cu102.html # !pip install torch-geometric # !pip install pyvista # !pip install --upgrade jsonschema # !pip install git+https://github.com/nicolas-chaulet/torch-points3d.git@e090530eab5e3e5798c5abc764088d6a1f9827c3 # !apt-get update # !apt-get install -qq xvfb libgl1-mesa-glx # + id="7U_MRvqiBg__" colab={"base_uri": "https://localhost:8080/"} outputId="f950d8e5-6779-4f51-bbbd-b8b2f50b9c5e" # !pip install pyvistaqt # !apt-get install build-essential python3-dev libopenblas-dev # !pip install -U git+https://github.com/NVIDIA/MinkowskiEngine@9f81ae66b33b883cd08ee4f64d08cf633608b118 --no-deps # + [markdown] id="0upTEPRr_ofL" # We also install torchsparse # + [markdown] id="x1Bc0Ait_oc1" # # + id="_fSreyeXWU1E" colab={"base_uri": "https://localhost:8080/"} outputId="65661791-165b-4733-cf27-cc263b3fbe25" # !apt-get install libsparsehash-dev # !pip install --upgrade git+https://github.com/mit-han-lab/torchsparse.git@v1.4.0 # + [markdown] id="l0q4WUP1_xL2" # ## Registration # # We will use pyvista for the visualization. But it is not interactive... # + id="NPVXHmzQMu_R" colab={"base_uri": "https://localhost:8080/", "height": 419} outputId="0fe47648-022d-4aa6-da85-c628ae498dda" import numpy as np import open3d as o3d import os import os.path as osp import pathlib import requests import torch from torch_points3d.applications.pretrained_api import PretainedRegistry from torch_points3d.core.data_transform import GridSampling3D, AddFeatByKey, AddOnes, Random3AxisRotation from torch_points3d.datasets.registration.pair import Pair from torch_points3d.utils.registration import get_matches, fast_global_registration from torch_geometric.data import Data from torch_geometric.transforms import Compose from torch_points3d.metrics.registration_metrics import compute_hit_ratio from zipfile import ZipFile import pyvista as pv import panel as pn pn.extension('vtk') os.system('/usr/bin/Xvfb :99 -screen 0 1024x768x24 &') os.environ['DISPLAY'] = ':99' os.environ['PYVISTA_OFF_SCREEN'] = 'True' os.environ['PYVISTA_USE_PANEL'] = 'True' # + [markdown] id="AET-aTq2_-7-" # We need to download the datasets, and the models # + id="aFs0aBZDWUwv" MODEL = {"MS_SVCONV_2cm_X2_3head_3dm.pt": "https://cloud.mines-paristech.fr/index.php/s/hRc6y2YIFtYsGAI/download", "MS_SVCONV_4cm_X2_3head_eth.pt": "https://cloud.mines-paristech.fr/index.php/s/pUmGPtHUG2ASxlJ/download"} DATA = {"gazebo_winter_12.pcd": "https://cloud.mines-paristech.fr/index.php/s/zgO88hYFeogTj2s/download", "gazebo_winter_11.pcd": "https://cloud.mines-paristech.fr/index.php/s/NpsabVL7bz5qFEe/download", "kitchen_0.ply": "https://cloud.mines-paristech.fr/index.php/s/lArxiaV0DPo4bBU/download", "kitchen_10.ply": "https://cloud.mines-paristech.fr/index.php/s/357BXcA2qcrw2Uy/download"} def download(url, out, name): """ download a file and extract the zip file """ req = requests.get(url) pathlib.Path(out).mkdir(exist_ok=True) with open(osp.join(out, name), "wb") as archive: archive.write(req.content) def extract(out, name): with ZipFile(osp.join(out, name+".zip"), "r") as zip_obj: zip_obj.extractall(osp.join(out, name)) # Download Models and data for the demo download(MODEL["MS_SVCONV_2cm_X2_3head_3dm.pt"], "models", "MS_SVCONV_2cm_X2_3head_3dm.pt") download(MODEL["MS_SVCONV_4cm_X2_3head_eth.pt"], "models", "MS_SVCONV_4cm_X2_3head_eth.pt") download(DATA["gazebo_winter_12.pcd"], "data", "gazebo_winter_12.pcd") download(DATA["gazebo_winter_11.pcd"], "data", "gazebo_winter_11.pcd") download(DATA["kitchen_0.ply"], "data", "kitchen_0.ply") download(DATA["kitchen_10.ply"], "data", "kitchen_10.ply") # + id="GNxw7wNb8Edi" def read_pcd(path): pcd = o3d.io.read_point_cloud(path) data = Pair(pos=torch.from_numpy(np.asarray(pcd.points)).float(), batch=torch.zeros(len(pcd.points)).long()) return data # + [markdown] id="2rpBdgsBAHuN" # modify the variable `choice_data` and `choice_model` if you want to change the dataset and the model. # For the transformation, we perform random rotation beforehand just to show that MS-SVConv is rotation invariant. # + id="1r4jSZWiungd" #@title Data and Model #@markdown Please choose the data and the model you want choice_data = "3dm" #@param ['eth', '3dm'] choice_model = "3dm" #@param ['eth', '3dm'] # + id="egHArbbq6ISY" # DATA pcd_path = { "eth": ["data/gazebo_winter_12.pcd", "data/gazebo_winter_11.pcd"], "3dm": ["data/kitchen_0.ply", "data/kitchen_10.ply"] } # Model pcd_model = { "eth": "models/MS_SVCONV_4cm_X2_3head_eth.pt", "3dm": "models/MS_SVCONV_2cm_X2_3head_3dm.pt" } # Data augmentation transfo_3dm = Compose([Random3AxisRotation(rot_x=180, rot_y=180, rot_z=180), GridSampling3D(size=0.02, quantize_coords=True, mode='last'), AddOnes(), AddFeatByKey(add_to_x=True, feat_name="ones")]) transfo_eth = Compose([Random3AxisRotation(rot_x=180, rot_y=180, rot_z=180), GridSampling3D(size=0.04, quantize_coords=True, mode='last'), AddOnes(), AddFeatByKey(add_to_x=True, feat_name="ones")]) pcd_DA = { "eth": transfo_eth, "3dm": transfo_3dm } model = PretainedRegistry.from_file(pcd_model[choice_model], mock_property={}) data_s = pcd_DA[choice_model](read_pcd(pcd_path[choice_data][0])) data_t = pcd_DA[choice_model](read_pcd(pcd_path[choice_data][1])) #pl1 = pvqt.BackgroundPlotter() pl1 = pv.Plotter(notebook=True) pl1.add_points(data_s.pos.numpy(),color=[0.9, 0.7, 0.1]) pl1.add_points(data_t.pos.numpy(),color=[0.1, 0.7, 0.9]) pl1.enable_eye_dome_lighting() pl1.show() # + id="hbeevGTAU52_" def ransac(pos_s, pos_t, feat_s, feat_t, distance_threshold=0.1): pcd_s = o3d.geometry.PointCloud() pcd_s.points = o3d.utility.Vector3dVector(pos_s.numpy()) pcd_t = o3d.geometry.PointCloud() pcd_t.points = o3d.utility.Vector3dVector(pos_t.numpy()) f_s = o3d.pipelines.registration.Feature() f_s.data = feat_s.T.numpy() f_t = o3d.pipelines.registration.Feature() f_t.data = feat_t.T.numpy() result = o3d.pipelines.registration.registration_ransac_based_on_feature_matching( source=pcd_s, target=pcd_t, source_feature=f_s, target_feature=f_t, mutual_filter=True, max_correspondence_distance=distance_threshold, estimation_method=o3d.pipelines.registration.TransformationEstimationPointToPoint(False), ransac_n=4, checkers=[o3d.pipelines.registration.CorrespondenceCheckerBasedOnEdgeLength(0.9), o3d.pipelines.registration.CorrespondenceCheckerBasedOnDistance(distance_threshold)], criteria=o3d.pipelines.registration.RANSACConvergenceCriteria(4000000, 500)) return torch.from_numpy(result.transformation).float() # + [markdown] id="mo8dbgNFApNv" # To registrate, we use RANSAC of Open3D, but it's possible to use an other estimator (such as Fast Global Registration or TEASER) # + id="xZddsisSVtKr" # Let us registrate !! # Compute the matches with torch.no_grad(): model.set_input(data_s, "cuda") feat_s = model.forward() model.set_input(data_t, "cuda") feat_t = model.forward() # select random points and compute transformation using FGR rand_s = torch.randint(0, len(feat_s), (5000, )) rand_t = torch.randint(0, len(feat_t), (5000, )) # matches = get_matches(feat_s[rand_s], feat_t[rand_t], sym=True) T_est = ransac(data_s.pos[rand_s], data_t.pos[rand_t], feat_s[rand_s], feat_t[rand_t]) print(T_est) # + id="5dGG8AbpCzW6" pl2 = pv.Plotter(notebook=True) transformed = data_s.pos @ T_est[:3, :3].T + T_est[:3, 3] pl2.add_points(np.asarray(transformed.cpu().numpy()),color=[0.9, 0.7, 0.1]) pl2.add_points(np.asarray(data_t.pos.cpu().numpy()),color=[0.1, 0.7, 0.9]) pl2.enable_eye_dome_lighting() pl2.show() # + [markdown] id="Rd5Yv9K-A__Y" # That's it ! Now, you know how to use MS-SVConv ! Don't hesitate using it in your projects. And if you like it, please cite our work : # ``` # @inproceedings{horache2021mssvconv, # title={3D Point Cloud Registration with Multi-Scale Architecture and Unsupervised Transfer Learning}, # author={<NAME> and <NAME> and <NAME>}, # year={2021}, # journal={arXiv preprint arXiv:2103.14533} # } # ``` # + id="YhVqaY5Mh_A2"
notebook/demo_MSSVConv.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import torch import torchvision.models as models vgg = models.vgg16(pretrained=True) # This may take a few minutes. print(vgg.features[0]) # .modules # + ConvTranspose2d_DEFAULT_KERNEL_DIM_SIZE = 5 ConvTranspose2d_DEFAULT_MAX_STRIDE = 4 ConvTranspose2d_DEFAULT_MAX_DILATION = 4 ConvTranspose2d_DEFAULT_MAX_INP_PADDING = 4 ConvTranspose2d_DEFAULT_MAX_OUT_PADDING = 4 def calc_parameters(lay): total = 0 for tensor in lay.parameters(): curr = 1 for el in tensor.shape: curr *= el total += curr return total def choose_parameters_in_ConvTranspose2d_space(input_shape, output_shape, kernel_dims=None, symmetric=True): batch_size, cin, hin, win = input_shape batch_size, cout, hout, wout = output_shape if kernel_dims is None: kernel_dims = range(1, 1 + ConvTranspose2d_DEFAULT_KERNEL_DIM_SIZE) input_ex = torch.randn((1, cin, hin, win)) strides = range(1, ConvTranspose2d_DEFAULT_MAX_STRIDE + 1) dilations = range(1, 1 + ConvTranspose2d_DEFAULT_MAX_DILATION) inp_pads = range(0, ConvTranspose2d_DEFAULT_MAX_INP_PADDING + 1) out_pads = range(0, ConvTranspose2d_DEFAULT_MAX_OUT_PADDING + 1) configurations = [] for stride1 in strides: for stride2 in strides: if stride1 != stride2 and symmetric: continue for dil1 in dilations: for dil2 in dilations: if dil1 != dil2 and symmetric: continue for kdim1 in kernel_dims: for kdim2 in kernel_dims: if kdim1 != kdim2 and symmetric: continue for ipad1 in inp_pads: for ipad2 in inp_pads: if ipad1 != ipad2 and symmetric: continue for opad1 in out_pads: for opad2 in out_pads: if opad1 != opad2 and symmetric: continue params = { 'in_channels': cin, 'out_channels': cout, 'kernel_size': (kdim1, kdim2), 'stride': (stride1, stride2), 'dilation': (dil1, dil2), 'padding': (ipad1, ipad2), 'output_padding': (opad1, opad2)} try: lay = torch.nn.ConvTranspose2d(**params) if lay(input_ex).shape != (1, cout, hout, wout): continue except Exception as exp: continue configurations.append((calc_parameters(lay), params)) configurations.sort(key=lambda x: x[0]) return [el[1] for el in configurations] # - def choose_parameters_in_Linear_space(input_shape, output_shape): return [{'in_features': input_shape[-1], 'out_features': output_shape[-1]}] input = torch.randn(1, 3, 32, 32) conv = torch.nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) output = conv(input) for el in choose_parameters_in_ConvTranspose2d_space(output.shape, input.shape): print(el)
RevLib.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # TensorFlow Eager Execution # + from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import tensorflow.contrib.eager as tfe tf.enable_eager_execution() print("TensorFlow version: {}".format(tf.VERSION)) print("Eager execution: {}".format(tf.executing_eagerly())) # - # ## Execution Style # # * [Eager execution](https://www.tensorflow.org/get_started/eager) # * 최근에 나온 방식 # * 변수값을 바로 확인할 수 있음 # * 마치 `numpy` 짜듯이 짤 수 있음 # * [Graph execution](https://www.tensorflow.org/get_started/get_started_for_beginners) # * TensorFlow 초창기 구현 방법 # * 여전히 많이 이용하고 있음 # * Graph 선언부분과 실행(Session)하는 부분이 분리되어 있음 # ## Eager Execution examples a = tf.add(3, 5) print(a) # ### 약간 더 복잡한 계산 x = 2 y = 3 w = tf.add(x, y) z = tf.multiply(x, y) p = tf.pow(z, w) print("x: ", x) print("y: ", y) print("w: ", w) print("z: ", z) print("p: ", p) # ### `Tensor` 변수와 일반 `python` 변수 x = tf.constant(2) y = tf.constant(3) w = x + y z = x * y p = tf.pow(z, w) print("x: ", x) print("y: ", y) print("w: ", w) print("z: ", z) print("p: ", p) # ### Eager Execution another examples # + tf.executing_eagerly() # => True x = [[2.]] m = tf.matmul(x, x) print("hello, {}".format(m)) # => "hello, [[4.]]" # - a = tf.constant([[1, 2], [3, 4]]) print(a) # => tf.Tensor([[1 2] # [3 4]], shape=(2, 2), dtype=int32) # Broadcasting support b = tf.add(a, 1) print(b) # => tf.Tensor([[2 3] # [4 5]], shape=(2, 2), dtype=int32) # Operator overloading is supported print(a * b) # => tf.Tensor([[ 2 6] # [12 20]], shape=(2, 2), dtype=int32) # + # Use NumPy functions import numpy as np c = np.multiply(a, b) print(c) # => [[ 2 6] # [12 20]] # - # ### `tf.Tensor.numpy()` # # * returns the object's value as a NumPy ndarray. # Obtain numpy value from a tensor: print(a.numpy()) # => [[1 2] # [3 4]]
week01/02_TF_eager.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # default_exp calibration # - # # Calibration # # > Functionality to calibrate a trained, binary classification model using temperature scaling. # # This functionality is based on <NAME>., <NAME>., <NAME>., & <NAME>. (2017, July). On calibration of modern neural networks. In International Conference on Machine Learning (pp. 1321-1330). PMLR. # # It's also heavily inspired in the following code https://github.com/gpleiss/temperature_scaling. We recommend the users to take a look at this great repo. #export from sklearn.calibration import calibration_curve from tsai.imports import * from tsai.data.core import * # + #export class ModelWithTemperature(nn.Module): """ A decorator which wraps a model with temperature scaling """ def __init__(self, model): super().__init__() self.model = model self.temperature = nn.Parameter(torch.ones(1,1)) def forward(self, input): logits = self.model(input) return self.temperature_scale(logits) def temperature_scale(self, logits): temperature = self.temperature.expand(logits.size(0), logits.size(1)).to(logits.device) return torch.div(logits, temperature) class TemperatureSetter(nn.Module): """ Calibrates a binary classification model optimizing temperature """ def __init__(self, model, lr=0.01, max_iter=1_000, line_search_fn=None, n_bins=10, verbose=True): super().__init__() self.model = ModelWithTemperature(model) if not hasattr(model, 'temperature_scale') else model self.lr, self.max_iter, self.line_search_fn, self.n_bins, self.verbose = lr, max_iter, line_search_fn, n_bins, verbose self.nll_criterion = CrossEntropyLossFlat() self.ece_criterion = ECELoss(n_bins) def forward(self, dl): logits_list = [] labels_list = [] with torch.no_grad(): for input, label in dl: logits = self.model(input) logits_list.append(logits) labels_list.append(label) logits = torch.cat(logits_list) labels = torch.cat(labels_list) if self.verbose: before_temperature_nll = self.nll_criterion(logits, labels).item() before_temperature_ece = self.ece_criterion(logits, labels).item() print(f'Before temperature - NLL: {before_temperature_nll:.3f}, ECE: {before_temperature_ece:.3f}') optimizer = torch.optim.LBFGS([self.model.temperature], lr=self.lr, max_iter=self.max_iter, line_search_fn=self.line_search_fn) def _evaluation(): optimizer.zero_grad() loss = self.nll_criterion(self.model.temperature_scale(logits), labels) loss.backward() return loss pv('Calibrating the model...', self.verbose) optimizer.step(_evaluation) pv('...model calibrated', self.verbose) if self.verbose: after_temperature_nll = self.nll_criterion(self.model.temperature_scale(logits), labels).item() after_temperature_ece = self.ece_criterion(self.model.temperature_scale(logits), labels).item() print(f'Optimal temperature: {self.model.temperature.item():.3f}') print(f'After temperature - NLL: {after_temperature_nll:.3f}, ECE: {after_temperature_ece:.3f}\n') self.logits = logits self.scaled_logits = self.model.temperature_scale(logits) self.labels = labels self.calibrated_model = self.model return self.calibrated_model class ECELoss(nn.Module): """Calculates the Expected Calibration Error of a model.""" def __init__(self, n_bins=10): super().__init__() bin_boundaries = torch.linspace(0, 1, n_bins + 1) self.bin_lowers = bin_boundaries[:-1] self.bin_uppers = bin_boundaries[1:] def forward(self, logits, labels): softmaxes = F.softmax(logits, dim=1) confidences, predictions = torch.max(softmaxes, 1) if isinstance(softmaxes, TSTensor): confidences, predictions = confidences.data, predictions.data accuracies = torch.eq(predictions.data, labels) ece = torch.zeros(1, device=logits.device) for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers): # Calculated |confidence - accuracy| in each bin in_bin = confidences.gt(bin_lower.item()) * confidences.le(bin_upper.item()) prop_in_bin = in_bin.float().mean() if prop_in_bin.item() > 0: accuracy_in_bin = accuracies[in_bin].float().mean() avg_confidence_in_bin = confidences[in_bin].mean() ece += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin return ece # - #export def plot_calibration_curve(labels, logits, cal_logits=None, figsize=(6,6), n_bins=10, strategy='uniform'): y_true = labels.cpu().numpy() pos_probas = F.softmax(logits, dim=1)[:, 1].detach().cpu().numpy() nn_y, nn_x = calibration_curve(y_true, pos_probas, n_bins=n_bins, strategy=strategy) fig, ax = plt.subplots(figsize=figsize) fig.suptitle("Calibration plot", fontsize=16) ax.plot(nn_x, nn_y, marker="o", linewidth=1, color='orange', label='probas') if cal_logits is not None: pos_cal_probas = F.softmax(cal_logits, dim=1)[:, 1].detach().cpu().numpy() cal_nn_y, cal_nn_x = calibration_curve(y_true, pos_cal_probas, n_bins=n_bins, strategy=strategy) ax.plot(cal_nn_x, cal_nn_y, marker="o", linewidth=1, color='purple', label='calibrated probas') ax.plot([0, 1], [0, 1], transform=ax.transAxes, color='gray', lw=1) ax.set_xlabel("Predicted probability", fontsize=12) ax.set_ylabel("True probability in each bin", fontsize=12) ax.set_xticks(np.linspace(0,1,11)) ax.set_yticks(np.linspace(0,1,11)) ax.set_xlim(0,1) ax.set_ylim(0,1) initial_ECE = ECELoss(n_bins)(logits, labels).item() if cal_logits is not None: final_ECE = ECELoss(n_bins)(cal_logits, labels).item() title = f"initial ECE: {initial_ECE:.3f} - final ECE: {final_ECE:.3f}" else: title = f"ECE: {initial_ECE:.3f}" plt.title(title) plt.legend(loc='best') plt.show() #export @patch def calibrate_model(self:Learner, X=None, y=None, lr=1e-2, max_iter=10_000, line_search_fn=None, n_bins=10, strategy='uniform', show_plot=True, figsize=(6,6), verbose=True): if X is not None and y is not None: dl = self.dls.valid.new_dl(X, y) else: dl = self.dls.valid assert dl.c == 2, "calibrate_model is only available for binary classification tasks" temp_setter = TemperatureSetter(self.model, lr=lr, max_iter=max_iter, line_search_fn=line_search_fn, n_bins=n_bins, verbose=verbose) self.calibrated_model = temp_setter(dl) if show_plot: plot_calibration_curve(temp_setter.labels, temp_setter.logits, temp_setter.scaled_logits, n_bins=n_bins, strategy=strategy, figsize=figsize) # + from tsai.basics import * from tsai.models.FCNPlus import FCNPlus X, y, splits = get_UCR_data('FingerMovements', split_data=False) tfms = [None, [TSClassification()]] batch_tfms = TSRobustScale() dls = get_ts_dls(X, y, splits=splits, tfms=tfms, batch_tfms=batch_tfms) learn = ts_learner(dls, FCNPlus, metrics=accuracy) learn.fit_one_cycle(2) # - learn.calibrate_model() calibrated_model = learn.calibrated_model #hide from tsai.imports import create_scripts from tsai.export import get_nb_name nb_name = get_nb_name() # nb_name = "052c_calibration.ipynb" create_scripts(nb_name);
nbs/052c_calibration.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- # # Run selection demonstration # Jelle, updated May 2019 # Run selection in strax is relatively simple. Let's start with setting up a basic XENON1T analysis: # + import strax import straxen st = straxen.contexts.strax_workshop_dali() # - # ### 1. Basic selections # Suppose we want to select runs that satisfy all of these criteria: # * Have a tag called `sciencerun2_preliminary` (or `_sciencerun2_preliminary`, we ignore leading underscores) # * Do NOT have tags `afterNG` or `AfterNG`, indicating the run was shortly after a neutron generator. # * Have `raw_records` accessible. # * Have a run mode that starts with `background` (e.g. `background_stable` and `background_triggerless`) # # Here's how you would do that: dsets = st.select_runs(include_tags='sciencerun2_preliminary', exclude_tags='?fterNG', available='raw_records', run_mode='background*') len(dsets) # The first time you run the cell above, it took a few seconds to fetch some information from the XENON runs db. If you run it again, or if you run some other selection, it won't have to (try it), and should return almost instantly. # # The results are returned as a dataframe: dsets.head() # In particular, the `name` field gives the `run_id` you feed to `st.get_data`. # ### 2. The `dsets` dataframe, more refined selections # The extra info in the `dsets` dataframe can be used for further selections, for example on the number of events or the start/stop times of the run. dsets = dsets[dsets['trigger.events_built'] > 10000] len(dsets) # You can also use it to get some quick statistics on the runs, such as the total uncorrected live-time: (dsets['end'] - dsets['start']).sum() # You might also want to check all combinations of tags that occur in the selected datasets, to see if anything odd is selected. Straxen has a utility function for this: strax.count_tags(dsets) # Hmm, maybe you want to add `wrongtime` to the list of excluded tags. Try it! # ### 3. Detailed run info and advanced selections # If you want to get more detailed run information on a single run, you can use the `run_metadata` method to fetch the entire run document: doc = st.run_metadata('180215_1029') print(list(doc.keys())) # Please do not use this in a loop over all runs, the runs database is almost 1 GB in size... This may become smaller in the future, if we decide to put chunk-level metadata somewhere else. # If you want to get a specific piece of information for many runs, you can tell straxen to fetch extra fields from the runs db with `scan_runs`: st.scan_runs(store_fields='quality.hv.anode') dsets = st.select_runs(include_tags='sciencerun1') # Now `dsets` has an extra column `quality__hv__anode` available that you can select on. We converted the dots (`.`) in the field name to double underscores (`__`) to ensure the column name remains a valid python identifier. Here's a histogram of the observed values: dsets.columns import matplotlib.pyplot as plt # %matplotlib inline plt.hist(dsets['quality.hv.anode'], bins=20); plt.xlabel("Anode voltage (V)") plt.ylabel("Number of runs") # Finally, if you want to do something truly custom, you can construct and run your own MongoDB query or aggregation. # # TODO: For now this doesn't work in this context, since the actual XENON run db is not activated # + # mongo_collection = st.storage[0].collection # doc = mongo_collection.find_one({'number': 10000}, projection=['name']) # doc['name']
notebooks/tutorials/run_selection.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:gt] # language: python # name: conda-env-gt-py # --- # # Mock exam paper # # [This is a mock paper to help with revision.](/{{root}}/assets/exm/mock/main.pdf)
nbs/exercises/Past exam mock.ipynb
# --- # jupyter: # jupytext: # formats: ipynb,md:myst # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Eliashberg theory for Holstein-Hubbard model # # Author: [<NAME>](mailto:<EMAIL>) and [<NAME>](mailto:<EMAIL>) # # ### Equations # # The (multiorbital) Hubbard model coupled to local phonons describes a simplest case where the electrons and phonons are correlated. # Such situation can be realized in a molecular-based systems such as fullerides. # While the DMFT approach to electron-phonon coupled systems is still technically challenging, the Eliashberg approach [1,2] is a powerful method in the weakly correlated regime and provides an intuitive understanding for the underlying physics. # # # The single-orbital case is known as a Holstein-Hubbard model whose Hamiltonian is given by # # $$ # \begin{align} # \mathscr H &= \mathscr H_{e0} + # \frac{U}{2}\sum_i :n_{i}^2: # + \omega_0 \sum_i a_i^\dagger a_i # + g \sum_i (a_i+a_i^\dagger) n_i # \end{align} # $$ # # where $n_i=\sum_{\sigma} n_{i\sigma} = \sum_{\sigma} c^\dagger_{i\sigma} c_{i\sigma}$ is the local number operator, and the colon represents a normal ordering. # # # We generalize it so as to deal with the three-orbital case relevant to fulleride superconductors (the Jahn-Teller-Hubbard model). # The details for the three-orbital model are provided in Ref [3], and here we explain the outline of the approach. # We begin with the Hamiltonian $\mathscr H = \mathscr H_{e} + \mathscr H_{ee} + \mathscr H_p + \mathscr H_{ep}$ # where # # $$ # \begin{align} # \mathscr H_{ee} &= \sum_{i\eta} I_\eta : T_{i\eta}^2: # \hspace{10mm} # \Big( T_{i\eta} = \sum_{\gamma\gamma'\sigma} c^\dagger_{i\gamma\sigma} \lambda^\eta_{\gamma\gamma'} c_{\gamma'\sigma} \Big) # \\ # \mathscr H_{p} &= \sum_{i\eta} \omega_\eta a_{i\eta}^\dagger a_{i\eta} = \sum_{i\eta} \frac{\omega_\eta}{4} (p_{i\eta}^2 + \phi_{i\eta}^2) # \equiv \mathscr H_{p,{\rm kin}} + \mathscr H_{p,{\rm pot}} # \\ # \mathscr H_{ep} &= \sum_{i\eta} g_\eta # \phi_{i\eta} # T_{i\eta} # \end{align} # $$ # # $\gamma$ is an orbital index. The $\eta$ distinguish the types of charge-orbital moments for electrons and vibration modes for phonons, respectively, # where $M=\sum_\gamma 1$, ${\rm Tr}(\hat \lambda^\eta)^2=2$, $\sum_\eta 1 = \frac{M(M+1)}{2}$. # We may use $M=1$ (single-orbital) or $M=3$ (three-orbital). # For examples, the charge operator is given by $T_{i,\eta=0} = \sqrt 2 \sum_\sigma n_{i\sigma}$ for $M=1$ and $T_{i,\eta=0} = \sqrt{\tfrac 2 3} \sum_\sigma (n_{i1\sigma}+n_{i2\sigma}+n_{i3\sigma})$ for $M=3$. # # # We have introduced displacement and momentum operators by $\phi_{i\eta} = a_{i\eta}+ a_{i\eta}^\dagger$ and $p_{i\eta} = (a_{i\eta} - a_{i\eta}^\dagger)/{\rm i}$, which satisfy the canonical commutation relation $[\phi_{i\eta},p_{j\eta'}] = 2{\rm i} \delta_{ij} \delta_{\eta\eta'}$. # $\mathscr H_{ee}$ is a compact multipole representation for the Hubbard or Slater-Kanamori interactions [4]. # More specifically, $I_0 = U/4$ for the single-orbital case, and $I_0 = 3U/4 -J$, $I_{\eta\neq 0} = J/2$ for the three-orbital case with the Hund's coupling $J$ [3]. # # # # We assume that there is no $\eta$-dependence, i.e., we write $g_\eta = g_0$ and $\omega_\eta = \omega_0$. # Assuming also that the self-energy is local as in DMFT, we obtain the Eliashberg equations # # $$ # \begin{align} # \Sigma(\tau) &= -U_{\rm eff}(\tau) G(\tau) # \\ # \Delta(\tau) &= U_{\rm eff}(\tau) F(\tau) # \\ # U_{\rm eff}(\tau) &= (U+2J)\delta(\tau) + (M+1) g_0^2 D (\tau) # \\ # \Pi (\tau) &= 4g_0^2 [ G(\tau) G(-\tau) - F(\tau)^2 ] # \end{align} # $$ # # where the local Green functions are defined by # $G(\tau) = - \langle \mathcal T c_{i\gamma\sigma}(\tau) c^\dagger_{i\gamma\sigma} \rangle$, # $F(\tau) = - \langle \mathcal T c_{i\gamma\uparrow}(\tau) c_{i\gamma\downarrow} \rangle$ # for electrons, and # $D(\tau) = - \langle \mathcal T \phi_{i\eta}(\tau) \phi_{i\eta} \rangle$ for phonons. # We have simplified the equations using the cubic symmetry. # The phase of the superconducting order parameter is fixed as $\Delta\in \mathbb R$. # If we take $M=1$ and correspondingly $J=0$, it reproduces the single-orbital Holstein-Hubbard model. # # # The internal energy may be evaluated through the single-particle Green functions. # In a manner similar to Ref. [5], # we have the following relations # # $$ # \begin{align} # 2MT\sum_{n}{\rm i}\omega_n G({\rm i}\omega_n) {\rm e}^{{\rm i} \omega_n 0^+} # &= \langle \mathscr H_{e0} \rangle + 2\langle \mathscr H_{ee} \rangle # + \langle \mathscr H_{ep} \rangle # \\ # \frac{M(M+1)}{2} T\sum_m \frac{({\rm i}\nu_m)^2}{2\omega_0} D({\rm i}\nu_m) {\rm e}^{{\rm i} \nu_m 0^+} # &= - 2\langle \mathscr H_{p,{\rm pot}}\rangle # - \langle \mathscr H_{ep}\rangle # = - 2\langle \mathscr H_{p,{\rm kin}}\rangle # \\ # 2M T\sum_n \Sigma({\rm i}\omega_n) G({\rm i}\omega_n) {\rm e}^{{\rm i} \omega_n 0^+} # &= 2\langle \mathscr H_{ee} \rangle # + \langle \mathscr H_{ep} \rangle # \\ # \frac{M(M+1)}{2} T\sum_m \Pi({\rm i}\nu_m) D({\rm i}\nu_m) {\rm e}^{{\rm i} \nu_m 0^+}&= - \langle \mathscr H_{ep} \rangle # \end{align} # $$ # # Thus the internal energy $\langle \mathscr H \rangle = \langle \mathscr H_{e0} + \mathscr H_{ee} + \mathscr H_{p,{\rm kin}} + \mathscr H_{p,{\rm pot}} + \mathscr H_{ep} \rangle$ is obtained. # The specific heat is then calculated numerically through differentiating it by temperature. # # # In addition to the above Eliashberg equations, the Dyson equation completes a closed set of the self-consistent equations. # The Green functions are given in the Fourier domain: # # $$ # \begin{align} # G({\rm i}\omega_n) &= \int {\rm d} \varepsilon \rho(\varepsilon) # \frac{\zeta ({\rm i}\omega_n) + \varepsilon}{\zeta({\rm i}\omega_n)^2- \Delta({\rm i}\omega_n)^2 - \varepsilon^2} # \\ # F({\rm i}\omega_n) &= \int {\rm d} \varepsilon \rho(\varepsilon) # \frac{\Delta ({\rm i}\omega_n)}{\zeta({\rm i}\omega_n)^2- \Delta({\rm i}\omega_n)^2 - \varepsilon^2} # \\ # \zeta({\rm i}\omega_n) &= {\rm i}\omega_n+\mu-\Sigma({\rm i}\omega_n) # \end{align} # $$ # # for electrons, and # # $$ # \begin{align} # D({\rm i}\nu_m)^{-1} &= D_0({\rm i}\nu_m)^{-1} - \Pi({\rm i}\nu_m) # \\ # D_0({\rm i}\nu_m) &= \frac{2\omega_0}{({\rm i}\nu_m)^2 - \omega_0^2} # \end{align} # $$ # # for phonons. # We take the semi-circular density of states $\rho(\varepsilon) = \frac{2}{\pi D^2} \sqrt{D^2-\varepsilon^2}$ for electron parts. # + id="TKeCOaRVlBRv" vscode={"languageId": "python"} ## Implementation: Eliashberg solver # + id="gqzztjs3lBRw" vscode={"languageId": "python"} import numpy as np # %matplotlib inline import matplotlib.pyplot as plt import sparse_ir plt.rcParams.update({ "font.family": "serif", "font.size": 16, }) # + id="Lg31SRXclBRw" vscode={"languageId": "python"} from numpy.polynomial.legendre import leggauss def scale_quad(x, w, xmin, xmax): """ Scale weights and notes of quadrature to the interval [xmin, xmax] """ assert xmin < xmax dx = xmax - xmin w_ = 0.5 * dx * w x_ = (0.5 * dx) * (x + 1) + xmin return x_, w_ class Eliashberg: def __init__(self, bset: sparse_ir.FiniteTempBasisSet, rho_omega, omega_range, U, J, omega0, g, deg_leggauss=100): assert isinstance(omega_range, tuple) assert omega_range[0] < omega_range[1] self.U = U self.J = J self.bset = bset self.beta = bset.beta self.rho_omega = rho_omega self.omega0 = omega0 self.g = g x_, w_ = leggauss(deg_leggauss) self.quad_rule = scale_quad(x_, w_, omega_range[0], omega_range[1]) self.omega = self.quad_rule[0] self.omega_coeff = rho_omega(self.omega) * self.quad_rule[1] # Sparse sampling in Matsubara frequencies self.iv_f = self.bset.wn_f * (1j * np.pi/self.beta) self.iv_b = self.bset.wn_b * (1j * np.pi/self.beta) # Phonon propagator self.d0_iv = 2 * omega0/(self.iv_b**2 - omega0**2) def xi_iv(self, mu, sigma_iv): """ Compute xi(iv) """ return self.iv_f + mu - sigma_iv def g_f_iv(self, mu, sigma_iv, delta_iv): """ Compute G(iv) and F(iv) from sigma(iv), Delta(iv) """ xi_iv = self.xi_iv(mu, sigma_iv) denominator = (xi_iv**2 - delta_iv**2)[:, None] - (self.omega**2)[None, :] numerator_G = xi_iv[:, None] + self.omega[None, :] numerator_F = delta_iv[:, None] g_iv = np.einsum('q,wq->w', self.omega_coeff, numerator_G/denominator, optimize=True) f_iv = np.einsum('q,wq->w', self.omega_coeff, numerator_F/denominator, optimize=True) return g_iv, f_iv def pi_tau(self, g_tau, f_tau): """ Compute Pi(tau) """ return - 4 * (self.g**2) * (g_tau * g_tau[::-1] + f_tau**2) def d_iv(self, phi_iv): """ Compute D(iv) """ return 1/(1/self.d0_iv - phi_iv) def sigma(self, g_tau, d_tau): """ Compute Sigma(tau) and Sigma(iv) """ sigma_tau = - 4 * (self.g**2) * d_tau * g_tau sigma_iv = self.to_matsu(sigma_tau, "F") return sigma_tau, sigma_iv def delta_iv(self, f_tau, d_tau): """ Compute Delta(iv) """ tl_delta_tau = (4 * self.g**2) * d_tau * f_tau tl_delta_iv = self.to_matsu(tl_delta_tau, "F") return tl_delta_iv + (self.U + 2*self.J) * f_tau[0] def _smpl_tau(self, stat): return {"F": self.bset.smpl_tau_f, "B": self.bset.smpl_tau_b}[stat] def _smpl_wn(self, stat): return {"F": self.bset.smpl_wn_f, "B": self.bset.smpl_wn_b}[stat] def to_tau(self, obj_iv, stat): """ Transform to tau """ return self._smpl_tau(stat).evaluate(self._smpl_wn(stat).fit(obj_iv)) def to_matsu(self, obj_tau, stat): """ Transform to Matsubara """ return self._smpl_wn(stat).evaluate(self._smpl_tau(stat).fit(obj_tau)) def internal_energy(self, sigma_iv=None, delta_iv=None, g_iv=None, d_iv=None, tau=0.0): """ Compute internal energy """ stat_sign = {0.0: 1, self.beta: -1}[tau] smpl_tau0 = [sparse_ir.TauSampling(b, [tau]) for b in [self.bset.basis_f, self.bset.basis_b]] e1 = stat_sign * smpl_tau0[0].evaluate(self.bset.smpl_wn_f.fit(self.iv_f * g_iv - 1)) e2 = stat_sign * smpl_tau0[0].evaluate( self.bset.smpl_wn_f.fit( g_iv * ((self.iv_f - sigma_iv)**2 - delta_iv**2)/(self.iv_f - sigma_iv) - 1 ) ) f2 = self.bset.smpl_tau_b.evaluate( self.bset.smpl_wn_b.fit( (self.omega0**-2) * ( (self.iv_b**2) * d_iv - 2 * self.omega0) ) ) return (3 * (e1 + e2 - self.omega0 * f2))[0] # + id="_Ao6y2AClBRx" vscode={"languageId": "python"} def solve(elsh, sigma_iv, delta_iv, niter, mixing, verbose=False, ph=False, atol=1e-10): """ Solve the self-consistent equation ph: Force ph symmetry """ sigma_iv_prev = None delta_iv_prev = None converged = False for iter in range(niter): # Update G and F g_iv, f_iv = elsh.g_f_iv(mu, sigma_iv, delta_iv) g_tau = elsh.to_tau(g_iv, "F") f_tau = elsh.to_tau(f_iv, "F") if ph: g_tau = 0.5 * (g_tau + g_tau[::-1]) g_tau[g_tau > 0] = 0 # Update Phi phi_tau = elsh.pi_tau(g_tau, f_tau) phi_iv = elsh.to_matsu(phi_tau, "B") phi_iv.imag = 0 # Update D d_iv = elsh.d_iv(phi_iv) d_tau = elsh.to_tau(d_iv, "B") # Update Sigma sigma_tau, sigma_iv_new = elsh.sigma(g_tau, d_tau) sigma_iv_prev = sigma_iv.copy() sigma_iv = (1-mixing) * sigma_iv + mixing * sigma_iv_new # Update Delta delta_iv_new = elsh.delta_iv(f_tau, d_tau) delta_iv_prev = delta_iv.copy() delta_iv = (1-mixing) * delta_iv + mixing * delta_iv_new delta_iv.imag = 0.0 delta_iv = 0.5 * (delta_iv + delta_iv[::-1]) diff_sigma = np.abs(sigma_iv_new - sigma_iv_prev).max() diff_delta = np.abs(delta_iv_new - delta_iv_prev).max() if verbose and iter % 100 == 0: print(f"iter= {iter} : diff_sigma= {diff_sigma}, diff_delta={diff_delta}") #print(max(diff_sigma, diff_delta), atol) if atol is not None and max(diff_sigma, diff_delta) < atol: converged = True break if not converged: print("Not converged!") # Internal energy u = elsh.internal_energy( sigma_iv=sigma_iv, delta_iv=delta_iv, g_iv=g_iv, d_iv=d_iv, tau=0.0) others = { 'sigma_tau': sigma_tau, 'phi_iv': phi_iv, 'g_iv': g_iv, 'f_iv': f_iv, 'd_iv': d_iv, 'd_tau': d_tau, 'f_tau': f_tau, 'g_tau': g_tau, 'u' : u } return sigma_iv, delta_iv, others # + id="edkPwYn6lBRy" vscode={"languageId": "python"} def add_noise(arr, noise): """ Add Gaussian noise to an array """ arr += noise*np.random.randn(*arr.shape) arr += noise*1j*np.random.randn(*arr.shape) return arr # + [markdown] id="bbnN_XEUlBRy" # ## Self-consistent calculation # + [markdown] id="n9UpuKDUlBRz" # ### Paramaters # # We now reproduce the results for $\lambda_0 = 0.125$ shown in Fig. 1 of Ref. [3]. # The parameter $g_0$ is related to $\lambda_0$ as # # $$ # g_0 = \sqrt{\frac{3 \lambda_0 \omega_0}{4}}. # $$ # # (In the code, we drop the suffix 0 for simplicity.) # We consider a semicircular density of state with a half bandwidth of $1/2$, $T=0.002$, $U=2$, $J/U = 0.03$ and half filling. # + id="W4_hSqKOlBRz" vscode={"languageId": "python"} beta = 500.0 D = 0.5 rho_omega = lambda omega: np.sqrt(D**2 - omega**2) / (0.5 * D**2 * np.pi) U = 2.0 J = 0.03 * U omega0 = 0.15 lambda0 = 0.125 mu = 0.0 # + [markdown] id="tCZP_p5GlBRz" # ### Setup IR basis # + id="jk8-i7TolBR1" vscode={"languageId": "python"} eps = 1e-7 wmax = 10*D bset = sparse_ir.FiniteTempBasisSet(beta, wmax, eps) # + [markdown] id="Hmt96VdGlBR1" # ### Solve the equation # + id="qUpSeHLMlBR1" outputId="00bc85c9-5a68-4c1e-d1a4-1c669ca03fdf" tags=["output_scroll"] vscode={"languageId": "python"} # Number of fermionic sampling frequencies nw_f = bset.wn_f.size # Initial guess noise = 1e-2 sigma_iv0 = add_noise(np.zeros(nw_f, dtype=np.complex128), noise) delta_iv0 = np.full(nw_f, 1.0, dtype=np.complex128) max_niter = 10000 mixing = 0.1 deg_leggauss = 100 # Degree of Gauss quadrature for DOS integration # Construct a solver g = np.sqrt(3 * lambda0 * omega0/4) elsh = Eliashberg(bset, rho_omega, (-D,D), U, J, omega0, g, deg_leggauss=deg_leggauss) # Solve the equation sigma_iv, delta_iv, others = solve(elsh, sigma_iv0, delta_iv0, max_niter, mixing, verbose=True, ph=True) # Result res = {"bset": bset, "sigma_iv": sigma_iv, "delta_iv": delta_iv, **others} # + id="PDEuUmFqlBR2" outputId="b9086ef3-0f54-4dd3-fa2b-500cb047f310" vscode={"languageId": "python"} # Let us check `F` is represented compactly in IR f_l = bset.smpl_wn_f.fit(res['f_iv']) plt.semilogy(np.abs(f_l), label=r"$|F_l|$", marker="o", ls="") plt.semilogy(bset.basis_f.s/bset.basis_f.s[0], label=r"$S_l/S_0$") plt.ylim([1e-8, 10]) plt.legend(frameon=False) plt.show() # + [markdown] id="rLCRj5BzlBR2" # ### Plot results # + id="GPObxMyLlBR2" outputId="cc1ace67-2596-4343-ea17-ae85f5443bdb" vscode={"languageId": "python"} def plot_res(res): """ For plotting results """ beta = res["bset"].beta iv_f = res["bset"].wn_f * (1j*np.pi/beta) iv_b = res["bset"].wn_b * (1j*np.pi/beta) plt.plot(iv_f.imag, res['sigma_iv'].imag, marker="x") plt.xlabel(r"$\omega_n$") plt.ylabel(r"Im $\Sigma(\mathrm{i}\omega_n)$") plt.xlim([-0.8, 0.8]) plt.xticks([-0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8]) plt.grid() plt.show() plt.plot(iv_b.imag, res['d_iv'].real, marker="x") plt.xlabel(r"$\nu_m$") plt.ylabel(r"Re $D(\mathrm{i}\nu_m)$") plt.xlim([-0.8, 0.8]) plt.xticks([-0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8]) #plt.ylim([-0.1, 0.1]) plt.grid() plt.show() plt.plot(bset.tau, res['d_tau'].real, marker="x") plt.xlabel(r"$\tau$") plt.ylabel(r"Re $D(\tau)$") plt.grid() plt.show() plt.plot(iv_f.imag, res['delta_iv'].real, marker="x") plt.xlabel(r"$\nu_m$") plt.ylabel(r"Re $\Delta(\mathrm{i}\nu_m)$") plt.xlim([-0.8, 0.8]) plt.xticks([-0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8]) plt.ylim([-0.05, 0.3]) plt.grid() plt.show() plt.plot(iv_f.imag, res['f_iv'].real, marker="x") plt.xlabel(r"$\omega_n$") plt.ylabel(r"Re $F(\mathrm{i}\omega_n)$") plt.xlim([-0.8, 0.8]) plt.xticks([-0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8]) plt.grid() plt.show() plt.plot(elsh.iv_b.imag, res['phi_iv'].real, marker="x") plt.xlabel(r"$\nu_m$") plt.ylabel(r"Re $\Pi(\mathrm{i}\nu_m)$") plt.xlim([-0.8, 0.8]) plt.grid() plt.show() plot_res(res) # + [markdown] id="8XbkZOtblBR3" # ## Second calculation on temperature dependence # # We now compute the temperature dependence of the specific heat for $\lambda_0=0.175$ shown in Fig. 5 of Ref. [1]. # + id="6MmWde_WlBR3" vscode={"languageId": "python"} lambda0 = 0.175 g = np.sqrt(3 * lambda0 * omega0/4) # + [markdown] id="LbYYybDOlBR3" # We now compute solutions by changing the temperature gradually. To use the same number of IR functions all the temperatures, we fix the UV cutoff $\Lambda$ to a common value. # + id="vVbBsh9AlBR3" vscode={"languageId": "python"} res_temp = {} temps = np.linspace(0.009, 0.013, 10) # Set Lambda to a large enough value for the lowest temperature Lambda_common = (10 * D)/temps.min() # Shift the mesh points by dt, which doubles the mesh size, # to compute the specific heat dt = 1e-5 temps_all = np.unique(np.hstack((temps, temps + dt))) bset = None sigma_iv0 = None elta_iv0 = None for temp in temps_all: beta = 1/temp if bset is None: bset = sparse_ir.FiniteTempBasisSet(beta, Lambda_common/beta, eps) else: # Reuse the SVE results bset = sparse_ir.FiniteTempBasisSet(beta, Lambda_common/beta, eps, sve_result=bset.sve_result) elsh = Eliashberg(bset, rho_omega, (-D, D), U, J, omega0, g, deg_leggauss=deg_leggauss) # Initial guess if sigma_iv0 is None: noise = 1e-5 sigma_iv0 = add_noise(np.zeros(bset.wn_f.size, dtype=np.complex128), noise) delta_iv0 = np.full(bset.wn_f.size, 1.0, dtype=np.complex128) # Solve! #sigma_iv, delta_iv, others = solve(elsh, sigma_iv0, delta_iv0, niter, mixing, verbose=True, ph=True) max_iter = 1000000 sigma_iv, delta_iv, others = solve(elsh, sigma_iv0, delta_iv0, max_iter, mixing, verbose=False, ph=True) res = {"sigma_iv": sigma_iv, "delta_iv": delta_iv} for k, v in others.items(): res[k] = v res_temp[temp] = res # Use the converged result for an initial guess for the next temperature sigma_iv0 = res["sigma_iv"].copy() delta_iv0 = res["delta_iv"].copy() # + id="SpNV13PilBR3" outputId="05ff830b-9b48-4e92-d572-1baa8772e953" vscode={"languageId": "python"} u_temps = np.array([res_temp[temp]["u"].real for temp in temps_all]) plt.plot(temps_all, u_temps, marker="x") plt.xlabel(r"$T$") plt.ylabel(r"$E(T)$") plt.show() # + id="lWck_VXqlBR4" outputId="482b7aa3-ef92-48bd-90f4-4c69753b0082" vscode={"languageId": "python"} u_dict = {temp: res_temp[temp]["u"].real for temp in temps_all} specific_heat = np.array([u_dict[temp+dt] - u_dict[temp] for temp in temps])/dt plt.plot(temps, specific_heat/temps, marker="o") plt.ylim([0, 1200]) plt.xlabel(r"$T$") plt.ylabel(r"$C(T)$") plt.show() # + [markdown] id="G4bMASdklBR4" # <!-- [1] <NAME>, <NAME> and <NAME> arXiv:2203.06946. --> # # [1] <NAME>, Zh. Eksperim. Teor. Fiz. **38**, 966 # (1960) [Sov. Phys. JETP **11**, 696 (1960)]. # # [2] <NAME>, Zh. Eksperim. Teor. Fiz. **43**, 1005 # (1962) [Sov. Phys. JETP **16**, 780 (1963)]. # # [3] <NAME>, <NAME>, and <NAME>, arXiv:2203.06946 (2022). # # [4] <NAME>, <NAME>, and <NAME>, Phys. Rev. B **104**, L081108 (2021). # # [5] <NAME>, Phys. Rev. **135**, A1481 (1964).
src/eliashberg_holstein_py.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + package_paths = [ '../input/pytorch-image-models/pytorch-image-models-master', #'../input/efficientnet-pytorch-07/efficientnet_pytorch-0.7.0' '../input/image-fmix/FMix-master' ] import sys; for pth in package_paths: sys.path.append(pth) from fmix import sample_mask, make_low_freq_image, binarise_mask # !pip install timm # + _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5" _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" from glob import glob from sklearn.model_selection import GroupKFold, StratifiedKFold import cv2 from skimage import io import torch from torch import nn import os from datetime import datetime import time import random import cv2 import torchvision from torchvision import transforms import pandas as pd import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt from torch.utils.data import Dataset,DataLoader from torch.utils.data.sampler import SequentialSampler, RandomSampler from torch.cuda.amp import autocast, GradScaler from torch.nn.modules.loss import _WeightedLoss import torch.nn.functional as F import timm import sklearn import warnings import joblib from sklearn.metrics import roc_auc_score, log_loss from sklearn import metrics import warnings import cv2 import pydicom #from efficientnet_pytorch import EfficientNet from scipy.ndimage.interpolation import zoom # - from pprint import pprint model_names = timm.list_models(pretrained=True) pprint(model_names) CFG = { 'fold_num': 5, 'seed': 719, 'model_arch': 'vit_base_patch32_384', 'img_size': 384, 'epochs': 10, 'train_bs': 16, 'valid_bs': 32, 'T_0': 10, 'lr': 1e-4, 'min_lr': 1e-6, 'weight_decay':1e-6, 'num_workers': 4, 'accum_iter': 2, # suppoprt to do batch accumulation for backprop with effectively larger batch size 'verbose_step': 1, 'device': 'cuda:0' } # + _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a" _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" train = pd.read_csv('../input/cassava-leaf-disease-classification/train.csv') train.head() # - train.label.value_counts() # > We could do stratified validation split in each fold to make each fold's train and validation set looks like the whole train set in target distributions. submission = pd.read_csv('../input/cassava-leaf-disease-classification/sample_submission.csv') submission.head() # # Helper Functions # + def seed_everything(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = True def get_img(path): im_bgr = cv2.imread(path) im_rgb = im_bgr[:, :, ::-1] #print(im_rgb) return im_rgb img = get_img('../input/cassava-leaf-disease-classification/train_images/1000015157.jpg') plt.imshow(img) plt.show() # - # # Dataset # + def rand_bbox(size, lam): W = size[0] H = size[1] cut_rat = np.sqrt(1. - lam) cut_w = np.int(W * cut_rat) cut_h = np.int(H * cut_rat) # uniform cx = np.random.randint(W) cy = np.random.randint(H) bbx1 = np.clip(cx - cut_w // 2, 0, W) bby1 = np.clip(cy - cut_h // 2, 0, H) bbx2 = np.clip(cx + cut_w // 2, 0, W) bby2 = np.clip(cy + cut_h // 2, 0, H) return bbx1, bby1, bbx2, bby2 class CassavaDataset(Dataset): def __init__(self, df, data_root, transforms=None, output_label=True, one_hot_label=False, do_fmix=False, fmix_params={ 'alpha': 1., 'decay_power': 3., 'shape': (CFG['img_size'], CFG['img_size']), 'max_soft': True, 'reformulate': False }, do_cutmix=False, cutmix_params={ 'alpha': 1, } ): super().__init__() self.df = df.reset_index(drop=True).copy() self.transforms = transforms self.data_root = data_root self.do_fmix = do_fmix self.fmix_params = fmix_params self.do_cutmix = do_cutmix self.cutmix_params = cutmix_params self.output_label = output_label self.one_hot_label = one_hot_label if output_label == True: self.labels = self.df['label'].values #print(self.labels) if one_hot_label is True: self.labels = np.eye(self.df['label'].max()+1)[self.labels] #print(self.labels) def __len__(self): return self.df.shape[0] def __getitem__(self, index: int): # get labels if self.output_label: target = self.labels[index] img = get_img("{}/{}".format(self.data_root, self.df.loc[index]['image_id'])) if self.transforms: img = self.transforms(image=img)['image'] if self.do_fmix and np.random.uniform(0., 1., size=1)[0] > 0.5: with torch.no_grad(): #lam, mask = sample_mask(**self.fmix_params) lam = np.clip(np.random.beta(self.fmix_params['alpha'], self.fmix_params['alpha']),0.6,0.7) # Make mask, get mean / std mask = make_low_freq_image(self.fmix_params['decay_power'], self.fmix_params['shape']) mask = binarise_mask(mask, lam, self.fmix_params['shape'], self.fmix_params['max_soft']) fmix_ix = np.random.choice(self.df.index, size=1)[0] fmix_img = get_img("{}/{}".format(self.data_root, self.df.iloc[fmix_ix]['image_id'])) if self.transforms: fmix_img = self.transforms(image=fmix_img)['image'] mask_torch = torch.from_numpy(mask) # mix image img = mask_torch*img+(1.-mask_torch)*fmix_img #print(mask.shape) #assert self.output_label==True and self.one_hot_label==True # mix target rate = mask.sum()/CFG['img_size']/CFG['img_size'] target = rate*target + (1.-rate)*self.labels[fmix_ix] #print(target, mask, img) #assert False if self.do_cutmix and np.random.uniform(0., 1., size=1)[0] > 0.5: #print(img.sum(), img.shape) with torch.no_grad(): cmix_ix = np.random.choice(self.df.index, size=1)[0] cmix_img = get_img("{}/{}".format(self.data_root, self.df.iloc[cmix_ix]['image_id'])) if self.transforms: cmix_img = self.transforms(image=cmix_img)['image'] lam = np.clip(np.random.beta(self.cutmix_params['alpha'], self.cutmix_params['alpha']),0.3,0.4) bbx1, bby1, bbx2, bby2 = rand_bbox((CFG['img_size'], CFG['img_size']), lam) img[:, bbx1:bbx2, bby1:bby2] = cmix_img[:, bbx1:bbx2, bby1:bby2] rate = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / (CFG['img_size'] * CFG['img_size'])) target = rate*target + (1.-rate)*self.labels[cmix_ix] #print('-', img.sum()) #print(target) #assert False # do label smoothing #print(type(img), type(target)) if self.output_label == True: return img, target else: return img # - # # Define Train\Validation Image Augmentations # + from albumentations import ( HorizontalFlip, VerticalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90, Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue, IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, IAAPiecewiseAffine, RandomResizedCrop, IAASharpen, IAAEmboss, RandomBrightnessContrast, Flip, OneOf, Compose, Normalize, Cutout, CoarseDropout, ShiftScaleRotate, CenterCrop, Resize ) from albumentations.pytorch import ToTensorV2 def get_train_transforms(): return Compose([ RandomResizedCrop(CFG['img_size'], CFG['img_size']), Transpose(p=0.5), HorizontalFlip(p=0.5), VerticalFlip(p=0.5), ShiftScaleRotate(p=0.5), HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5), RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.5), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0), CoarseDropout(p=0.5), Cutout(p=0.5), ToTensorV2(p=1.0), ], p=1.) def get_valid_transforms(): return Compose([ CenterCrop(CFG['img_size'], CFG['img_size'], p=1.), Resize(CFG['img_size'], CFG['img_size']), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0), ToTensorV2(p=1.0), ], p=1.) # - # # Model class CassvaImgClassifier(nn.Module): def __init__(self, model_arch, n_class, pretrained=True): super().__init__() self.model = timm.create_model(model_arch, pretrained=pretrained) # if pretrained: # self.model.load_state_dict(torch.load(MODEL_PATH)) # n_features = self.model.classifier.in_features # self.model.classifier = nn.Linear(n_features, n_class) self.model.head = nn.Linear(self.model.head.in_features, n_class) # Add by barklan ''' self.model.classifier = nn.Sequential( nn.Dropout(0.3), #nn.Linear(n_features, hidden_size,bias=True), nn.ELU(), nn.Linear(n_features, n_class, bias=True) ) ''' def forward(self, x): x = self.model(x) return x # # Training APIs # + def prepare_dataloader(df, trn_idx, val_idx, data_root='../input/cassava-leaf-disease-classification/train_images/'): from catalyst.data.sampler import BalanceClassSampler train_ = df.loc[trn_idx,:].reset_index(drop=True) valid_ = df.loc[val_idx,:].reset_index(drop=True) train_ds = CassavaDataset(train_, data_root, transforms=get_train_transforms(), output_label=True, one_hot_label=False, do_fmix=False, do_cutmix=False) valid_ds = CassavaDataset(valid_, data_root, transforms=get_valid_transforms(), output_label=True) train_loader = torch.utils.data.DataLoader( train_ds, batch_size=CFG['train_bs'], pin_memory=False, drop_last=False, shuffle=True, num_workers=CFG['num_workers'], #sampler=BalanceClassSampler(labels=train_['label'].values, mode="downsampling") ) val_loader = torch.utils.data.DataLoader( valid_ds, batch_size=CFG['valid_bs'], num_workers=CFG['num_workers'], shuffle=False, pin_memory=False, ) return train_loader, val_loader def train_one_epoch(epoch, model, loss_fn, optimizer, train_loader, device, scheduler=None, schd_batch_update=False): model.train() t = time.time() running_loss = None pbar = tqdm(enumerate(train_loader), total=len(train_loader)) for step, (imgs, image_labels) in pbar: imgs = imgs.to(device).float() image_labels = image_labels.to(device).long() #print(image_labels.shape, exam_label.shape) with autocast(): image_preds = model(imgs) #output = model(input) #print(image_preds.shape, exam_pred.shape) loss = loss_fn(image_preds, image_labels) scaler.scale(loss).backward() if running_loss is None: running_loss = loss.item() else: running_loss = running_loss * .99 + loss.item() * .01 if ((step + 1) % CFG['accum_iter'] == 0) or ((step + 1) == len(train_loader)): # may unscale_ here if desired (e.g., to allow clipping unscaled gradients) scaler.step(optimizer) scaler.update() optimizer.zero_grad() if scheduler is not None and schd_batch_update: scheduler.step() if ((step + 1) % CFG['verbose_step'] == 0) or ((step + 1) == len(train_loader)): description = f'epoch {epoch} loss: {running_loss:.4f}' pbar.set_description(description) if scheduler is not None and not schd_batch_update: scheduler.step() def valid_one_epoch(epoch, model, loss_fn, val_loader, device, scheduler=None, schd_loss_update=False): model.eval() t = time.time() loss_sum = 0 sample_num = 0 image_preds_all = [] image_targets_all = [] pbar = tqdm(enumerate(val_loader), total=len(val_loader)) for step, (imgs, image_labels) in pbar: imgs = imgs.to(device).float() image_labels = image_labels.to(device).long() image_preds = model(imgs) #output = model(input) #print(image_preds.shape, exam_pred.shape) image_preds_all += [torch.argmax(image_preds, 1).detach().cpu().numpy()] image_targets_all += [image_labels.detach().cpu().numpy()] loss = loss_fn(image_preds, image_labels) loss_sum += loss.item()*image_labels.shape[0] sample_num += image_labels.shape[0] if ((step + 1) % CFG['verbose_step'] == 0) or ((step + 1) == len(val_loader)): description = f'epoch {epoch} loss: {loss_sum/sample_num:.4f}' pbar.set_description(description) image_preds_all = np.concatenate(image_preds_all) image_targets_all = np.concatenate(image_targets_all) print('validation multi-class accuracy = {:.4f}'.format((image_preds_all==image_targets_all).mean())) if scheduler is not None: if schd_loss_update: scheduler.step(loss_sum/sample_num) else: scheduler.step() # - # reference: https://www.kaggle.com/c/siim-isic-melanoma-classification/discussion/173733 class MyCrossEntropyLoss(_WeightedLoss): def __init__(self, weight=None, reduction='mean'): super().__init__(weight=weight, reduction=reduction) self.weight = weight self.reduction = reduction def forward(self, inputs, targets): lsm = F.log_softmax(inputs, -1) if self.weight is not None: lsm = lsm * self.weight.unsqueeze(0) loss = -(targets * lsm).sum(-1) if self.reduction == 'sum': loss = loss.sum() elif self.reduction == 'mean': loss = loss.mean() return loss # # Main Loop if __name__ == '__main__': # for training only, need nightly build pytorch seed_everything(CFG['seed']) folds = StratifiedKFold(n_splits=CFG['fold_num'], shuffle=True, random_state=CFG['seed']).split(np.arange(train.shape[0]), train.label.values) for fold, (trn_idx, val_idx) in enumerate(folds): # we'll train fold 0 first # if fold > 0: # break print('Training with {} started'.format(fold)) print(len(trn_idx), len(val_idx)) train_loader, val_loader = prepare_dataloader(train, trn_idx, val_idx, data_root='../input/cassava-leaf-disease-classification/train_images/') device = torch.device(CFG['device']) model = CassvaImgClassifier(CFG['model_arch'], train.label.nunique(), pretrained=True).to(device) scaler = GradScaler() optimizer = torch.optim.Adam(model.parameters(), lr=CFG['lr'], weight_decay=CFG['weight_decay']) #scheduler = torch.optim.lr_scheduler.StepLR(optimizer, gamma=0.1, step_size=CFG['epochs']-1) scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=CFG['T_0'], T_mult=1, eta_min=CFG['min_lr'], last_epoch=-1) #scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer=optimizer, pct_start=0.1, div_factor=25, # max_lr=CFG['lr'], epochs=CFG['epochs'], steps_per_epoch=len(train_loader)) loss_tr = nn.CrossEntropyLoss().to(device) #MyCrossEntropyLoss().to(device) loss_fn = nn.CrossEntropyLoss().to(device) for epoch in range(CFG['epochs']): train_one_epoch(epoch, model, loss_tr, optimizer, train_loader, device, scheduler=scheduler, schd_batch_update=False) with torch.no_grad(): valid_one_epoch(epoch, model, loss_fn, val_loader, device, scheduler=None, schd_loss_update=False) torch.save(model.state_dict(),'{}_fold_{}_{}'.format(CFG['model_arch'], fold, epoch)) #torch.save(model.cnn_model.state_dict(),'{}/cnn_model_fold_{}_{}'.format(CFG['model_path'], fold, CFG['tag'])) del model, optimizer, train_loader, val_loader, scaler, scheduler torch.cuda.empty_cache()
cassava-train.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Sample HackerRank Coding Exercise # - https://www.hackerrank.com/contests/intro-to-statistics/challenges/temperature-predictions/problem # - Take care with 2-D: you may need to use the correlation in the variables to improve the fit! # %matplotlib inline from IPython.core.display import display, HTML import matplotlib.pyplot as plt import matplotlib.dates as mdates from pylab import rcParams import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas_profiling from pylab import rcParams rcParams['figure.figsize'] = 10, 6 plt.rc("font", size=14) # + import os import calendar import collections from collections import defaultdict, OrderedDict from scipy.stats import linregress from datetime import datetime from dateutil.relativedelta import * import itertools from dateutil import parser import pandas as pd pd.set_option('display.max_columns', 100) import numpy as np import scipy import statsmodels import statsmodels.api as sm import statsmodels.formula.api as smf import statsmodels.tsa.api as smt import sympy import requests from bs4 import BeautifulSoup from scipy.stats import mode from scipy import interp from sklearn import linear_model from sklearn import preprocessing, linear_model, metrics from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.cross_validation import cross_val_score from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import GridSearchCV from sklearn.multiclass import OneVsRestClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score, f1_score, classification_report, roc_curve, auc from sklearn.pipeline import Pipeline, FeatureUnion # - df = pd.read_clipboard(header = 0) display(df) # use the full set from HackerRank df = df_hacker_full pd.to_numeric(df_answer) df_answer = pd.read_clipboard(header=None) #[1] display(df_answer) # ## Treat missing values in a standard way # + df2 = df.copy(deep = True) df2[["tmax_clean", "tmin_clean"]] = df[["tmax", "tmin"]].replace(to_replace= r'(?i)missing', value=np.nan, regex= True) df2["tmax_clean"] = df2["tmax_clean"].apply(pd.to_numeric) df2["tmin_clean"] = df2["tmin_clean"].apply(pd.to_numeric) df2.head(5) # - # ### Convert to datetime index # + d = dict(zip(pd.date_range('2000-01-01', freq='M', periods=12).strftime('%B'), range(1,13))) df2["month_number"] = df2["month"].replace(d) df2["yyyy"] = df2["yyyy"].map(str) df2["date_time"] = df2['month'] + "-" + df2["yyyy"] df2["date_time"] = df2["date_time"].apply(lambda x: pd.to_datetime(x,format = '%B-%Y')) df2.set_index("date_time", inplace = True) pandas_profiling.ProfileReport(df2[["tmax_clean", "tmin_clean", "month_number"]]) # - # # Correlation among the Temperature Min and Max Values df2.plot(x='tmin_clean', y='tmax_clean', style='o') # # Perform Linear interpolation [tmin,tmax] # - leverage the correlation in the data # + x = df2.dropna(how='any',subset= ["tmin_clean", "tmax_clean"]).tmin_clean.values y = df2.dropna(how='any',subset= ["tmin_clean", "tmax_clean"]).tmax_clean.values stats = linregress(x, y) m = stats.slope b = stats.intercept print(m,b) fig2, ax2 = plt.subplots(figsize=(10,6)) plt.scatter(x, y) plt.plot(x, m * x + b, color="red") # I've added a color argument here ax2.set_title("Temperature Correlation (Dropouts Removed)") ax2.set_ylabel("Temp_Max") ax2.set_xlabel("Temp_Min") plt.tight_layout() plt.savefig("TempCorrelation.png") plt.show() my_dict = OrderedDict() for idx, row in df2.iterrows(): if (("Missing" in row["tmin"]) & (not "Missing" in row["tmax"])): my_dict[row["tmin"]] = 1/float(m)*(row["tmax_clean"] - b) if (("Missing" in row["tmax"]) & (not "Missing" in row["tmin"])): my_dict[row["tmax"]] = m * row["tmin_clean"] + b print(my_dict) my_list = list(my_dict.values()) print() for elem in my_list: print(elem) df_answer["my_answer"] = my_list df_answer["delta"] = df_answer[0] - df_answer["my_answer"] df_answer # - # ## SciKit Learn Fit based on [month_number, tmin, tmax] ignoring the year. # - Use data without Nan's as the training set # - Use the tmin = nan as those to predict based on [month_number, tmax] # - Use the tmax = nan as those to predict based on [month_number, tmin] # + from sklearn.linear_model import LinearRegression df_train = df2.dropna(how='any',subset= ["tmin_clean", "tmax_clean"]) df_train = df_train[["month_number", "tmax_clean", "tmin_clean"]] df_test = df2[df2[["tmin_clean", "tmax_clean"]].isnull().any(axis=1)] df_test = df_test[["month_number", "tmax_clean", "tmin_clean"]] X_train = df_train[["month_number", "tmax_clean"]].values Y_train = df_train["tmin_clean"].values X_mintest = df_test[df_test["tmin_clean"].isnull()][["month_number", "tmax_clean"]].values reg = LinearRegression() model = reg.fit(X_train, Y_train) tmin_predict = model.predict(X_mintest) X_train = df_train[["month_number", "tmin_clean"]].values Y_train = df_train["tmax_clean"].values X_maxtest = df_test[df_test["tmax_clean"].isnull()][["month_number", "tmin_clean"]].values reg = LinearRegression() model = reg.fit(X_train, Y_train) tmax_predict = model.predict(X_maxtest) df_final = df2.copy(deep = True) df_final.loc[df_final["tmax_clean"].isnull(),"tmax_hat"] = tmax_predict df_final.loc[df_final["tmin_clean"].isnull(),"tmin_hat"] = tmin_predict my_dict = OrderedDict() for idx, row in df_final.iterrows(): if "Missing" in row["tmin"]: my_dict[row["tmin"]] = row["tmin_hat"] if "Missing" in row["tmax"]: my_dict[row["tmax"]] = row["tmax_hat"] my_list = list(my_dict.values()) print() for elem in my_list: print(elem) # - (df_answer.dtype) df_answer["sckit_answer"] = my_list df_answer["delta"] = df_answer[0] - df_answer["sckit_answer"] df_answer # # Apply Pandas built in interpolation methods # - https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.interpolate.html # # Types of missing data: # - if upsampling is required: # upsampled = df.series.resample('D') # - if the dates are missing # df = df.reindex(pd.date_range("2011-01-01", "2011-10-31"), fill_value="NaN") # - if the data contains duplicates: # df.drop_duplicates(keep = 'first', inplace = True) # # - forward fill copies values forward. Limit will impact how big a gap you will fill # https://chrisalbon.com/machine_learning/preprocessing_dates_and_times/handling_missing_values_in_time_series/ # https://chrisalbon.com/python/data_wrangling/pandas_missing_data/ # # - methods: {‘linear’, ‘time’, ‘index’, ‘values’, ‘nearest’, ‘zero’, 'slinear’, ‘quadratic’, ‘cubic’, ‘barycentric’, # ‘krogh’, ‘polynomial’, ‘spline’, ‘piecewise_polynomial’, ‘from_derivatives’, ‘pchip’, ‘akima’} # # - method='quadratic' if you are dealing with a time series that is growing at an increasing rate. # - method='pchip' if you have values approximating a cumulative distribution function. # - method='akima': to fill missing values with goal of smooth plotting. # + df_interp = df2.copy(deep = True) df_interp["tmin_hat"] = df_interp["tmin_clean"].interpolate(axis=0, method='time',\ limit=None, inplace=False, limit_direction='forward', limit_area=None, downcast=None).ffill().bfill() df_interp["tmax_hat"] = df_interp["tmax_clean"].interpolate(axis=0, method='time',\ limit=None, inplace=False, limit_direction='forward', limit_area=None, downcast=None).ffill().bfill() df_interp[["tmin", "tmin_clean", "tmin_hat", "tmax", "tmax_clean", "tmax_hat"]].head(7) # - df_interp[["tmax_hat", "tmin_hat"]] = df_interp[["tmax_clean", "tmin_clean"]].interpolate(method='polynomial', order=2).ffill().bfill() df_interp[["tmin", "tmin_clean", "tmin_hat", "tmax", "tmax_clean", "tmax_hat"]].head(7) # + df_interp = df2.copy(deep = True) df_interp["tmin_hat"] = df_interp["tmin_clean"].interpolate(axis=0, method='time',\ limit=None, inplace=False, limit_direction='forward', limit_area=None, downcast=None).ffill().bfill() df_interp["tmax_hat"] = df_interp["tmax_clean"].interpolate(axis=0, method='time',\ limit=None, inplace=False, limit_direction='forward', limit_area=None, downcast=None).ffill().bfill() df_interp[["tmin", "tmin_clean", "tmin_hat", "tmax", "tmax_clean", "tmax_hat"]].head(7) # - # ## Impose constraints # - 1908 <=time <= 2013 # - -75 <= Tmax/Tmin <= 75 df_interp["temp_constraint_v"] = df_interp["tmax_hat"]/df_interp["tmin_hat"] df_interp[abs(df_interp["temp_constraint_v"]) > 75] # + df_interp[['tmin', 'tmin_hat']].plot(figsize=(12, 8)) plt.show() df_interp[['tmax', 'tmax_hat']].plot(figsize=(12, 8)) plt.show() df_interp["min_resid"] = df_interp['tmin_clean'] - df_interp['tmin_hat'] df_interp["min_resid"].plot(figsize=(12, 8)) plt.show() df_interp["max_resid"] = df_interp['tmax_clean'] - df_interp['tmax_hat'] df_interp["max_resid"].plot(figsize=(12, 8)) plt.show() # - # Print the missing values df_final = df_interp[df_interp['tmin'].str.startswith("Missing") | df_interp['tmax'].str.startswith("Missing")] df_final my_dict = OrderedDict() for idx, row in df_final.iterrows(): if "Missing" in row["tmin"]: my_dict[row["tmin"]] = row["tmin_hat"] if "Missing" in row["tmax"]: my_dict[row["tmax"]] = row["tmax_hat"] #print(my_dict) my_list = list(my_dict.values()) print() for elem in my_list: print(elem) df_answer["my_answer"] = my_list df_answer["delta"] = df_answer[0] - df_answer["my_answer"] df_answer df2.head(10) df_interp df_hacker_full = df_interp[["yyyy", "month", "tmax", "tmin"]].reset_index() df_hacker_full.drop("date_time", inplace = True, axis = 1) df_hacker_full df_answer
Tutorials/Interpolation/Practice_interp_old.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.5 64-bit (''asg'': conda)' # name: python3 # --- # # Inference # **Predict the timestamps for possible subtitles of your input audio** # + import os import warnings import librosa import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.utils.data as data from catalyst.dl import SupervisedRunner, CallbackOrder, Callback, CheckpointCallback from fastprogress import progress_bar # - from utils import check_type, extract_audio, mono_load, get_duration from config import InferenceConfig as IC from csrc.configurations import DatasetConfig as DC from csrc.configurations import ModelConfig as MC # + # For better debugging os.environ["CUDA_LAUCH_BLOCKING"] = "1" # - # ## User configurations ### IMPORTANT PARAM PERIOD = 5# 10, 5, 3, 2, 1 ### IMPORTANT PARAM THRESHOLD = 0.8# 0.5, 0.9 # + # Those need no modification. # Audio Sample rate. DO NOT change. SR = DC.dataset_sample_rate # Tag encoding. DO NOT change. CODING = IC.coding_map # + # Set and audiohandler your input file. ### Target file for inferencing. TARGET_FILE_PATH = "./src/src-test/src-test.wav" TARGET_FILE_PATH = extract_audio(TARGET_FILE_PATH) if check_type(TARGET_FILE_PATH) else TARGET_FILE_PATH ### Output csv file name. OUTPUT_FILE_NAME = "test" OUTPUT_FILE = f"./inf/{OUTPUT_FILE_NAME}.csv" OUTPUT_SOURCE_FILE = f"./inf/{OUTPUT_FILE_NAME}-all.csv" if os.path.exists(OUTPUT_FILE): print("!Warning: Output file already exists, are you sure to rewrite the file?") # Target model used for this prediction. Must be corresponding to the model during the training process. ### Set the model file path. The file path must be valid MODEL_PATH = "./train/logs/sp2-32000hz/checkpoints/best.pth" print(f"USING MODEL: {MODEL_PATH}") # - # ## Dataset from csrc.dataset import PANNsDataset # ## Model from csrc.models import PANNsCNN14Att, AttBlock # ## Inference Settings device = torch.device('cuda:0') model = PANNsCNN14Att(**MC.sed_model_config) model.att_block = AttBlock(2048, 2, activation='sigmoid') model.att_block.init_weights() model.load_state_dict(torch.load(MODEL_PATH, map_location(torch.device("cpu")))['model_state_dict']) model.to(device) model.eval() y, _ = mono_load(TARGET_FILE_PATH) dataframe = pd.DataFrame() # ## Prediction begin! # + from utils import get_duration audio_duration = get_duration(audio_file_path=TARGET_FILE_PATH, y=y, sr=SR) print(f"Audio file duration: {audio_duration}s") # + audios = [] len_y = len(y) start = 0 end = PERIOD * SR # Split audio into clips. while True: y_batch = y[start:end].astype(np.float32) if len(y_batch) != PERIOD * SR: y_pad = np.zeros(PERIOD * SR, dtype=np.float32) y_pad[:len(y_batch)] = y_batch audios.append(y_pad) break start = end end += PERIOD * SR audios.append(y_batch) # Get tensors arrays = np.asarray(audios) tensors = torch.from_numpy(arrays) estimated_event_list = [] global_time = 0.0 for image in progress_bar(tensors): image = image.view(1, image.size(0)) image = image.to(device) with torch.no_grad(): prediction = model(image) framewise_outputs = prediction["framewise_output"].detach( ).cpu().numpy()[0] thresholded = framewise_outputs >= THRESHOLD for target_idx in range(thresholded.shape[1]): if thresholded[:, target_idx].mean() == 0: pass else: detected = np.argwhere(thresholded[:, target_idx]).reshape(-1) head_idx = 0 tail_idx = 0 while True: if (tail_idx + 1 == len(detected)) or ( detected[tail_idx + 1] - detected[tail_idx] != 1): onset = 0.01 * detected[ head_idx] + global_time offset = 0.01 * detected[ tail_idx] + global_time onset_idx = detected[head_idx] offset_idx = detected[tail_idx] max_confidence = framewise_outputs[ onset_idx:offset_idx, target_idx].max() mean_confidence = framewise_outputs[ onset_idx:offset_idx, target_idx].mean() estimated_event = { "speech_recognition": CODING[target_idx], "start": onset, "end": offset, "max_confidence": max_confidence, "mean_confidence": mean_confidence, } estimated_event_list.append(estimated_event) head_idx = tail_idx + 1 tail_idx = tail_idx + 1 if head_idx >= len(detected): break else: tail_idx += 1 global_time += PERIOD prediction_df = pd.DataFrame(estimated_event_list) # - # ## Post process # + # Secure output file offset: max offset should be less than audio duration. max_offset = prediction_df.iloc[-1].end if max_offset > audio_duration: prediction_df.iloc[-1].end = audio_duration # - prediction_df[prediction_df.speech_recognition=="speech"].to_csv(OUTPUT_FILE, index=False) prediction_df.to_csv(OUTPUT_SOURCE_FILE, index=False)
inference.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/ashesm/ISYS5002_PORTFOLIO/blob/main/sql_shell.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="mbsVgk4dW_nz" # #SQL via Python # # In this notebook we discuss all the CRUD operations on a SQLite 3 database in Python. # # We assume some basic understanding ot SQL # # ## Import the library # + id="LPimUgLJW-zI" import sqlite3 # + [markdown] id="Hw8dIXJ-XmD3" # ## Create a connection # # We use the connect method and pass the name of the database # + id="mrad4SnyXxgQ" conn = sqlite3.connect("mytest.db") # + [markdown] id="mejA7Nv4XyPH" # ## Create a cursor object # # A cursor acts a middleware between a connection and SQL query # + id="ZTlVz29LYR9b" cursor = conn.cursor() # + [markdown] id="Sn6PJmYtYdWr" # # Create Table # # Use a common 'pattern' # # 1. Create a SQL command as a string # 2. User cursor to execture the command # 3. If needed fetch the results # + id="SIGT5zH0Ykd4" query = """ CREATE TABLE USER ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER ); """ # + id="xuIEUIhRR-GK" colab={"base_uri": "https://localhost:8080/"} outputId="21ed8de0-156f-4a35-a140-cdb335e9774d" cursor.execute(query) # + [markdown] id="pn3Pj3hlYsBK" # # Insert into Table # + id="sDDF56NqYy1D" query = "INSERT INTO user VALUES (1, 'Michael', 21);" # + id="dKkHLZe8TF_L" colab={"base_uri": "https://localhost:8080/"} outputId="56866720-f4f3-4fee-c8cf-625d17348119" cursor.execute(query) # + [markdown] id="0q9-ZbAHY30U" # ## Fetching Data # + id="6fft_Fo-Y6TM" colab={"base_uri": "https://localhost:8080/"} outputId="bbe6eff3-522f-4857-8c2d-1cce91a3af41" query = "SELECT * FROM user;" cursor.execute(query) # + id="nEl6VMWoTfZ-" colab={"base_uri": "https://localhost:8080/"} outputId="2464e772-8f13-4d04-f3f6-a557f4dcd58f" result = cursor.fetchall() result[0] # + [markdown] id="CMhqzLZbY8r-" # ## Updating Data # + id="ZYniV-zoTd-z" query = """ UPDATE user SET name = "Batman" WHERE name = 'Michael'; """ # + id="ojzfQW6vY_uX" colab={"base_uri": "https://localhost:8080/"} outputId="14b80d79-85be-494c-8296-4a492c728efd" conn.execute(query) # + id="x0TCc-nsUi07" colab={"base_uri": "https://localhost:8080/"} outputId="ce1338f4-e98b-4412-da6f-9c379c32bbb6" query = "SELECT * FROM user;" cursor.execute(query) result = cursor.fetchall() result # + [markdown] id="-tk5M9E9ZBPO" # ## Delete Data # + id="VI52gWODZCsF" colab={"base_uri": "https://localhost:8080/"} outputId="39be502e-9f19-440a-9897-52746af34229" query = """ DELETE FROM user WHERE name = 'Batman'; """ conn.execute(query) query = "SELECT * FROM user;" cursor.execute(query) result = cursor.fetchall() result # + [markdown] id="ZqFcuamRZJ9W" # ## View Schema # + id="1Ovfl-_OZOPk" colab={"base_uri": "https://localhost:8080/"} outputId="752df13c-ed47-4241-b902-c7effa29f8fd" query = "SELECT name FROM sqlite_master WHERE type = 'table';" cursor.execute(query) result = cursor.fetchall() result # + id="B6-fiF01VuIi" colab={"base_uri": "https://localhost:8080/"} outputId="e1bab3b4-72de-49ec-ead2-25b5277d2d82" def get_tables(cursor): query = "SELECT name FROM sqlite_master WHERE type = 'table';" cursor.execute(query) result = cursor.fetchall() tables = [] for item in result: tables.append(item[0]) return(tables) get_tables(cursor) # + id="4A69GZERWdnh" colab={"base_uri": "https://localhost:8080/"} outputId="84e121f9-e10e-41c4-d8f1-e075a9bd3185" for table in get_tables(cursor): cursor.execute("PRAGMA table_info('%s')" % table) result = cursor.fetchall() print(table + ":" + str(result) + '\n') # + [markdown] id="-ldwT9WyZE-2" # ## Delete Table # + id="cyFWke0AZHI-"
sql_shell.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # <font color ='0c6142' size=6)> Chemistry </font> <font color ='708090' size=3)> for Technology Students at GGC </font> # *** # # Introduction to Notebooks # This notebook will be used to probe concepts and solve problems in chemistry. You will refer to the [online textbook, Chemistry-2e](https://openstax.org/details/books/chemistry-2e), published by [OpenStax](https://openstax.org/), and other sources. # # Your __investigation__ in Chemistry will be _with this notebook_ combined with your __development__ as an information technology student. The combination is not arbitrary: many of the tools used by research chemists, indeed scientists in any discipline, are based on information technology. # # Thus, a scientist with advanced computer skills has access to avenues otherwise inaccessible, and a computer programmer who has experience with domains in science such as biology or chemistry can offer extra value to industry. At the end of this course - no matter what your direction - you will be faster, stronger, and more insightful. # # # Let's start with an introduction to a few tools. # *** # ### Python # We will be using a very intuitive, very popular, very powerful scripting language: Python. # # Let's look at a small and simple demonstration. In the cell below, type `1+1` and then `shift` + `enter`. 1+1 # So you can see that the cells (which have Python running in the background) recognize numbers and some(?) mathematical operations. Try more! # # What about words? Ok. Not so simple. Computers recognize words as strings of characters or labels. We will deal with those soon. For now, let's get our first look at a string. # # In the cell below, type the following code: # # ` # print('Hello, World!') # ` # # and then `shift` + `enter`. # Now try it without the quotes. Or try it with double quotes: `"`, instead of single quotes `'`. # These two exercises are just a taste, and may be too simple to grab your interest. Hold on - we will get into some really elegant tools here, soon. # *** # Let's go to [Chapter 1](../../chapters/ch01/sections/chem4tech01_01.ipynb), or # back to [Table of Contents](../../../chem4tech.ipynb)
chapters/ch00/.ipynb_checkpoints/chem4tech_00-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- region = 'us-east-2' endpoint='ENDPOINT' threshold = 0.5 bucket = 'BUCKET' prefix = 'kubeflow-batch/in' import boto3 client = boto3.client('sagemaker-runtime', region_name=region) import numpy as np test_data = np.load('test_data.npy') test_labels = np.load('test_labels.npy') # We need a JSON serializer, so let's reuse one from the [SageMaker Python SDK](https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/predictor.py). I've copied relevant bits of the code below, but we could install the SageMaker Python module and import it instead. # + import json import six def _ndarray_to_list(data): """ Args: data: """ return data.tolist() if isinstance(data, np.ndarray) else data def _json_serialize_from_buffer(buff): """ Args: buff: """ return buff.read() def json_serial(data): if isinstance(data, dict): # convert each value in dict from a numpy array to a list if necessary, so they can be # json serialized return json.dumps({k: _ndarray_to_list(v) for k, v in six.iteritems(data)}) # files and buffers if hasattr(data, "read"): return _json_serialize_from_buffer(data) return json.dumps(_ndarray_to_list(data)) # - def predict(data): response = client.invoke_endpoint( EndpointName = endpoint, Body=json_serial(data), ContentType='application/json' ) body = response['Body'].read().decode() j = json.loads(body) return j['predictions'][0][0] preds = [] for i in range(0, len(test_labels)): pred = predict(test_data[i]) label = test_labels[i] if pred > threshold: pred = 1 else: pred = 0 preds.append(pred) import pandas as pd from sklearn.metrics import confusion_matrix,classification_report confusion_matrix(preds, test_labels) print(classification_report(preds, test_labels)) # ## Transform to JSON # # In preparation for the next section, we're going to save our data in JSON format. json_records = [] for i in range(0, len(test_labels)): j = json_serial(test_data[i]) json_records.append(j) with open("batch_records.json", "w") as json_file: for j in json_records: json_file.write(j) json_file.write("\n") # + import os s3 = boto3.client('s3') s3.upload_file('batch_records.json', bucket, os.path.join(prefix, 'batch_records.json'))
static/files/customer_churn_inference.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # # Semantic Phasor Demo # # This notebook shows an interesting property of phasors when applied to textual data. We hope this will convince readers that this is a promising approach to creating vector representations of documents. # # ## What the heck is a phasor? # # A phasor is just a complex number, but it has an interpretation built in: it represents *both* the amplitude and the phase of a sine wave of a fixed frequency. That is, it represents both how tall the wave is, and also where the wave starts (in the middle, up high, or down low). # # The output of a Fourier transform for a particular frequency is the same thing as a phasor. So in a sense "doing stuff with phasors" is just another way of saying "Fourier analysis." But we talk about them here as phasors because it emphasizes this: # # ### Phasors can be added and subtracted just like vectors. # # When you add two phasors for a given frequency together, you get a new phasor. It represents a wave with the same frequency, but with a different amplitude, and a different phase offset. There's a nice way of visualizing the geometry of this operation -- this is from the Wikipedia article on [phasors](https://en.wikipedia.org/wiki/Phasor): # # <img src="assets/Sumafasores.gif" alt="An image showing the geometry of phasor addition." width="200px" /> # # The purple phasor is the sum of the red and blue phasors. Adding together wave signals seems a bit complicated, but the underlying geometry is the same as ordinary vector addition. It's just that the vectors are also rotating at a fixed rate around the origin. # # Because you can add and subtract phasors just like vectors, you can combine them with other vector-like objects -- including word embedding vectors. As long as the Fourier transform is run over dimensions that are orthogonal to one another, the resulting vectors are composable in the same way as word embeddings. # # ## What does this notebook do with phasors? # # We wanted to see if there are any obvious patterns that phasors preserve. So we decided to see what happens when you "rotate" a text. # # Suppose you sliced off the first few hundred words of a text, tacked them on at the end, and then repeated that process until you were back where you began. It's as if you laid the words of the text out on a big wheel and started spinning it. Early rotations would start near the beginning of the original story, and end near the beginning again. Middle rotations would start in the middle of the original story, and end in the middle again. The very last one would be identical to the original. # # This notebook shows what happens if you take those rotated texts and do the following: # # 1. Convert them into word vectors. # 2. Perform Fourier transforms over each dimension, and converting the resulting phasors into ordinary vectors, which represent whole documents. # 3. Pass the resulting document vectors to a UMAP model, which tries to preserve the topology of its input in a lower dimension. # # What will it look like? Let's see! # + import itertools import spacy import numpy import umap import matplotlib.pyplot as plt # %matplotlib inline en = spacy.load('en_core_web_md') # - # After a few imports, we load two files -- Frankenstein and Hamlet, both from Project Gutenberg -- and parse them using `spacy`. We use `spacy` because it provides pre-trained word vectors. with open('assets/frank.txt') as ip: frank = ip.read() with open('assets/ham.txt') as ip: ham = ip.read() frank_sp = en(frank) ham_sp = en(ham) # Here are some utility functions. # # - `text_vecs` takes the parsed text and generates the vectors, optionally rotating them by the number of words given by `offset`. # - `group_sum` chunks the text up and sums the chunks, which makes the Fourier transform faster without losing too much accuracy. (Ideally, we'd like to do the transform over the raw data, but that takes a lot of time.) # - `fft_vecs` takes the vectors for a text, performs the Fourier transform, and packages the result into one long vector. # + def text_vecs(text_sp, offset=0): a = text_sp[offset:] b = text_sp[:offset] return numpy.array([t.vector.reshape(-1) for part in [a, b] for t in part]) def group_sum(vec, n_groups): size = len(vec) / n_groups ends = [] for i in range(1, n_groups + 1): ends.append(int(size * i)) ends[-1] = len(vec) sums = [] start = 0 for e in ends: sums.append(vec[start:e].sum()) start = e return numpy.array(sums) def fft_vecs(vecs, n_bands=10): fft_cols = [] n_groups = 1 while n_groups < n_bands * 4: n_groups *= 2 for col in range(vecs.shape[1]): vec = vecs[:, col] vec = group_sum(vec, n_groups) fft = numpy.fft.rfft(vec) fft_cols.append(fft[:n_bands]) return numpy.array(fft_cols).reshape(-1) # - # Here's a quick check to make sure the first function isn't doing something obviously wrong. frank_vecs = numpy.array([t.vector.reshape(-1) for t in frank_sp]) assert (text_vecs(frank_sp, 0) == frank_vecs).all() # ## Step 1 # # Now we generate the rotated word vectors. These are lists of matrices with 300 columns and VERYMANY rows, where VERYMANY is the number of words in the text. We're doing it in a slow way, so it takes a little while. frank_rotations = (text_vecs(frank_sp, offset) for offset in range(0, len(frank_sp), (len(frank_sp) // 100) + 1)) ham_rotations = (text_vecs(ham_sp, offset) for offset in range(0, len(ham_sp), (len(ham_sp) // 100) + 1)) rotations = itertools.chain(frank_rotations, ham_rotations) # ## Step 2 # # Now we do the fourier transforms. This also takes a little while. rot_vecs_fft = [fft_vecs(r) for r in rotations] # We want to hold on to a copy of the original fourier transform data just in case, so we give it a new name for manipulation. If we ever want to reset anything below without having to re-do the fourier transforms, we can just run the below cell again. rot_vecs = rot_vecs_fft # Now we unpack the fourier transformed data into regular vectors. This means decomposing the complex numbers into pairs of regular floating point numbers. For our purposes, this is fine, because we aren't doing any multiplication. # + rot_vecs = [[(x.real, x.imag) for x in arr] for arr in rot_vecs] rot_vecs = [[k for i_j in arr for k in i_j] for arr in rot_vecs] rot_vec_array = numpy.array(rot_vecs) rot_vec_array.shape # - # ## Step 3 # # Finally, we pass the resulting document vectors to UMAP. To review, right now, we have 200 vectors of 6000 dimensions each. Each vector represents one document, and each document is a version of either *Frankenstein* or *Hamlet* rotated by some number of words. # # We want to see how `UMAP` lays out these vectors. Without getting into details, UMAP is a very useful algorithem that takes points in a high-dimensional space and tries to preserve the topology of those points in a low-dimensional space. This is different from more familiar alogirthms like t-SNE, which only try to preserve distance; UMAP actually assumes that the input data has an overall shape, and does its best to reproduce that same shape in a lower dimension. # # What shape will we see? um = umap.UMAP(n_neighbors=5) vis = um.fit_transform(rot_vec_array) plt.gca().axis('equal') plt.scatter(vis[:, 0], vis[:, 1], c=[i / len(vis) for i in range(len(vis))], cmap='plasma') # UMAP has done a great job of recreating the topology of the original data. The data was generated by rotation, and so it has given us circles! # # This doesn't prove that phasors will solve any real-world problems. But it does show that they do a good job of preserving certain information about the relative position of semantic peaks and troughs in documents. And it strongly suggests that they will help find duplicate documents without being overly sensitive to front- and end-matter. Since the overall peaks and troughs of two duplicates will be the same, any differences in offset will show up as small displacements around a circle.
notebooks/semantic-phasor-demo.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Techno-economic analysis # [TEA](../TEA.txt) objects can perform cashflow analysis on a [System](../System.txt) object and arguments for cashflow analysis. These include arguments such as operating days, lang factor, and income tax, as well as arguments for taking into account startup operation, construction schedule, and capital cost financing. # ### Inhereting from TEA objects # Depending on the rigour and flexibility of the techno-economic analysis, different parameters may be needed to calculate total depreciable capital (TDC), fixed capital investment (FCI), and fixed operating cost (FOC). For this reason, the TEA object is left as an *abstract class* with *abstract methods* `_TDC`, `_FCI`, and `_FOC`. Here is an example TEA subclass from the lipidcane biorefinery design for the co-production of ethanol and biodiesel: # + import biosteam as bst import numpy as np class LipidcaneTEA(bst.TEA): """ Create a LipidcaneTEA object for techno-economic analysis of a biorefinery [1]_. Parameters ---------- system : System Should contain feed and product streams. IRR : float Internal rate of return (fraction). duration : tuple[int, int] Start and end year of venture (e.g. (2018, 2038)). depreciation : str 'MACRS' + number of years (e.g. 'MACRS7'). operating_days : float Number of operating days per year. income_tax : float Combined federal and state income tax rate (fraction). lang_factor : float Lang factor for getting fixed capital investment from total purchase cost. If no lang factor, estimate capital investment using bare module factors. startup_schedule : tuple[float] Startup investment fractions per year (e.g. (0.5, 0.5) for 50% capital investment in the first year and 50% investment in the second). WC_over_FCI : float Working capital as a fraction of fixed capital investment. labor_cost : float Total labor cost (USD/yr). fringe_benefits : float Cost of fringe benefits as a fraction of labor cost. property_tax : float Fee as a fraction of fixed capital investment. property_insurance : float Fee as a fraction of fixed capital investment. supplies : float Yearly fee as a fraction of labor cost. maintenance : float Yearly fee as a fraction of fixed capital investment. administration : float Yearly fee as a fraction of fixed capital investment. References ---------- .. [1] <NAME>., <NAME>., & <NAME>. (2016). Techno-economic analysis of biodiesel and ethanol co-production from lipid-producing sugarcane. Biofuels, Bioproducts and Biorefining, 10(3), 299–315. https://doi.org/10.1002/bbb.1640 """ def __init__(self, system, IRR, duration, depreciation, income_tax, operating_days, lang_factor, construction_schedule, WC_over_FCI, labor_cost, fringe_benefits, property_tax, property_insurance, supplies, maintenance, administration): # Huang et. al. does not take into account financing or startup # so these parameters are 0 by default super().__init__(system, IRR, duration, depreciation, income_tax, operating_days, lang_factor, construction_schedule, startup_months=0, startup_FOCfrac=0, startup_VOCfrac=0, startup_salesfrac=0, finance_interest=0, finance_years=0, finance_fraction=0, WC_over_FCI=WC_over_FCI) self.labor_cost = labor_cost self.fringe_benefits = fringe_benefits self.property_tax = property_tax self.property_insurance = property_insurance self.supplies= supplies self.maintenance = maintenance self.administration = administration # The abstract _DPI method should take installed equipment cost # and return the direct permanent investment. Huang et. al. assume # these values are equal def _DPI(self, installed_equipment_cost): return installed_equipment_cost # The abstract _TDC method should take direct permanent investment # and return the total depreciable capital. Huang et. al. assume # these values are equal def _TDC(self, DPI): return DPI # The abstract _FCI method should take total depreciable capital # and return the fixed capital investment. Again, Huang et. al. # assume these values are equal. def _FCI(self, TDC): return TDC # The abstract _FOC method should take fixed capital investment # and return the fixed operating cost. def _FOC(self, FCI): return (FCI*(self.property_tax + self.property_insurance + self.maintenance + self.administration) + self.labor_cost*(1+self.fringe_benefits+self.supplies)) # - # ### Perform cash flow analysis # Create a TEA object from a system: # + tags=["nbval-ignore-output"] from biorefineries import lipidcane as lc lipidcane_tea = LipidcaneTEA(system=lc.lipidcane_sys, IRR=0.15, duration=(2018, 2038), depreciation='MACRS7', income_tax=0.35, operating_days=200, lang_factor=3, construction_schedule=(0.4, 0.6), WC_over_FCI=0.05, labor_cost=2.5e6, fringe_benefits=0.4, property_tax=0.001, property_insurance=0.005, supplies=0.20, maintenance=0.01, administration=0.005) lipidcane_tea.show() # Print TEA summary at current options # Ignore the warnings, these are taken care of internally. # - # Retrieve complete cashflow analysis as a DataFrame object: lipidcane_tea.get_cashflow_table() # ### Find production cost, price, and IRR # Find production cost: products = [bst.main_flowsheet('ethanol'), bst.main_flowsheet('biodiesel')] costs = lipidcane_tea.production_costs(products)# USD/yr np.round(costs / 1e6) # million USD / yr # Solve for the price of a stream at the break even point: feed = bst.main_flowsheet('lipidcane') price = lipidcane_tea.solve_price(feed) # USD/kg round(price, 5) # Solve for the IRR at the break even point: lipidcane_tea.IRR = lipidcane_tea.solve_IRR() lipidcane_tea.show() # Note that the cashflow table is created up to date: lipidcane_tea.get_cashflow_table() # ### System report # Save stream tables, utility requirements, itemized costs, TEA results, and a cash flow table: # + # Try this on your computer and open excel: # lc.lipidcane_sys.save_report('Lipidcane report.xlsx') # Ignore the warning. The flowsheet is saved on the excel file # as a really big image and Python thinks it could be a # malicious file cause its so big.
docs/tutorial/Techno-economic_analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import argparse,os import pandas as pd import os.path as osp import numpy as np import glob import seaborn as sns import matplotlib.pyplot as plt K = 150 def histogram_intersection(h1, h2): set1 = set(h1[:K]) set2 = set(h2[:K]) commonElems = len(set1.intersection(set2)) return commonElems/K def plotCorrelationPlots(featureDF,feature): corr = featureDF.corr(method=histogram_intersection) # Generate a mask for the upper triangle mask = np.triu(np.ones_like(corr, dtype=bool)) # Set up the matplotlib figure f = plt.figure(figsize=(45, 35)) # Generate a custom diverging colormap cmap = sns.diverging_palette(250, 20, as_cmap=True) #cmap = sns.color_palette("Greens", as_cmap=True) # Draw the heatmap with the mask and correct aspect ratio ax = sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0, square=False, linewidths=.5, cbar_kws={"shrink": 0.8}) #g.ax_heatmap.set_xticklabels(g.ax_heatmap.get_xmajorticklabels(), fontsize = 35) #ax.figure.axes[-1].yticks.set_size(150) #print(ax.figure.axes[-1].yaxis.get_major_ticks()) cbar = ax.collections[0].colorbar # here set the labelsize by 20 cbar.ax.tick_params(labelsize=55,label2On='bold') plt.xticks(rotation=90,weight='bold',fontsize=35) plt.yticks(rotation=0,weight='bold',fontsize=35) for tick in cbar.ax.yaxis.get_major_ticks(): #print(tick.label) tick.label.set_fontweight('bold') plt.savefig(feature+"_correlation.png",fmt='png',bbox_to_inches='tight') featureDF.to_csv(feature+".csv",index=False) def computeCorrelationCoeffs(dfDict): desList = dfDict.keys() areaDF = None for i,des in enumerate(desList): dfList = dfDict[des] areaSIDrank = dfList[0]["sid"] #print(areaSIDrank) if areaDF is None: areaDF = pd.DataFrame({des : areaSIDrank.to_list()}) else: #areaDF.insert(i,des,areaSIDrank) #print(areaSIDrank) areaDF[des] = areaSIDrank.to_list() #plotCorrelationPlots(areaDF,'area') #plotCorrelationPlots(delayDF,'delay') #plotCorrelationPlots(adpDF,'ADP') plotCorrelationPlots(areaDF,'AND') INPUT_CSV_FOLDER = "/home/abc586/OPENABC_DATASET/graphml/postProcessing/final" csvFiles = glob.glob(osp.join(INPUT_CSV_FOLDER,"*.csv")) dfDict = {} for csv_file in csvFiles: #print(csv_file) desName = osp.basename(csv_file).split("processed_")[-1].split(".csv")[0] df = pd.read_csv(csv_file) df['desName'] = desName df_area = df.sort_values(['AND'],ascending=True) dfDict[desName] = [df_area] #df['ADP'] = df['area']*df['delay'] #df['AIGcells'] = df['AND']+df['NOT'] computeCorrelationCoeffs(dfDict)
analysis/findCommonTopKSynth.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.5 64-bit (''hf'': conda)' # name: python3 # --- # # Huggingface Sagemaker-sdk - Deploy 🤗 Transformers for inference # # 1. [Introduction](#Introduction) # 2. [Deploy a trained Hugging Face Transformer model on to SageMaker for inference](#Deploy-a-trained-Hugging-Face-Transformer-model-on-to-SageMaker-for-inference) # a. [Deploy the model directly after training](#Deploy-the-model-directly-after-training) # b. [Deploy the model using `model_data`](#Deploy-the-model-using-model_data) # 3. [Deploy one of the 10 000+ Hugging Face Transformers to Amazon SageMaker for Inference](#Deploy-one-of-the-10-000+-Hugging-Face-Transformers-to-Amazon-SageMaker-for-Inference) # # # Welcome to this getting started guide, we will use the new Hugging Face Inference DLCs and Amazon SageMaker Python SDK to deploy two transformer model for inference. # In the first example we deploy a trained Hugging Face Transformer model on to SageMaker for inference. # In the second example we directly deploy one of the 10 000+ Hugging Face Transformers from the [Hub](https://huggingface.co/models) to Amazon SageMaker for Inference.< # ## API - [SageMaker Hugging Face Inference Toolkit](https://github.com/aws/sagemaker-huggingface-inference-toolkit) # # Using the `transformers pipelines`, we designed an API, which makes it easy for you to benefit from all `pipelines` features. The API is oriented at the API of the [🤗 Accelerated Inference API](https://api-inference.huggingface.co/docs/python/html/detailed_parameters.html), meaning your inputs need to be defined in the `inputs` key and if you want additional supported `pipelines` parameters you can add them in the `parameters` key. Below you can find examples for requests. # # **text-classification request body** # ```python # { # "inputs": "Camera - You are awarded a SiPix Digital Camera! call 09061221066 fromm landline. Delivery within 28 days." # } # ``` # **question-answering request body** # ```python # { # "inputs": { # "question": "What is used for inference?", # "context": "My Name is Philipp and I live in Nuremberg. This model is used with sagemaker for inference." # } # } # ``` # **zero-shot classification request body** # ```python # { # "inputs": "Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!", # "parameters": { # "candidate_labels": [ # "refund", # "legal", # "faq" # ] # } # } # ``` # !pip install "sagemaker>=2.48.0" --upgrade # ## Deploy a Hugging Face Transformer model from S3 to SageMaker for inference # # There are two ways on how you can deploy you SageMaker trained Hugging Face model from S3. You can either deploy it after your training is finished or you can deploy it later using the `model_data` pointing to you saved model on s3. # # ### Deploy the model directly after training # # If you deploy you model directly after training you need to make sure that all required files are saved in your training script, including the Tokenizer and the Model. # ```python # from sagemaker.huggingface import HuggingFace # # ############ pseudo code start ############ # # # create HuggingFace estimator for running training # huggingface_estimator = HuggingFace(....) # # # starting the train job with our uploaded datasets as input # huggingface_estimator.fit(...) # # ############ pseudo code end ############ # # # deploy model to SageMaker Inference # predictor = huggingface_estimator.deploy(initial_instance_count=1, instance_type="ml.m5.xlarge") # # # example request, you always need to define "inputs" # data = { # "inputs": "Camera - You are awarded a SiPix Digital Camera! call 09061221066 fromm landline. Delivery within 28 days." # } # # # request # predictor.predict(data) # # ``` # # ### Deploy the model using `model_data` # + from sagemaker.huggingface.model import HuggingFaceModel import sagemaker role = sagemaker.get_execution_role() # create Hugging Face Model Class huggingface_model = HuggingFaceModel( model_data="s3://hf-sagemaker-inference/model.tar.gz", # path to your trained sagemaker model role=role, # iam role with permissions to create an Endpoint transformers_version="4.6", # transformers version used pytorch_version="1.7", # pytorch version used py_version="py36", # python version of the DLC ) # - # deploy model to SageMaker Inference predictor = huggingface_model.deploy( initial_instance_count=1, instance_type="ml.m5.xlarge" ) # + # example request, you always need to define "inputs" data = { "inputs": "The new Hugging Face SageMaker DLC makes it super easy to deploy models in production. I love it!" } # request predictor.predict(data) # - # delete endpoint predictor.delete_endpoint()
sagemaker/10_deploy_model_from_s3/deploy_transformer_model_from_s3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # DECISION TREE # [Freq. asked MCQ] --> Root note (Main/source), Internal note( Middle), Leaf note(Terminal).\ # Entropy and GINI Index # GAIN, C4.5, C5.5 ALGORITHM ### IMPORTANT THEORY Qs --> Refer notes # - import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset=pd.read_excel("Linear regression 1.xlsx") x=dataset.iloc[:,:-1].values # when 'iloc[:,:-1]' is given, all the contents present in the row will be taken (since, ':' is given) and all the columns except the last will be taken since ':-1' is given --> This is defined as 'x'. *** NOTE: in 'iloc[:,:-1]', the ':' / first part inside the bracket represents rows and the last part implies columns. x y=dataset.iloc[:,-1].values # when 'iloc[:,1]' is given, all the contents present in the row will be taken (since, ':' is given) and ONLY last column will be taken since ':-1' is given --> This is defined as 'y'. y from sklearn.tree import DecisionTreeRegressor regressor=DecisionTreeRegressor(random_state=0) regressor.fit(x,y) ypred=regressor.predict(x) ypred plt.scatter(x,y, color='red') plt.plot(x, regressor.predict(x), color= 'blue') plt.xlabel('Package') plt.ylabel('Sales') plt.show()
Decision Tree.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] pycharm={"name": "#%% md\n"} # ## ANJUMSO # # Welcome to **ANJUMSO** - Annotated Jupyter Modelling Software. # # In order to run the code, please, install Anaconda 3.8: https://www.anaconda.com/products/individual # # After the installation, download (click "code" and choose .zip) the given repository and unpack it on your PC. # In the folder you will find the following files: # # 1. ANJUMSO.ipynb - JuPyTer notebook, that includes model and auxiliary functions # 2. Model Parameters.xlsx - Parameters of the model and model initial conditions that are stored as the Excel file. # You can edit it and this will result in the parameter change in the model. Each module of the model has its own # parameters and they are stored on the corresponding sheets of the Excel file # 3. Exp_data.xlsx - ANJUMSO can read and display experimental data for the comparison with the modeling results # # Excel files are to be stored in the same folder as the model. # # The example model is the model of platelet collagen receptor GPVI and is based on the models from: # Martyanov *et. al.* The Biophys. J. 2020; <NAME> *et. al.* Life 2020; Sveshnikova *et. al.* JTH 2016. # Model validation data were taken from: Dunster *et. al.* PLOS Comp. Biol. 2015; Poulter *et. al.* JTH 2017. # # To run the model - execute all of the code cells. You can change the parameters of the model dynamically # by passing the model the name of the module, the name of the parameter and the range of the parameter variation. # You can also change the variables that are displayed in the plots by changing of the corresponding variable number. # The instructions for these are given in the corresponding code parts. To run calculation click "Run interact". # # Parameter and variable description is given in the excel files. # # The model is solved using Python Scipy solve_ivp method, that utilizes LSODA. # # res1 and res2 - functions for plotting of the calculation results (see cell 3). Change the number of the variable, # calculated in solution based on the variables, returned by the model # (Variable numbers are given alongside "return"). Depending on the variable type (umol, # uMol, N), variables can be multiplied or denoted by Avogadro Constant (NA), Cytosol Volume (Volume), Plasma # Membrane Area (Area) etc. In the example cytosolic calcium concentration is depicted. # # # Enjoy! # + pycharm={"name": "#%%\n"} # Python libraries, used in the model import math import numpy as np import matplotlib.pyplot as plt import pandas as pd import ipywidgets as widgets from ipywidgets import interact_manual, interact from scipy.integrate import solve_ivp # import warnings # warnings.filterwarnings('ignore') # + pycharm={"name": "#%%\n"} # Model definition def GPVI_model(time, z, clustering_pars, kinases_pars, pars1, LAT_pars, calcium_pars, PAR_pars): # Model variable unpacking. Variables have to be in the same order, as they would be returned by the model. # This is critical GPVI, GPVI_Act, GPVI_Clust, Ip, Syk, Syk_A, LAT, LAT_p, PIP2, PIP3, PLCg2, PLCg2_A, IP3, \ Ca_cyt, Ca_dts, Ca_buf, buf,\ IP3R_n, IP3R_o, IP3R_a, IP3R_i1, IP3R_i2, IP3R_s,\ Serca2b_e1, Serca2b_e1_ca, Serca2b_e1_2ca, Serca2b_e2, Serca2b_e1_2ca_p, Serca2b_e2_2ca_p, Serca2b_e2_p,\ par1, sfllrn, thr, par1_a, gqgtp, gqgdp, plcgqgtp, plcgqgdp, par1_gq, \ gtp, par1_gqgtp, gdp, par1_gqgdp, plcgqgtppip2, plc, pip2, \ ca_ex, ip3r, \ orai1_closed, orai1_opened, stim1, stim1ca, ca_mit, phi, mptp_opened, mptp_closed = z CRP = kinases_pars['Pars_Horm']['CRP'] # GPVI clustering module parameters kf_act = clustering_pars['Pars_Horm']['Kf_Ligation'] kr_act = clustering_pars['Pars_Horm']['Kr_Ligation'] k1 = clustering_pars['Pars_Horm']['k1'] k2 = clustering_pars['Pars_Horm']['k2'] k3 = clustering_pars['Pars_Horm']['k3'] k_1 = clustering_pars['Pars_Horm']['k_1'] k_2 = clustering_pars['Pars_Horm']['k_2'] # GPVI clustering module equations dGPVIdt = - kf_act * CRP * GPVI + kr_act * GPVI_Act dGPVI_Actdt = kf_act * CRP * GPVI - kr_act * GPVI_Act - k1 * GPVI_Clust * GPVI_Act + k_1 * GPVI_Clust - \ 2 * k2 * GPVI_Act * GPVI_Act dGPVI_Clustdt = - (k_2 * GPVI_Clust + k3) * GPVI_Clust + k2 * GPVI_Act * GPVI_Act # Tyrosine kinase activation module parameters kcat_SFK_A = kinases_pars['Pars_Horm']['kcat_SFK'] kr_P = kinases_pars['Pars_Horm']['kr_P'] kcat_CD148 = kinases_pars['Pars_Horm']['kcat_CD148'] pp_act = kinases_pars['Pars_Horm']['pp_act'] A = kinases_pars['Pars_Horm']['Monomer_Size'] * 1e-18 kf_Syk = kinases_pars['Pars_Horm']['kf_Syk'] kr_Syk = kinases_pars['Pars_Horm']['kr_Syk'] CD148 = kinases_pars['Pars_Horm']['CD148'] S = clustering_pars['Pars_Horm']['S'] V = clustering_pars['Pars_Horm']['V'] NA = clustering_pars['Pars_Horm']['Avog'] GPVI_0 = pars1[0] # Tyrosine kinase activation module equations if GPVI_Clust * S * NA < 1: Size = 1 SFK_A = 0 else: Size = (GPVI_0 - (GPVI_Act + GPVI)) / GPVI_Clust if math.isnan(Size): Size = 1 if math.isinf(Size): Size = 1 if abs(Size) > 1000: Size = 1 SFK_A = ((kcat_CD148 / kcat_SFK_A) * Size * (CD148 * pp_act * GPVI_Clust) / (GPVI_Act + GPVI)) ** (1 / 2) dIp = kcat_SFK_A * (SFK_A / (Size * A * NA)) * (1 - Ip) / (A * NA) - kr_P * Ip dSyk_A = kf_Syk * Ip / (A * NA) * Syk + SFK_A / (Size * A * NA) * kcat_SFK_A * Syk - kr_Syk * Syk_A dSyk = - kf_Syk * Ip / (A * NA) * Syk - SFK_A / (Size * A * NA) * kcat_SFK_A * Syk + kr_Syk * Syk_A # LAT module parameters kcat_Syk = kinases_pars['Pars_Horm']['kcat_Syk'] KM_Syk = kinases_pars['Pars_Horm']['KM_Syk'] kr_LAT = kinases_pars['Pars_Horm']['Kr_LAT'] kD_Syk = kinases_pars['Pars_Horm']['KD_Syk'] kcat_PI3K = LAT_pars['Pars_Horm']['kcat_PI3K'] KM_PI3K = LAT_pars['Pars_Horm']['KM_PI3K'] kr_PIP3 = LAT_pars['Pars_Horm']['kr_PIP3'] kD_PI3K = LAT_pars['Pars_Horm']['kD_PI3K'] PI3K = LAT_pars['Pars_Horm']['PI3K'] / (NA * V) kcat_Btk = LAT_pars['Pars_Horm']['kcat_Btk'] KM_Btk = LAT_pars['Pars_Horm']['KM_Btk'] kD_Btk = LAT_pars['Pars_Horm']['kD_Btk'] kD_PLCg2 = LAT_pars['Pars_Horm']['kD_PLCg2'] kr_PLCg2 = LAT_pars['Pars_Horm']['kr_PLCg2'] Btk = LAT_pars['Pars_Horm']['Btk'] / (NA * V) # LAT module equations dLATp_dt = kcat_Syk * (Syk_A / (NA * V)) * LAT / (KM_Syk / kD_Syk) - kr_LAT * LAT_p dLAT_dt = (- kcat_Syk * (Syk_A / (NA * V)) * LAT / (KM_Syk / kD_Syk) + kr_LAT * LAT_p) # PAR Receptor parameters and equations k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, km_1, km_2, km_3, \ km_4, km_5, km_6, km_7, km_8, km_9, km_10, km_11, gamma_1, gamma_2, \ gamma_3, gamma_4, gamma_5, gamma_6, gamma_7, gamma_8, gamma_9, gamma_10, \ gamma_11, V_1, V_2, K_1, K_2, K_3, k_1, k_2, k_3, k_4, k_5, L1, L3, L5, K3, \ K5, K6, K7, K8, km2, km3, km4, kc3, k_12, k_13, phi_a1, phi_a2, phi_a3, \ phi_a4, phi_m, phi_m2, phi_m3, k_thr, jres, F, R, T = PAR_pars j1 = k1 * par1 * sfllrn - km_1 * par1_a j2 = k2 * par1_a j3 = k3 * gqgtp j4 = k4 * plcgqgtp j5 = k5 * par1_gq * gtp - km_2 * par1_gqgtp j6 = k6 * par1_gq * gdp - km_3 * par1_gqgdp j7 = k7 * par1_a * gqgdp - km_4 * par1_gqgdp j8 = km_5 * par1_gqgtp j9 = k8 * plcgqgtppip2 j10 = k9 * plcgqgtp - km_6 * plc * gqgtp j11 = k10 * plcgqgtppip2 - km_7 * pip2 * plcgqgtp j12 = k11 * plcgqgdp - km_8 * plc * gqgdp jthr = k_thr * par1 * thr # PM p1 = gamma_1 * np.log(ca_ex / Ca_cyt) p2 = (V_1 * np.power(Ca_cyt, 2)) / (K_1 * K_1 + np.power(Ca_cyt, 2)) # SOCE s1 = k_12 * orai1_closed * stim1 - km_10 * orai1_opened s2 = k_13 * stim1 * np.power(Ca_dts, 3) - km_11 * stim1ca s3 = gamma_4 * orai1_opened * np.log(ca_ex / Ca_cyt) # mitochondria m1 = gamma_5 / (1 + K6 / ca_mit) * np.exp(F * (phi - phi_a1) / (2 * R * T)) m2 = gamma_6 * Ca_cyt * np.power((phi - phi_a2), 3) * 2 * F * phi * (Ca_cyt - ca_mit * np.exp(-2 * F * phi / (R * T))) / ( R * T * (1 - np.exp(-2 * F * phi / (R * T))) * (K7 * K7 + np.power(Ca_cyt, 2)) * (np.power(phi_m, 3) + np.power(phi - phi_a2, 3))) m3 = m2 * gamma_7 / gamma_6 m4 = m1 * gamma_8 / gamma_5 m5 = gamma_9 * np.exp(F * phi / (R * T)) - jres m6 = gamma_10 * mptp_opened / (1 + np.exp(-(phi - phi_a3) / phi_m2)) - np.power(ca_mit, 4) * \ mptp_closed * np.exp(-(phi - phi_a4) / phi_m3) / (np.power(K8, 4) + np.power(ca_mit, 4)) m7 = gamma_11 * mptp_opened * F * phi * (np.exp(F * phi / (R * T)) - np.exp(-F * phi / (R * T))) / ( R * T * (1 - np.exp(-F * phi / (R * T)))) dpar1 = -j1 - jthr dsfllrn = -j1 dpar1_a = j1 - j2 - j7 + j8 + jthr dgqgtp = -j3 + j8 dgqgdp = j3 - j7 + j10 + j12 dplcgqgtp = -j4 + j9 - j10 + j11 dplcgqgdp = j4 - j12 dpar1_gq = -j5 - j6 dgtp = -j5 dpar1_gqgtp = j5 - j8 dgdp = -j6 dpar1_gqgdp = j6 + j7 dplcgqgtppip2 = -j9 - j11 dplc = j10 + j12 dpip2 = 0#j11 #+ j13 dca_ex = -p1 + p2 - s3 # print(p1 - p2 + s3 + m1 - m2) dca_mit = -m1 + m2 dphi = -m3 - m4 - m5 - m7 dmptp_opened = -m6 dmptp_closed = m6 dorai1_closed = -s1 dorai1_opened = s1 dstim1 = -s2 dstim1ca = s2 dthr = 0 dip3r = 0 # Calcium Module parameters V_IM = calcium_pars['Value']['V_IM'] V_DTS = calcium_pars['Value']['V_DTS'] kcat_PLCg2 = calcium_pars['Value']['kcat_PLCg2'] KM_PLCg2 = calcium_pars['Value']['KM_PLCg2'] kr_IP3 = calcium_pars['Value']['kr_IP3'] kf_Buf = calcium_pars['Value']['kf_Buf'] kr_Buf = calcium_pars['Value']['kr_Buf'] O_1 = V_IM * 0.12 * 11.94 / (0.12 + Ca_cyt) O_2 = V_IM * 90.56 O_3 = V_IM * 1.7768 / (0.12 + Ca_cyt) O_4 = V_IM * 0.84 O_5 = V_IM * (37.4 * 0.025 + 1.7 * Ca_cyt) / (0.025 + Ca_cyt * 0.145 / 0.12) O_6 = V_IM * (1.4 + Ca_cyt * 2.5) O_7 = V_IM * 1.7768 / (0.12 + Ca_cyt * 0.145 / 0.12) IP3R_num = V_IM * (IP3R_a + IP3R_i1 + IP3R_i2 + IP3R_n + IP3R_o + IP3R_s) O_P0 = (V_IM * (0.9 * IP3R_a + 0.1 * IP3R_o) / IP3R_num)**5.5 I_1 = V_IM * 160 I_2 = V_IM * 940 I_3 = V_IM * 1.6 I_4 = V_IM * 900 I_5 = V_IM * 250 I_6 = V_IM * 8e-5 I_7 = V_IM # Calcium Module equations dPIP3 = (S/V) * kcat_PI3K * (LAT_p * PI3K / kD_PI3K) * PIP2 / (KM_PI3K / kD_PI3K + PIP2) - kr_PIP3 * PIP3 dPIP2 = - (S/V) * kcat_PI3K * (LAT_p * PI3K / kD_PI3K) * PIP2 / (KM_PI3K / kD_PI3K + PIP2) \ + kr_PIP3 * PIP3 - kcat_PLCg2 * PIP2 * PLCg2_A / (KM_PLCg2 / kD_PLCg2) * Ca_cyt / (Ca_cyt + 0.2) \ + kr_IP3 * IP3 - j9 * 10 #- \ # (kcat_PLCg2 * PLCg2_A * PIP2 * (S / V) / (KM_PLCg2 / kD_PLCg2) * Ca_cyt / (Ca_cyt + 0.2) # - kr_IP3 * IP3) / S dIP3 = kcat_PLCg2 * PIP2 * PLCg2_A / (KM_PLCg2 / kD_PLCg2) * Ca_cyt / (Ca_cyt + 0.2) - kr_IP3 * IP3 \ + (O_6 * IP3R_o - O_5 * IP3R_n * IP3) / V + j9 * 10 # dIP3 = (kcat_PLCg2 * PLCg2_A * PIP2 * (S / V) / (KM_PLCg2 / kD_PLCg2) * Ca_cyt / (Ca_cyt + 0.2) # - kr_IP3 * IP3)/V# + O_6 * IP3R_o - O_5 * IP3R_n * IP3) / V + j9 * 1e13 dPLCg2_A = (S/V) * kcat_Btk * (PIP3 * Btk / kD_Btk) \ * (PLCg2 * LAT_p / kD_PLCg2) / (KM_Btk / kD_Btk + (PLCg2 * LAT_p / kD_PLCg2)) - kr_PLCg2 * PLCg2_A dPLCg2 = - (S/V) * kcat_Btk * (PIP3 * Btk / kD_Btk) \ * (PLCg2 * LAT_p / kD_PLCg2) / (KM_Btk / kD_Btk + (PLCg2 * LAT_p / kD_PLCg2)) - kr_PLCg2 * PLCg2_A # print(IP3, dIP3) dCa_cyt = (0.1351 * I_7 * math.log(Ca_dts / Ca_cyt) + 800 * IP3R_num * O_P0 * math.log(Ca_dts / Ca_cyt) - O_2 * IP3R_o * Ca_cyt + O_1 * IP3R_a - O_7 * IP3R_n * Ca_cyt + O_4 * IP3R_i1 - O_3 * IP3R_a * Ca_cyt + O_4 * IP3R_i2 + I_1 * Serca2b_e1_ca - I_2 * Serca2b_e1 * Ca_cyt + I_3 * Serca2b_e1_2ca - I_4 * Serca2b_e1_ca * Ca_cyt - V * 4 * kf_Buf * Ca_cyt**4 * buf + V * 4 * kr_Buf * Ca_buf) / V + p1 - p2 + s3 + m1 - m2 dCa_dts = (- 0.1351 * I_7 * math.log(Ca_dts / Ca_cyt) - 800 * IP3R_num * O_P0 * math.log(Ca_dts / Ca_cyt) + 2 * I_5 * Serca2b_e2_2ca_p - 2 * I_6 * Serca2b_e2_p * Ca_dts**2) / V_DTS - s2 / 3 dbuf = (- V * 4 * kf_Buf * Ca_cyt**4 * buf + 4 * V * kr_Buf * Ca_buf) / V dCa_buf = (V * 4 * kf_Buf * Ca_cyt**4 * buf - V * 4 * kr_Buf * Ca_buf) / V dIP3R_n = (- O_5 * IP3R_n * IP3 + O_6 * IP3R_o + O_4 * IP3R_i1 - O_7 * IP3R_n * Ca_cyt) / V_IM dIP3R_o = (O_1 * IP3R_a - O_2 * IP3R_o * Ca_cyt + O_5 * IP3R_n * IP3 - O_6 * IP3R_o + V_IM * 29.8 * IP3R_s - V_IM * 0.11 * IP3R_o) / V_IM dIP3R_a = (- O_1 * IP3R_a + O_2 * IP3R_o * Ca_cyt + O_4 * IP3R_i2 - O_3 * IP3R_a * Ca_cyt) / V_IM dIP3R_i1 = (- O_4 * IP3R_i1 + O_7 * IP3R_n * Ca_cyt) / V_IM dIP3R_i2 = (- O_4 * IP3R_i2 + O_3 * IP3R_a * Ca_cyt) / V_IM dIP3R_s = (- V_IM * 29.8 * IP3R_s + V_IM * 0.11 * IP3R_o) / V_IM dSerca2b_e1 = (I_1 * Serca2b_e1_ca - I_2 * Serca2b_e1 * Ca_cyt - V_IM * 200 * Serca2b_e1 + V_IM * 280 * Serca2b_e2) / V_IM dSerca2b_e1_2ca = (- I_3 * Serca2b_e1_2ca + I_4 * Serca2b_e1_ca * Ca_cyt + V_IM * 60 * Serca2b_e1_2ca_p - V_IM * 600 * Serca2b_e1_2ca) / V_IM dSerca2b_e1_2ca_p = (- V_IM * 60 * Serca2b_e1_2ca_p + V_IM * 600 * Serca2b_e1_2ca + V_IM * 25 * Serca2b_e2_2ca_p - V_IM * 65 * Serca2b_e1_2ca_p) / V_IM dSerca2b_e1_ca = (- I_1 * Serca2b_e1_ca + I_2 * Serca2b_e1 * Ca_cyt + I_3 * Serca2b_e1_2ca - I_4 * Serca2b_e1_ca * Ca_cyt) / V_IM dSerca2b_e2 = (V_IM * 105 * Serca2b_e2_p - V_IM * 1.6 * Serca2b_e2 + V_IM * 200 * Serca2b_e1 - V_IM * 280 * Serca2b_e2) / V_IM dSerca2b_e2_2ca_p = (- V_IM * 25 * Serca2b_e2_2ca_p + V_IM * 65 * Serca2b_e1_2ca_p - I_5 * Serca2b_e2_2ca_p + I_6 * Serca2b_e2_p * Ca_dts**2) / V_IM dSerca2b_e2_p = (I_5 * Serca2b_e2_2ca_p - I_6 * Serca2b_e2_p * Ca_dts**2 - V_IM * 105 * Serca2b_e2_p + V_IM * 1.6 * Serca2b_e2) / V_IM # print(dCa_cyt, dca_cyt) return [dGPVIdt, dGPVI_Actdt, dGPVI_Clustdt, dIp, dSyk, # 0 - 4 dSyk_A, dLAT_dt, dLATp_dt, dPIP2, dPIP3, # 5 - 9 dPLCg2, dPLCg2_A, dIP3, # 10 - 12 dCa_cyt, dCa_dts, dCa_buf, dbuf, # 13 - 16 dIP3R_n, dIP3R_o, dIP3R_a, dIP3R_i1, dIP3R_i2, dIP3R_s, # 17 - 22 dSerca2b_e1, dSerca2b_e1_ca, dSerca2b_e1_2ca, dSerca2b_e2, dSerca2b_e1_2ca_p, # 23 - 27 dSerca2b_e2_2ca_p, dSerca2b_e2_p, # 28 - 29 dpar1, dsfllrn, dthr, dpar1_a, dgqgtp, dgqgdp, dplcgqgtp, dplcgqgdp, dpar1_gq, # 30 - 38 dgtp, dpar1_gqgtp, dgdp, dpar1_gqgdp, dplcgqgtppip2, dplc, dpip2, # 39 - 46 dca_ex, dip3r, # 47 - 56 dorai1_closed, dorai1_opened, dstim1, dstim1ca, dca_mit, dphi, dmptp_opened, dmptp_closed] # + pycharm={"name": "#%%\n"} # %matplotlib inline def plotter(time, data, plot_list, plot_dict, initial_cond_dict, V_Cyt, S_PM, NA): model_variables = list(plot_dict.keys()) # size = [0, ] # for i in range(1, len(data[0])): # size.append((initial_cond_dict['GPVI'] - data[0][i] - data[1][i]) / # (data[2][i])) def single_plot_data(Variable=plot_list[0], Multiplier=1, Export=False, Dualplot=True, Secondplot=plot_list[1], Sec_Multiplier=1): if Export: data_out = list(map(list, zip(*data))) df_out = pd.DataFrame(data_out, columns=model_variables) df_out['Time'] = time df_out.set_index('Time').to_excel('Model_Output.xlsx') plotting_data = [] for i in range(len(data[plot_dict[Variable]])): plotting_data.append(data[plot_dict[Variable]][i] * Multiplier) plt.plot(time, plotting_data, label=Variable) if Dualplot: dualplotting_data = [] for i in range(len(data[plot_dict[Variable]])): dualplotting_data.append(data[plot_dict[Secondplot]][i] * Sec_Multiplier) plt.plot(time, dualplotting_data, label=Secondplot) plt.legend() # If you want to add experimental data, specify the sheet with the data and provide the names of the columns # in the Exp_data file. Then, uncomment the line "plt.scatter(timepoints, val)" and your experimental data # will appear on the selected plot. # data = pd.read_excel('Exp_data.xlsx', sheet_name='SykY525') # timepoints = data['Time'] # val = data['Syk'] # plt.scatter(timepoints, val) plt.show() multipliers = [('None', 1), ('To uMols from units (Cytosol)', 1 / (NA * V_Cyt)), ('To units from uMols (Cytosol)', (NA * V_Cyt)), ('To umols / m^2 from units (Membrane)', 1 / (NA * S_PM)), ('To units from umols / m^2 (Membrane)', (NA * S_PM))] # model_var_drop = widgets.Dropdown(options=model_variables) # mult_var_drop = widgets.Dropdown(options=multipliers) # butt.on_click(on_butt_clicked) # widgets.VBox([model_var_drop, multipliers, butt,outt]) interact_manual(single_plot_data, Variable=model_variables, Multiplier=multipliers, Export=[('No', False), ('Yes', True)], Dualplot=[('No', False), ('Yes', True)], Secondplot=model_variables, Sec_Multiplier=multipliers) # interact_manual(model_output()) # + pycharm={"name": "#%%\n"} # Model calculation and plotting def plot_model(clust_pars, kin_pars, LAT_pars, calcium_pars, PAR1_initial, PAR1_parameters, InitCond, time_calc, ssteps, varying_list, plot_list): # clust_pars - clustering module parameters # kin_pars - kinase module parameters # LAT_pars - LAT module parameters # calcium_pars - Calcium module parameters # InitCond - Initial conditions # time_calc - maximal time of calculation # ssteps - number of timesteps # varying list - list of parametes, varied, using sliders def slidercalc(**kwargs): keylist = list(kwargs.keys()) for j in range(len(keylist)): if keylist[j].split('.')[0] == 'Initial': InitCond['Value'][keylist[j].split('.')[1]] = \ kwargs[keylist[j]] if keylist[j].split('.')[0] == 'Clustering': clust_pars['Pars_Horm'][keylist[j].split('.')[1]] = \ kwargs[keylist[j]] if keylist[j].split('.')[0] == 'KinaseActivation': kin_pars['Pars_Horm'][keylist[j].split('.')[1]] = \ kwargs[keylist[j]] if keylist[j].split('.')[0] == 'LAT_Pars': LAT_pars['Pars_Horm'][keylist[j].split('.')[1]] = \ kwargs[keylist[j]] if keylist[j].split('.')[0] == 'calcium_pars': calcium_pars['Value'][keylist[j].split('.')[1]] = \ kwargs[keylist[j]] if keylist[j].split('.')[0] == 'PAR1_Initial': PAR1_initial['Value'][keylist[j].split('.')[1]] = \ kwargs[keylist[j]] NA = 6.02e17 Volume = clust_pars['Pars_Horm']['V'] Area = clust_pars['Pars_Horm']['S'] initial_cond_dict = {'GPVI': InitCond['Value']['GPVI'] / (NA * Area), 'GPVI_Act': InitCond['Value']['GPVI_Act'] / (NA * Area), 'GPVI_Clust': InitCond['Value']['Clusters'] / (NA * Area), 'Ip': InitCond['Value']['Ip'], 'Syk': InitCond['Value']['Syk'], 'Syk_A': InitCond['Value']['Syk_A'], 'LAT': InitCond['Value']['LAT'] / (NA * Area), 'LAT_p': InitCond['Value']['LAT_p'] / (NA * Area), 'PIP2': InitCond['Value']['PIP2'] / (NA * Area), 'PIP3': InitCond['Value']['PIP3'] / (NA * Area), 'PLCg2': InitCond['Value']['PLCg2'] / (NA * Volume), 'PLCg2_A': InitCond['Value']['PLCg2_A'] / (NA * Volume), 'IP3': InitCond['Value']['IP3'], 'Ca_cyt': InitCond['Value']['Ca_cyt'], 'Ca_dts': InitCond['Value']['Ca_dts'], 'Ca_buf': InitCond['Value']['Ca_buf'], 'buf': InitCond['Value']['buf'], 'IP3R_n': InitCond['Value']['IP3R_n'], 'IP3R_o': InitCond['Value']['IP3R_o'], 'IP3R_a': InitCond['Value']['IP3R_a'], 'IP3R_i1': InitCond['Value']['IP3R_i1'], 'IP3R_i2': InitCond['Value']['IP3R_i2'], 'IP3R_s': InitCond['Value']['IP3R_s'], 'Serca2b_e1': InitCond['Value']['Serca2b_e1'], 'Serca2b_e1_ca': InitCond['Value']['Serca2b_e1_ca'], 'Serca2b_e1_2ca': InitCond['Value']['Serca2b_e1_2ca'], 'Serca2b_e2': InitCond['Value']['Serca2b_e2'], 'Serca2b_e1_2ca_p': InitCond['Value']['Serca2b_e1_2ca_p'], 'Serca2b_e2_2ca_p': InitCond['Value']['Serca2b_e2_2ca_p'], 'Serca2b_e2_p': InitCond['Value']['Serca2b_e2_p'], 'par1': PAR1_initial['Value']['par1'], 'thr': PAR1_initial['Value']['thr'], 'sfllrn': PAR1_initial['Value']['sfllrn'], 'par1_a': PAR1_initial['Value']['par1_a'], 'gqgtp': PAR1_initial['Value']['gqgtp'], 'gqgdp': PAR1_initial['Value']['gqgdp'], 'plcgqgtp': PAR1_initial['Value']['plcgqgtp'], 'plcgqgdp': PAR1_initial['Value']['plcgqgdp'], 'par1_gq': PAR1_initial['Value']['par1_gq'], 'gtp': PAR1_initial['Value']['gtp'], 'par1_gqgtpgdp': PAR1_initial['Value']['par1_gqgtpgdp'], 'gdp': PAR1_initial['Value']['gdp'], 'par1_gqgdp': PAR1_initial['Value']['par1_gqgdp'], 'plcgqgtppip2': PAR1_initial['Value']['plcgqgtppip2'], 'plc': PAR1_initial['Value']['plc'], 'pip2': PAR1_initial['Value']['pip2'], 'ca_ex': PAR1_initial['Value']['ca_ex'], 'ip3r': PAR1_initial['Value']['ip3r'], 'orai1_closed': PAR1_initial['Value']['orai1_closed'], 'orai1_opened': PAR1_initial['Value']['orai1_opened'], 'stim1': PAR1_initial['Value']['stim1'], 'stim1ca': PAR1_initial['Value']['stim1ca'], 'ca_mit': PAR1_initial['Value']['ca_mit'], 'phi': PAR1_initial['Value']['phi'], 'mptp_opened': PAR1_initial['Value']['mptp_opened'], 'mptp_closed': PAR1_initial['Value']['mptp_closed']} Initial = list(initial_cond_dict.values()) initial_names = list(initial_cond_dict.keys()) plot_dict = {} for i in range(len(Initial)): plot_dict[initial_names[i]] = i model_calc = solve_ivp(GPVI_model, [0, time_calc], Initial, args=(clust_pars, kin_pars, Initial, LAT_pars, calcium_pars, PAR1_parameters, ), max_step=100000, dense_output=True, method='LSODA', rtol=1e-6, atol=1e-12) time = np.linspace(0, time_calc, ssteps) solution = model_calc.sol(time) transposed = list(map(list, zip(*solution.T))) plotter(time, transposed, plot_list, plot_dict, initial_cond_dict, V_Cyt=Volume, S_PM=Area, NA=NA) # return res2 def gen_slider(input_list): if input_list[0] == 'KinaseActivation': return widgets.FloatSlider( value=kin_pars['Pars_Horm'][input_list[1]], min=input_list[2], max=input_list[3], step=(input_list[3] - input_list[2]) / 1000, description=input_list[1], disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.5f') elif input_list[0] == 'Clustering': return widgets.FloatSlider( value=clust_pars['Pars_Horm'][input_list[1]], min=input_list[2], max=input_list[3], step=(input_list[3] - input_list[2]) / 1000, description=input_list[1], disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.5f') if input_list[0] == 'LAT_Pars': return widgets.FloatSlider( value=LAT_pars['Pars_Horm'][input_list[1]], min=input_list[2], max=input_list[3], step=(input_list[3] - input_list[2]) / 1000, description=input_list[1], disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.5f') if input_list[0] == 'calcium_pars': return widgets.FloatSlider( value=calcium_pars['Value'][input_list[1]], min=input_list[2], max=input_list[3], step=(input_list[3] - input_list[2]) / 1000, description=input_list[1], disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.5f') if input_list[0] == 'Initial': return widgets.FloatSlider( value=InitCond['Value'][input_list[1]], min=input_list[2], max=input_list[3], step=(input_list[3] - input_list[2]) / 100, description=input_list[1], disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.5f') if input_list[0] == 'PAR1_Initial': return widgets.FloatSlider( value=PAR1_initial['Value'][input_list[1]], min=input_list[2], max=input_list[3], step=(input_list[3] - input_list[2]) / 100, description=input_list[1], disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.5f') weight_sliders = [gen_slider(varying_list[i]) for i in range(len(varying_list))] kwargs = {varying_list[i][0] + '.' + varying_list[i][1]: slider for i, slider in enumerate(weight_sliders)} interact_manual(slidercalc, **kwargs) # + pycharm={"name": "#%%\n"} clustering_pars = pd.read_excel('Model_Parameters.xlsx', sheet_name='Clustering').set_index('Parname') kinase_pars = pd.read_excel('Model_Parameters.xlsx', sheet_name='KinaseActivation').set_index('Parname') InitialValues = pd.read_excel('Model_Parameters.xlsx', sheet_name='InitialConcentrations').set_index('Name') LAT_pars = pd.read_excel('Model_Parameters.xlsx', sheet_name='LAT_Pars').set_index('Parname') calcium_pars = pd.read_excel('Model_Parameters.xlsx', sheet_name='CalciumModule').set_index('Parname') PAR1_init = pd.read_excel('Model_Parameters.xlsx', sheet_name='InitPAR1').set_index('Name') PAR1_pars = pd.read_excel('Model_Parameters.xlsx', sheet_name='PAR1').set_index('Name')['Value'].tolist() # List of modules, in which parameters can be varied # clustering_pars - clustering module parameters # kinase_pars - kinase module parameters # LAT_pars - LAT module parameters # calcium_pars - Calcium module parameters # InitialValues - Initial conditions # PAR1_Initial - Initial conditions for PAR1 module # To generate the slider, add to the varying list parameter of the plot_model function: # [Name of the module, Name of the desired parameter, # min value, max value]. E.g. you want to create slider for the initial concentration of SFLLRN: # It can be found in the PAR1_Initial module, see names on the corresponding sheet in Model_Parameters.xlsx. # So, you add: # ['PAR1_Initial', 'sfllrn', 0, 100] # You can generate as many parameters, as you wish # To the parameter plot_list you pass list of lists, where each element is: # [Name of the variable you want to plot, plot_model(clustering_pars, kinase_pars, LAT_pars, calcium_pars, InitCond=InitialValues, PAR1_initial=PAR1_init, PAR1_parameters=PAR1_pars, time_calc=10, ssteps=100, varying_list = [['Initial', 'GPVI', 1000, 10000], ['Initial', 'buf', 0, 30], ['Initial', 'Syk', 1000, 10000], ['LAT_Pars', 'kr_PLCg2', 0.01, 0.1], ['calcium_pars', 'kf_Buf', 0.1, 50], ['KinaseActivation', 'CRP', 0, 100], ['PAR1_Initial', 'par1', 0, 1], ['PAR1_Initial', 'sfllrn', 0, 100]], plot_list=['Ca_cyt', 'Ca_dts'])
ANJUMSO.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:neuro] * # language: python # name: conda-env-neuro-py # --- import nilearn import pandas as pd import numpy as np import os subjects = os.listdir('./data/images/Control')\ + os.listdir('./data/images/Schizoaffective')\ + os.listdir('./data/images/Schizophrenia')\ + os.listdir('./data/images/Schizophrenia_Strict') for i in range(len(subjects)): subjects[i] = subjects[i][4:-30] data = pd.read_csv('./data/participants.csv') # + language="bash" # mkdir ./data/mean_images # mkdir ./data/max_images # mkdir ./data/min_images # mkdir ./data/std_images # # mkdir ./data/mean_images/Control # mkdir ./data/mean_images/Schizoaffective # mkdir ./data/mean_images/Schizophrenia # mkdir ./data/mean_images/Schizophrenia_Strict # # mkdir ./data/max_images/Control # mkdir ./data/max_images/Schizoaffective # mkdir ./data/max_images/Schizophrenia # mkdir ./data/max_images/Schizophrenia_Strict # # mkdir ./data/min_images/Control # mkdir ./data/min_images/Schizoaffective # mkdir ./data/min_images/Schizophrenia # mkdir ./data/min_images/Schizophrenia_Strict # # mkdir ./data/std_images/Control # mkdir ./data/std_images/Schizoaffective # mkdir ./data/std_images/Schizophrenia # mkdir ./data/std_images/Schizophrenia_Strict # + import nilearn.image as nli from scipy import ndimage def process_file(file): x = nli.load_img(file).slicer[..., 15:].get_fdata() mean = x.mean(axis=3) max_ = x.max(axis=3) min_ = x.min(axis=3) std = x.std(axis=3) return ndimage.rotate(mean, 90, reshape=False), ndimage.rotate(max_, 90, reshape=False), ndimage.rotate(min_, 90, reshape=False), ndimage.rotate(std, 90, reshape=False), # + # %%time for index, row in data.iterrows(): type_ = '' if row['diagnosis'] == 'Control': type_ = 'Control' elif row['diagnosis'] == 'Schizoaffective': type_ = 'Schizoaffective' elif row['diagnosis'] == 'Schizophrenia': type_ = 'Schizophrenia' elif row['diagnosis'] == 'Schizophrenia_Strict': type_ = 'Schizophrenia_Strict' file = './data/images/'+type_+'/sub-'+row['id']+'_task-rest_bold_MNI_3mm.nii.gz' mean, max_, min_, std = process_file(file) np.savez_compressed('./data/mean_images/'+type_+'/sub-'+row['id'], mean) np.savez_compressed('./data/max_images/'+type_+'/sub-'+row['id'], max_) np.savez_compressed('./data/min_images/'+type_+'/sub-'+row['id'], min_) np.savez_compressed('./data/std_images/'+type_+'/sub-'+row['id'], std) # -
Mean, Max, Min, Std Volume Extractor.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # Example 00 # -- # # A simple example consisting only of a point source and a spherical crystal. # # See [documentation] for a discription of all options. # # [documentation]: https://xicsrt.readthedocs.io/en/latest/apidoc/examples.example_00.example_00.html # %matplotlib notebook import numpy as np import xicsrt xicsrt.warn_version('0.8') # + config = {} config['general'] = {} config['general']['number_of_iter'] = 5 config['general']['save_images'] = False config['sources'] = {} config['sources']['source'] = {} config['sources']['source']['class_name'] = 'XicsrtSourceDirected' config['sources']['source']['intensity'] = 1e3 config['sources']['source']['wavelength'] = 3.9492 config['sources']['source']['spread'] = np.radians(5.0) config['optics'] = {} config['optics']['detector'] = {} config['optics']['detector']['class_name'] = 'XicsrtOpticDetector' config['optics']['detector']['origin'] = [0.0, 0.0, 1.0] config['optics']['detector']['zaxis'] = [0.0, 0.0, -1] config['optics']['detector']['xsize'] = 0.2 config['optics']['detector']['ysize'] = 0.2 results = xicsrt.raytrace(config) # + import xicsrt.visual.xicsrt_3d__plotly as xicsrt_3d xicsrt_3d.plot(results) # + import xicsrt.visual.xicsrt_2d__matplotlib as xicsrt_2d fig = xicsrt_2d.plot_intersect(results, 'detector', aspect='equal') # -
examples/example_00/example_00.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # [View in Colaboratory](https://colab.research.google.com/github/Masum06/Deep-learning-with-PyTorch-video/blob/master/PyTorch_Packt.ipynb) # + [markdown] id="EsHq8CE-UPXA" colab_type="text" # ### Installation # + [markdown] id="ZWW9pDJpUDkH" colab_type="text" # Fast.ai has all dependencies installed and more. So we install this instead of PyTorch # + id="yHERGYo-RdQ9" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 2292} outputId="ca71b7cf-fdf8-4b13-9d75-91521a6f4e0a" # !pip install fastai # + id="HYtQfIdDUAHX" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 90} outputId="69d8705d-26ab-418d-93a4-e157e821758d" # !git clone https://github.com/PacktPublishing/Deep-learning-with-PyTorch-video.git # + id="krcB3VTGWGfY" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="f5b7b375-5415-4aa0-9151-0b9bf3717772" # cd Deep-learning-with-PyTorch-video/ # + [markdown] id="aLvr8-XNfU_Z" colab_type="text" # ## Simple NN # + id="bCN_gvgrfWwp" colab_type="code" colab={} import torch import torch.nn as nn import matplotlib.pyplot as plt from torch.autograd import Variable # Custom DataSet from data import iris # + id="SKXqZj5ofYsp" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 199} outputId="ef1de5de-770a-4447-a12c-52c44056f87c" # !head data/iris.data.txt # + [markdown] id="BQrsgvzAgxSy" colab_type="text" # ### Create the Fully Connected Feed Forward Neural Network # + [markdown] id="q-xvgywQg03B" colab_type="text" # **Create the module** # + id="NoEmV7n9gEi7" colab_type="code" colab={} class IrisNet(nn.Module): # this is how to create a neural network in PyTorch, inherit nn.Module class def __init__(self, input_size, hidden1_size, hidden2_size, num_classes): # Constructor function, passed with the object. We can initialize it if we want super(IrisNet, self).__init__() # assigning the same to parent class # names are arbitrary # just defining functions here. That will be used later. # Here we are creating the computational graph self.fc1 = nn.Linear(input_size, hidden1_size) self.relu1 = nn.ReLU() self.fc2 = nn.Linear(hidden1_size, hidden2_size) self.relu2 = nn.ReLU() self.fc3 = nn.Linear(hidden2_size, num_classes) def forward(self, x): out = self.fc1(x) out = self.relu1(out) out = self.fc2(out) out = self.relu2(out) out = self.fc3(out) return out # + [markdown] id="336S_AVWg8ug" colab_type="text" # **Print the module** # + id="gE8lbZTSg_3G" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 145} outputId="c477e09d-4a2c-47fd-cd7b-e6709a22764e" model = IrisNet(4, 100, 50, 3) print(model) # + [markdown] id="e2A3GoI-hDCG" colab_type="text" # ### Create DataLoader # + id="qG9prtp-hH0O" colab_type="code" colab={} batch_size = 60 iris_data_file = 'data/iris.data.txt' # + [markdown] id="kDnxYG2ilff4" colab_type="text" # Batch size is how many data the network will handle at a time. It helps with the limitation of RAM. If the dataset is too high we cannot load the whole into RAM and GPU memory. So, we split our training set into multiple batches. batch_size * number_of_batches = 1 epoch. That means, if there is 120 data, we cannot load all of them together, we load 60 at a time twice. That means in 2 batch. # + id="4rYoIFIdhLVM" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="06be2848-c349-44fd-cbd3-000bd2398e61" # Get the datasets train_ds, test_ds = iris.get_datasets(iris_data_file) # How many instances have we got? print('# instances in training set: ', len(train_ds)) print('# instances in testing/validation set: ', len(test_ds)) # Create the dataloaders - for training and validation/testing # We will be using the term validation and testing data interchangably train_loader = torch.utils.data.DataLoader(dataset=train_ds, batch_size=batch_size, shuffle=True) # PyTorch library, can't argue with that test_loader = torch.utils.data.DataLoader(dataset=test_ds, batch_size=batch_size, shuffle=True) # + [markdown] id="cYy0u3g1hN6I" colab_type="text" # ### Instantiate the network, the loss function and the optimizer # + [markdown] id="uia37Zdtm0LL" colab_type="text" # We could look into what other kind of Optimizers are available here # # Notice, we never defined the Backpropagation function. That is taken care of by the library itself. # # As the architecture is known, there is no harm if the library automatically takes care of the Backprop. # + id="ArYfaSYkhRiH" colab_type="code" colab={} # Our model net = IrisNet(4, 100, 50, 3) # 4 row in dataset, sepal and petal length and width # Out loss function criterion = nn.CrossEntropyLoss() # where did we use it?? # in training # Our optimizer learning_rate = 0.001 optimizer = torch.optim.SGD(net.parameters(), lr=learning_rate, nesterov=True, momentum=0.9, dampening=0) # + [markdown] id="6J4SVaoehUu_" colab_type="text" # ### Train it # + [markdown] id="zXdU_TgFri9z" colab_type="text" # This is the hardest part to understand. Lot of stuff going on, not everything makes sense. We can watch the video again if it explained WTF just happened, so that in future we can make our own network without seeing anything from the scratch. # + id="jORC5lC4hXzr" colab_type="code" colab={} num_epochs = 500 train_loss = [] test_loss = [] train_accuracy = [] test_accuracy = [] for epoch in range(num_epochs): train_correct = 0 # How many correct in this epoch. To calculate accuracy train_total = 0 for i, (items, classes) in enumerate(train_loader): # Convert torch tensor to Variable # WTF is a Variable here??? items = Variable(items) classes = Variable(classes) # Who the Fuck defined 'net'??? net.train() # Put the network into training mode optimizer.zero_grad() # Clear off the gradients from any past operation outputs = net(items) # Do the forward pass loss = criterion(outputs, classes) # Calculate the loss loss.backward() # Calculate the gradients with help of back propagation optimizer.step() # Ask the optimizer to adjust the parameters based on the gradients # Record the correct predictions for training data train_total += classes.size(0) _, predicted = torch.max(outputs.data, 1) train_correct += (predicted == classes.data).sum() print ('Epoch %d/%d, Iteration %d/%d, Loss: %.4f' %(epoch+1, num_epochs, i+1, len(train_ds)//batch_size, loss.data[0])) net.eval() # Put the network into evaluation mode # Book keeping # Record the loss train_loss.append(loss.data[0]) # What was our train accuracy? train_accuracy.append((100 * train_correct / train_total)) # How did we do on the test set (the unseen set) # Record the correct predictions for test data test_items = torch.FloatTensor(test_ds.data.values[:, 0:4]) test_classes = torch.LongTensor(test_ds.data.values[:, 4]) outputs = net(Variable(test_items)) loss = criterion(outputs, Variable(test_classes)) test_loss.append(loss.data[0]) _, predicted = torch.max(outputs.data, 1) total = test_classes.size(0) correct = (predicted == test_classes).sum() test_accuracy.append((100 * correct / total)) # + [markdown] id="2Bfz0xoIhg0w" colab_type="text" # **Plot loss function** # + id="fc8KXG8ghjO1" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 498} outputId="434eecf4-28a1-4e5d-aedd-113b97adb4fb" fig = plt.figure(figsize=(12, 8)) plt.plot(train_loss, label='train loss') plt.plot(test_loss, label='test loss') plt.title("Train and Test Loss") plt.legend() plt.show() # + id="XLf0CKZEhl4_" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 498} outputId="18834123-0e01-490a-ebe2-a9239ed6621f" fig = plt.figure(figsize=(12, 8)) plt.plot(train_accuracy, label='train accuracy') plt.plot(test_accuracy, label='test accuracy') plt.title("Train and Test Accuracy") plt.legend() plt.show() # + [markdown] id="ckmDt2VihsDZ" colab_type="text" # ### Savign the model to disk, and loading it back # + id="D9_ZIaMqhtDw" colab_type="code" colab={} torch.save(net.state_dict(), "./2.model.pth") # + id="igdXTIHUhvnZ" colab_type="code" colab={} net2 = IrisNet(4, 100, 50, 3) net2.load_state_dict(torch.load("./2.model.pth")) # + id="7xoTnX2-hye8" colab_type="code" colab={} output = net2(Variable(torch.FloatTensor([[5.1, 3.5, 1.4, 0.2]]))) # + id="GeSndUn7h1fh" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="0dff320a-5b64-4336-dd60-980b299e9b74" _, predicted_class = torch.max(output.data, 1) print('Predicted class: ', predicted_class.numpy()[0]) print('Expected class: ', 0 ) # + id="0spzdiG4rWyC" colab_type="code" colab={}
PyTorch_Packt.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # In what follows we will demonstrate some of the basic network capabilities of the networkx package, but first we need some network data to play with. I sugest obtaining you linkedin contact network - it is straightforward to download your linkedin contacts, but the connections between them are unknown. For the purposes of illustation we will employ a few simple heuristics to obtain a more natural looking network. Instructions for obtaining the network from linkedin are on the blog post https://towardsdatascience.com/visualizing-my-linkedin-network-c4b232ab2ad0 and breifly summarised in the course notes. #credit for what follows: https://towardsdatascience.com/visualizing-my-linkedin-network-c4b232ab2ad0 import pandas as pd df = pd.read_csv('../data/Connections.csv') df.head() # Now, we should tidy up the linkedin data a little. Most likely, you'll have some anonymous/nameless individuals in your contact list (atleast I do). Seek them out and assign them generic but unique names. #replace the NaNs with strings i=1 for ind in df.index: if isinstance(df['First Name'][ind] ,str) & isinstance(df['Last Name'][ind] ,str) : #do nothing pass #empty if statements confuse python else : df['First Name'][ind]='FirstName'+str(i) df['Last Name'][ind]='LastName'+str(i) i+=1 # Now we are ready to construct a network. Admittedly, this construction is a little artificial for linkedin data. But, this serves as a good demonstration of using network representations to seek out coincidence, and structure in unstructured data. Do contacts cluster? In what follows, we map each individual to a node and connect nodes if the individuals: (a) are from the same company, or (b) connected over linkedin within a short time window of each other. For your own data set, you may want to adjust the window. # + import networkx as nx import matplotlib.pyplot as plt from datetime import timedelta, datetime G=nx.Graph() for nodei in df.index: nodeilabel= df['First Name'][nodei]+" "+df['Last Name'][nodei] nodeitime=df['Connected On'][nodei] nodeicomp=df['Company'][nodei] for nodej in df.index: if nodei!=nodej: if nodeicomp==df['Company'][nodej]: #are the nodes from the same company? G.add_edge(nodeilabel,df['First Name'][nodej]+" "+df['Last Name'][nodej]) date1=datetime.strptime(nodeitime, '%d %b %Y').date() date2=datetime.strptime(df['Connected On'][nodej], '%d %b %Y').date() if (abs(date2-date1)<timedelta(days=0)): #are the nodes from the same time? G.add_edge(nodeilabel,df['First Name'][nodej]+" "+df['Last Name'][nodej]) # - nx.draw_kamada_kawai(G) # We don't have time to go through all this here, but in what follows we can run through the computation of some of the network quantities discussed before. Are the high ranked individuals important? Are they clustered? Do the clusters correspond to meaningful organisation/groups/themes? (For my linkedin network they do). # + #Credit: the following code is from https://programminghistorian.org/en/lessons/exploring-and-analyzing-network-data-with-python#centrality from operator import itemgetter degree_dict = dict(G.degree(G.nodes())) nx.set_node_attributes(G, degree_dict, 'degree') sorted_degree = sorted(degree_dict.items(), key=itemgetter(1), reverse=True) print("Top 20 nodes by degree:") for d in sorted_degree[:20]: print(d) # + betweenness_dict = nx.betweenness_centrality(G) # Run betweenness centrality eigenvector_dict = nx.eigenvector_centrality(G) # Run eigenvector centrality # Assign each to an attribute in your network nx.set_node_attributes(G, betweenness_dict, 'betweenness') nx.set_node_attributes(G, eigenvector_dict, 'eigenvector') # + sorted_betweenness = sorted(betweenness_dict.items(), key=itemgetter(1), reverse=True) print("Top 20 nodes by betweenness centrality:") for b in sorted_betweenness[:20]: print(b) # + #First get the top 20 nodes by betweenness as a list top_betweenness = sorted_betweenness[:20] #Then find and print their degree for tb in top_betweenness: # Loop through top_betweenness degree = degree_dict[tb[0]] # Use degree_dict to access a node's degree, see footnote 2 print("Name:", tb[0], "| Betweenness Centrality:", tb[1], "| Degree:", degree) # - from networkx.algorithms import community #This part of networkx, for community detection, needs to be imported separately. communities = community.greedy_modularity_communities(G) # + modularity_dict = {} # Create a blank dictionary for i,c in enumerate(communities): # Loop through the list of communities, keeping track of the number for the community for name in c: # Loop through each person in a community modularity_dict[name] = i # Create an entry in the dictionary for the person, where the value is which group they belong to. # Now you can add modularity information like we did the other metrics nx.set_node_attributes(G, modularity_dict, 'modularity') # + # First get a list of just the nodes in that class class0 = [n for n in G.nodes() if G.nodes[n]['modularity'] == 0] # Then create a dictionary of the eigenvector centralities of those nodes class0_eigenvector = {n:G.nodes[n]['eigenvector'] for n in class0} # Then sort that dictionary and print the first 5 results class0_sorted_by_eigenvector = sorted(class0_eigenvector.items(), key=itemgetter(1), reverse=True) print("Modularity Class 0 Sorted by Eigenvector Centrality:") for node in class0_sorted_by_eigenvector[:5]: print("Name:", node[0], "| Eigenvector Centrality:", node[1]) # - for i,c in enumerate(communities): # Loop through the list of communities if len(c) > 2: # Filter out modularity classes with 2 or fewer nodes print('Class '+str(i)+':', list(c)) # Print out the classes and their members
notebooks/3_Networks.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np from datetime import datetime from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://capMaster:#jackpot<EMAIL>#<EMAIL>:23306/varejo") con = engine.connect() df = pd.read_sql("select distinct cnpj from fluxo_justa", con) con.close() df.head() # + # df = df.iloc[1:, :] # - df["cnpj"].iloc[0] df.head() df["flag_cnpj"] = df.apply(lambda x : int(len(x["cnpj"])==14), axis=1) df.head() df = df[df['flag_cnpj']==1] df.head() lista_cnpj = df["cnpj"].tolist() lista_cnpj.__len__() # + from pricing.service.scoring.lscore import LScoring from pricing.utils import formata_cnpj import pandas as pd import numpy as np from datetime import datetime from dateutil.relativedelta import relativedelta from sqlalchemy import create_engine class CriteriosElegibilidade(object): def __init__(self, cnpj, produto): self.cnpj = cnpj self.produto = produto self.elegibilidade_dividas=1.5 self.elegibilidade_transacoes = 12 self.dados = None self.flag_faturamento = None self.fat_medio = None self.flag_transacoes = None self.flag_cheques = None self.flag_dividas = None self.data_consulta = None self.scoring = None self.prop_boleto = None def get_dados(self): if self.produto in ["tomatico", "padrao"]: engine = create_engine("mysql+pymysql://capMaster:#jackpot123#@<EMAIL>.sa-<EMAIL>:23306/credito-digital") con = engine.connect() else: engine = create_engine("mysql+pymysql://capMaster:#jackpot123#@<EMAIL>:23306/varejo") con = engine.connect() query_wirecard = "select cnpj, data, valor, numero_transacoes from fluxo_wirecard where cnpj='{}'".format(self.cnpj) query_pv = "select cpf_cnpj as cnpj, data, valor, valor_boleto, numero_transacoes from fluxo_pv where cpf_cnpj='{}'".format(formata_cnpj(self.cnpj)) query_tomatico = "select cnpj, dataFluxo as data, valorFluxo as valor from tb_Fluxo where cnpj='{}'".format(self.cnpj) query_justa = "select cnpj, data, valor, numero_transacoes from fluxo_justa where cnpj='{}'".format(self.cnpj) dict_query = {"tomatico" : query_tomatico, "padrao" : query_tomatico, "wirecard" : query_wirecard, "moip" : query_wirecard, "pagueveloz" : query_pv, "justa" : query_justa } query = dict_query.get(self.produto) df = pd.read_sql(query, con) con.close() df = df.groupby("data").sum().reset_index() try: df["data"] = df.apply(lambda x : x["data"].date(), axis=1) except: pass self.dados = df return def mensaliza(self, df): df.index = pd.to_datetime(df.data) if self.produto=='pagueveloz': df = df.resample('MS').sum()[["valor", "valor_boleto"]].reset_index() else: df = df.resample('MS').sum().reset_index() return df def check_faturamento(self): if self.produto == 'pagueveloz': df = self.dados[["data", "valor", "valor_boleto"]] else: df = self.dados[["data", "valor"]] df = self.mensaliza(df) df6 = df.sort_values("data", ascending=False).iloc[:6, :] df6["data"] = df6.apply(lambda x : x["data"].date(), axis=1) flag_faturamento = int((len(df6)==6) and (0 not in df6["valor"].tolist()) and (df6["data"].max()==datetime.now().date().replace(day=1) - relativedelta(months=1))) self.flag_faturamento = flag_faturamento self.fat_medio = df.sort_values("data", ascending=False).iloc[:12, :]["valor"].mean() if self.produto == 'pagueveloz': db = df.sort_values("data", ascending=False).iloc[:12, :] db["prop"] = db["valor_boleto"].sum()/db["valor"].sum() self.prop_boleto = db["prop"].iloc[0] return def check_transacoes(self): if self.produto != 'tomatico': try: df = self.dados[["data", "numero_transacoes"]] df.index = pd.to_datetime(df.data) df.resample('MS').sum().reset_index() df = df.iloc[:12, :] media_transacoes = df["numero_transacoes"].mean() flag_transacoes = int(media_transacoes > self.elegibilidade_transacoes) self.flag_transacoes = flag_transacoes except: self.flag_transacoes = 1 return def get_dividas(self): engine = create_engine("mysql+pymysql://capMaster:#jackpot123#@<EMAIL>:23306/varejo") con = engine.connect() query = "select * from consultas_idwall_operacoes where cnpj_cpf='{}'".format(self.cnpj) df = pd.read_sql(query, con) con.close() if df.empty: return df df = df[df['data_ref']==df['data_ref'].max()] lista_consultas = df['numero_consulta'].unique().tolist() df = df[(df['data_ref']==df['data_ref'].max()) & (df['numero_consulta']==lista_consultas[0])] return df def check_cheques(self): dfdiv = self.get_dividas() if dfdiv.empty: flag_cheques = 1 data_consulta = None else: flag_cheques = int('cheques' not in dfdiv["tipo"].tolist()) data_consulta = dfdiv["data_ref"].max() self.flag_cheques = flag_cheques self.data_consulta = data_consulta return def check_dividas(self): dfdiv = self.get_dividas() if dfdiv.empty: self.flag_dividas = 1 self.data_consulta = None else: df = dfdiv[dfdiv['tipo']!="cheques"] if df.empty: self.flag_dividas = 1 self.data_consulta = dfdiv["data_ref"].iloc[0] else: total_dividas = df["valor"].sum() fat_medio = self.fat_medio prop = total_dividas/fat_medio flag_dividas = int(prop <=self.elegibilidade_dividas) self.flag_dividas = flag_dividas self.data_consulta = df["data_ref"].iloc[0] return def analisa(self): self.get_dados() self.check_faturamento() self.check_transacoes() self.check_cheques() self.check_dividas() return # - res[0] el = "03869173000139" pa = CriteriosElegibilidade(cnpj=el, produto='justa') pa.analisa() pa.flag_cheques resp = [] err = [] for el in lista_cnpj: try: pa = CriteriosElegibilidade(cnpj=el, produto='justa') pa.analisa() _df = pd.DataFrame() _df["cnpj"] = [el] _df["flag_faturamento"] = [pa.flag_faturamento] _df["flag_transacoes"] = [pa.flag_transacoes] _df["flag_cheques"] = [pa.flag_cheques] _df["flag_dividas"] = [pa.flag_dividas] _df["historico"] = [len(pa.dados)] _df["data_consulta"] = [pa.data_consulta] resp.append(_df) except: print("erro") err.append(el) err.__len__() err2 = [] for el in err: try: pa = CriteriosElegibilidade(cnpj=el, produto='justa') pa.analisa() _df = pd.DataFrame() _df["cnpj"] = [el] _df["flag_faturamento"] = [pa.flag_faturamento] _df["flag_transacoes"] = [pa.flag_transacoes] _df["flag_cheques"] = [pa.flag_cheques] _df["flag_dividas"] = [pa.flag_dividas] _df["historico"] = [len(pa.dados)] _df["data_consulta"] = [pa.data_consulta] resp.append(_df) except: err2.append(el) err2 final = pd.concat(resp) final.shape final.head() final["data_consulta"] = final.apply(lambda x : x["data_consulta"].date() if not x["data_consulta"] is None else x["data_consulta"], axis=1) final["flag_consulta"] = final.apply(lambda x : int(x["data_consulta"] is None), axis=1) final[(final["flag_consulta"]==1)]["flag_faturamento"].unique().tolist() final[(final["flag_consulta"]==1) & (final["flag_faturamento"]==1)].to_excel("atualizar_divida.xlsx") final[final["flag_consulta"]==1]["flag_faturamento"].unique().tolist() final[(final["flag_consulta"]==1) & (final["flag_faturamento"]==1)]["cnpj"].unique().tolist() final.head() final["flag_aprovacao"] = final["flag_faturamento"]*final["flag_transacoes"]*final["flag_cheques"]*final["flag_dividas"] final.groupby("flag_aprovacao").count() final.shape final.head() # + engine = create_engine("mysql+pymysql://capMaster:#jackpot123#@captalys.cmrbivuuu7sv.sa-east-1.rds.amazonaws.com:23306/varejo") con = engine.connect() for el in final["cnpj"].unique().tolist(): dt = final[final["cnpj"]==el] flag = dt["flag_aprovacao"].iloc[0] con.execute("update fluxo_justa set flag_aprovacao={} where cnpj='{}'".format(flag, el)) con.close() # + engine = create_engine("mysql+pymysql://capmaster:#jackpot123#@<EMAIL>.<EMAIL>.sa-east-1.rds.amazonaws.com:23306/varejo") con = engine.connect() for el in final["cnpj"].unique().tolist(): dt = final[final["cnpj"]==el] flag = dt["flag_aprovacao"].iloc[0] con.execute("update fluxo_justa set flag_aprovacao={} where cnpj='{}'".format(flag, el)) con.close() # - lista_pricing = final[final["flag_aprovacao"]==1]["cnpj"] lista_pricing.__len__() from tqdm import tqdm_notebook import requests lista_pricing = ["20737475000334","20737475000415", "20593518000274", "20593518000355", "20604000000370", "20604000000299"] # + url = "https://api.pricing.captalys.io/models/PricingPadrao" header = {"X-Consumer-Custom-Id": "justa"} fr = [] err = [] for el in tqdm_notebook(lista_pricing): try: pa = CriteriosElegibilidade(cnpj=el, produto='justa') pa.get_dados() dff = pa.dados dff['adquirentes'] = "justa" fat_medio = dff.groupby(["data"]).sum()["valor"].mean() dff.dropna(inplace=True) fluxos = dict() for adq in dff['adquirentes'].unique().tolist(): dt = dff[dff['adquirentes']==adq] dt['data'] = dt.apply(lambda x : str(x['data'].day) + "-" +str(x['data'].month)+"-" + str(x['data'].year), axis=1) fluxos[adq] = dt[['data', 'valor']].to_dict("records") body = { "fluxos" : fluxos, "cnpj" : str(el), "cnae" : "4744-0", "volume_escolhido" : 0.5*fat_medio } req = requests.post(url, headers=header, json=body) js = req.json() if len(js) == 0: vol_max = 0 else: vol_max = js.get("valor_maximo") fr.append(pd.DataFrame({"cnpj" : [el], "vol_max" : [vol_max]})) except: print("error") err.append(el) # + url = "https://api.pricing.captalys.io/models/PricingPadrao" header = {"X-Consumer-Custom-Id": "justa"} fr = [] # err = [] for el in tqdm_notebook(err): try: pa = CriteriosElegibilidade(cnpj=el, produto='justa') pa.get_dados() dff = pa.dados dff['adquirentes'] = "justa" fat_medio = dff.groupby(["data"]).sum()["valor"].mean() dff.dropna(inplace=True) fluxos = dict() for adq in dff['adquirentes'].unique().tolist(): dt = dff[dff['adquirentes']==adq] dt['data'] = dt.apply(lambda x : str(x['data'].day) + "-" +str(x['data'].month)+"-" + str(x['data'].year), axis=1) fluxos[adq] = dt[['data', 'valor']].to_dict("records") body = { "fluxos" : fluxos, "cnpj" : str(el), "cnae" : "4744-0", "volume_escolhido" : dfvol[dfvol['cnpj']==el]["vol_max"].iloc[0] } req = requests.post(url, headers=header, json=body) js = req.json() if len(js) == 0: vol_max = 0 else: js = js.get("propostas")[0] devido = js.get("devido") r = js.get("retencao") fr.append(pd.DataFrame({"cnpj" : [el], "devido" : [devido], "retencao" : [r]})) except: print("error") err.append(el) # - df1 = pd.concat(fr) df2 = pd.concat(fr) df2 res = pd.concat([df1, df2]) res.merge(dfvol, left_on='cnpj', right_on="cnpj", how='left').to_excel("analise_planeta_20190725.xlsx") df1 = pd.concat(fr).dropna() df1 df2 = pd.concat(fr) dfvol = pd.concat([df1, df2]) dfvol js.get("propostas")[0] err dfp = pd.concat(fr) dfp.sort_values("vol_max") dfp[dfp["vol_max"]>0].to_excel("trava.xlsx") dfp.head() dfp[dfp["cnpj"]=='20737475000415'] sem_proposta = dfp[dfp["vol_max"]==0]["cnpj"].tolist() sem_proposta.__len__() engine = create_engine("mysql+pymysql://capMaster:#jackpot123#<EMAIL>:23306/varejo") con = engine.connect() for el in sem_proposta: con.execute("update fluxo_justa set flag_aprovacao=0 where cnpj='{}'".format(el)) con.close() engine = create_engine("mysql+pymysql://capmaster:#jackpot123#@<EMAIL>sv.sa-east-1.rds.amazonaws.com:23306/varejo") con = engine.connect() for el in sem_proposta: con.execute("update fluxo_justa set flag_aprovacao=0 where cnpj='{}'".format(el)) con.close() df_aprov = dfp[dfp["vol_max"]>0] df_aprov.shape dfop = pd.read_excel("analise_justa_final.xlsx") dfop.head() dfop["cnpj"] = dfop["cnpj"].astype(str) dfop["cnpj"] = dfop.apply(lambda x : "0" + x["cnpj"] if len(x["cnpj"])==13 else ("00" + x["cnpj"] if len(x['cnpj'])==12 else x["cnpj"]), axis=1) lista_op = dfop["cnpj"].unique().tolist() df_aprov.shape df_aprov = df_aprov[~df_aprov["cnpj"].isin(lista_op)] df_aprov.head() df_aprov.shape dftrava = pd.read_excel("consulta_trava_justa_20190612.xlsx") dftrava["cnpj"].iloc[0] dftrava["cnpj"] = dftrava["cnpj"].astype(str) dftrava[dftrava.index==84]["cnpj"].iloc[0] dftrava["cnpj"] = dftrava.apply(lambda x : "00" + x["cnpj"] if len(x["cnpj"])==12 else ("0" + x["cnpj"] if len(x["cnpj"])==13 else x["cnpj"]), axis=1) dftrava[dftrava["cnpj"]=='04943517000175'] fr = [] for el in dftrava["cnpj"].unique().tolist(): dt = dftrava[dftrava['cnpj']==el] lista_trava = dt['trava'].tolist() flag_trava = 'S' if 'S' in lista_trava else 'N' fr.append(pd.DataFrame({'cnpj' : [el], 'flag_trava' : [flag_trava]})) resp = pd.concat(fr) df_aprov.shape ret = df_aprov.merge(resp, left_on='cnpj', right_on='cnpj', how='left') ret[ret["cnpj"].isin(["30589990000106", "30589922000106", "30589922000147"])] ret.to_excel("pre_analise_justa_201906.xlsx") final["flag_pricing"] = final.apply(lambda x : 0 if x["cnpj"] in sem_proposta else 1, axis=1) final[final["flag_pricing"]==0].head() final.groupby("flag_aprovacao").count() final["flag_proposta"] = final.apply(lambda x : int(x["cnpj"] not in sem_proposta) if x["flag_aprovacao"]==1 else None, axis=1) final.drop(columns=['flag_consulta'], axis=1, inplace=True) final["produto"] = "justa" final["data_atualizacao"] = datetime.now().date() final["flag_aprovacao2"] = final.apply(lambda x : x["flag_aprovacao"] if x["flag_proposta"]==1 else 0, axis=1) final.drop(columns=["historico", "flag_aprovacao"], axis=1, inplace=True) final.rename(columns={"flag_aprovacao2" : "flag_aprovacao"}, inplace=True) final.head() engine = create_engine("mysql+pymysql://capMaster:#<EMAIL>#<EMAIL>:23306/varejo") con = engine.connect() final.to_sql("pre_analise", schema='varejo', con=con, if_exists='append', index=False) con.close() engine = create_engine("mysql+pymysql://capMaster:#<EMAIL>#<EMAIL>:23306/apiPricing") con = engine.connect() dfacomp = pd.read_sql("select cnpj, produto from acompanhamento where produto='JUSTA' and status!='QUITADA'", con) con.close() df_aprov.shape dfacomp df_aprov = df_aprov[~df_aprov["cnpj"].isin(dfacomp["cnpj"].tolist())] df_aprov.shape df_aprov.head() df_aprov.to_excel("pre_aprovados_justa_20190704.xlsx") cnpj = "00150714000186" produto = "justa" def get_score(cnpj, produto): url = "https://api.pricing.captalys.io/models/scoring/{}/{}".format(cnpj, produto) req = requests.get(url) return req.json().get("score") get_score(cnpj, produto) df_aprov["score"] = df_aprov.apply(lambda x : get_score(x["cnpj"], "justa"), axis=1) el = "00150714000186" produto = "justa" def get_fat_medio(cnpj, produto): ce = CriteriosElegibilidade(cnpj=cnpj, produto=produto) ce.get_dados() return np.around(ce.dados["valor"].mean(), 2) df_aprov["fat_medio"] = df_aprov.apply(lambda x : get_fat_medio(x["cnpj"], "justa"), axis=1) df_aprov["produto"] = "Justa" df_aprov["modelo"] = "PricingPadrao" df_aprov.rename(columns={'vol_max' : 'proposta_max'}, inplace=True) df_aprov["data_posicao"] = datetime.now().date() df_aprov.shape engine = create_engine("mysql+pymysql://capMaster:#<EMAIL>pot123#@<EMAIL>:23306/varejo") con = engine.connect() df_aprov.to_sql("propostas_mensais", schema="varejo", con=con, if_exists='append', index=False) con.close()
Modelagem/pre_analysis/pre_analise_justa.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # default_exp gradient # - #hide # %load_ext autoreload # %autoreload 2 # # gradient - Approximating the gradient # # # # A collection of classes and functions used to approximate the gradient. # *** # ## Background # # Spall's simultaneous perturbation stochastic approximation (SPSA) of the gradient provides an efficient means to approximate the gradient of high-dimensional models, even when only noisy evaluations of the objective function are available. This is in constrast to more typical applications of stochastic gradient descent, where the noisiness of the gradient comes not from the objective function itself, but rather from evaluating the gradient on subsets of the data. # # ### Approximating the gradient with SPSA # # The general idea of SPSA is reasonably straightforward. Given a step size $c_t$ and a vector of perturbations $\delta$, we first generate forward and backward perturbations all model parameters simultaneously # # $$\theta^+ = \theta + c_t \delta$$ # $$\theta^- = \theta - c_t \delta$$ # # The perturbation, $\delta$ is often sampled from a shifted and rescaled Bernoulli distribution as follows: # # $$b_1, b_2,..., b_m \sim Bernoulli(p=.5)$$ # $$\delta_i = 2b_i -1$$ # # where $\delta_i$ is the direction in which the $i$-th model parameter will be moved in the forward perturbation. # # We then evaluate the cost function $F(\theta, X)$ at the two perturbed parameters # # $$y^+ = F(\theta^+, X)$$ # $$y^- = F(\theta^-, X)$$ # # The gradient is approximated as the slope of the line between the points $(\theta^+, y^+)$ and $(\theta^-, y^-)$: # # $$\hat{g}= \frac{y^+-y^-}{\theta^+ - \theta^-}= \frac{y^+-y^-}{2 c_t \delta}$$ # # A major advantage of this approximation is that in its simplest form, only two evaluations of the cost function are required, regardless of the dimensionality of the model. This is in constrast to the [finite-differences approximation]() which requires each model parameter be perturbed separately. #hide from nbdev.showdoc import * #export import numpy import scipy from abc import ABC, abstractmethod # + #export class GradientBase(ABC): """A helper class that provides a standard means to create classes to provide gradients or their approximations to GradientDescent.""" @abstractmethod #This is the workhorse of the class def evaluate(self): pass # - # # *** # # ```GradientDescent``` must be passed an object with a method called ```.evaluate()```. This should store as an attribute the cost function to be evaluated and take the following inputs: # # 1. theta - A 1-D numpy array of model parameters # 2. c_k - A step size that may be used in the gradient evaluation # 3. gradient_reps - The number of times to evaluate the gradient (multiple evaluations will be averaged) # 4. update_rvs - Whether regenerated random variables stored in the cost function after each gradient evaluation # # It should return a vector of the same length as ```theta``` containing an estimate of the cost function's gradient at ```theta```. # # Any approach to gradient evaluation will require the first argument, ```theta```. The latter three are only necessary when using an approximation of the gradient. # # + #export class SPSAGradient(GradientBase): """A class for computing the SPSA gradient estimate.""" def __init__(self, param_subsets=None,fraction=None, cost=None): self.cost=cost self.param_subsets=param_subsets if self.param_subsets is not None: self.param_subsets=numpy.array(self.param_subsets) self.subsets=set(list(param_subsets)) def set_cost(self, cost): self.cost=cost def evaluate(self, theta, c_k, gradient_reps=1, update_rvs=False): """Inputs 1. theta - A 1-D numpy array of model parameters 2. c_k - A step size that may be used in the gradient evaluation 3. gradient_reps - The number of times to evaluate the gradient (multiple evaluations will be averaged) 4. update_rvs - Whether regenerated random variables stored in the cost function after each gradient evaluation Returns an array gradient estimates the same size as theta """ # assert len(theta)==len(self.) #If no subsets were defined, then now we'll define all model parameters as one set assert self.cost is not None if self.param_subsets is None: self.param_subsets=numpy.zeros(theta.shape[0]) self.subsets=set(list(self.param_subsets)) #evaluate the gradient separately for different groups of parameters grad_list=[] for rep in range(gradient_reps): if update_rvs==True: #Regenerate the random numbers in the cost with each gradient self.cost.sample_rvs() ghat=numpy.zeros(theta.shape) for s in self.subsets: param_filter=self.param_subsets==s ghat+=self.SPSA( theta, c_k, param_filter) grad_list.append(ghat) if gradient_reps==1: return grad_list[0] else: #We need to average # print (grad_list) # print ( numpy.mean(grad_list,0)) # print (jabber) return numpy.mean(grad_list,0) def SPSA(self, theta, ck, param_ind): """ Inputs: cost - a function that takes model parameters and data as inputs and returns a single float data - the data the model is being fit to theta - a set model parameters ck - the step size to be used during perturbation of the model parameters Outputs: An estimate of the gradient """ #Draw the perturbation delta=2.*scipy.stats.bernoulli.rvs(p=.5,size=theta.shape[0])-1. #hold delta constant for the parameters not under consideration delta[~param_ind]=0. #Perturb the parameters forwards and backwards thetaplus=theta+ck*delta thetaminus=theta-ck*delta #Evaluate the objective after the perturbations yplus=self.cost.evaluate(thetaplus) yminus=self.cost.evaluate(thetaminus) #Compute the slope across the perturbation ghat=(yplus-yminus)/(2*ck*delta) ghat[~param_ind]=0 return ghat # - # *** # # The `SPSAGradient` class is used by `GradientDescent` to approximate the gradient of an objective function, which can then be used to update model parameters. # # This takes two arguments, both of which are optional: # # 1. ```param_subsets``` (optional) - A list or array of labels that defines groups of parameters. For example, \[0,0,0,1,1,1] defines the first three model parameters as group 0 and the last three as belong to group 1. # # 2. ```cost``` (optional) - The cost function used in the gradient evaluation. When passing an instance of the `SPSAGradient` class to the `GradientDescent` optimizer, this should be left undefined. The `GradientDescent` object will automatically add the cost function being optimized to the `SPSAGradient` if its cost function has not been defined. # # # # #### Perturbing subset of parameters # # In some models, it might be desirable to evaluate the gradient separately for different subsets of parameters. For example, in variational inference, the means of the posterior approximation have a much stronger impact on the loss function than the standard deviations do. In that case, perturbing all parameters at once is likely to pick up the impact of perturbing the means on the gradient, but perhaps not the standard deviations. # # The ```param_labels``` option permits to the gradient approximation to be evaluated separately for subsets of parameters. If, for example. ```param_labels=[0,0,0,1,1,1]```, then the gradient will be approximated in two steps. The gradient will be estimated first for the three first parameters, perturbing them while holding the other parameters constant. Then the parameters labelled ```1``` will be perturbed, while all others are held constant. The cost of doing this is the number of cost function evaluations increases from $2$ to $2n$, where is $n$ number of parameter subset to be evaluated separately. # # #### Averaging multiple gradient approximations # # By default calling ```evaluate``` approximates the gradient from a single forward and backward perturbation. The argument ```gradient_reps``` can instead be set to an integer value greater than 1, to instead return the average of multiple gradient evaluations. If ```gradient_reps``` is set to $r$, ```evaluate``` will return the average of $r$ gradient approximations. This may lead to faster convergences.
04_gradient.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import matplotlib.pyplot as plt # %matplotlib inline df = pd.read_csv('marital status.csv'); df df.isnull().sum() missing = df['status'].median() df.status = df.status.fillna(missing) df df.isnull().sum() df['status'].value_counts() x = df[['age']] y = df[['status']] x # + # import the class from sklearn.linear_model import LogisticRegression # instantiate the model logreg = LogisticRegression(solver='liblinear') # - logreg.fit(x,y) logreg.predict(x) y_pred = logreg.predict(x) from sklearn import metrics print(metrics.accuracy_score(y, y_pred)) from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(x,y, random_state = 1, test_size = 0.30) # + # import the class from sklearn.linear_model import LogisticRegression # instantiate the model logreg = LogisticRegression(solver='liblinear') # - # fit the model with data logreg.fit(X_train , Y_train) X_test # predict the response values for the observations in X logreg.predict(X_test)
Machine Learning Models/Supervised Learning/Classification/Logistic Regression.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.5.3 # language: julia # name: julia-1.5 # --- using PyPlot using LinearAlgebra # for svd and trig functions using Printf using Statistics # for mean function function plot_singular_vectors(V_or_U, ax, width, head_length, head_width, labels, label_dist) x_plot = V_or_U .- head_length .* V_or_U ./ norm.(V_or_U) ax.arrow(0, 0, x_plot[1,1], x_plot[2,1], width=width, head_width=head_width, head_length=head_length, fc="#a9a9a9", ec="#a9a9a9", zorder=10) ax.arrow(0, 0, x_plot[1,2], x_plot[2,2], width=width, head_width=head_width, head_length=head_length, fc="#a9a9a9", ec="#a9a9a9", zorder=10) x_label = V_or_U .+ V_or_U ./ norm(V_or_U) .* label_dist ax.text(x_label[1,1], x_label[2,1], labels[1], fontsize=20) ax.text(x_label[1,2], x_label[2,2], labels[2], fontsize=20) end function move_axes_to_origin(ax, axes_coords::Union{Missing, Array{Float64,2}}=missing) ax.xaxis.tick_bottom() ax.xaxis.set_ticks_position("top") ax.xaxis.set_label_position("bottom") ax.spines["right"].set_position("zero") ax.spines["right"].set_linewidth(3.5) ax.spines["left"].set_color("none") ax.yaxis.tick_right() ax.spines["top"].set_position("zero") ax.spines["top"].set_linewidth(3.5) ax.spines["bottom"].set_color("none") ax.set_axisbelow(false) ax.set_xticks([]) ax.set_yticks([]) if typeof(axes_coords) != Missing @assert length(axes_coords) == 4 && size(axes_coords) == (2,2) ax.xaxis.set_label_coords(axes_coords[1,1], axes_coords[1,2]) ax.yaxis.set_label_coords(axes_coords[2,1], axes_coords[2,2]) end end function plot_apple_unit_circle(ax, T::Array{Float64, 2}; N::Int=250) # Lets first grab the `hsv` colormap from the matplotlib package # and normalize it using `vmin` and `vmax` # set_array([]) is an obscure trick which allows me to use # the colormap properly for some reason cnorm = PyPlot.matplotlib.colors.Normalize(vmin=0, vmax=2*π) m = plt.cm.ScalarMappable(norm=cnorm, cmap=plt.cm.hsv) m.set_array([]) θ = range(0, stop=2*π, length=N) a = transpose(hcat(cos.(θ), sin.(θ))) for i = 1:length(θ)-1 ax.plot([a[1,i], a[1,i+1]], [a[2,i], a[2,i+1]], lw=8, c=m.to_rgba(mean(θ[i:i+1]))) end F = svd(T) plot_singular_vectors(F.V, ax, 0.02, 0.1, 0.1, ["\$\\mathbf{v}_1\$", "\$\\mathbf{v}_2\$"], 0.2) move_axes_to_origin(ax, [1.01 0.59; 0.55 0.97]) ax.set_aspect("equal") ax.set_xlabel("\$a_1^{*}\$", fontsize=20) ax.set_ylabel("\$a_2^{*}\$", fontsize=20, rotation=0) ax.set_xticks([-1, 1]) ax.set_xticklabels(ax.get_xticks(), fontsize=18) ax.set_yticks([-1, 1]) ax.set_yticklabels(ax.get_yticks(), fontsize=18) end fig, ax = plt.subplots() T = [26. 74.; 66. 34.] plot_apple_unit_circle(ax, T) fig.savefig("apple_circle.png", transparent="true", dpi=300, format="png") function plot_quality_ellipse(ax, T::Array{Float64, 2}; N::Int=250) # We will use the same exact colormap because the colors will # correspond to each other on the unit circle and the ellipse cnorm = PyPlot.matplotlib.colors.Normalize(vmin=0, vmax=2*π) m = plt.cm.ScalarMappable(norm=cnorm, cmap=plt.cm.hsv) m.set_array([]) θ = range(0, stop=2*π, length=N) a = transpose(hcat(cos.(θ), sin.(θ))) q = T * a for i = 1:length(θ)-1 ax.plot([q[1,i], q[1,i+1]], [q[2,i], q[2,i+1]], lw=8, c=m.to_rgba(mean(θ[i:i+1]))) end F = svd(T) Uσ = F.U .* [F.S[1] F.S[2]; F.S[1] F.S[2]] plot_singular_vectors(Uσ, ax, 1.0, 9.0, 9.0, ["\$\\mathbf{u}_1\$", "\$\\mathbf{u}_2\$"], 15.) move_axes_to_origin(ax, [1.01 0.60; 0.55 0.95]) ax.set_aspect("equal") ax.set_xlabel("\$q_1^{*}\$", fontsize=20) ax.set_ylabel("\$q_2^{*}\$", fontsize=20, rotation=0) ax.set_xticks([-50, 50]) ax.set_xticklabels(ax.get_xticks(), fontsize=18) ax.set_yticks([-50, 50]) ax.set_yticklabels(ax.get_yticks(), fontsize=18) end function make_svd_visualization(T::Array{Float64, 2}; extra_arrow::Union{Array{Float64, 1}, Missing}=missing, label_postfix="") fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(11, 5), gridspec_kw = Dict("top" => 1.0, "bottom" => 0.0)) plot_apple_unit_circle(axs[1], T) plot_quality_ellipse(axs[2], T) if ismissing(extra_arrow) fig.savefig("svd_viz" * label_postfix * ".png", transparent="true", format="png", dpi=300) else extra_arrow = extra_arrow ./ norm(extra_arrow) extra_quality_arrow = T * extra_arrow x_plot = extra_arrow .- 0.1 .* extra_arrow ./ norm(extra_arrow) x_quality_plot = extra_quality_arrow .- 9 .* extra_quality_arrow ./ norm.(extra_quality_arrow) axs[1].arrow(0, 0, x_plot[1,1], x_plot[2,1], width=0.01, head_width=0.1, head_length=0.1, fc="#800000", ec="#800000", zorder=10) axs[2].arrow(0, 0, x_quality_plot[1,1], x_quality_plot[2,1], width=1., head_width=9., head_length=9., fc="#800000", ec="#800000", zorder=10) fig.savefig("svd_viz_w_vector" * label_postfix * ".png", transparent="true", format="png", dpi=300) end return end T = [26. 74.; 66. 34.] make_svd_visualization(T) make_svd_visualization(T, extra_arrow=[4.,-2.]) make_svd_visualization(T, extra_arrow=[0.,-2.], label_postfix="2")
blog/visualize_svd_extra/svd_visualization.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Simple notebook pipeline # # Welcome to your first steps with Kubeflow Pipelines (KFP). This notebook demos: # # * Defining a Kubeflow pipeline with the KFP SDK # * Creating an experiment and submitting pipelines to the KFP run time environment using the KFP SDK # # Reference documentation: # * https://www.kubeflow.org/docs/pipelines/sdk/sdk-overview/ # * https://www.kubeflow.org/docs/pipelines/sdk/build-component/ # ### Prerequisites: Install or update the pipelines SDK # # You may need to **restart your notebook kernel** after updating the KFP sdk. # # This notebook is intended to be run from a Kubeflow notebook server. (From other environments, you would need to pass different arguments to the `kfp.Client` constructor.) # You may need to restart your notebook kernel after updating the kfp sdk # !python3 -m pip install kfp --upgrade --user # ### Setup # EXPERIMENT_NAME = 'Simple notebook pipeline' # Name of the experiment in the UI BASE_IMAGE = 'tensorflow/tensorflow:2.0.0b0-py3' # Base image used for components in the pipeline import kfp import kfp.dsl as dsl from kfp import compiler from kfp import components # ### Create pipeline component # #### Create a python function @dsl.python_component( name='add_op', description='adds two numbers', base_image=BASE_IMAGE # you can define the base image here, or when you build in the next step. ) def add(a: float, b: float) -> float: '''Calculates sum of two arguments''' print(a, '+', b, '=', a + b) return a + b # #### Build a pipeline component from the function # Convert the function to a pipeline operation. add_op = components.func_to_container_op( add, base_image=BASE_IMAGE, ) # ### Build a pipeline using the component @dsl.pipeline( name='Calculation pipeline', description='A toy pipeline that performs arithmetic calculations.' ) def calc_pipeline( a='0', b='7', c='17', ): #Passing pipeline parameter and a constant value as operation arguments add_task = add_op(a, 4) #Returns a dsl.ContainerOp class instance. #You can create explicit dependency between the tasks using xyz_task.after(abc_task) add_2_task = add_op(a, b) add_3_task = add_op(add_task.output, add_2_task.output) # ### Compile and run the pipeline # Kubeflow Pipelines lets you group pipeline runs by *Experiments*. You can create a new experiment, or call `kfp.Client().list_experiments()` to see existing ones. # If you don't specify the experiment name, the `Default` experiment will be used. # # You can directly run a pipeline given its function definition: # Specify pipeline argument values arguments = {'a': '7', 'b': '8'} # Launch a pipeline run given the pipeline function definition kfp.Client().create_run_from_pipeline_func(calc_pipeline, arguments=arguments, experiment_name=EXPERIMENT_NAME) # The generated links below lead to the Experiment page and the pipeline run details page, respectively # Links above may be wrong due to a host and ui-host diff. # Links should look like: # > http://{kubeflow_ip:port}/pipeline#/experiments/details/{id} # Alternately, you can separately compile the pipeline and then upload and run it as follows: # Compile the pipeline pipeline_func = calc_pipeline pipeline_filename = pipeline_func.__name__ + '.pipeline.zip' compiler.Compiler().compile(pipeline_func, pipeline_filename) # Get or create an experiment client = kfp.Client() experiment = client.create_experiment(EXPERIMENT_NAME) # Links above may be wrong due to a host and ui-host diff. # Links should look like: # > http://{kubeflow_ip:port}/pipeline#/experiments/details/{id} # Submit the compiled pipeline for execution: # + # Specify pipeline argument values arguments = {'a': '7', 'b': '8'} # Submit a pipeline run run_name = pipeline_func.__name__ + ' run' run_result = client.run_pipeline(experiment.id, run_name, pipeline_filename, arguments) # The generated link below leads to the pipeline run information page. # - # Links above may be wrong due to a host and ui-host diff. # Links should look like: # > http://{kubeflow_ip:port}/pipeline#/experiments/details/{id} # ### That's it! # You just created and deployed your first pipeline in Kubeflow! You can put more complex python code within the functions, and you can import any libraries that are included in the base image (you can use [VersionedDependencies](https://kubeflow-pipelines.readthedocs.io/en/latest/source/kfp.compiler.html#kfp.compiler.VersionedDependency) to import libraries not included in the base image). # ---- # Copyright 2019 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
03-pipelines/simple-notebook-pipeline_[TF2]/.ipynb_checkpoints/Simple_Notebook_Pipeline-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="d223de71-001" colab_type="text" # #1. Install Dependencies # First install the libraries needed to execute recipes, this only needs to be done once, then click play. # # + id="d223de71-002" colab_type="code" # !pip install git+https://github.com/google/starthinker # + [markdown] id="d223de71-003" colab_type="text" # #2. Get Cloud Project ID # To run this recipe [requires a Google Cloud Project](https://github.com/google/starthinker/blob/master/tutorials/cloud_project.md), this only needs to be done once, then click play. # # + id="d223de71-004" colab_type="code" CLOUD_PROJECT = 'PASTE PROJECT ID HERE' print("Cloud Project Set To: %s" % CLOUD_PROJECT) # + [markdown] id="d223de71-005" colab_type="text" # #3. Get Client Credentials # To read and write to various endpoints requires [downloading client credentials](https://github.com/google/starthinker/blob/master/tutorials/cloud_client_installed.md), this only needs to be done once, then click play. # # + id="d223de71-006" colab_type="code" CLIENT_CREDENTIALS = 'PASTE CLIENT CREDENTIALS HERE' print("Client Credentials Set To: %s" % CLIENT_CREDENTIALS) # + [markdown] id="d223de71-007" colab_type="text" # #4. Execute Test Script # This does NOT need to be modified unless you are changing the recipe, click play. # # + id="d223de71-008" colab_type="code" from starthinker.util.configuration import Configuration from starthinker.util.configuration import execute from starthinker.util.recipe import json_set_fields USER_CREDENTIALS = '/content/user.json' TASKS = [ { 'hello': { 'auth': 'user', 'hour': [ 1 ], 'say': 'Hello At 1', 'sleep': 0 } }, { 'hello': { 'auth': 'user', 'hour': [ 3 ], 'say': 'Hello At 3', 'sleep': 0 } }, { 'hello': { 'auth': 'user', 'hour': [ ], 'say': 'Hello Manual', 'sleep': 0 } }, { 'hello': { 'auth': 'user', 'hour': [ 23 ], 'say': 'Hello At 23 Sleep', 'sleep': 30 } }, { 'hello': { 'auth': 'user', 'say': 'Hello At Anytime', 'sleep': 0 } }, { 'hello': { 'auth': 'user', 'hour': [ 1, 3, 23 ], 'say': 'Hello At 1, 3, 23', 'sleep': 0 } }, { 'hello': { 'auth': 'user', 'hour': [ 3 ], 'say': 'Hello At 3 Reordered', 'sleep': 0 } } ] execute(Configuration(project=CLOUD_PROJECT, client=CLIENT_CREDENTIALS, user=USER_CREDENTIALS, verbose=True), TASKS, force=True)
colabs/test.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Lab 2 # ### Part 3. Poetry generation # # Let's try to generate some poetry using RNNs. # # You have several choices here: # # * The Shakespeare sonnets, file `sonnets.txt` available in the notebook directory. # # * Роман в стихах "<NAME>" <NAME>. В предобработанном виде доступен по [ссылке](https://github.com/attatrol/data_sources/blob/master/onegin.txt). # # * Some other text source, if it will be approved by the course staff. # # Text generation can be designed in several steps: # # 1. Data loading. # 2. Dictionary generation. # 3. Data preprocessing. # 4. Model (neural network) training. # 5. Text generation (model evaluation). # import string import os # ### Data loading: Shakespeare # Shakespeare sonnets are awailable at this [link](http://www.gutenberg.org/ebooks/1041?msg=welcome_stranger). In addition, they are stored in the same directory as this notebook (`sonnetes.txt`). Simple preprocessing is already done for you in the next cell: all technical info is dropped. # + if not os.path.exists('sonnets.txt'): # !wget https://raw.githubusercontent.com/girafe-ai/ml-mipt/21f_basic/homeworks_basic/lab02_deep_learning/sonnets.txt with open('sonnets.txt', 'r') as iofile: text = iofile.readlines() TEXT_START = 45 TEXT_END = -368 text = text[TEXT_START : TEXT_END] assert len(text) == 2616 # - # In opposite to the in-class practice, this time we want to predict complex text. Let's reduce the complexity of the task and lowercase all the symbols. # # Now variable `text` is a list of strings. Join all the strings into one and lowercase it. # + # Join all the strings into one and lowercase it # Put result into variable text. # Your great code here rows = text text = (''.join(text)).lower() assert len(text) == 100225, 'Are you sure you have concatenated all the strings?' assert not any([x in set(text) for x in string.ascii_uppercase]), 'Uppercase letters are present' print('OK!') # - # ### Data loading: "<NAME>" # # + # #!wget https://raw.githubusercontent.com/attatrol/data_sources/master/onegin.txt #with open('onegin.txt', 'r', encoding='utf8') as iofile: # text = iofile.readlines() #text = [x.replace('\t\t', '') for x in text] # - # In opposite to the in-class practice, this time we want to predict complex text. Let's reduce the complexity of the task and lowercase all the symbols. # # Now variable `text` is a list of strings. Join all the strings into one and lowercase it. # Join all the strings into one and lowercase it # Put result into variable text. # Your great code here # text = (''.join(text)).lower() # Put all the characters, that you've seen in the text, into variable `tokens`. tokens = sorted(set(text)) tokens.append('|') # Create dictionary `token_to_idx = {<char>: <index>}` and dictionary `idx_to_token = {<index>: <char>}` # dict <index>:<char> # Your great code here token_to_idx = {token: idx for idx, token in enumerate(tokens)} # dict <char>:<index> # Your great code here id_to_token = {token_to_idx[token] : token for token in tokens} rows = [x.replace('\n', '') for x in rows] rows = [x.lower() for x in rows] MAX_LENGTH = max(map(len, rows)) # + import numpy as np def to_matrix(rows, max_len=None, pad=token_to_idx['|'], dtype='int32', batch_first = True): max_len = max_len or max(map(len, rows)) rows_ix = np.zeros([len(rows), max_len], dtype) + pad for i in range(len(rows)): line_ix = [token_to_idx[c] for c in rows[i]] rows_ix[i, :len(line_ix)] = line_ix if not batch_first: # convert [batch, time] into [time, batch] rows_ix = np.transpose(rows_ix) return rows_ix # - print('\n'.join(rows[::2000])) print(to_matrix(rows[::2000])) # *Comment: in this task we have only 38 different tokens, so let's use one-hot encoding.* # ### Building the model # Now we want to build and train recurrent neural net which would be able to something similar to Shakespeare's poetry. # # Let's use vanilla RNN, similar to the one created during the lesson. import torch, torch.nn as nn import torch.nn.functional as F class CharRNNCell(nn.Module): """ Implement the scheme above as torch module """ def __init__(self, num_tokens=len(tokens), embedding_size=16, rnn_num_units=64): super(self.__class__,self).__init__() self.num_units = rnn_num_units self.embedding = nn.Embedding(num_tokens, embedding_size) self.rnn_update = nn.Linear(embedding_size + rnn_num_units, rnn_num_units) self.rnn_to_logits = nn.Linear(rnn_num_units, num_tokens) def forward(self, x, h_prev): """ This method computes h_next(x, h_prev) and log P(x_next | h_next) We'll call it repeatedly to produce the whole sequence. :param x: batch of character ids, containing vector of int64 :param h_prev: previous rnn hidden states, containing matrix [batch, rnn_num_units] of float32 """ # get vector embedding of x x_emb = self.embedding(x) # compute next hidden state using self.rnn_update # hint: use torch.cat(..., dim=...) for concatenation x_and_h = torch.cat([x_emb, h_prev], dim= 1) h_next = self.rnn_update(x_and_h) h_next = torch.tanh(h_next) assert h_next.size() == h_prev.size() #compute logits for next character probs logits = self.rnn_to_logits(h_next) return h_next, F.log_softmax(logits, -1) def initial_state(self, batch_size): """ return rnn state before it processes first input (aka h0) """ return torch.zeros(batch_size, self.num_units, requires_grad=True) # Plot the loss function (axis X: number of epochs, axis Y: loss function). # + from IPython.display import clear_output from random import sample char_rnn = CharRNNCell() criterion = nn.NLLLoss(ignore_index=token_to_idx['|']) opt = torch.optim.Adam(char_rnn.parameters()) history = [] batch_size = 64 num_epoch = 3000 # - def rnn_loop(char_rnn, batch_ix): """ Computes log P(next_character) for all time-steps in names_ix :param names_ix: an int32 matrix of shape [batch, time], output of to_matrix(names) """ batch_size, max_length = batch_ix.size() hid_state = char_rnn.initial_state(batch_size) logprobs = [] for x_t in batch_ix.transpose(0,1): hid_state, logp_next = char_rnn(x_t, hid_state) # <-- here we call your one-step code logprobs.append(logp_next) return torch.stack(logprobs, dim=1) from matplotlib import pyplot as plt # + for i in range(num_epoch): batch_ix = to_matrix(sample(rows, batch_size), max_len=MAX_LENGTH) batch_ix = torch.tensor(batch_ix, dtype=torch.int64) logp_seq = rnn_loop(char_rnn, batch_ix) # compute loss predictions_logp = logp_seq[:, :-1] #--log od probs of next tokens actual_next_tokens = batch_ix[:, 1:] #real tokens loss = criterion( predictions_logp.contiguous().view(-1, len(tokens)), actual_next_tokens.contiguous().view(-1) ) # train with backprop loss.backward() opt.step() opt.zero_grad() history.append(loss.data.numpy()) if (i+1)%100==0: clear_output(True) plt.plot(history, label='loss') plt.legend() plt.show() assert np.mean(history[:10]) > np.mean(history[-10:]), "RNN didn't converge." # - def generate_sample(char_rnn, seed_phrase=' ', max_length=MAX_LENGTH, temperature=1.0): ''' The function generates text given a phrase of length at least SEQ_LENGTH. :param seed_phrase: prefix characters. The RNN is asked to continue the phrase :param max_length: maximum output length, including seed_phrase :param temperature: coefficient for sampling. higher temperature produces more chaotic outputs, smaller temperature converges to the single most likely output ''' x_sequence = [token_to_idx[token] for token in seed_phrase] x_sequence = torch.tensor([x_sequence], dtype=torch.int64) hid_state = char_rnn.initial_state(batch_size=1) #feed the seed phrase, if any for i in range(len(seed_phrase) - 1): hid_state, _ = char_rnn(x_sequence[:, i], hid_state) #start generating for _ in range(max_length - len(seed_phrase)): hid_state, logp_next = char_rnn(x_sequence[:, -1], hid_state) p_next = F.softmax(logp_next / temperature, dim=-1).data.numpy()[0] # sample next token and push it back into x_sequence next_ix = np.random.choice(len(tokens),p=p_next) next_ix = torch.tensor([[next_ix]], dtype=torch.int64) x_sequence = torch.cat([x_sequence, next_ix], dim=1) return ''.join([tokens[ix] for ix in x_sequence.data.numpy()[0]]) for _ in range(10): print(generate_sample(char_rnn)) # ### More poetic model # # Let's use LSTM instead of vanilla RNN and compare the results. # Plot the loss function of the number of epochs. Does the final loss become better? class CharLSTM(nn.Module): def __init__(self, num_tokens=len(tokens), emb_size=16, num_units=64): super(self.__class__, self).__init__() self.num_units = num_units self.emb = nn.Embedding(num_tokens, emb_size) self.lstm = nn.LSTM(emb_size, num_units, batch_first=True) self.hid_to_logits = nn.Linear(num_units, num_tokens) def forward(self, x, hid_states=None): assert isinstance(x.data, torch.LongTensor) x_emb = self.emb(x) if hid_states is None: hid_states = self.initial_state(1) h_seq, hid_states = self.lstm(self.emb(x), hid_states) next_logits = self.hid_to_logits(h_seq) next_logp = F.log_softmax(next_logits, dim=-1) return next_logp, hid_states def initial_state(self, batch_size): """ return rnn state before it processes first input (aka h0) """ return (torch.zeros(1, batch_size, self.num_units, requires_grad=True), torch.zeros(1, batch_size, self.num_units, requires_grad=True)) model = CharLSTM() opt = torch.optim.Adam(model.parameters()) history = [] criterion = nn.NLLLoss(ignore_index=token_to_idx['|']) batch_size = 64 num_epoch = 3000 # + for i in range(num_epoch): batch_ix = to_matrix(sample(rows, batch_size), max_len=MAX_LENGTH) batch_ix = torch.tensor(batch_ix, dtype=torch.int64) logp_seq, hid_states = model(batch_ix, hid_states=model.initial_state(batch_size=batch_size)) # compute loss predictions_logp = logp_seq[:, :-1] actual_next_tokens = batch_ix[:, 1:] loss = criterion( predictions_logp.contiguous().view(-1, len(tokens)), actual_next_tokens.contiguous().view(-1) ) # train with backprop loss.backward() opt.step() opt.zero_grad() history.append(loss.data.numpy()) if (i+1)%100==0: clear_output(True) plt.plot(history,label='loss') plt.legend() plt.show() assert np.mean(history[:10]) > np.mean(history[-10:]), "RNN didn't converge." # - # Generate text using the trained net with different `temperature` parameter: `[0.1, 0.2, 0.5, 1.0, 2.0]`. # # Evaluate the results visually, try to interpret them. def generate_sample(model, seed_phrase=' ', max_length=MAX_LENGTH, temperature=1.0): ''' The function generates text given a phrase of length at least SEQ_LENGTH. :param seed_phrase: prefix characters. The RNN is asked to continue the phrase :param max_length: maximum output length, including seed_phrase :param temperature: coefficient for sampling. higher temperature produces more chaotic outputs, smaller temperature converges to the single most likely output ''' x_sequence = [token_to_idx[token] for token in seed_phrase] x_sequence = torch.tensor([x_sequence], dtype=torch.int64) hid_state = model.initial_state(batch_size=1) #feed the seed phrase, if any for i in range(len(seed_phrase) - 1): _, hid_state = model(x_sequence[:, i].view(1, 1), hid_state) #start generating for _ in range(max_length - len(seed_phrase)): logp_next, hid_state = model(x_sequence[:, -1].view(1, 1), hid_state) p_next = F.softmax(logp_next / temperature, dim=-1).data.numpy()[0] # sample next token and push it back into x_sequence next_ix = np.random.choice(len(tokens), p=p_next.ravel()) next_ix = torch.tensor([[next_ix]], dtype=torch.int64) x_sequence = torch.cat([x_sequence, next_ix], dim=1) return ''.join([tokens[ix] for ix in x_sequence.data.numpy()[0]]) # + # Text generation with different temperature values here temps = [0.1, 0.2, 0.5, 1.0, 2.0] for t in temps: print(generate_sample(model, seed_phrase=' ', temperature=t)) # - # It seems that the best temperature is around 0.5, lower temperature model produces too many repeating words, higher temperature model generates non-existing words. # ### Saving and loading models # Save the model to the disk, then load it and generate text. Examples are available [here](https://pytorch.org/tutorials/beginner/saving_loading_models.html]). torch.save(model.state_dict(), 'lstm.model') model = CharLSTM() model.load_state_dict(torch.load('lstm.model')) # + # Text generation with different temperature values here temps = [0.1, 0.2, 0.5, 1.0, 2.0] for t in temps: print(generate_sample(model, seed_phrase=' ', temperature=t)) # - # ### References # 1. <a href='http://karpathy.github.io/2015/05/21/rnn-effectiveness/'> <NAME> blog post about RNN. </a> # There are several examples of genration: Shakespeare texts, Latex formulas, Linux Sourse Code and children names. # 2. <a href='https://github.com/karpathy/char-rnn'> Repo with char-rnn code </a> # 3. Cool repo with PyTorch examples: [link](https://github.com/spro/practical-pytorch`)
lab02_deep_learning/Lab2_DL_part3_poetry.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Data Analysis and Visualization # # This phase aims to analyze and visualize the data to provide meaningful insights. # # ### Objectives # 1. Perform basic analysis # 2. Perform exploratory data analysis # 3. Perform classical analysis # 4. Perform regression analysis import sys, os import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sys.path.append(os.path.abspath(os.path.join('..', 'utils'))) from utility import chi_square_test, MyLabelEncoder, plot_corr # !pip install squarify import squarify data = pd.read_csv('../Data/train.csv') data.shape # The data contains `381109` rows and `12` columns data.head() data.info() # **Observations** # # - There are no missing values in the dataset data.describe() license_dict = {0: "No License", 1: "Has License"} insured_dict = {0: "No", 1: "Yes"} response_dict = {0: "Not interested", 1: "Interested"} # + # visualization for distribution of the reponse labels_pct = (data['Response'].value_counts(normalize=True) * 100).tolist() # normalize the value counts to percentage labels = data['Response'].value_counts().tolist() labels_dict = {'Interested': str(round(labels_pct[0],2)) + '%', 'Not Interested': str(round(labels_pct[1], 2)) + '%' } fig, ax = plt.subplots(1, 1, figsize=(10, 8)) data['Response'].value_counts().plot(kind='bar') plt.text(0, labels[0] + 3000, labels_dict['Interested'], fontsize=11) plt.text(1, labels[1] + 3000, labels_dict['Not Interested'], fontsize=11) ax.set_xticklabels([response_dict[0], response_dict[1]]) plt.xticks(rotation=0) plt.title('Distribution of response', fontsize=16) fig.savefig('plots/response_distr.jpeg', dpi=82) plt.show() # - # **Observation** # - The dataset is imbalanced, only 12.26% of all `policy holders` that had a health insurance were interested in vehicle insurance. contigency_pct = pd.crosstab(data['Response'], data['Vehicle_Damage'], normalize=True) * 100 contigency_pct fig = plt.figure(figsize=(8,3)) plt.title('Contigency table of Response based on Vehicle_Damage(%)') sns.heatmap(contigency_pct, annot=True) fig.savefig('plots/response_veh_dam.jpeg', dpi=82) plt.show() # **Observations** # # 1. 49% of all policy holders with no vehicle damage in the past and were not interested in a vehicle insurance # 2. 0.26% of all policy holders with no vehicle damage in the past and were interested in a vehicle insurance # 3. 38% of all policy holders with a vehicle damage in the past were not interested in a vehicle insurance # 4. 12% of all policy holders with a vehicle damage in the past were interested in a vehicle insurance. label = data.groupby('Vehicle_Damage')['Response'].sum().index.get_level_values(0).tolist() totals = data.groupby('Vehicle_Damage')['Response'].count().reset_index().Response.values.tolist() sizes = data.groupby('Vehicle_Damage')['Response'].sum().reset_index().Response.values.tolist() sizes_pct = [size/data.shape[0]*100 for size, total in zip(sizes, totals)] label_fmt = [f'{label} = {size_pct:.2f}%' for label, size_pct in zip(label, sizes_pct)] color = ['green', 'blue'] # + fig, ax = plt.subplots(1, figsize=(8, 6)) squarify.plot(sizes=sizes_pct, label=label_fmt, color=color, alpha=.4, pad=False) plt.axis('off') plt.title('Treemap of policy holder interested in Vehicle Insurance\nBased on Vehicle Damage', fontsize=12) fig.savefig('plots/response_vehicle_dam.jpg', dpi=80) plt.show() # - # - Out of all policy holders that were interested in a vehicle insurance, 12.00% had a vehicle damage in the past. # - Out of all policy holders that were interested in a vehicle insurance, 0.26% did not have any occurence of vehicle damage in the past. # # > We can clearly observe that the chances of requesting for a vehicle insurance increases if the policy holder have encountered a vehicle damage in the past # histogram of age fig, ax = plt.subplots(figsize=(10, 8)) sns.histplot(x='Age', hue='Response', data=data, ax=ax) plt.title('Histogram of policy holder"s Age') fig.savefig('plots/age_dist.jpeg', dpi=82) plt.show() # histogram of age fig, ax = plt.subplots(figsize=(10, 8)) sns.boxplot(x='Response', y='Age', data=data, ax=ax) plt.title('Box plot of policy holder"s age based on Response') ax.set_xticklabels(['Not interested', 'Interested']) fig.savefig('plots/age_boxplot.jpg', dpi=82) plt.show() # + interested = data[data['Response'] == 1] not_interested = data[data['Response'] == 0] age_stat = pd.DataFrame(columns=['Interested', 'Not Interested'], index=['Mean', 'Median', 'Skew', 'Kurtosis']) age_stat.loc['Mean', 'Interested'] = interested['Age'].mean() age_stat.loc['Median', 'Interested'] = interested['Age'].median() age_stat.loc['Skew', 'Interested'] = interested['Age'].skew() age_stat.loc['Kurtosis', 'Interested'] = interested['Age'].kurtosis() age_stat.loc['Mean', 'Not Interested'] = not_interested['Age'].mean() age_stat.loc['Median', 'Not Interested'] = not_interested['Age'].median() age_stat.loc['Skew', 'Not Interested'] = not_interested['Age'].skew() age_stat.loc['Kurtosis', 'Not Interested'] = not_interested['Age'].kurtosis() age_stat # - # **Observation** # 1. The distribution of policy holders that are interested in vehicle insurance approximates a normal distribution # 2. Age 40 - 50 are more likely to be interested in vehicle insurance # 3. Age 20 - 34 are less likely to be interested in vehicle insurance # 4. The distribution of policy holders that are not interested in vehicle insurance shows a bit of skewness # 5. The median age of policy holders that are interested in vehicle insurance is 43 while the median age of policy holders that are not interested in vehicle insurance is 34 # histogram of age fig, ax = plt.subplots(figsize=(10, 8)) sns.histplot(x='Annual_Premium', data=data, ax=ax) fig.savefig('plots/annual_premium_hist.jpeg', dpi=82) plt.show() mask_2630 = data['Annual_Premium'] == 2630 data[mask_2630].shape[0] / data.shape[0] * 100 response_rate1 = data[mask_2630]['Response'].value_counts(normalize=True)[1] mask_g2630l100000 = (data['Annual_Premium'] > 2630) & (data['Annual_Premium'] < 100000) data[mask_g2630l100000].shape[0] / data.shape[0] * 100 response_rate2 = data[mask_g2630l100000]['Response'].value_counts(normalize=True)[1] mask_g100000 = data['Annual_Premium'] >= 100000 data[mask_g100000].shape[0] / data.shape[0] * 100 response_rate3 = data[mask_g100000]['Response'].value_counts(normalize=True)[1] temp_df = pd.DataFrame(columns=['Annual_Premium Response Rate(%)'], index=['= 2630', '> 2630 and < 100000', '>= 100000']) temp_df.loc['= 2630', 'Annual_Premium Response Rate(%)'] = response_rate1 * 100 temp_df.loc['> 2630 and < 100000', 'Annual_Premium Response Rate(%)'] = response_rate2 * 100 temp_df.loc['>= 100000', 'Annual_Premium Response Rate(%)'] = response_rate3 * 100 temp_df # **Observations** # 1. 17% of the data have an annual_premium amount of 2630.0 # 2. 82% of the data have an annual_premium amount greater than 2630 and less than 100000 # 3. 20% of the data have an annual_premium amount greater than or equal to 100000 # 4. We can clearly observe that the response rate of policy holders that have an annual premium fee of 2630 is 13.10% which is 0.84% more than the expected response rate total of 12.26% # 5. We can clearly observe that the response rate of policy holders that have an annual premium fee of > 2630 and < 100000 is 12.07% which is 0.19% less than the expected response rate total of 12.26% # 6. We can clearly observe that the response rate of policy holders that have an annual premium fee of >= 100000 is 15.81% which is 3.55% more than the expected response rate total of 12.26% # # > We conclude that on average the likelihood that a policy holder that has a health insurance would be interested in a vehicle insurance increases by 3.55% if the policy holders needs to pay an annual premium greater than 100000. # # sns.histplot(x='Vintage', data=data) plt.show() sns.kdeplot(x='Vintage', data=data, fill=True, hue='Response') plt.show() data['Previously_Insured'].value_counts(normalize=True) contigency_pct = pd.crosstab(data['Response'], data['Previously_Insured'], normalize=True) * 100 contigency_pct fig = plt.figure(figsize=(8,3)) plt.title('Contigency table of Response based on Previously Insured(%)') sns.heatmap(contigency_pct, annot=True) fig.savefig('plots/response_prev_ins.jpeg', dpi=82) plt.show() # **Observations** # # 1. 42% of all policy holders had no vehicle insurance in the past and were not interested in a vehicle insurance # 2. 12% of all policy holders had no vehicle insurance in the past and were interested in a vehicle insurance # 3. 46% of all policy holders had a vehicle insurance in the past and were not interested in a vehicle insurance # 4. 0.041% of all policy holders had a vehicle insurance in the past and were interested in a vehicle insurance cat_attribs = [attr for attr in data.columns if data[attr].dtype == np.dtype('O')] enc = MyLabelEncoder(cat_attribs) data = enc.fit_transform(data) corr = data.corr() fig = plot_corr(corr) fig.savefig('plots/corr_map.jpeg', dpi=82) # ### Classical Analysis data.head() X_attribs = ['Gender', 'Driving_License', 'Previously_Insured', 'Vehicle_Age', 'Vehicle_Damage'] chi_square_test(X_attribs, 'Response', data)
DataAnalysisAndViz/analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # coding: utf-8 import pandas as pd import numpy as np data = pd.read_table('fruit_data_with_colors_miss.txt') data data = pd.read_table('fruit_data_with_colors_miss.txt',na_values=['.','?']) data data.fillna(0) data.describe() data.fillna(data.mean()) pd.Series(data['fruit_subtype'].value_counts()).idxmax() data = data.fillna(data.mean()) data data['fruit_subtype'] = data['fruit_subtype'].fillna(pd.Series(data['fruit_subtype'].value_counts()).idxmax()) data data = pd.read_table('fruit_data_with_colors_miss.txt',na_values=['.','?']) data data.shape[0] data.isnull().sum() data.isnull().sum()/data.shape[0] * 100 data = data[['fruit_label','fruit_name','fruit_subtype','width','height','color_score']] data data = pd.read_table('fruit_data_with_colors_miss.txt',na_values=['.','?']) data = data.fillna(data.mean()) data = data[['mass','width','height','color_score']] data data.describe() #(valor - min) / (max-min) (25 - 12) / (59-12) (59-12) / (59-12) from sklearn.preprocessing import MinMaxScaler mm = MinMaxScaler() mm.fit(data) data_escala = mm.transform(data) data_escala data = pd.read_table('fruit_data_with_colors_miss.txt',na_values=['.','?']) data = data.fillna(data.mean()) macas = data[data['fruit_name'] == 'apple'] macas.describe() est = macas['mass'].describe() macas[(macas['mass'] > est['mean'] + (est['std']) * 2)] macas[(macas['mass'] < est['mean'] - (est['std']) * 2)] est['std']
Material, Exercicios/Codigos/iadell2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.6.8 64-bit # name: python3 # --- import pandas as pd import os import seaborn as sns import matplotlib.pyplot as plt import ast import numpy as np def main(experiment_name, pivot_on='num_groups'): print(experiment_name) df = pd.read_csv( os.path.join('figures', experiment_name, 'experiment_results.csv')) df['avg_accuracy'] = df['accuracies'].apply(lambda y: np.mean(ast.literal_eval(y))) df_pivot = df.pivot(index=pivot_on, columns='lstm_hidden_size', values='avg_accuracy').T plt.figure(figsize=(16,8)) sns.heatmap(df_pivot, annot=True, fmt='.2f')#, cmap='viridis') plt.savefig(f'figures//{experiment_name}.png', facecolor='white', transparent=False) plt.show() experiment_name = 'numGroups_vs_LSTMHiddenSize' main(experiment_name) experiment_name = 'numGroups_vs_LSTMHiddenSize_withReducerAttentionAndDropout' main(experiment_name) experiment_name = 'numGroups_vs_LSTMHiddenSize_withReducerAveragePooling' main(experiment_name) experiment_name = 'numGroups_vs_LSTMHiddenSize_withReducerAveragePoolingAndDropout' main(experiment_name) # From this, we conclude the averaging is scaling better than the attention layer. experiment_name = 'numNonzeros_vs_LSTMHiddenSize_withReducerAveragePoolingAndDropout' main(experiment_name, pivot_on='num_nonzeros_per_group') experiment_name = 'numNonzeros_vs_LSTMHiddenSize_GroupsSameNumNonzero_withReducerAveragePoolingAndDropout' main(experiment_name, pivot_on='num_nonzeros_per_group')
visualize_results.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # # !wget https://f000.backblazeb2.com/file/malay-dataset/voxceleb/voxceleb2-test-sample.json # # !wget https://f000.backblazeb2.com/file/malay-dataset/voxceleb/voxceleb2-test-labels.pkl # + import os os.environ['CUDA_VISIBLE_DEVICES'] = '' os.environ['MALAYA_USE_HUGGINGFACE'] = 'true' # - import malaya_speech import json import pickle from tqdm import tqdm with open('/home/husein/youtube/voxceleb2-test-sample.json') as fopen: sample_files = json.load(fopen) with open('/home/husein/youtube/voxceleb2-test-labels.pkl', 'rb') as fopen: labels = pickle.load(fopen) model = malaya_speech.speaker_vector.deep_model(model = 'vggvox-v2') # + unique_files = [] for l in labels: unique_files.extend(l[1:]) unique_files = list(set(unique_files)) # - unique_files[0] vectors = {} for f in tqdm(unique_files): y, _ = malaya_speech.load(f) v = model.vectorize([y])[0] vectors[f] = v # + import numpy as np scores, ls = [], [] for i in tqdm(range(len(labels))): ls.append(labels[i][0]) scores.append(np.sum(vectors[labels[i][1]] * vectors[labels[i][2]])) # - len(scores) def calculate_eer(y, y_score): from scipy.optimize import brentq from sklearn.metrics import roc_curve from scipy.interpolate import interp1d fpr, tpr, thresholds = roc_curve(y, y_score, pos_label=1) eer = brentq(lambda x : 1. - x - interp1d(fpr, tpr)(x), 0., 1.) thresh = interp1d(fpr, thresholds)(eer) return eer, thresh calculate_eer(ls, scores)
pretrained-model/speaker-embedding/calculate-EER/vggvox-v2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import numpy as np import pandas as pd import tensorflow as tf import re import string from tensorflow.keras import layers from tensorflow.keras import losses from tensorflow import keras # requires update to tensorflow 2.4 # >>> conda activate PIC16B # >>> pip install tensorflow==2.4 from tensorflow.keras.layers.experimental.preprocessing import TextVectorization from tensorflow.keras.layers.experimental.preprocessing import StringLookup from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder # for embedding viz import plotly.express as px import plotly.io as pio pio.templates.default = "plotly_white" # - df = pd.read_csv("../datasets/tcc_ceds_music.csv") df.columns scalars = ['dating', 'violence', 'world/life', 'night/time', 'shake the audience', 'family/gospel', 'romantic', 'communication', 'obscene', 'music', 'movement/places', 'light/visual perceptions', 'family/spiritual', 'like/girls', 'sadness', 'feelings', 'danceability', 'loudness', 'acousticness', 'instrumentalness', 'valence', 'energy'] data = { "lyrics" : df["lyrics"], "scalars": df[scalars], "genre" : df["genre"] } # parameters for pipeline num_genres = len(df["genre"].unique()) size_vocabulary = 2000 # + # inputs lyrics_input = keras.Input( shape = (None,), name = "lyrics" ) scalars_input = keras.Input( shape = len(scalars), name = "scalars" ) # + lyrics_features = layers.Embedding(size_vocabulary, 30)(lyrics_input) lyrics_features = layers.LSTM(128)(lyrics_features) merged = layers.concatenate([lyrics_features, scalars_input]) hidden_1 = layers.Dense(128, name = "hidden_1")(merged) output = layers.Dense(num_genres)(hidden_1) model = keras.Model( inputs = [lyrics_input, scalars_input], outputs = output ) # - model.summary() keras.utils.plot_model(model, "multi_input_and_output_model.png", show_shapes=True)
HW/music-scratch-2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # PyCBC: Python Software to Study Gravitational Waves# # # PyCBC is software developed by a collaboration of LIGO scientists. It is open source and freely available. We use PyCBC in the detection of gravitational waves from binary mergers such as GW150914. Below you will find links to examples that explore gravitational wave data, how we find potential signals, and learn about them. This notebook is interactive so feel free to modify yourself! Note that many of these are simplified for illustrative purposes. # # * Learn more about [PyCBC](https://pycbc.org/) # * Get a the complete LIGO PyCBC environment with our [docker images](http://pycbc/pycbc/latest/html/docker.html) # * Find more examples on our [documentation pages](http://pycbc.org/pycbc/latest/html/) # * PyCBC is open source and available on [github](https://github.com/gwastro/pycbc). # # ### [LOSC](https://losc.ligo.org/about/) ### # LIGO makes data open to the public through the LIGO Open Science Center. You can download data used on these pages from there and much more! # # Tutorials # # The following tutorials are meant to introduce one to the pycbc library and doing some basic analysis of gravitational-wave data. They are largely meant to be followed in sequence and build upon each other. If you want to learn to use the PyCBC library, it is strongly suggested to start here! # #### [1. Work with accessing the catalog of gravitational-wave mergers and LIGO/Virgo data](tutorial/1_CatalogData.ipynb) ### # #### [2. Visualize gravitational-wave data and start into signal processing](tutorial/2_VisualizationSignalProcessing.ipynb) ### # #### [3. Generate template waveforms and matched filtering](tutorial/3_WaveformMatchedFilter.ipynb) ### # #### [4. Signal Consistency testing and significance of GW170814 Virgo observation](tutorial/4_ChisqSignificance.ipynb) ### # # Further Short Examples # # ### GW170817: Investigate the first binary neutron star merger observed with gravitational waves! ## # #### [Estimate the mass of the inspiralling neutron stars and see the signal in the data](examples/gw170817_mass_estimate.ipynb) ### # ### GW150914: Investigate the first BBH merger detected ## # #### [See the signal in the data](examples/gw150914_look.ipynb) ### # #### [Listen to the merger converted to audio](examples/gw150914_audio.ipynb) ### # #### [Generate the estimated gravitational waveform and calculate the signal-to-noise](examples/gw150914_snr.ipynb) ### # #### [Estimate the mass of the black holes in the merger and subtract from the data](examples/mass_estimate_subtract.ipynb) ### # ### GW151226 ## # #### [Generate the estimated gravitational waveform and calculate the signal-to-noise](examples/gw151226_snr.ipynb) ### # ### LVT151012 ## # #### [Generate the estimated gravitational waveform and calculate the signal-to-noise](examples/lvt151012_snr.ipynb) ### # ### GW170104 ## # #### [See the time frequency track of the signal in the data](examples/gw170104_look.ipynb) ### # ### Waveforms for Gravitational-wave Mergers ## # #### [Generate your first waveform here!](examples/waveforms_start.ipynb) ### # #### [See the effect of changing the sky location and orientation of a merger signal](examples/waveform_skyloc_orientation.ipynb) ### # #### [Compare how similar waveforms are to each other](examples/waveform_similarity.ipynb) ### # ### Generating Simulated Noise ## # #### [Generate noise directly in the frequency domain](examples/generate_noise_in_frequency_domain.ipynb) ###
PyCBC-Tutorials-master/index.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # 假设我是一名证券分析师,我跟踪了很多支股票,每一支股价信息存在不同的csv表格里面。 # 现在我要,把不同股票的信息(AAPL.csv, AMAZ.csv等等,文件名称是股票代码),合并到一个excel文件里(如stock_price.xlsx)。 # 在合并文件里,每一个sheet都是不同的股票信息,sheet的名字是股票代码。 # 在一个sheet中,有7列,分别是交易日期,开盘价,当日最高价,最低价,复权后的最高,最低价,以及成交量。 # # 需要做的事情有: # 1. 利用其他的excel表格,生成stock_price.xlsx这样的一个合并表格 # 2. 算出每一支股票在每一个自然月中价格变动幅度(百分数),另存成一个sheet # 3. 算出每支股票近一年的涨幅(百分数),生成一个新sheet,两列,第一列是股票代码,第二列是涨幅,按照涨幅从大到小排序 # # 合并出来的表可能很大,excel加载慢,复杂运算可能造成司机,python读取和操作更快 # 这个可能也可以用在银行客户管理上,可以用于合并每一个客户的存取款信息及账户余额信息,计算每月平均存款数值,检测账户金额异常变动等 # 头文件的引用 import pandas as pd import os # ## 个股csv文件读取 data = dict() for file in os.listdir('./'): file_split = file.split('.') if file_split[-1]=='csv': f = pd.read_csv(file_split[0]+".csv") data[file_split[0]] = f print(type(data)) stock_names = list(data.keys()) stock_names type(data['AMZN']) # ## 文件数据概述 example=data['AMZN'].copy() example.head(2) example.columns example.describe() # 上面没有Date数据描述的原因是因为Date不是数字类型,是string object example.dtypes # #### 我们会想把日期转换为Python专门的Date格式,因为Python集成了许多对日期的操作可以直接使用,比如说日期可以直接比较大小,可以固定间隔采样日期等操作,我们就不需要自己考虑年月日之间的关系了。 # 此时Date列里是字符串 example['Date'][0] example['Date'] = pd.to_datetime(example['Date'], format="%Y/%m/%d") # 这时Date里已经是Python的日期格式了 example.dtypes # 将日期设为表格的y轴(index轴) example = example.set_index('Date') example.head(2) # 日期可以方便的直接比较 example.loc[example.index < '2014-12-03'] # 现在我们把上面的代码整理一下,写成一个对每只股票数据整理的函数 def readData(stock_data: pd.DataFrame) -> pd.DataFrame: """ Read the date column into datetime64, and make this column the index Args: stock_data: A dataframe that contains ['Date', 'Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'] Returns: Returns a dataframe with the date as row index """ stock_data['Date'] = pd.to_datetime(stock_data['Date'], format="%Y/%m/%d") stock_data = stock_data.set_index('Date') return stock_data # 我们把每一个股票的数据都处理一下 for stock_code in stock_names: data[stock_code] = readData(data[stock_code]) # #### 让我们看看Python日期模块有多强大,可以简单完成任意时间内的价格变动分析 # 看每两周的数据 example.resample('2W').first().head(2) # 以收盘价为参考看每个月价格的变动幅度 example['Close'].resample('1M').first() # 甚至是看最近的52周(一年)之内每个月的价格变动幅度 example['Close'].last('52W').resample('1M').first() # 有现成的函数ohlc()代表每个间隔内的open, high, low, close信息 monthly_ohlc = example['Close'].resample('1M').ohlc() monthly_ohlc # 这个表格每行的意思是,比如在2014年12月(11月只有一天所以用12月做例子)里收盘价从532跌倒了524,这个月里最高达到了525最低494,是不是非常简单。 # # 这里如果我们想在表格里加一列表示波动幅度百分比呢? monthly_ohlc['fluctuation %'] = (monthly_ohlc['close']-monthly_ohlc['open'])/monthly_ohlc['open']*100 monthly_ohlc.head(4) # 整理上面的代码,写一个函数可以生成每个股票的monthly浮动 def get_monthly(stock_data: pd.DataFrame) -> pd.DataFrame: monthly = stock_data['Close'].resample('1M').ohlc() monthly['fluctuation %'] = (monthly['close']-monthly['open'])/monthly['open']*100 return monthly for stock_code in list(stock_names): data[stock_code+"_monthly"] = get_monthly(data[stock_code]) data.keys() # ## 获取这一自然年内的股价 # 获取当前年份 year_now = example.last('1D').index[0].year year_now a_year_data = example[example.index.year == year_now] a_year_data.head(5) yearly_ohlc = a_year_data['Close'].resample('1Y').ohlc() yearly_ohlc # 加上浮动百分比,公司名称,与年份 yearly_ohlc['fluctuation %'] = (yearly_ohlc['close']-yearly_ohlc['open'])/yearly_ohlc['open']*100 yearly_ohlc["company_code"] = 'AMZN' yearly_ohlc["year"] = year_now yearly_ohlc.reset_index(drop=True,inplace=True) yearly_ohlc # 这时我们编写一个函数将将所有公司的这个信息拼起来,就是上面的代码和起来 def thisYearChanges(data): all_stocks = pd.DataFrame() for stock_code in stock_names: stock_data = data[stock_code] # 获取当前年份 year_now = stock_data.last('1D').index[0].year # 只选用今年的数据 a_year_data = stock_data[stock_data.index.year == year_now] # 今年一整年收盘价的汇总 yearly_ohlc = a_year_data['Close'].resample('1Y').ohlc() # 添加浮动百分比,公司名称与年份到表格中 yearly_ohlc['fluctuation%'] = (yearly_ohlc['close']-yearly_ohlc['open'])/yearly_ohlc['open']*100 yearly_ohlc["company_code"] = stock_code yearly_ohlc["year"] = year_now # 去掉Date信息因为不再重要了 yearly_ohlc.reset_index(drop=True,inplace=True) all_stocks = all_stocks.append(yearly_ohlc) return all_stocks trend = thisYearChanges(data).sort_values(by=["fluctuation%"], ascending=False) trend # ## 下面我们来把我们处理好的data变量和trend变量储存到一个excel的不同tab里面去 output_file_name = "cleaned_data.xlsx" # + # Create a Pandas Excel writer using XlsxWriter as the engine. writer = pd.ExcelWriter(output_file_name, engine='xlsxwriter') # 写入data for stock_code in data.keys(): data[stock_code].to_excel(writer, sheet_name=stock_code) #写入trend trend.to_excel(writer, sheet_name="Trend", index=False) writer.save() # - # ## 代码纯享 # # 下面我们把这整个教程之中的有效代码提取出来,供大家快速翻阅(只是从上面复制粘贴下来的) # 头文件的引用 import pandas as pd import os # 读取各个股票csv文件 data = dict() for file in os.listdir('./'): file_split = file.split('.') if file_split[-1]=='csv': f = pd.read_csv(file_split[0]+".csv") data[file_split[0]] = f stock_names = list(data.keys()) # + # 我们将每个日期字符串转换成Python的日期格式 def readData(stock_data: pd.DataFrame) -> pd.DataFrame: # Read the date column into datetime64, and make this column the index stock_data['Date'] = pd.to_datetime(stock_data['Date'], format="%Y/%m/%d") stock_data = stock_data.set_index('Date') return stock_data # 我们把每一个股票的数据都处理一下 for stock_code in stock_names: data[stock_code] = readData(data[stock_code]) # - # 分析近一个自然年之内所有股票的波动幅度 def thisYearChanges(data): all_stocks = pd.DataFrame() for stock_code in stock_names: stock_data = data[stock_code] # 获取当前年份 year_now = stock_data.last('1D').index[0].year # 只选用今年的数据 a_year_data = stock_data[stock_data.index.year == year_now] # 今年一整年收盘价的汇总 yearly_ohlc = a_year_data['Close'].resample('1Y').ohlc() # 添加浮动百分比,公司名称与年份到表格中 yearly_ohlc['fluctuation%'] = (yearly_ohlc['close']-yearly_ohlc['open'])/yearly_ohlc['open']*100 yearly_ohlc["company_code"] = stock_code yearly_ohlc["year"] = year_now # 去掉Date信息因为不再重要了 yearly_ohlc.reset_index(drop=True,inplace=True) all_stocks = all_stocks.append(yearly_ohlc) return all_stocks trend = thisYearChanges(data).sort_values(by=["fluctuation%"], ascending=False) # 写一个函数可以生成每个股票的monthly浮动 def get_monthly(stock_data: pd.DataFrame) -> pd.DataFrame: monthly = stock_data['Close'].resample('1M').ohlc() monthly['fluctuation %'] = (monthly['close']-monthly['open'])/monthly['open']*100 return monthly for stock_code in stock_names: data[stock_code+"_monthly"] = get_monthly(data[stock_code]) # + # 保存至excel中 output_file_name = "cleaned_data.xlsx" # Create a Pandas Excel writer using XlsxWriter as the engine. writer = pd.ExcelWriter(output_file_name, engine='xlsxwriter') # 写入data for stock_code in data.keys(): data[stock_code].to_excel(writer, sheet_name=stock_code) #写入trend trend.to_excel(writer, sheet_name="Trend", index=False) writer.save() # -
course1_stock_excel/scene1/code.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="4Cmw2pFjWQvf" import numpy as np from scipy.stats import norm from scipy.optimize import minimize, rosen import sklearn.gaussian_process as gp from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import ConstantKernel, Matern, WhiteKernel, RBF,ExpSineSquared import math import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") # + colab={"base_uri": "https://localhost:8080/"} id="Lb8LTLt6Wq0N" outputId="2ffe5568-bc68-472b-f73e-61f364efb6f3" lbound = -1 rbound = 2 X = np.arange(lbound,rbound, 0.01).reshape(-1, 1) def function(X,noise=0): return -np.sin(3*X) - X**2 + 0.7*X + noise * np.random.randn(*X.shape) # return (math.pow((x2-5.1/(4*math.pow(3.14,2))*math.pow(x1,2)+5/3.14*x1-6),2)+10*(1-1/(8*3.14))*math.cos(x1)+10) function(np.array([[-0.36],[5]])) # + colab={"base_uri": "https://localhost:8080/"} id="aF7TRiGfYDNd" outputId="0a1779d7-fb3d-447d-efd3-0a57419e0c5d" a = np.linspace(-1,2,100) a = a.reshape(-1,1) l = function(a) print(np.max(l)) # + id="T0R0zcyRg4mB" ## return probability of improvement for random sample/s X def PI(X,X_t,gpr,e): y_t = gpr.predict(X_t) X = X.reshape((-1,1)) y,std = gpr.predict(X,return_std=True) std = std.reshape(-1,1) best_y = np.max(y_t) return norm.cdf((y-best_y-e)/std) def EI(X,X_t,gpr,e): y_t = gpr.predict(X_t) X = X.reshape((-1,1)) y,std = gpr.predict(X,return_std=True) std = std.reshape(-1,1) best_y = np.max(y_t) a = (y-best_y-e) ei = a*norm.cdf(a/std) + std*norm.pdf(a/std) ei[std==0] = 0 return ei # + id="V6Sl9E-UTDw7" ## function to get next point that optimise aquisition function def next_acquisition_point(X_t,gpr,e,trials,acq_func): min_val = 1 min_x = None def min_obj(x): return -acq_func(x,X_t,gpr,e) random_starts = np.random.uniform(-1,2,size=(trials,1)) for st in random_starts: candidate = minimize(min_obj,x0=st,bounds=np.array([[-1,2]]),method='L-BFGS-B') if candidate.fun < min_val: min_val = candidate.fun min_x = candidate.x return min_x.reshape(-1,1) # + id="FHse6G55Uk4o" ## Using BO for function optimisation def get_optimum(acq_func,runs=50): best_val = 0.500270129755324 iters = 30 dp = np.zeros((runs,iters+1)) for run in range(runs): kernel = ConstantKernel(1.0) * WhiteKernel() + ConstantKernel(1.0) * RBF() + 1.0 * ExpSineSquared() # kernel = ConstantKernel(1.0) * Matern(length_scale=1.0, nu=2.5) gpr = GaussianProcessRegressor(kernel=kernel, alpha=0) X_t = np.array([[-0.9]]) y_t = function(X_t) optimality_gap = best_val-y_t[0,0] dp[run,0] = optimality_gap for i in range(1,iters+1): gpr.fit(X_t,y_t) X_next = next_acquisition_point(X_t,gpr,0.001,10,acq_func) y_next = function(X_next) X_t = np.concatenate((X_t,X_next),axis=0) y_t = np.concatenate((y_t,y_next),axis=0) if best_val-y_t[i,0] < optimality_gap: optimality_gap = best_val-y_t[i,0] dp[run,i] = optimality_gap if runs==1: print(X_t) print(y_t) return dp dp_PI = get_optimum(PI,10) dp_EI = get_optimum(EI,10) # + id="GrckfiPpRRWt" def random_search(runs=10): best_val = 0.500270129755324 iters = 30 dp = np.zeros((runs,iters+1)) for run in range(10): X_t = np.array([[-0.9]]) y_t = function(X_t) optimality_gap = best_val-y_t[0,0] dp[run,0] = optimality_gap for i in range(1,iters+1): X_next = np.random.uniform(-1,2,size=(1,1)) y_next = function(X_next) X_t = np.concatenate((X_t,X_next),axis=0) y_t = np.concatenate((y_t,y_next),axis=0) if best_val-y_t[i,0] < optimality_gap: optimality_gap = best_val-y_t[i,0] dp[run,i] = optimality_gap return dp dp_random = random_search(10) # + id="At0Z1sw5wq0b" colab={"base_uri": "https://localhost:8080/", "height": 970} outputId="69f78da9-cba4-4bd4-c9eb-befd40961a45" ## plot showing optimality gap between max value obtained in each iteration and best value that can be obtained in the bound for two different aquisition functions - PI and EI. x = range(31) y = [] y1 = [] y2 = [] for i in range(31): mean = np.mean(dp_PI[:,i]) std = np.std(dp_PI[:,i]) dev_up = np.max(dp_PI[:,i]) dev_down = np.min(dp_PI[:,i]) y.append(mean) y1.append(mean-std/4) y2.append(mean+std/4) # y1.append(dev_up) # y2.append(dev_down) fig = plt.figure(num=1, figsize=(15, 15), dpi=80, facecolor='w', edgecolor='k') ax = fig.add_subplot(111) ax.fill_between(x, y1, y2, color="red", alpha=0.4,label='PI') ax.plot(x,y,'--',color='red') x = range(31) y = [] y1 = [] y2 = [] for i in range(31): mean = np.mean(dp_EI[:,i]) std = np.std(dp_EI[:,i]) dev_up = np.max(dp_EI[:,i]) dev_down = np.min(dp_EI[:,i]) y.append(mean) y1.append(mean-std/4) y2.append(mean+std/4) ax.fill_between(x, y1, y2, color="blue", alpha=0.4,label = 'EI') ax.plot(x,y,'--',color='blue') ax.legend(loc='upper right', borderpad=1, labelspacing=1,prop={'size':15}) ax.set_ylabel("Optimality Gap") ax.set_xlabel("Iteration no.") x = range(31) y = [] y1 = [] y2 = [] for i in range(31): mean = np.mean(dp_random[:,i]) std = np.std(dp_random[:,i]) dev_up = np.max(dp_random[:,i]) dev_down = np.min(dp_random[:,i]) y.append(mean) y1.append(mean-std/4) y2.append(mean+std/4) ax.fill_between(x, y1, y2, color="violet", alpha=0.4,label = 'Random search') ax.plot(x,y,'--',color='violet') ax.legend(loc='upper right', borderpad=1, labelspacing=1,prop={'size':15}) ax.set_ylabel("Optimality Gap") ax.set_xlabel("Iteration no.") ## plt.show(1) # + id="Lg2VEuVvtT7J"
practice-notebooks/BO.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Scraping necessary Frankenstein text from Gutenberg # Steps taken in pre-processing include: # 1. Downloading data from [Project Gutenberg](http://www.gutenberg.org/files/84/84-h/84-h.htm) # 2. Removing all Letter headings and Chapter headings (using Regex) # 3. Removing all empty lines (using Regex) # # I was able to accomplish all steps externally in VS Code.
DATA_Scraping/Scraping necessary Frankenstein text from Gutenberg.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # ### Let's import some libraries import numpy as np import pyart from pyscancf import pyscancf as pcf import matplotlib.pyplot as plt import xarray as xr import glob # ### Specify the input data directory and where do you want to save out data indir = 'B16' outdir = 'B16/output/' # ### if you want only polar data you have to put gridder option False, otherwise True, # Here, I will put it fasle and create only polar data, later I will call get_grid function and convert it to grid separately. pcf.cfrad(input_dir=indir, output_dir=outdir, gridder=False) # ### Now the polar data is generated, let's read polar data through pyart polar_files = sorted(glob.glob('B16/output/polar*nc')) print(len(polar_files)) print(polar_files) # Let's save our data in radars list radars = [] for file in polar_files: radar = pyart.io.read_cfradial(file) radars.append(radar) radars[0].info() # + ### Lets create a display, suppose we will want to see what is in these two file; # - for radar in radars: print(radar.fields.keys()) fig = plt.figure(figsize=[14,13]) for i in range(len(radars)): display = pyart.graph.RadarDisplay(radars[i]) display.plot('REF',sweep=0,cmap='pyart_NWSRef',ax = plt.subplot(2,2,i+1)) display.plot('VELH',sweep=0,cmap='pyart_NWSVel',ax=plt.subplot(2,2,i+3)) plt.show() import wradlib as wrl first_sweep = radar.fields['REF']['data'][radar.get_slice(0)] ## take only rain of first sweep first_sweep.shape p_rain = [] for radar in radars: polar_rain = wrl.zr.z_to_r(wrl.trafo.idecibel(first_sweep)) p_rain.extend(polar_rain) xr.DataArray(p_rain).mean(axis=1).plot() len(p_rain) # ### Now let's create this polar data to grid from netCDF4 import num2date for radar in radars: grid = pcf.get_grid(radar) pyart.io.write_grid(outdir+'grid_'+num2date( radar.time['data'],radar.time['units'])[0].strftime('%Y%m%d%H%M%S')+'.nc',grid) # ### Now we have created grid files, lets read them, with pyart grid_files = sorted(glob.glob('B16/output/grid*nc')) print(len(grid_files)) grids = [] for gfile in grid_files: grid = pyart.io.read_grid(gfile) pcf.plot_cappi(grid,'REF') grids.append(grid)
Examples/Example2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <NAME>. Сборник задач по линейной алгебре. СПб.: Лань, 2010. import numpy as np from datetime import date import myfunc from myfunc import det # # Глава 1. Определители # ## §1. Определители 2-го и 3-го порядков # + all_problems = [i for i in range(1, 123)] solved_Jupyter = [i for i in range(1, 5)]\ + [i for i in range(22, 30)]\ + [i for i in range(43, 56)]\ + [i for i in range(74, 78)]\ + [i for i in range(82, 86)] solved_by_hand = [] problems_num = [i for i in range(1, 123)] solved = solved_Jupyter + solved_by_hand problems_marked = ['\u0336'.join(' ' + str(i)) if i in solved else str(i) for i in all_problems] print(*problems_marked) print('\nРешены в Jupyter:') print(*solved_Jupyter) print('\nРешены в тетради:') print(*solved_by_hand) print('\nОсталось решить:') print(*[i for i in all_problems if i not in solved]) # - # Вычислить определители: problems = { 1: [ [5, 2], [7, 3] ], 2: [ [1, 2], [3, 4] ], 3: [ [3, 2], [8, 5] ], 4: [ [6, 9], [8, 12] ] } def print_answer1_4(N, m): """Выводит ответ на задания 1 - 4""" print(f'{N}. Ответ: {int(det(m))}') for N, m in problems.items(): print_answer1_4(N, m) # Задания 5 - 21 в решаются в символьном виде. # Пользуясь определителями, решить системы уравнений: problems = { 22: ([ [2, 5], [3, 7] ], [1, 2]), 23: ([ [2, -3], [4, -5] ], [4, 10]), 24: ([ [5, 7], [1, 2] ], [1, 0]), 25: ([ [4, 7], [5, 8] ], [-13, -14]) } def print_answer22_25(N, m, b): """Выводит ответ на задания 22 - 25""" print(f'{N}. Ответ: {myfunc.det_solve_2(m, b)}') for N, (m, b) in problems.items(): print_answer22_25(N, m, b) # 24 задача: опечатка либо в задаче, либо в ответе # Задания 26 - 27 решаются в символьном виде # Исследовать, будет ли система уравнений опреленна, неопределенна или противоречива: problems = { 28: ([ [4, 6], [6, 9] ], [2, 3]) } for N, (m, b) in problems.items(): D = det(m) m = np.array(m) det_1 = det(np.column_stack([b, m[:, 1]])) det_2 = det(np.column_stack([m[:, 0], b])) print(f'{N}. Определители D = {D}, D1 = {det_1}, D2 = {det_2}') if D == 0 and det_1 == 0 and det_2 == 0: print('Ответ: Все определители равны нулю, правило Крамера не подходит.'\ + '\nСистема неопределенна (имеет бесконечно много решений).') problems = { 29: ([ [3, -2], [6, -4] ], [2, 3]) } for N, (m, b) in problems.items(): D = det(m) m = np.array(m) det_1 = det(np.column_stack([b, m[:, 1]])) det_2 = det(np.column_stack([m[:, 0], b])) print(f'{N}. Определители D = {D}, D1 = {det_1}, D2 = {det_2}') print('Ответ: определитель системы равен нулю, а другие определители нулю не равны.'\ + '\nСистема противоречива (не имеет решений).') # Задания 29 - 37 решаются в символьном виде. Задания 38 - 42 на доказательства. # Вычислить определители 3-го порядка: problems = { 43: [ [2, 1, 3], [5, 3, 2], [1, 4, 3] ], 44: [ [3, 2, 1], [2, 5, 3], [3, 4, 2] ], 45: [ [4, -3, 5], [3, -2, 8], [1, -7, -5] ], 46: [ [3, 2, -4], [4, 1, -2], [5, 2, -3] ], 47: [ [3, 4, -5], [8, 7, -2], [2, -1, 8] ], 48: [ [4, 2, -1], [5, 3, -2], [3, 2, -1] ], 49: [ [1, 1, 1], [1, 2, 3], [1, 3, 6] ], 50: [ [0, 1, 1], [1, 0, 1], [1, 1, 0] ], 51: [ [5, 6, 3], [0, 1, 0], [7, 4, 5] ], 52: [ [2, 0, 3], [7, 1, 6], [6, 0, 5] ], 53: [ [1, 5, 25], [1, 7, 49], [1, 8, 64] ], 54: [ [1, 1, 1], [4, 5, 9], [16, 25, 81] ], 55: [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] } def print_answer43_55(N, m): """Выводит ответ на задания 43 - 55""" print(f'{N}. Ответ: {int(det(m))}.') for N, m in problems.items(): print_answer43_55(N, m) # Задания 56 - 73 решаются в символьном виде. # Пользуясь определителями, решить системы уравнений: 74 - 77 problems = { 74: ([ [2, 3, 5], [3, 7, 4], [1, 2, 2] ], [10, 3, 3]), 75: ([ [5, -6, 4], [3, -3, 2], [4, -5, 2] ], [3, 2, 1]), 76: ([ [4, -3, 2], [6, -2, 3], [5, -3, 2] ], [-4, -1, -3]), 77: ([ [5, 2, 3], [2, -2, 5], [3, 4, 2] ], [-2, 0, -10]) } def print_answer74_77(N, m, b): """Выводит ответ на задания 74 - 77""" print(f'{N}. Ответ: {myfunc.det_solve_3(m, b)}') for N, (m, b) in problems.items(): print_answer74_77(N, m, b) # Задания 78 - 81 решаются в символьном виде. # Исследовать, будет ли система уравнений опреленна, неопределенна или противоречива: # + problems = { 82: ([ [2, -3, 1], [3, -5, 5], [5, -8, 6] ], [2, 3, 5]), 83: ([ [4, 3, 2], [1, 3, 5], [3, 6, 9] ], [1, 1, 2]), 84: ([ [5, -6, 1], [3, -5, -2], [2, -1, 3] ], [4, 3, 5]), 85: ([ [2, -1, 3], [3, -2, 2], [5, -4, 0] ], [4, 3, 2]) } # - for N, (m, b) in problems.items(): D = det(m) m = np.array(m) det_1 = det(np.column_stack([b, m[:, 1], m[:, 2]])) det_2 = det(np.column_stack([m[:, 0], b, m[:, 2]])) det_3 = det(np.column_stack([m[:, 0], m[:, 1], b])) print(f'{N}. Определители D = {D}, D1 = {det_1}, D2 = {det_2}, D2 = {det_3},') if not any([D, det_1, det_2, det_3]): print('Ответ: Система неопределенна.') elif D == 0 and any([det_1, det_2, det_3]): print('Ответ: Система противоречива.') elif D != 0: print('Ответ: Система определенна и имеет одно решение.') # Задания 90 - 122 решаются в символьном виде. # ## §4. Вычисление определителей с числовыми элементами # + all_problems = [i for i in range(257, 278)] solved_Jupyter = [i for i in range(257, 263)]\ + [272] solved_by_hand = [] problems_num = [i for i in range(257, 279)] solved = solved_Jupyter + solved_by_hand problems_marked = ['\u0336'.join(' ' + str(i)) if i in solved else str(i) for i in all_problems] print(*problems_marked) print('\nРешены в Jupyter:') print(*solved_Jupyter) print('\nРешены в тетради:') print(*solved_by_hand) print('\nОсталось решить:') print(*[i for i in all_problems if i not in solved]) # - # Вычислить определители: problems = { 257: [ [1, 1, 1, 1], [1, -1, 1, 1], [1, 1, -1, 1], [1, 1, 1, -1] ], 258: [ [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 0, 1], [1, 1, 1, 0] ], 259: [ [2, -5, 1, 2], [-3, 7, -1, 4], [5, -9, 2, 7], [4, -6, 1, 2] ], 260: [ [-3, 9, 3, 6], [-5, 8, 2, 7], [4, -5, -3, -2], [7, -8, -4, -5] ], 261: [ [3, -3, -5, 8], [-3, 2, 4, -6], [2, -5, 7, 5], [-4, 3, 5, -6] ], 262: [ [2, -5, 4, 3], [3, -4, 7, 5], [4, -9, 8, 5], [-3, 2, -5, 3] ], 272: [ [35, 59, 71, 52], [42, 70, 77, 54], [43, 68, 72, 52], [29, 49, 65, 50] ] } for N, m in problems.items(): m = np.array(m) print(f'{N}. Ответ: {round(np.linalg.det(m))}') # В задачнике ответ к задаче 261 неправильный? # Все остальные задания данного параграфа однотипные и решаются аналогично # + m = np.array([ [-3, 9, 3, 6], [-5, 8, 2, 7], [4, -5, -3, -2], [7, -8, -4, -5] ]) b = [1, 1, 1, 1] # - print(round(np.linalg.det(m))) print(m) for i in range(m.shape[1]): M = m.copy() M[:, i] = b print(M)
linear_algebra/Linear_Algebra_Prosk.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- #Import the libraries import warnings import itertools import pandas_datareader as web import pandas as pd import numpy as np import statsmodels.api as sm import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') d = pd.read_csv('events.csv') d d['Date'] = pd.to_datetime(d['Date'],format = ('%Y%m%d')) d = d.set_index(['Date']) del d['Unnamed: 0'] d y = d['affect'].resample('MS').sum() y y.plot(figsize=(15, 6)) plt.show() #Creating the training data set p=d=q= range(0,2) pdq = list(itertools.product(p,d,q)) seasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(itertools.product(p,d,q))] print('Examples of parameter combinations for seasonal ARIMA...') print('SARIMAX: {} x {}'.format(pdq[1],seasonal_pdq[1])) print('SARIMAX: {} x {}'.format(pdq[1],seasonal_pdq[2])) print('SARIMAX: {} x {}'.format(pdq[2],seasonal_pdq[3])) print('SARIMAX: {} x {}'.format(pdq[2],seasonal_pdq[4])) # + warnings.filterwarnings("ignore") for param in pdq: for param_seasonal in seasonal_pdq: try: mod = sm.tsa.statespace.SARIMAX(y,order=param,seasonal_order=param_seasonal, enforce_stationarity=False, enforce_invertibility=False) results = mod.fit() print('ARIMA{}x{}12 - AIC:{}'.format(param,param_seasonal,results.aic)) except: continue # - mod = sm.tsa.statespace.SARIMAX(y,order=(1,1,1), seasonal_order =(1,1,1,12), enforce_stationarity = False, enforce_invertibility = False) results = mod.fit() print(results.summary().tables[1]) results.plot_diagnostics(figsize=(15,12)) plt.show() pred = results.get_prediction(start=pd.to_datetime('2015-01-01'),dynamic=False) pred_ci = pred.conf_int() # + plt.figure(figsize=(15, 6)) ax = y['2004':].plot(label='observed') pred.predicted_mean.plot(ax = ax,label='One-step ahead Forecast',alpha=.7) ax.fill_between(pred_ci.index,pred_ci.iloc[:, 0], pred_ci.iloc[:, 1],color='k',alpha=.2) ax.set_xlabel('Year') ax.set_ylabel('Cases') plt.legend() plt.show() # + y_forecasted = pred.predicted_mean y_truth = y['2015-01-01':] mse = ((y_forecasted - y_truth) **2).mean() print('The Mean Squared Error of our forecasts is {}'.format(round(mse,2))) # - pred_dynamic = results.get_prediction(start=pd.to_datetime('2015-01-01'),dynamic=True, full_result=True) pred_dynamic_ci = pred_dynamic.conf_int() # + plt.figure(figsize=(15,6)) ax = y['2004':].plot(label='observed', figsize=(20, 15)) pred_dynamic.predicted_mean.plot(label='Dynamic Forecast', ax=ax) ax.fill_between(pred_dynamic_ci.index, pred_dynamic_ci.iloc[:, 0], pred_dynamic_ci.iloc[:, 1], color='k', alpha=.25) ax.fill_betweenx(ax.get_ylim(), pd.to_datetime('2015-01-01'), y.index[-1], alpha=.1, zorder=-1) ax.set_xlabel('Year') ax.set_ylabel('Cases') plt.legend() plt.show() # + # Extract the predicted and true values of our time series y_forecasted = pred_dynamic.predicted_mean y_truth = y['2015-01-01':] # Compute the mean square error mse = ((y_forecasted - y_truth) ** 2).mean() print('The Mean Squared Error of our forecasts is {}'.format(round(mse, 2))) # + # Get forecast 500 steps ahead in future pred_uc = results.get_forecast(steps=50) # Get confidence intervals of forecasts pred_ci = pred_uc.conf_int() # + ax = y.plot(label='observed', figsize=(20, 15)) pred_uc.predicted_mean.plot(ax=ax, label='Forecast') ax.fill_between(pred_ci.index, pred_ci.iloc[:, 0], pred_ci.iloc[:, 1], color='k', alpha=.25) ax.set_xlabel('Year') ax.set_ylabel('Cases') plt.legend() plt.show() # -
projects/Insurgency_prediction Using ARIMAmodel/Insurgency prediction.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Title # + import warnings, re, glob, datetime, csv, sys, os, base64, io, spacy import pandas as pd import numpy as np from lxml import etree import dash, dash_table import dash_core_components as dcc from dash.dependencies import Input, Output, State import dash_html_components as html from jupyter_dash import JupyterDash # Import spaCy language model. nlp = spacy.load('en_core_web_sm') # Ignore simple warnings. warnings.simplefilter('ignore', DeprecationWarning) # Declare directory location to shorten filepaths later. abs_dir = "/Users/quinn.wi/Documents/SemanticData/" # - # ## Declare Functions # + # %%time """ XML Parsing Function: Get Namespaces """ def get_namespace(root): namespace = re.match(r"{(.*)}", str(root.tag)) ns = {"ns":namespace.group(1)} return ns # """ # XML Parsing Function: Retrieve XPaths # """ # def get_abridged_xpath(child): # while child.getparent().get('{http://www.w3.org/XML/1998/namespace}id') is None: # elem = child.getparent() # if elem.getparent().get('{http://www.w3.org/XML/1998/namespace}id') is not None: # ancestor = elem.getparent().tag # xml_id = elem.getparent().get('{http://www.w3.org/XML/1998/namespace}id') # abridged_xpath = f'.//ns:body//{ancestor}[@xml:id="{xml_id}"]/{child.tag}' # return abridged_xpath """ XML Parsing Function: Retrieve XPaths DOES NOT USE WHILE LOOP, which was breaking after adjustments. """ def get_abridged_xpath(child): if child.getparent().get('{http://www.w3.org/XML/1998/namespace}id') is not None: ancestor = child.getparent().tag xml_id = child.getparent().get('{http://www.w3.org/XML/1998/namespace}id') abridged_xpath = f'.//ns:body//{ancestor}[@xml:id="{xml_id}"]/{child.tag}' return abridged_xpath """ XML Parsing Function: Convert to String """ def get_text(elem): text_list = [] text = ''.join(etree.tostring(elem, encoding='unicode', method='text', with_tail=False)) text_list.append(re.sub(r'\s+', ' ', text)) return ' '.join(text_list) """ XML Parsing Function: Get Encoded Content """ def get_encoding(elem): encoding = etree.tostring(elem, pretty_print = True).decode('utf-8') encoding = re.sub('\s+', ' ', encoding) # remove additional whitespace return encoding """ XML Function: Build KWIC of Found Entities in Up Converted Encoding """ def get_kwic_encoding(converted_entity, converted_encoding, kwic_range): # Create keyword-in-context encoding fragments. c_entity_sequence = converted_entity.split(' ') c_encoding_sequence = converted_encoding.split(' ') # If tokenized sequence of converted entity is a subset in tokenized encoding... if c_encoding_sequence <= c_entity_sequence: sequence_list = [] # Create a list of index values where c_entity_sequence occurs in converted_encoding for i in c_entity_sequence: for idx, item in enumerate(c_encoding_sequence): if item == i: sequence_list.append(idx) else: # Create regex to account for possible encoding within converted entity. conv_ent_re = re.sub('<w>(.*)</w>', '<w>.*\\1.*</w>', i) if re.match(conv_ent_re, item): sequence_list.append(idx) # Return KWIC using list range. if sequence_list[0] - kwic_range < 0: # If first item in KWIC - kwic range is less than zero, start KWIC view at beginning of string. # Last item in list = sequence_list[-1] + 1 kwic_encoding = c_encoding_sequence[0: sequence_list[-1] + 1 + kwic_range] else: kwic_encoding = c_encoding_sequence[sequence_list[0] - kwic_range: sequence_list[-1] + 1 + kwic_range] # Convert list to string. kwic_encoding = ' '.join(kwic_encoding) return kwic_encoding """ XML Parsing Function: Write New Encoding with Up-Conversion """ def make_ner_suggestions(previous_encoding, entity, label, subset_ner, kwic_range, banned_list): # Regularize spacing & store data as new variable ('converted_encoding'). converted_encoding = re.sub('\s+', ' ', previous_encoding, re.MULTILINE) # Create regex that replaces spaces with underscores if spaces occur within tags. # This regex treats tags as a single token later. tag_regex = re.compile('<(.*?)>') # Accumulate underscores through iteration for match in re.findall(tag_regex, previous_encoding): replace_space = re.sub('\s', '_', match) converted_encoding = re.sub(match, replace_space, converted_encoding) # Up-convert entity (label remains unchanged). label = subset_ner[label] converted_entity = ' '.join(['<w>' + e + '</w>' for e in entity.split(' ')]) # Up-Converstion # Tokenize encoding and text, appending <w> tags, and re-join. converted_encoding = converted_encoding.split(' ') for idx, item in enumerate(converted_encoding): item = '<w>' + item + '</w>' converted_encoding[idx] = item converted_encoding = ' '.join(converted_encoding) # Get KWIC Encoding. prev_kwic_encoding = get_kwic_encoding(converted_entity, converted_encoding, kwic_range) prev_kwic_encoding = re.sub('<[/]?w>', '', prev_kwic_encoding) # Find converted entities and kwic-converted entities, even if there's additional encoding within entity. try: entity_regex = re.sub('<w>(.*)</w>', '(\\1)(.*?</w>)', converted_entity) entity_match = re.search(entity_regex, converted_encoding) ban_decision = [] for i in banned_list: if i in entity_match.group(0): ban_decision.append('y') if 'y' in ban_decision: return prev_kwic_encoding, "Already Encoded", "Already Encoded" # If expanded regex is in previous encoding, find & replace it with new encoding. elif entity_match: new_encoding = re.sub(f'{entity_match.group(0)}', f'<{label}>{entity_match.group(1)}</{label}>{entity_match.group(2)}', converted_encoding) # Remove <w> tags to return to well-formed xml. new_encoding = re.sub('<[/]?w>', '', new_encoding) # Remove underscores. new_encoding = re.sub('_', ' ', new_encoding) # Repeate process for KWIC new_kwic_encoding = re.sub(f'{entity_match.group(0)}', f'<{label}>{entity_match.group(1)}</{label}>{entity_match.group(2)}', prev_kwic_encoding) new_kwic_encoding = re.sub('<[/]?w>', '', new_kwic_encoding) new_kwic_encoding = re.sub('_', ' ', new_kwic_encoding) return prev_kwic_encoding, new_encoding, new_kwic_encoding else: return prev_kwic_encoding, 'Error Making NER Suggestions', 'Error Making NER Suggestions' # Up-conversion works well because it 'breaks' if an entity already has been encoded: # <w>Abel</w> (found entity) does not match <w><persRef_ref="abel-mary">Mrs</w> <w>Abel</persRef></w> # <persRef> breaks function and avoids duplicating entities. except: return 'Error Occurred with Regex.' """ NER Function """ # spaCy def get_spacy_entities(text, subset_ner): sp_entities_l = [] doc = nlp(text) for ent in doc.ents: if ent.label_ in subset_ner.keys(): sp_entities_l.append((str(ent), ent.label_)) else: pass return sp_entities_l """ XML & NER: Retrieve Contents """ def get_contents(ancestor, xpath_as_string, namespace, subset_ner): textContent = get_text(ancestor) # Get plain text. encodedContent = get_encoding(ancestor) # Get encoded content. sp_entities_l = get_spacy_entities(textContent, subset_ner) # Get named entities from plain text. return (sp_entities_l, encodedContent) """ XML: & NER: Create Dataframe of Entities """ def make_dataframe(child, df, ns, subset_ner, filename, descendant_order): abridged_xpath = get_abridged_xpath(child) entities, previous_encoding = get_contents(child, './/ns:.', ns, subset_ner) df = df.append({ 'file':re.sub('.*/(.*.xml)', '\\1', filename), 'descendant_order': descendant_order, # 'abridged_xpath':abridged_xpath, 'previous_encoding': previous_encoding, 'entities':entities, }, ignore_index = True) return df """ Parse Contents: XML Structure (ouput-data-upload) """ def parse_contents(contents, filename, date, ner_values): ner_values = ner_values.split(',') content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string).decode('utf-8') label_dict = {'PERSON':'persName', 'LOC':'placeName', # Non-GPE locations, mountain ranges, bodies of water. 'GPE':'placeName', # Countries, cities, states. 'FAC':'placeName', # Buildings, airports, highways, bridges, etc. 'ORG':'orgName', # Companies, agencies, institutions, etc. 'NORP':'name', # Nationalities or religious or political groups. 'EVENT':'name', # Named hurricanes, battles, wars, sports events, etc. 'WORK_OF_ART':'name', # Titles of books, songs, etc. 'LAW':'name', # Named documents made into laws. } #### Subset label_dict with input values from Checklist ***** subset_ner = {k: label_dict[k] for k in ner_values} # Run XML Parser + NER here. try: # Assume that the user uploaded a CSV file if 'csv' in filename: df = pd.read_csv( io.StringIO(decoded) ) # Assume that the user uploaded an XML file elif 'xml' in filename: xml_file = decoded.encode('utf-8') df = pd.DataFrame(columns = ['file', 'abridged_xpath', 'previous_encoding', 'entities']) root = etree.fromstring(xml_file) ns = get_namespace(root) # Search through elements for entities. desc_order = 0 for child in root.findall('.//ns:body//ns:div[@type="docbody"]', ns): abridged_xpath = get_abridged_xpath(child) for descendant in child: desc_order = desc_order + 1 df = make_dataframe(descendant, df, ns, subset_ner, filename, desc_order) df['abridged_xpath'] = abridged_xpath # Join data df = df \ .explode('entities') \ .dropna() df[['entity', 'label']] = pd.DataFrame(df['entities'].tolist(), index = df.index) df['new_encoding'] = df \ .apply(lambda row: make_ner_suggestions(row['previous_encoding'], row['entity'], row['label'], subset_ner, 4, banned_list), axis = 1) df[['prev_kwic', 'new_encoding', 'new_kwic']] = pd.DataFrame(df['new_encoding'].tolist(), index = df.index) # Add additional columns for user input. df['accept_changes'] = '' df['make_hand_edits'] = '' # Drop rows if 'new_encoding' value equals 'Already Encoded'. df = df[df['new_encoding'] != 'Already Encoded'] except Exception as e: return html.Div([ f'There was an error processing this file: {e}.' ]) # Return HTML with outputs. return html.Div([ # Print file info. html.Div([ html.H4('File Information'), html.P(f'{filename}, {datetime.datetime.fromtimestamp(date)}'), ]), html.Br(), # Return data table of element and attribute info. dash_table.DataTable( data = df.to_dict('records'), columns = [{'name':i, 'id':i} for i in df.columns], page_size=5, export_format = 'csv', style_cell_conditional=[ { 'if': {'column_id': c}, 'textAlign': 'left' } for c in ['Date', 'Region'] ], style_data_conditional=[ { 'if': {'row_index': 'odd'}, 'backgroundColor': 'rgb(248, 248, 248)' } ], style_header={ 'backgroundColor': 'rgb(230, 230, 230)', 'fontWeight': 'bold' } ), ]) # - # ## APP # + # %%time app = JupyterDash(__name__) # Preset Variables. ner_labels = ['PERSON','LOC','GPE','FAC','ORG','NORP','EVENT','WORK_OF_ART','LAW'] # Banned List (list of elements that already encode entities) banned_list = ['persRef'] # Layout. app.layout = html.Div([ # Title html.H1('Named Entity Recognition Helper'), # Add or substract labels to list for NER to find. Complete list of NER labels: https://spacy.io/api/annotation html.H2('Select Entities to Search For'), dcc.Checklist( id = 'ner-checklist', options = [{ 'label': i, 'value': i } for i in ner_labels], value = ['PERSON', 'LOC', 'GPE'] ), # Upload Data Area. html.H2('Upload File'), dcc.Upload( id = 'upload-data', children = html.Div([ 'Drag and Drop or ', html.A('Select File') ]), style={ 'width': '95%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px' }, multiple=True # Allow multiple files to be uploaded ), html.Div(id = 'output-data-upload'), ]) # Callbacks. # Upload callback variables & function. @app.callback(Output('output-data-upload', 'children'), [Input('upload-data', 'contents'), Input('ner-checklist', 'value')], [State('upload-data', 'filename'), State('upload-data', 'last_modified')]) def update_output(list_of_contents, ner_values, list_of_names, list_of_dates): if list_of_contents is not None: children = [ parse_contents(c, n, d, ner) for c, n, d, ner in zip(list_of_contents, list_of_names, list_of_dates, ner_values) ] return children if __name__ == "__main__": app.run_server(mode = 'inline', debug = True) # mode = 'inline' for JupyterDash # - # ## Test Area # + # %%time filename = abs_dir + "Data/TestEncoding/EditingData/test_xml-before.xml" # filename = abs_dir + "Data/TestEncoding/EditingData/JQADiaries-v33-1821-12-p001_copy.xml" xml_file = open(filename).read() root = etree.fromstring(xml_file.encode('utf-8')) ns = get_namespace(root) subset_ner = {'PERSON':'persName', 'LOC':'placeName'} # + # %%time """ XML Function: Build KWIC of Found Entities in Up Converted Encoding """ def get_kwic_encoding(entity, converted_encoding, kwic_range): # Create keyword-in-context encoding fragments. expanded_conv_regex = '<w>' + ''.join([e + '(<.*?>)*' for e in list(entity)]) + '.*?</w>' c_entity_sequence = expanded_conv_regex.split(' ') c_encoding_sequence = converted_encoding.split(' ') # Create a list of index values sequence_list = [] for i in c_entity_sequence: for idx, item in enumerate(c_encoding_sequence): if re.search(i, item): sequence_list.append(idx) else: pass # Return KWIC using list range. if sequence_list: if sequence_list[0] - kwic_range < 0: # If first item in KWIC - kwic range is less than zero, start KWIC view at beginning of string. # Last item in list = sequence_list[-1] + 1 kwic_encoding = c_encoding_sequence[0: sequence_list[-1] + 1 + kwic_range] else: kwic_encoding = c_encoding_sequence[sequence_list[0] - kwic_range: sequence_list[-1] + 1 + kwic_range] # Convert list to string. kwic_encoding = ' '.join(kwic_encoding) return kwic_encoding else: pass """ XML Parsing Function: Write New Encoding with Up-Conversion """ def make_ner_suggestions(previous_encoding, entity, label, subset_ner, kwic_range, banned_list): # Up-convert entity (label remains unchanged). label = subset_ner[label] # Regularize spacing & store data as new variable ('converted_encoding'). converted_encoding = re.sub('\s+', ' ', previous_encoding, re.MULTILINE) # Create regex that replaces spaces with underscores if spaces occur within tags. # This regex treats tags as a single token later. tag_regex = re.compile('<(.*?)>') # Accumulate underscores through iteration for match in re.findall(tag_regex, previous_encoding): replace_space = re.sub('\s', '_', match) converted_encoding = re.sub(match, replace_space, converted_encoding) # Up-Converstion # Tokenize encoding and text, appending <w> tags, and re-join. converted_encoding = converted_encoding.split(' ') for idx, item in enumerate(converted_encoding): item = '<w>' + item + '</w>' converted_encoding[idx] = item converted_encoding = ' '.join(converted_encoding) try: # # Get KWIC Encoding. # prev_kwic_encoding = get_kwic_encoding(entity, converted_encoding, kwic_range) # prev_kwic_encoding = re.sub('<[/]?w>', '', prev_kwic_encoding) # Find converted entities and kwic-converted entities, even if there's additional encoding within entity. expanded_conv_regex = '<w>' + ''.join([e + '(<.*?>)*' for e in list(entity)]) + '.*?</w>' entity_match = re.search(expanded_conv_regex, converted_encoding) print (expanded_conv_regex, '\t', entity_match) ban_decision = [] for i in banned_list: if i in entity_match.group(0): ban_decision.append('y') if 'y' in ban_decision: print ('Already Encoded') # return prev_kwic_encoding, "Already Encoded", "Already Encoded" # If expanded regex is in previous encoding, find & replace it with new encoding. elif entity_match: new_encoding = re.sub(f'{entity_match.group(0)}', f'<{label}>{entity_match.group(1)}</{label}>{entity_match.group(2)}', converted_encoding) # Remove <w> tags to return to well-formed xml. new_encoding = re.sub('<[/]?w>', '', new_encoding) # Remove underscores. new_encoding = re.sub('_', ' ', new_encoding) # # Repeate process for KWIC # new_kwic_encoding = re.sub(f'{entity_match.group(0)}', # f'<{label}>{entity_match.group(1)}</{label}>{entity_match.group(2)}', # prev_kwic_encoding) # new_kwic_encoding = re.sub('<[/]?w>', '', new_kwic_encoding) # new_kwic_encoding = re.sub('_', ' ', new_kwic_encoding) # return prev_kwic_encoding, new_encoding, new_kwic_encoding print ('New Encoding') else: print ('NER Suggestions Error') # return prev_kwic_encoding, 'Error Making NER Suggestions', 'Error Making NER Suggestions' # # Up-conversion works well because it 'breaks' if an entity already has been encoded: # # <w>Abel</w> (found entity) does not match <w><persRef_ref="abel-mary">Mrs</w> <w>Abel</persRef></w> # # <persRef> breaks function and avoids duplicating entities. except: print ('Error', converted_encoding) return f'Error Occurred with Regex: {entity}', f'Error Occurred with Regex: {entity}', f'Error Occurred with Regex: {entity}' # + # %%time df = pd.DataFrame(columns = ['file', 'abridged_xpath', 'previous_encoding', 'entities']) # Search through elements for entities. desc_order = 0 for child in root.findall('.//ns:body//ns:div[@type="docbody"]', ns): abridged_xpath = get_abridged_xpath(child) for descendant in child: desc_order = desc_order + 1 df = make_dataframe(descendant, df, ns, subset_ner, filename, desc_order) df['abridged_xpath'] = abridged_xpath df = df \ .explode('entities') \ .dropna() df[['entity', 'label']] = pd.DataFrame(df['entities'].tolist(), index = df.index) df['new_encoding'] = df \ .apply(lambda row: make_ner_suggestions(row['previous_encoding'], row['entity'], row['label'], subset_ner, 4, banned_list), axis = 1) # df[['prev_kwic', 'new_encoding', 'new_kwic']] = pd.DataFrame(df['new_encoding'].tolist(), # index = df.index) df # + previous_encoding new_encoding # -
Jupyter_Notebooks/Interfaces/NER_Application/Drafts/APP_NER-XML-Helper-KWIC.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="s9N4cSkfl3Cq" executionInfo={"status": "ok", "timestamp": 1607379261284, "user_tz": 420, "elapsed": 2202, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj0bZgeJltb1614xnp_aFGIfVHnwAd5gecCy-8E9Q=s64", "userId": "18135691317909881633"}} import networkx as nx import numpy as np import matplotlib.pyplot as plt import scipy.stats # + id="WMRZiM_ll6Q1" executionInfo={"status": "ok", "timestamp": 1607379276987, "user_tz": 420, "elapsed": 1677, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj0bZgeJltb1614xnp_aFGIfVHnwAd5gecCy-8E9Q=s64", "userId": "18135691317909881633"}} dHp = np.loadtxt('/content/drive/MyDrive/PhD work/data/undirected networks/virgili emails/dHp.txt') # + id="zTvvFGxJRHd2" executionInfo={"status": "ok", "timestamp": 1607379281888, "user_tz": 420, "elapsed": 1776, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj0bZgeJltb1614xnp_aFGIfVHnwAd5gecCy-8E9Q=s64", "userId": "18135691317909881633"}} n,n = dHp.shape adj = np.ones((n,n)) # ------------------------------------------------------- # create graph gg = nx.Graph() adj = np.zeros((n,n)) for i in range(n): gg.add_node(i) r,c = dHp.shape for i in range(r): for j in range(c): if dHp[i,j]==1: adj[i,j] = 1 for i in range(r): for j in range(c): if adj[i,j]==1: #detecting where there is an edge gg.add_edge(i,j) # + colab={"base_uri": "https://localhost:8080/"} id="CHwf8pZrmfJH" executionInfo={"status": "ok", "timestamp": 1607379286123, "user_tz": 420, "elapsed": 579, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj0bZgeJltb1614xnp_aFGIfVHnwAd5gecCy-8E9Q=s64", "userId": "18135691317909881633"}} outputId="f3ea107d-d23e-4e82-bfcc-f67ae3d2862f" print(nx.info(gg)) # + colab={"base_uri": "https://localhost:8080/"} id="6ETu7OsImlBj" executionInfo={"status": "ok", "timestamp": 1607378718369, "user_tz": 420, "elapsed": 700, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj0bZgeJltb1614xnp_aFGIfVHnwAd5gecCy-8E9Q=s64", "userId": "18135691317909881633"}} outputId="c7eeb267-bf71-4d88-bc76-f2964674e297" print(nx.is_connected(fb)) # + colab={"base_uri": "https://localhost:8080/", "height": 906} id="pKN_dKDemwaD" executionInfo={"status": "ok", "timestamp": 1606949196754, "user_tz": 420, "elapsed": 56515, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj0bZgeJltb1614xnp_aFGIfVHnwAd5gecCy-8E9Q=s64", "userId": "18135691317909881633"}} outputId="749818f2-3843-4e13-84f0-89bd3a7e505c" # show network: pos = nx.spring_layout(gg) import warnings warnings.filterwarnings('ignore') plt.style.use('fivethirtyeight') plt.rcParams['figure.figsize'] = (20, 15) plt.axis('off') nx.draw_networkx(gg, pos, with_labels = False, node_size = 35) plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="qchQQFDQx0lt" executionInfo={"status": "ok", "timestamp": 1606951613708, "user_tz": 420, "elapsed": 680, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj0bZgeJltb1614xnp_aFGIfVHnwAd5gecCy-8E9Q=s64", "userId": "18135691317909881633"}} outputId="fe2d4be6-dea3-4618-abd3-15d1cda2fcd3" max(deg) # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="6yQ8XAivnsCV" executionInfo={"status": "ok", "timestamp": 1607379341220, "user_tz": 420, "elapsed": 516, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj0bZgeJltb1614xnp_aFGIfVHnwAd5gecCy-8E9Q=s64", "userId": "18135691317909881633"}} outputId="417067e8-8ee1-4a73-fa52-67bc62fc6f49" # node degree distribution: deg = np.zeros((gg.number_of_nodes())) j = 0 for nd in gg.nodes(): deg[j] = gg.degree(nd) j = j + 1 plt.figure(1) plt.hist(deg, histtype='stepfilled', color = "skyblue", alpha=0.6, label = 'Virgili network', bins=100) plt.title('Histogram of node degree distribution') plt.xlabel('Node degree') plt.ylabel('Frequency') # plt.title('Histogram of node degree distribution', fontsize = 60) # plt.xlabel('Node degree', fontsize = 60) # plt.ylabel('Frequency', fontsize = 60) # plt.rcParams['figure.figsize'] = [10, 8] # # We change the fontsize of minor ticks label # plt.tick_params(axis='both', which='major', labelsize=40) # plt.tick_params(axis='both', which='minor', labelsize=40) # plt.rc('legend',fontsize=40) plt.legend() plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="rTkTlRI7PQHX" executionInfo={"status": "ok", "timestamp": 1607379348361, "user_tz": 420, "elapsed": 747, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj0bZgeJltb1614xnp_aFGIfVHnwAd5gecCy-8E9Q=s64", "userId": "18135691317909881633"}} outputId="5aefea1c-b0e8-4a8d-fbe7-3a9f235dbbf2" np.mean(deg) # + colab={"base_uri": "https://localhost:8080/"} id="OK5-5HffPPy0" executionInfo={"status": "ok", "timestamp": 1607379350140, "user_tz": 420, "elapsed": 537, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj0bZgeJltb1614xnp_aFGIfVHnwAd5gecCy-8E9Q=s64", "userId": "18135691317909881633"}} outputId="6bcc933f-3052-49f4-8f7f-96b67bb8cd80" np.median(deg) # + colab={"base_uri": "https://localhost:8080/"} id="n81IH8KfPPUz" executionInfo={"status": "ok", "timestamp": 1607379351789, "user_tz": 420, "elapsed": 879, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj0bZgeJltb1614xnp_aFGIfVHnwAd5gecCy-8E9Q=s64", "userId": "18135691317909881633"}} outputId="055b259e-1a8c-4a75-de70-7c60663b2b4d" scipy.stats.mode(deg) # + id="FseiwsmGo4zQ" # # low rankness: from scipy.sparse.csgraph import dijkstra A = nx.adjacency_matrix(fb) D = np.array(dijkstra(A)) np.savetxt('/content/drive/MyDrive/PhD work/data/undirected networks/facebook/dHp.txt', D) # + id="2l95czwXqKqc" # D = np.loadtxt('/content/drive/MyDrive/PhD work/data/undirected networks/facebook/dHp.txt') D = np.loadtxt('/content/drive/MyDrive/PhD work/data/undirected networks/virgili emails/dHp.txt') # + colab={"base_uri": "https://localhost:8080/", "height": 558} id="AH7m-zizpolW" executionInfo={"status": "ok", "timestamp": 1606951537932, "user_tz": 420, "elapsed": 55311, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj0bZgeJltb1614xnp_aFGIfVHnwAd5gecCy-8E9Q=s64", "userId": "18135691317909881633"}} outputId="ef5be73f-2084-49ab-d8b2-ae7852449216" [u,S,vt] = np.linalg.svd(D) ln_sv = S ln_sv = np.log(S) plt.plot( ln_sv, 'k--', label='Facebook network') plt.title('Log of singular values for Facebook network') plt.ylabel('Log of Singular Values') plt.xlabel('Component Number') plt.legend(loc='upper right') plt.show() # + id="iZUcngJhqGny"
Colab Notebooks/virgili.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + [markdown] id="GzTf1WsT6hAl" # # A 🤗 tour of transformer applications # + [markdown] id="BSZqyAh_DvqU" # In this notebook we take a tour around transformers applications. The transformer architecture is very versatile and allows us to perform many NLP tasks with only minor modifications. For this reason they have been applied to a wide range of NLP tasks such as classification, named entity recognition, or translation. # + [markdown] id="lJJQ_HFuDvqV" tags=[] # ## Pipeline # + [markdown] id="7pVLgR88DvqV" tags=[] # We experiment with models for these tasks using the high-level API called pipeline. The pipeline takes care of all preprocessing and returns cleaned up predictions. The pipeline is primarily used for inference where we apply fine-tuned models to new examples. # + [markdown] id="G67RTb2dDvqV" # <img src="https://github.com/huggingface/workshops/blob/main/machine-learning-tokyo/images/pipeline.png?raw=1" alt="Alt text that describes the graphic" title="Title text" width=800> # + colab={"base_uri": "https://localhost:8080/", "height": 321} id="8r-qIToMDvqW" outputId="22286216-72e6-4102-edf4-a97c310b688d" from IPython.display import YouTubeVideo YouTubeVideo('1pedAIvTWXk') # + [markdown] id="04k-nStR6SJX" tags=[] # ## Setup # + [markdown] id="YSw8t0RWDvqX" # Before we start we need to make sure we have the transformers library installed as well as the sentencepiece tokenizer which we'll need for some models. # + id="PoaK0l4yo5-L" tags=[] # %%capture # !pip install transformers # !pip install sentencepiece # + [markdown] id="DglLMvEMDvqY" # Furthermore, we create a textwrapper to format long texts nicely. # + id="Wk1fCfDix7Vp" import textwrap wrapper = textwrap.TextWrapper(width=80, break_long_words=False, break_on_hyphens=False) # + [markdown] id="mXAlr2u76bkg" tags=[] # ## Classification # + [markdown] id="amrlJNI9DvqZ" # We start by setting up an example text that we would like to analyze with a transformer model. This looks like your standard customer feedback from a transformer: # + colab={"base_uri": "https://localhost:8080/"} id="5_zlpsqys9Xl" outputId="11f4fd6c-33f7-4104-b147-9572eb953642" text = """Dear Amazon, last week I ordered an Optimus Prime action figure \ from your online store in Germany. Unfortunately, when I opened the package, \ I discovered to my horror that I had been sent an action figure of Megatron \ instead! As a lifelong enemy of the Decepticons, I hope you can understand my \ dilemma. To resolve the issue, I demand an exchange of Megatron for the \ Optimus Prime figure I ordered. Enclosed are copies of my records concerning \ this purchase. I expect to hear from you soon. Sincerely, Bumblebee.""" print(wrapper.fill(text)) # + [markdown] id="LkrhsqmRDvqa" # One of the most common tasks in NLP and especially when dealing with customer texts is _sentiment analysis_. We would like to know if a customer is satisfied with a service or product and potentially aggregate the feedback across all customers for reporting. # + [markdown] id="yZT2gGkzDvqb" # For text classification the model gets all the inputs and makes a single prediction as shown in the following example: # + [markdown] id="T4Rb3oe-Dvqb" # <img src="https://github.com/huggingface/workshops/blob/main/machine-learning-tokyo/images/clf_arch.png?raw=1" alt="Alt text that describes the graphic" title="Title text" width=600> # + [markdown] id="MM2ZZoerDvqb" # We can achieve this by setting up a `pipeline` object which wraps a transformer model. When initializing we need to specify the task. Sentiment analysis is a subfield of text classification where a single label is given to a # + colab={"base_uri": "https://localhost:8080/", "height": 162, "referenced_widgets": ["d4f58eb74fd54c5cb02d577e4037876f", "902db76d95784e01b18ad81475945104", "c7aab4bc1420429f8a59857db0c3c6ac", "36e897e2124f457a8fa7890d196c60e5", "e8f2d4dd46e04914bccc8e469034c16a", "80f151ef28fa44699682b19998f65caa", "20b1d8dd4de84b8ab104ef4cab25196d", "f6cb9c4a435f4df1a9823de4908426ae", "2e2778c21c464b01ae7193d4422eea68", "b7e9f529bcab4cbcbde4d54aac36d4a8", "a094f954a5da4bb08dca04707db78557", "<KEY>", "<KEY>", "232873beacde41569030ed7055109e74", "<KEY>", "<KEY>", "5f2082058e2144c28886e2fa43773fd4", "650986a56c8e44d19a6231c42b2a2e0e", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "7103eada31c742f68657fb97de19fed1", "<KEY>", "fbfb9c65d2fb436cb5b4bad2f601aff8", "3963cf206ba440edac5c2c928c87d18a", "a6f65a8a19bc45579320571e3e50438f", "2c119a8eaaba4f318bf6cedec25da680", "<KEY>", "<KEY>", "48ca18059b5b48e2a39b403dc739e82b", "2a9978d4704f44c3a71752d87b9b4aa8", "60322d7550644c6ab97a71e3695eda92", "<KEY>", "d7e96b0d83624ed983754715ec9d9910", "<KEY>", "620fbf203a8f4efe8ca4048926e5e71f", "<KEY>", "<KEY>", "6b7c035771c74353acf4ac3a1c095f53", "<KEY>", "46e341011e3044819af0ece9a5168cc0", "8e0b71df3a164126a596910f3a3d6a64"]} id="K3ckzsscpPUh" outputId="024bbc39-cc1d-4816-c005-072ea964c2a7" from transformers import pipeline sentiment_pipeline = pipeline('text-classification') # + [markdown] id="4-JvPV-IDvqc" # You can see a warning message: we did not specify in the pipeline which model we would like to use. In that case it loads a default model. The `distilbert-base-uncased-finetuned-sst-2-english` model is a small BERT variant trained on [SST-2](https://paperswithcode.com/sota/sentiment-analysis-on-sst-2-binary) which is a sentiment analysis dataset. # + [markdown] id="14-9I6cRDvqc" # You'll notice that the first time you execute the model a download is executed. The model is downloaded from the 🤗 Hub! The second time the cached model will be used. # + [markdown] id="G3qkCt07Dvqd" # Now we are ready to run our example through pipeline and look at some predictions: # + colab={"base_uri": "https://localhost:8080/"} id="uWEfVEll5qgu" outputId="0ddd5048-f776-4327-a303-d760aec3d498" sentiment_pipeline(text) # + [markdown] id="xyKN1JDYDvqd" # The model predicts negative sentiment with a high confidence which makes sense. You can see that the pipeline returns a list of dicts with the predictions. We can also pass several texts at the same time in which case we would get several dicts in the list for each text one. # + [markdown] id="M0c9r_ZC66rC" tags=[] # ## Named entity recognition # + [markdown] id="D0Aw3fYaDvqe" # Let's see if we can do something a little more sophisticated. Instead of just finding the overall sentiment let's see if we can extract named entities such as organizations, locations, or individuals from the text. This task is called named entity recognition (NER). Instead of predicting just a class for the whole text a class is predicted for each token, thus this task belongs to the category of token classification: # + [markdown] id="I4tR3C7_Dvqe" # <img src="https://github.com/huggingface/workshops/blob/main/machine-learning-tokyo/images/ner_arch.png?raw=1" alt="Alt text that describes the graphic" title="Title text" width=550> # + [markdown] id="sPvWZmU1Dvqf" # Again, we just load a pipeline for the NER task without specifying a model. This will load a default BERT model that has been trained on the [CoNLL-2003](https://huggingface.co/datasets/conll2003). # + colab={"base_uri": "https://localhost:8080/", "height": 162, "referenced_widgets": ["05f15aaa119c486991f715a4e8287f0d", "e236c55c854d49d7b239e8986a1e763e", "a82778c6f3dd44d9a49faf916cec2a0c", "46bd8e3dc2354659aa64bafb6b82dd0d", "6dddd228ccb14a67962dd7a4429dd5fe", "089f624589d54ec1909446b12bb34900", "6d5afecbaf4346539569039b093145f6", "cea44c3671794b01925a29bbd9971319", "c23595bd4b3a4b9c8b0721ef6140dcc8", "<KEY>", "<KEY>", "<KEY>", "2a5b084049204e3ca6c0617ad87ea9af", "<KEY>", "<KEY>", "125ab4b8fa9f4c31a95b2a1ded2e5306", "<KEY>", "<KEY>", "ddeeb8dd22ba4ca197c3cd9df6f064f9", "<KEY>", "<KEY>", "d9701a023e8f486881fb1187160fa4ca", "<KEY>", "37f978e07e534ecaba0713d536f017e4", "<KEY>", "97d14eab6d204253b3b21e1dfe2a3bc7", "<KEY>", "<KEY>", "defa70f60acf4b7c9a38dc756d849671", "226ead98416d4731ac747331b08ac672", "daba80b3bf1d42388e5af1122e1d71cc", "<KEY>", "5ca1f7cc662d4f6bbd42ddcc66eaf9e6", "<KEY>", "<KEY>", "<KEY>", "19bb1c7d0e604fecafadc2ff0510d79d", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "52bf1e99d78947af9b214577033f01f8", "c44099133e7c42f183c3353bfd3f0c65"]} id="9neufY3itR1V" outputId="ebeee7be-d381-438a-9051-18269b35d1ab" ner_pipeline = pipeline('ner') # + [markdown] id="-YWdgXyODvqf" # When we pass our text through the model we get a long list of dicts: each dict corresponds to one detected entity. Since multiple tokens can correspond to a a single entity we can apply an aggregation strategy that merges entities if the same class appears in consequtive tokens. # + colab={"base_uri": "https://localhost:8080/"} id="9Q1Ns7TXt0Y4" outputId="651cabdb-4720-45c7-8ea9-f7a9c294298e" entities = ner_pipeline(text, aggregation_strategy="simple") print(entities) # + [markdown] id="Su1xNy1zDvqg" # Let's clean the outputs a bit up: # + colab={"base_uri": "https://localhost:8080/"} id="WSffmwPn5kVT" outputId="56f73e15-263d-4767-fa9a-525bfa6d4532" for entity in entities: print(f"{entity['word']}: {entity['entity_group']} ({entity['score']:.2f})") # + [markdown] id="xZ7RX6OXDvqg" # It seems that the model found most of the named entities but was confused about the class of the transformer characters. This is no surprise since the original dataset probably did not contain many transformer characters. For this reason it makes sense to further fine-tune a model on your on dataset! # + [markdown] id="xzqKbiD87A8v" tags=[] # ## Question-answering # + [markdown] id="l--riwHrDvqh" # We have now seen an example of text and token classification using transformers. However, there are more interesting tasks we can use transformers for. One of them is question-answering. In this task the model is given a question and a context and needs to find the answer to the question within the context. This problem can be rephrased into a classification problem: For each token the model needs to predict whether it is the start or the end of the answer. In the end we can extract the answer by looking at the span between the token with the highest start probability and highest end probability: # + [markdown] id="R-7QA_cFDvqh" # <img src="https://github.com/huggingface/workshops/blob/main/machine-learning-tokyo/images/qa_arch.png?raw=1" alt="Alt text that describes the graphic" title="Title text" width=600> # + [markdown] id="NY1ZYoR6Dvqh" # You can imagine that this requires quite a bit of pre- and post-processing logic. Good thing that the pipeline takes care of all that! # + colab={"base_uri": "https://localhost:8080/", "height": 194, "referenced_widgets": ["6231f1eeba1242eb90cf0acc213f7ee3", "d38445bf84674c5fb9fadee7f2d6906e", "11a90d0786c6447183f8fdcc33e003e1", "87bc3fb937fb4696b363ebd01bc720e6", "f8ab269801364805a241f476fbb68be5", "1cc3e5788107409c8a668301b3481a8f", "b974d81ffbe9464cb73afc0de0c6311f", "280002fd9b054cae8986bf52f0a9c725", "3741a7b8be234088a69f1f167e3b8816", "<KEY>", "1f844947182440818a9711e318ca9d6b", "8adfde1529ee4f808c79d420a73b0625", "<KEY>", "15494cf03a5d4d83a1fde774ada39fc9", "<KEY>", "211fbbf5c2864e7d902242e30d34b99a", "af9c9376d76e4d5b85d719a431c524da", "<KEY>", "3e1743c2157a4ec897fe6277665a3b9b", "7a1f43a2a99146a1bea3d80191e39f5e", "e81a8641e0ef46a7ab7ec543289c6b7a", "b38332fb274a41e488ca36db0edead67", "<KEY>", "d16d5039f239415faacef8b357ff797c", "534d455a81b64c48a297da2128660ba0", "54a63697ea764e0dac83899a113d79b0", "8ffd6d57c52c41f0a45c67484ffc7e94", "<KEY>", "02e0f62a92934c3e8ce3332ed831cf07", "<KEY>", "3047e75650dc4cbe99c6a9942db5f1f8", "<KEY>", "1d791ff641d5469bba5785d25035a9a3", "144eb3a1bc9f452ba0112dbe0dfedf6b", "d7dabddd893a4acc944749d7659ab2a0", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "702d96134c7a468aac2ee8b9eec34d64", "<KEY>", "<KEY>", "2b7ae31dc7634d32b4e843048d26f43b", "7d5e7554cfdc47de901e66260f37e81c", "<KEY>", "5db36084ce4543ed925c61538b52e656", "a89214e5f6184f6ebe655ddd2acca483", "3228b08e678f4d07bee7fa4bc012e2c8", "<KEY>", "0a538e86c862418890934a183fd5e855", "036bee2297574765a5c60ecf5644bb83", "<KEY>", "<KEY>", "3977e66c40934e1bb0d6329cbe0f8f84"]} id="0JDtC90lugqX" outputId="e65e3477-bd2e-4e9f-c992-49efb8595660" qa_pipeline = pipeline("question-answering") # + [markdown] id="KkQPviRTDvqi" # This default model is trained on the canonical [SQuAD dataset](https://huggingface.co/datasets/squad). Let's see if we can ask it what the customer wants: # + colab={"base_uri": "https://localhost:8080/"} id="C85OWgOu5coO" outputId="6f98ed64-46ea-4632-b968-581de1f87639" question = "What does the customer want?" outputs = qa_pipeline(question=question, context=text) outputs # + colab={"base_uri": "https://localhost:8080/"} id="iYRcWxkrthRs" outputId="6dde6834-f7fb-4f30-f474-a07e66492537" question2 = "How much the product?" outputs2 = qa_pipeline(question=question2, context=text) outputs2 # + [markdown] id="dZudlnD9Dvqj" # Awesome, that sounds about right! # + [markdown] id="nXf6qViJ7FNk" jp-MarkdownHeadingCollapsed=true tags=[] # ## Summarization # + [markdown] id="gOwy0ncrDvqj" # Let's see if we can go beyond these natural language understanding tasks (NLU) where BERT excels and delve into the generative domain. Note that generation is much more expensive since we usually generate one token at a time and need to run this several times. # + [markdown] id="eFKqI9NRDvqj" # <img src="https://github.com/huggingface/workshops/blob/main/machine-learning-tokyo/images/gen_steps.png?raw=1" alt="Alt text that describes the graphic" title="Title text" width=600> # + [markdown] id="NUVru-mzDvqk" # A popular task involving generation is summarization. Let's see if we can use a transformer to generate a summary for us: # + colab={"base_uri": "https://localhost:8080/", "height": 194, "referenced_widgets": ["<KEY>", "d5581a3706244487a0edf07e936d36d3", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "5596158a72324525b28aca3d8435eeaa", "<KEY>", "<KEY>", "74deb3395fad49c4985c0e509fb3b49e", "<KEY>", "<KEY>", "faaa554cd45342b4b80d24303e00e94c", "9020f8216e1d4844822af8c79500accb", "8b29d3862031419496b1b1d5b2ea0edb", "<KEY>", "<KEY>", "8cd0f0aee6044934928c3a54c256276a", "<KEY>", "4170cad5b46b424485300688c2c8332c", "ec0e283c74b849ed85ff5e7904e6a3b1", "49c5e46ad3964b2a8e38a71a1936e405", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "9d43f0d54d4147168cce6ba4da23adcf", "<KEY>", "9ac149b7a30c4afe800fb0a3cf6246b0", "<KEY>", "<KEY>", "<KEY>", "4f9ce7e281f846cfa652b132a25942e0", "<KEY>", "<KEY>", "<KEY>", "b4ccec17140e4d2aa767b81e50cfea21", "<KEY>", "93637d02535640b6bac0c9e270d04328", "6e0782aea6a5410daa0def41474f49a9", "<KEY>", "<KEY>", "e0424d771c584c49a53e1caa27e53d3e", "5137391154e84239939940eb50b18ac4", "<KEY>", "<KEY>", "1348e2163ed644a3b6f9dbe290b18261", "<KEY>", "f85fc9da050247e5b82d6d61a649f9c2", "2169108bc9dd456f87a6a7af331be17c", "c948840d1d2b4e928b1f45dbfaf2760c"]} id="ICsvWI1Pu6BT" outputId="d3816cd1-f7f6-4e7d-e7bd-606ab5c8547f" summarization_pipeline = pipeline("summarization") # + [markdown] id="iC536PrZDvqk" # This model is trained was trained on the [CNN/Dailymail dataset](https://huggingface.co/datasets/cnn_dailymail) to summarize news articles. # + colab={"base_uri": "https://localhost:8080/"} id="BYjuIjL1vDYP" outputId="259cb5ca-e48d-440d-afc6-ab9970c695ff" outputs = summarization_pipeline(text, max_length=45, clean_up_tokenization_spaces=True) print(wrapper.fill(outputs[0]['summary_text'])) # + [markdown] id="COD8oN7d7Ic4" tags=[] # ## Translation # + [markdown] id="ioRsVpbHDvql" # But what if there is no model in the language of my data? You can still try to translate the text. The Helsinki NLP team has provided over 1000 language pair models for translation. Here we load one that translates English to Japanese: # + id="cMF1FRfWvYrG" colab={"base_uri": "https://localhost:8080/", "height": 241, "referenced_widgets": ["cd2fcefefcc84ab29e7430f62a47bfd6", "<KEY>", "12c7fd7e09bb4d02909e306d4e1b8f4b", "<KEY>", "<KEY>", "<KEY>", "266c1e199c6a49b3a3cdeec03bebb077", "4b180a204cde46ecaba6c61f7279fe07", "f6ca041b5e9344dc81cd74237e337aff", "<KEY>", "109659c32c99420a8222960cdcd4ef56", "e0b7922800e6489c89a9469e823cbd4c", "<KEY>", "ee477bc5dd054e23a2bdbfedd570baba", "f06e71abe259488e8c120f87d74f23b7", "44132a5723ed4c359947b546660ff1a7", "dcd240300976419a93528f1802fbf748", "<KEY>", "<KEY>", "520d97e0f1b54e06b9931c7dcea382da", "<KEY>", "d26bd2a48dc2403487251dba1006820c", "e9b15ebee08e417b8bde63faf70454d1", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "9a9b84b364724e86810d7847d213a655", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "f218486554e04914b6438211b8492ba0", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "aa9806109fad4f7aa792cbe684ff6e64", "<KEY>", "0d6498ea7baf428c886bac43275be47d", "5fcea841191443639fb495bc6a496813", "<KEY>", "a51f58d84bb747bab292a621d7d37609", "<KEY>", "1b7a496c077e468a8074f8d151a34f08", "1acd036fa41f4cd0ade38855715a660a", "9ffdecb2af424043ac4aaa00d2b2b346", "af5d333cf82644dea1dff923ac600f4f", "7795a0bcf0a740bcb90ee96e4c3ea188", "<KEY>", "<KEY>", "<KEY>", "97d66e5ed97749e2a210f3760fee79ce", "be93fb5446944649aaf72be57ae5ccf0", "<KEY>", "65b0090fff044890ace0ed4ed10d59d9", "<KEY>", "ad4b26a94f854d97baedbce3dfc1c10b", "<KEY>", "4c3cadba7f1447c59e29d31c5a11c4fe", "<KEY>", "<KEY>", "<KEY>", "e1d650437436495da13476b3e90f748d", "e285b5752d7c4999ad2fc7149f5fe461", "<KEY>", "7d93b0640eb446a0897eaac58f851467", "<KEY>", "cf9ebbb6ea254ebd9b50e24a90758826", "<KEY>", "<KEY>", "c0165cb5a6d54348a5edb73df2c3ee0a", "<KEY>"]} outputId="18df76da-fc3d-4039-ec47-d31f268a5ba0" translator = pipeline("translation_en_to_ja", model="Helsinki-NLP/opus-tatoeba-en-ja") # + [markdown] id="s2Ge5c10Dvqm" # Let's translate the a text to Japanese: # + id="u5nWlQApDHCz" text = 'At the MLT workshop in Tokyo we gave an introduction about Transformers.' # + colab={"base_uri": "https://localhost:8080/"} id="Aijh7j_Gvyeu" outputId="d1bc4227-eac1-49ff-c7cd-e5f6570901ce" outputs = translator(text, clean_up_tokenization_spaces=True) print(wrapper.fill(outputs[0]['translation_text'])) # + [markdown] id="q-lP6QUQDvqm" # We can see that the text is clearly not perfectly translated, but the core meaning stays the same. Another cool application of translation models is data augmentation via backtranslation! # + [markdown] id="8-miZB1m8YVM" tags=[] # ## Custom Model # + [markdown] id="XaBDCa0PDvqn" # As a last example let's have a look at a cool application showing the versatility of transformers: zero-shot classification. In zero-shot classification the model receives a text and a list of candidate labels and determines which labels are compatible with the text. Instead of having fixed classes this allows for flexible classification without any labelled data! Usually this is a good first baseline! # + id="6HURf6JS8Xko" colab={"base_uri": "https://localhost:8080/", "height": 177, "referenced_widgets": ["798365f4465746578087ba90d68bf7a8", "e37cf6fa762e49719282c74e29bf707a", "b07db81b51be4bb485203d9af2c3c4c6", "40cd822d030640afb48710ab152d5897", "ef30afcb22ed4f229a151b8206ea3b42", "aa2445ff1f8e4ec89434b02b6c06bc78", "13a47ca76f5d45b1b9bb0e3067d63ba6", "5b2e29bb2bbc46f0b2eb3db3db6e9195", "a3967343909947c4be8686593845e3a4", "003937c7c3274c488e463a9d67f0ac6c", "<KEY>", "bd8ab62d51c44ed89c80820de1b3728a", "<KEY>", "70c14b470b2e45968a0d8c34a0e5a6d8", "46ad54782b994d258a6abe4a8f14428f", "687241fcb8874ef7a6046e948ee7ea99", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "845a3f6ce7fe4e779a8c8ba546bcd957", "d0d7e4977a7e4de8b9ac5b9236cdd07b", "621fb8b62b2941d1be953c6725e54daf", "<KEY>", "c3f374033de44cbebe69f4d1c6283918", "<KEY>", "e18085964b2c4e3a934c00945388a6b5", "<KEY>", "<KEY>", "d3ac0731f3f04aeea8f2a7c35c083b2e", "fae58480457545ac8105fe23ef86fd71", "6e3e7f169dbe4e92a314347cf588a32d", "<KEY>", "<KEY>", "7dea851fca46420b9b7e0f4d42ce17b9", "fd09a1f0e83446eaa54c1902c43aa9a1", "dbc112165e7949d98d798128b6b9db84", "4604921dfc734aba99986c387100d716", "<KEY>", "6433de318dfe4bbc8498c7c4475c6620", "1e1e8effaa0440378e675a385caea5f3", "<KEY>", "<KEY>", "<KEY>", "34e006ca28e94c0e806eaaae796c7c33", "<KEY>", "<KEY>", "<KEY>", "898b8ef33ce745a8ab812070f3c792c4", "<KEY>", "dc441361a4ed44a3924ffee53fe82da7", "<KEY>", "<KEY>", "<KEY>"]} outputId="28fb535e-de28-4540-9ca7-01b592bbcbf3" zero_shot_classifier = pipeline("zero-shot-classification", model="vicgalle/xlm-roberta-large-xnli-anli") # + [markdown] id="7z01wJrvDvqn" # Let's have a look at an example: # + id="SjMXSBx5897m" text = '東京のMLTワークショップで,トランスフォーマーについて紹介しました.' classes = ['Japan', 'Switzerland', 'USA'] # + colab={"base_uri": "https://localhost:8080/"} id="l6U71HAL9oBG" outputId="a0e7b745-8866-4bd8-9480-299213547f2f" zero_shot_classifier(text, classes) # + [markdown] id="LGwLNx0PDvqo" # This seems to have worked really well on this short example. Naturally, for longer and more domain specific examples this approach might suffer. # + [markdown] id="WGnElSPY7ta7" tags=[] # ## More pipelines # + [markdown] id="F-jmgxDyDvqo" # There are many more pipelines that you can experiment with. Look at the following list for an overview: # + colab={"base_uri": "https://localhost:8080/"} id="m28XOn4t5YlM" outputId="53318537-e6d9-42fc-b71c-666acf73a30e" from transformers import pipelines for task in pipelines.SUPPORTED_TASKS: print(task) # + [markdown] id="V0Fl9HbdDvqp" # Transformers not only work for NLP but can also be applied to other modalities. Let's have a look at a few. # + [markdown] id="MElFihO0Dvqp" tags=[] # ### Computer vision # + [markdown] id="5JartRCsDvqq" # Recently, transformer models have also entered computer vision. Check out the DETR model on the [Hub](https://huggingface.co/facebook/detr-resnet-101-dc5): # + [markdown] id="5wwkfybM7MZU" # <img src="https://github.com/huggingface/workshops/blob/main/machine-learning-tokyo/images/object_detection.png?raw=1" alt="Alt text that describes the graphic" title="Title text" width=400> # + [markdown] id="ObzbVHFnL0hv" tags=[] # ### Audio # + [markdown] id="aSdPHGNxDvqr" # Another promising area is audio processing. Especially Speech2Text there have been some promising advancements recently. See for example the [wav2vec2 model](https://huggingface.co/facebook/wav2vec2-base-960h): # + [markdown] id="J_bZrjQUDvqr" # <img src="https://github.com/huggingface/workshops/blob/main/machine-learning-tokyo/images/speech2text.png?raw=1" alt="Alt text that describes the graphic" title="Title text" width=400> # + [markdown] id="nZtrfoydDvqr" tags=[] # ### Table QA # + [markdown] id="L4wR2N0RDvqr" # Finally, a lot of real world data is still in form of tables. Being able to query tables is very useful and with [TAPAS](https://huggingface.co/google/tapas-large-finetuned-wtq) you can do tabular question-answering: # + [markdown] id="rfmSOzcNDvqr" # <img src="https://github.com/huggingface/workshops/blob/main/machine-learning-tokyo/images/tapas.png?raw=1" alt="Alt text that describes the graphic" title="Title text" width=400> # + [markdown] id="kJITTXMcDvqr" tags=[] # ## Cache # + [markdown] id="vkvhxVGTDvqs" # Whenever we load a new model from the Hub it is cached on the machine you are running on. If you run these examples on Colab this is not an issue since the persistent storage will be cleaned after your session anyway. However, if you run this notebook on your laptop you might have just filled several GB of your hard drive. By default the cache is saved in the folder `~/.cache/huggingface/transformers`. Make sure to clear it from time to time if your hard drive starts to fill up. # + id="dXHCk79KDvqs"
HuggingFace/Hands-on_Workshop/01_transformers_tour.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Terror Attack City # # ##### Given file “terrorismData.csv” # # It is an open source data including info on terrorism attacks around the world from 1970 through 2017. This dataset includes systematic data on domestic and international terrorist incidents that have occurred during this period. # # ### Problem Statement: # The most Dangerous city in jammu and kashmir and the terrorist group which is most active in that city ? # # Print count of number of attacks in that city as integer value import numpy as np import pandas as pd import warnings warnings.filterwarnings('ignore') df = pd.read_csv('terrorismData.csv') df.head() df.shape df.columns df.isnull().sum() df.describe() df.Country.value_counts() df.Region.value_counts() east_asia = df[df.Region == 'South Asia'] east_asia['Country'].value_counts() india = df[df.Country == 'India'] for city in india['City']: print(city) jammu = india[india.City == 'Jammu'] jammu.isnull().sum() jammu['Wounded'] = np.array(jammu['Wounded'], dtype=int) jammu['Killed'] = np.array(jammu['Killed'], dtype=int) jammu['Wounded'].fillna(0, inplace = True) jammu.isnull().sum() jammu['NumberOfAttack'] = jammu['Killed'] + jammu['Wounded'] jammu.head() jammu[['City','Year','NumberOfAttack','Group']] jammu.Group.unique() # ## Terror Attack # # ### Problem Statement # # Find out the country with Highest Number of Terror Attack and in which year the most number of terrorist attack happened in that country ? df.head() df.isnull().sum() new_df = df[['Country','Year','Killed','Wounded']] new_df.head() new_df.shape new_df.isnull().sum() new_df.dropna(inplace = True) new_df.isnull().sum() new_df.shape # + new_df['Killed'] = np.array(new_df['Killed'], dtype = int) new_df['Wounded'] = np.array(new_df['Wounded'], dtype= int) # - new_df.dtypes new_df['NumberOfAttack'] = new_df['Killed'] + new_df['Wounded'] new_df new_df[['Country','Year','NumberOfAttack']].sort_values(by = ['NumberOfAttack'], ascending=False) # The county with the Highest Number of Terror Attack is United States and In 2001 the most number (9574) of terrorist attack happened in that country. # ## Terror DeadliestAttack # # ### Problem Statement: # Most Deadliest attack in a history of Humankind ? # # Note: Here Deadliest attack means, in which the most number of people killed new_df = df[['Country','Group','Killed']] new_df.head() new_df.isnull().sum() new_df.dropna(inplace = True) new_df.isnull().sum() new_df['Killed'] = np.array(new_df['Killed'], dtype=int) new_df.dtypes new_df.sort_values(by = ['Killed'], ascending=False).head() # Most Deadliest attack in the history of humankind is from ISIL which killed almost 1570 people # ## Terror Government # # ### Problem Statement: # There was formation of new government in india on 26 May 2014. So current government's span is from 26th May 2014 to current. find out two things from this period. # 1. Total number of attacks done in this period in india. find this count as integer. # 2. which terrorist group was most active in this period in india. Most active means, group which has done maximum number of attacks # 3. Ignore the unknown group. india_df = df[df['Country']== 'India'] india_df.head() india_df.reset_index(inplace= True) india_df.head() india_df.shape india_from_2014 = india_df[india_df['Year'] >= 2014] india_from_2014.head() india_from_2014['Year'].unique() india_from_2014.shape india_from_2014_May = india_from_2014[india_from_2014['Month']>=5] india_from_2014_May.head() india_from_2014_May.shape # Total attack done in this period in india is 2469 india_from_2014_May.isnull().sum() india_from_2014_May.dropna(inplace = True) india_from_2014_May.isnull().sum() india_from_2014_May['Group'].value_counts() # Maoists is the terrorist group which wasm most active during this time. # # Note - Unknown group is ignored
Pandas/Terror Attack.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.7.9 64-bit (''python-course'': virtualenv)' # name: python3 # --- # + [markdown] id="Hu-DQLCysvHt" # # "Chapitre 4 : Les exceptions" # > "Python : Chapitre 4 - Lesson 1" # # - toc: false # - badges: true # - hide_binder_badge: true # - hide_github_badge: true # - comments: false # - layout: post # - author: AXI Academy # - permalink: /python-intro-gen/chapter/4/lesson/1/ # - # ## 1. Les types des erreurs # # Les erreurs ou les exceptions dans un programme sont souvent appelées bugs. Ils sont presque toujours la faute du programmeur. Le processus de recherche et d'élimination des erreurs est appelé débuggage. Les erreurs peuvent être classées en trois grands groupes : # - Erreurs de syntaxe # - Erreurs d'exécution # - Erreurs logiques # # ### Les erreurs de syntaxe (`SyntaxError`) # # Python trouvera ce genre d'erreurs lorsqu'il essaiera d'analyser votre programme et se terminera avec un message d'erreur sans rien exécuter. Les erreurs de syntaxe sont des erreurs dans l'utilisation du langage Python, et sont analogues aux fautes d'orthographe ou de grammaire dans une langue comme le français : par exemple, la phrase `Vous du thé ?`, n'a pas de sens, il manque un verbe. # # Les erreurs de syntaxe Python courantes incluent : # - omettre un mot-clé # - mettre un mot-clé au mauvais endroit # - omettre un symbole, comme un deux-points, une virgule ou des crochets # - faute d'orthographe d'un mot-clé # - indentation incorrecte # - bloc vide # # > il est interdit pour tout bloc (comme un corps `if`, ou le corps d'une fonction) d'être laissé complètement vide. Si vous voulez qu'un bloc ne fasse rien, vous pouvez utiliser l'instruction pass à l'intérieur du bloc. # # Python fera de son mieux pour vous dire où se trouve l'erreur, mais parfois ses messages peuvent être trompeurs : par exemple, si vous oubliez d'échapper un guillemet à l'intérieur d'une chaîne, vous pouvez obtenir une erreur de syntaxe faisant référence à un endroit plus loin dans votre code, même si ce n'est pas la vraie source du problème. Si vous ne voyez rien de mal sur la ligne spécifiée dans le message d'erreur, essayez de revenir en arrière sur les quelques lignes précédentes. Au fur et à mesure que vous programmez, vous vous améliorerez dans l'identification et la correction des erreurs. # # Voici quelques erreurs de syntaxe : # + myfunction(x, y): return x + y else: print("Hello!") if mark >= 50 print("You passed!") if arriving: print("Hi!") esle: print("Bye!") if flag: print("Flag is set!") # - # ### Les erreurs d'exécution # # Si un programme est syntaxiquement correct, c'est-à-dire exempt d'erreurs de syntaxe, il sera exécuté par l'interpréteur Python. Cependant, le programme peut se fermer de manière inattendue pendant l'exécution s'il rencontre une erreur d'exécution, un problème qui n'a pas été détecté lors de l'analyse du programme, mais qui n'est révélé que lorsqu'une ligne particulière est exécutée. Lorsqu'un programme s'arrête à cause d'une erreur d'exécution, nous disons qu'il a planté. # # Considérez les instructions en français : `battez les bras et envolez-vous pour l'Australie`. Bien que l'instruction soit structurellement correcte et que vous puissiez parfaitement comprendre sa signification, il vous est impossible de la suivre. # # Quelques exemples d'erreurs d'exécution Python : # - division par zéro # - effectuer une opération sur des types incompatibles # - utilisant un identifiant qui n'a pas été défini # - accéder à un élément de liste, une valeur de dictionnaire ou un attribut d'objet qui n'existe pas # - essayer d'accéder à un fichier qui n'existe pas # # Des erreurs d'exécution se glissent souvent si vous ne prenez pas en compte toutes les valeurs possibles qu'une variable pourrait contenir, en particulier lorsque vous traitez une entrée utilisateur. Vous devriez toujours essayer d'ajouter des vérifications à votre code pour vous assurer qu'il peut traiter les mauvaises entrées et les cas extrêmes avec élégance. Nous verrons cela plus en détail dans le chapitre sur la gestion des exceptions. # ### Les erreurs logiques # # Les erreurs logiques sont les plus difficiles à corriger. Elles se produisent lorsque le programme s'exécute sans plantage, mais produit un résultat incorrect. L'erreur est causée par une erreur dans la logique du programme. Vous ne recevrez pas de message d'erreur, car aucune erreur de syntaxe ou d'exécution ne s'est produite. Vous devrez trouver le problème par vous-même en examinant toutes les parties pertinentes de votre code - bien que certains outils puissent signaler un code suspect qui pourrait provoquer un comportement inattendu. # # Parfois, il ne peut y avoir absolument rien de mal avec votre implémentation Python d'un algorithme, l'algorithme lui-même peut être incorrect. Cependant, le plus souvent, ces types d'erreurs sont causés par la négligence du programmeur. Voici quelques exemples d'erreurs qui conduisent à des erreurs logiques : # - utiliser le mauvais nom de variable # - indentation d'un bloc au mauvais niveau # - utiliser la division entière au lieu de la division à virgule flottante # - se tromper de priorité d'opérateur # - se tromper dans une expression booléenne # # Si vous orthographiez mal un nom d'identifiant, vous pouvez obtenir une erreur d'exécution ou une erreur logique, selon que le nom mal orthographié soit défini ou non. # # Une source courante de confusion de noms de variables et d'indentation incorrecte est la copie et le collage fréquents de gros blocs de code. Si vous avez de nombreuses lignes en double avec des différences mineures, il est très facile de rater une modification nécessaire lorsque vous modifiez vos lignes collées. Vous devriez toujours essayer d'éliminer les doublons excessifs à l'aide de fonctions et de boucles. # ## Exercice 1 # # - 1) Trouvez toutes les erreurs de syntaxe dans l'extrait de code ci-dessus (dans la partie erreurs de syntaxe) et expliquez pourquoi ce sont des erreurs. # - 2) Trouvez des sources potentielles d'erreurs d'exécution dans cet extrait de code : dividend = float(input("Please enter the dividend: ")) divisor = float(input("Please enter the divisor: ")) quotient = dividend / divisor quotient_rounded = math.round(quotient) # - 3) Trouvez des sources potentielles d'erreurs d'exécution dans cet extrait de code : for x in range(a, b): c, d, e = my_list[x] print(f"({c}, {d}, {e})") # - 4) Trouvez des sources potentielles d'erreurs logiques dans cet extrait de code : # + product = 0 for i in range(10): product *= i sum_squares = 0 for i in range(10): i_sq = i**2 sum_squares += i_sq nums = 0 for num in range(10): num += num # - # ## 2. La gestion des exceptions # # Jusqu'à présent, les programmes que nous avons écrits ont généralement ignoré le fait que les choses peuvent mal tourner. Nous avons essayé d'éviter les erreurs d'exécution en vérifiant les données qui peuvent être incorrectes avant de les utiliser, mais nous n'avons pas encore vu comment nous pouvons gérer les erreurs lorsqu'elles se produisent. Jusqu'à présent, nos programmes ont crashé soudainement chaque fois qu'ils en ont rencontré une. # # Dans certaines situations, des erreurs d'exécution sont susceptibles de se produire. Chaque fois que nous essayons de lire un fichier ou d'obtenir des informations d'un utilisateur, il est possible que quelque chose d'inattendu se produise : le fichier peut avoir été déplacé ou supprimé, ou l'utilisateur peut saisir des données qui ne sont pas au bon format. Les bons programmeurs devraient ajouter des garde-fous à leurs programmes afin que des situations courantes comme celle-ci puissent être gérées avec élégance. Un programme qui plante chaque fois qu'il rencontre un problème facilement prévisible n'est pas très agréable à utiliser. La plupart des utilisateurs s'attendent à ce que les programmes soient suffisamment robustes pour se remettre de ce genre de revers. # # Si nous savons qu'une section particulière de notre programme est susceptible de provoquer une erreur, nous pouvons dire à Python quoi faire si cela se produit. Au lieu de laisser l'erreur planter notre programme, nous pouvons l'intercepter, faire quelque chose et permettre au programme de continuer. # # Toutes les erreurs d'exécution (et de syntaxe) que nous avons rencontrées sont appelées `exception` en Python. Python les utilise pour indiquer que quelque chose d'exceptionnel s'est produit et que votre programme ne peut pas continuer à moins qu'il ne soit géré. Toutes les exceptions sont des sous-classes de la classe `Exception`, nous en apprendrons plus sur les classes et sur la façon d'écrire vos propres types d'exceptions dans les chapitres suivants. # # ### Les instructions : `try`/`except` # # Pour gérer les exceptions possibles, nous utilisons un bloc `try`/`except` : try: age = int(input("Please enter your age: ")) print("I see that you are %d years old." % age) except ValueError: print("Hey, that wasn't a number!") # Python essaiera de traiter toutes les instructions à l'intérieur du bloc `try`. Si une `ValueError` se produit à tout moment pendant son exécution, le flux de contrôle passera immédiatement au bloc `except` et toutes les instructions restantes dans le bloc `try` seront ignorées. # # Dans cet exemple, nous savons que l'erreur est susceptible de se produire lorsque nous essayons de convertir l'entrée de l'utilisateur en un entier. Si la chaîne d'entrée n'est pas un nombre, cette ligne déclenchera une `ValueError` : c'est pourquoi nous l'avons spécifié comme le type d'erreur que nous allons gérer. # # Nous aurions pu spécifier un type d'erreur plus général ou même laisser le type complètement de côté, ce qui aurait fait que la clause except correspondrait à n'importe quel type d'exception, mais cela aurait été une mauvaise idée. Et si nous obtenions une erreur complètement différente que nous n'avions pas prévue ? Cela serait également traité, et nous ne remarquerions même pas que quelque chose d'inhabituel allait mal. Nous pouvons également vouloir réagir de différentes manières à différents types d'erreurs. Nous devrions toujours essayer de choisir des types d'erreur spécifiques plutôt que généraux pour nos clauses except. # # Il est possible pour une clause `except` de gérer plus d'un type d'erreur : nous pouvons fournir un tuple de types d'exception au lieu d'un seul type : # try: dividend = int(input("Please enter the dividend: ")) divisor = int(input("Please enter the divisor: ")) print(f"{dividend} / {divisor} = {dividend/divisor}") except(ValueError, ZeroDivisionError): print("Oops, something went wrong!") # Un bloc `try`/`except` peut également avoir plusieurs clauses `except`. Si une exception se produit, Python vérifiera chaque clause `except` de haut en bas pour voir si le type d'exception correspond. Si aucune des clauses `except` ne correspond, l'exception sera considérée comme non gérée et votre programme plantera : try: dividend = int(input("Please enter the dividend: ")) divisor = int(input("Please enter the divisor: ")) print("%d / %d = %f" % (dividend, divisor, dividend/divisor)) except ValueError: print("The divisor and dividend have to be numbers!") except ZeroDivisionError: print("The dividend may not be zero!") # Notez que dans l'exemple ci-dessus, si une `ValueError` se produit, nous ne saurons pas si cela a été causé par le dividende ou le diviseur (qui n'est pas un entier), l'une ou l'autre des lignes d'entrée pourrait provoquer cette erreur. Si nous voulons donner à l'utilisateur un retour plus précis sur l'entrée erronée, nous devrons envelopper chaque ligne d'entrée dans un bloc try-except séparé : # + try: dividend = int(input("Please enter the dividend: ")) except ValueError: print("The dividend has to be a number!") try: divisor = int(input("Please enter the divisor: ")) except ValueError: print("The divisor has to be a number!") try: print("%d / %d = %f" % (dividend, divisor, dividend/divisor)) except ZeroDivisionError: print("The dividend may not be zero!") # - # ### Comment une exception est gérée # # Lorsqu'une exception se produit, le flux normal d'exécution est interrompu. Python vérifie si la ligne de code qui a causé l'exception se trouve à l'intérieur d'un bloc `try`/`except`. Si c'est le cas, il vérifie si l'un des blocs `except` associés au bloc `try` peut gérer ce type d'exception. Si un gestionnaire approprié est trouvé, l'exception est gérée et le programme continue à partir de l'instruction suivante après la fin de ce `try`/`except`. # # S'il n'y a pas de tel gestionnaire, ou si la ligne de code n'était pas dans un bloc `try`, Python montera d'un niveau de portée : si la ligne de code qui a causé l'exception était à l'intérieur d'une fonction, cette fonction se terminera immédiatement, et la ligne qui a appelé la fonction sera traitée comme si elle avait levé l'exception. Python vérifiera si cette ligne est à l'intérieur d'un bloc `try`, et ainsi de suite. Lorsqu'une fonction est appelée, elle est placée sur la pile de Python, dont nous parlerons dans le chapitre sur les fonctions. Python parcourt cette pile lorsqu'il essaie de gérer une exception. # # Si une exception est levée par une ligne qui se trouve dans le corps principal de votre programme, pas à l'intérieur d'une fonction, le programme se terminera. Lorsque le message d'exception est affiché, vous devriez également voir une trace : une liste qui montre le chemin emprunté par l'exception, jusqu'à la ligne d'origine qui a causé l'erreur. # # La gestion des exceptions nous offre un autre moyen de gérer les situations sujettes aux erreurs dans notre code. Au lieu d'effectuer plus de vérifications avant de faire quelque chose pour nous assurer qu'une erreur ne se produira pas, nous essayons simplement de le faire et si une erreur se produit, nous la traitons. Cela peut nous permettre d'écrire du code plus simple et plus lisible. Regardons un exemple d'entrée plus compliqué : un dans lequel nous voulons continuer à demander à l'utilisateur d'entrer jusqu'à ce que l'entrée soit correcte. Nous allons essayer d'écrire cet exemple en utilisant les deux approches différentes : # + # with checks n = None while n is None: s = input("Please enter an integer: ") if s.lstrip('-').isdigit(): n = int(s) else: print("%s is not an integer." % s) # with exception handling n = None while n is None: try: s = input("Please enter an integer: ") n = int(s) except ValueError: print("%s is not an integer." % s) # - # ### Les avantages de la gestion des exceptions # # - Il sépare le code normal du code qui gère les erreurs. # - Les exceptions peuvent facilement être transmises aux fonctions de la pile jusqu'à ce qu'elles atteignent une fonction qui sache comment les gérer. Les fonctions intermédiaires n'ont pas besoin d'avoir de code de gestion des erreurs. # - Les exceptions sont livrées avec de nombreuses informations d'erreur utiles intégrées - par exemple, elles peuvent imprimer un retraçage qui nous aide à voir exactement où l'erreur s'est produite. # # # ### Les instructions `else` et `finally` # # Il y a deux autres clauses que nous pouvons ajouter à un bloc `try`/`except` : `else` et `finally`. `else` ne sera exécuté que si la clause `try` ne lève pas d'exception : try: age = int(input("Please enter your age: ")) except ValueError: print("Hey, that wasn't a number!") else: print("I see that you are %d years old." % age) # Nous voulons afficher un message sur l'âge de l'utilisateur uniquement si la conversion d'entier réussit. Dans le premier exemple de gestionnaire d'exceptions, nous plaçons cette instruction `print` directement après la conversion à l'intérieur du bloc `try`. Dans les deux cas, l'instruction ne sera exécutée que si l'instruction de conversion ne lève pas d'exception, mais la placer dans le bloc `else` est une meilleure pratique : cela signifie que le seul code à l'intérieur du bloc `try` est la seule ligne qui est le potentiel source de l'erreur que nous voulons traiter. # # La clause `finally` sera exécutée à la fin du bloc `try`/`except` quoi qu'il arrive : # - s'il n'y a pas d'exception # - si une exception est levée et gérée, # - si une exception est levée et non gérée # Nous pouvons utiliser la clause `finally` pour le code de nettoyage que nous voulons toujours exécuter : try: age = int(input("Please enter your age: ")) except ValueError: print("Hey, that wasn't a number!") else: print("I see that you are %d years old." % age) finally: print("It was really nice talking to you. Goodbye!") # ## Exercice 2 # # - 1) Étendez le programme de l'exercice 7 du chapitre sur les boucles pour y inclure la gestion des exceptions. Chaque fois que l'utilisateur entre une entrée de type incorrect, continuez à demander à l'utilisateur la même valeur jusqu'à ce qu'elle soit entrée correctement. # ## L'instruction `as` # # Les objets d'exception de Python contiennent plus d'informations que le type d'erreur. Ils sont également accompagnés d'une sorte de message, nous avons déjà vu certains de ces messages s'afficher lorsque nos programmes se sont écrasés. Souvent, ces messages ne sont pas très conviviaux : si nous voulons signaler une erreur à l'utilisateur, nous devons généralement écrire un message plus descriptif qui explique comment l'erreur est liée à ce que l'utilisateur a fait. Par exemple, si l'erreur a été causée par une entrée incorrecte, il est utile d'indiquer à l'utilisateur laquelle des valeurs d'entrée est incorrecte. # # Parfois, le message d'exception contient des informations utiles que nous souhaitons afficher à l'utilisateur. Pour accéder au message, nous devons pouvoir accéder à l'objet exception. Nous pouvons affecter l'objet à une variable que nous pouvons utiliser dans la clause `except` comme ceci : try: age = int(input("Please enter your age: ")) except ValueError as err: print(err) # `err` n'est pas une `string`, mais Python sait comment la convertir. La représentation sous forme de `string` d'une exception est le message, ce qui est exactement ce que nous voulons. Nous pouvons également combiner le message d'exception avec notre propre message : try: age = int(input("Please enter your age: ")) except ValueError as err: print(f"You entered incorrect age input: \"{err}\"") # ## Lever des exceptions # # Nous pouvons lever des exceptions nous-mêmes en utilisant l'instruction `raise` : try: age = int(input("Please enter your age: ")) if age < 0: raise ValueError("%d is not a valid age. Age must be positive or zero.") except ValueError as err: print("You entered incorrect age input: %s" % err) else: print("I see that you are %d years old." % age) # Nous pouvons lever notre propre `ValueError` si l'entrée age est un entier valide, mais elle est négative. Lorsque nous faisons cela, cela a exactement le même effet que toute autre exception, le flux de contrôle quittera immédiatement la clause `try` à ce stade et passera à la clause `except`. Cette clause `except` peut également correspondre à notre exception, car il s'agit également d'une `ValueError`. # # Nous avons choisi `ValueError` comme type d'exception car c'est le plus approprié pour ce type d'erreur. Rien ne nous empêche d'utiliser une classe d'exception complètement inappropriée ici, mais nous devons essayer d'être cohérents. Voici quelques types d'exceptions courants que nous sommes susceptibles de générer dans notre propre code : # - 1) `TypeError`: c'est une erreur qui indique qu'une variable a le mauvais type pour une opération. Nous pouvons l'augmenter dans une fonction si un paramètre n'est pas d'un type que nous savons gérer. # - 2) `ValueError`: cette erreur est utilisée pour indiquer qu'une variable a le bon type mais la mauvaise valeur. Par exemple, nous l'avons utilisé lorsque l'âge était un entier, mais le mauvais type d'entier. # - 3) `NotImplementedError`: nous verrons dans le chapitre suivant comment nous utilisons cette exception pour indiquer qu'une méthode de classe doit être implémentée dans une classe enfant. # # Nous pouvons également écrire nos propres classes d'exceptions personnalisées basées sur des classes d'exceptions existantes. # # Quelque chose que nous pouvons vouloir faire est de lever une exception que nous venons d'intercepter, peut-être parce que nous voulons la gérer partiellement dans la fonction actuelle, mais aussi pour y répondre dans le code qui a appelé la fonction : try: age = int(input("Please enter your age: ")) except ValueError as err: print("You entered incorrect age input: %s" % err) raise err # ## Exercice 3 # # - 1) Réécrivez le programme de la première question de l'exercice 2 afin qu'il affiche le texte de l'exception originale de Python à l'intérieur de la clause `except` au lieu d'un message personnalisé. # - 2) Réécrivez le programme à partir de la deuxième question de l'exercice 2 de sorte que l'exception qui est interceptée dans la clause `except` soit relancée après l'impression du message d'erreur. # ## 3. Débugger le code # # Les erreurs de syntaxe sont généralement assez simples à débugger : le message d'erreur nous montre la ligne du fichier où se trouve l'erreur, et il devrait être facile de la trouver et de la corriger. # # Les erreurs d'exécution peuvent être un peu plus difficiles à débugger : le message d'erreur et le `traceback` peuvent nous dire exactement où l'erreur s'est produite, mais cela ne nous dit pas nécessairement quel est le problème. Parfois, ils sont causés par quelque chose d'évident, comme un nom d'identifiant incorrect, mais parfois ils sont déclenchés par un état particulier du programme : il n'est pas toujours clair lequel des nombreuses variables a une valeur inattendue. # # Les erreurs logiques sont les plus difficiles à corriger car elles ne provoquent aucune erreur pouvant être attribuée à une ligne particulière du code. Tout ce que nous savons, c'est que le code ne se comporte pas comme il devrait l'être. Parfois, la recherche de la zone du code à l'origine du comportement incorrect peut prendre beaucoup de temps. # # Il est important de tester votre code pour vous assurer qu'il se comporte comme vous l'attendez. Un moyen simple et rapide de tester qu'une fonction fait ce qu'il faut, par exemple, consiste à insérer une instruction `print` après chaque ligne qui renvoie les résultats intermédiaires qui ont été calculés sur cette ligne. La plupart des programmeurs le font intuitivement lorsqu'ils écrivent une fonction, ou peut-être s'ils ont besoin de comprendre pourquoi elle ne fait pas la bonne chose : def hypotenuse(x, y): print("x is %f and y is %f" % (x, y)) x_2 = x**2 print(x_2) y_2 = y**2 print(y_2) z_2 = x_2 + y_2 print(z_2) z = math.sqrt(z_2) print(z) return z # C'est une chose rapide et facile à faire, et même les programmeurs expérimentés sont coupables de le faire de temps en temps, mais cette approche présente plusieurs inconvénients : # # - 1) Dès que la fonction fonctionne, nous sommes susceptibles de supprimer toutes les instructions d'impression, car nous ne voulons pas que notre programme affiche toutes ces informations de débuggage tout le temps. Le problème est que le code change souvent, la prochaine fois que nous voulons tester cette fonction, nous devrons ajouter à nouveau les instructions `print`. # - 2) Pour éviter de réécrire les instructions `print` si nous en avons à nouveau besoin, nous pouvons être tentés de les commenter au lieu de les supprimer. Les laissant encombrer notre code et éventuellement devenir tellement désynchronisés qu'ils finissent par être complètement inutiles de toute façon . # - 3) Pour afficher toutes ces valeurs intermédiaires, nous avons dû étaler la formule à l'intérieur de la fonction sur plusieurs lignes. Parfois, il est utile de diviser un calcul en plusieurs étapes, s'il est très long et que tout mettre sur une seule ligne le rend difficile à lire, mais parfois cela rend simplement notre code inutilement verbeux. Voici à quoi ressemblerait normalement la fonction ci-dessus : def hypotenuse(x, y): return math.sqrt(x**2 + y**2) # Comment pouvons-nous mieux faire que ça ? Si nous voulons inspecter les valeurs des variables à différentes étapes de l'exécution d'un programme, nous pouvons utiliser un outil comme `pdb` (ou plutôt son évolution : `ipdb` si le package est installé). Si nous voulons que notre programme affiche des messages informatifs, éventuellement dans un fichier, et que nous voulons pouvoir contrôler le niveau de détail au moment de l'exécution sans avoir à modifier quoi que ce soit dans le code, nous pouvons utiliser la journalisation. # # Plus important encore, pour vérifier que notre code fonctionne correctement maintenant et continuera à fonctionner correctement, nous devons écrire une suite permanente de tests que nous pouvons exécuter régulièrement sur notre code. Nous discuterons plus en détail des tests dans un chapitre ultérieur. # # ### pdb (ou ipdb) # # `pdb` est un module Python intégré que nous pouvons utiliser pour débugger un programme pendant son exécution. Nous pouvons soit importer le module et utiliser ses fonctions depuis notre code, soit l'invoquer en tant que script lors de l'exécution de notre fichier de code. Nous pouvons utiliser pdb pour parcourir notre programme, ligne par ligne ou par incréments plus importants, inspecter l'état à chaque étape et effectuer un "post-mortem" du programme s'il plante. # + import pdb try: age_str = input("Please enter your age: ") age = int(age_str) except ValueError as err: pdb.set_trace() # - # ### Logging # # Parfois, il est utile qu'un programme envoie des messages à une console ou à un fichier pendant son exécution. Ces messages peuvent être utilisés comme enregistrement de l'exécution du programme et nous aident à trouver des erreurs. Parfois, un bug se produit par intermittence et nous ne savons pas ce qui le déclenche, si nous ajoutons une sortie de débuggage à notre programme uniquement lorsque nous voulons commencer une recherche active du bug, nous ne pourrons peut-être pas le reproduire. Si notre programme enregistre les messages dans un fichier tout le temps, nous pouvons constater que des informations utiles ont été enregistrées lorsque nous vérifions le journal (logs) après que le bug se soit produit. # # Certains types de messages sont plus importants que d'autres, les erreurs sont des événements notables qui doivent presque toujours être enregistrés. Les messages qui enregistrent qu'une opération s'est terminée avec succès peuvent parfois être utiles, mais ne sont pas aussi importants que les erreurs. Des messages détaillés qui débuggent chaque étape d'un calcul peuvent être intéressants si nous essayons de débugger le calcul, mais s'ils étaient affichés tout le temps, ils rempliraient la console de bruit (ou rendraient notre fichier de logs vraiment, vraiment gros). # # Nous pouvons utiliser le module de log de Python pour ajouter la journalisation à notre programme de manière simple et cohérente. Les instructions de log sont presque comme les instructions d'affichage, mais chaque fois que nous enregistrons un message, nous spécifions un niveau pour le message. Lorsque nous exécutons notre programme, nous définissons un niveau de log souhaité pour le programme. Seuls les messages dont le niveau est supérieur ou égal au niveau que nous avons défini apparaîtront dans le journal. Cela signifie que nous pouvons temporairement activer la journalisation détaillée et la désactiver à nouveau en modifiant simplement le niveau de log à un seul endroit. # # Il existe un ensemble cohérent de noms de niveau de log que la plupart des langues utilisent. Dans l'ordre, de la valeur la plus élevée (la plus sévère) à la valeur la plus basse (la moins sévère), ce sont : # - CRITICAL : pour les erreurs très graves # - ERROR : pour les erreurs moins graves # - WARNING : pour les avertissements # - INFO : pour les messages informatifs importants # - DEBUG : pour des messages de débuggage détaillés # # # Ces noms sont utilisés pour les constantes entières définies dans le module de log : `logging`. Le module fournit également des méthodes que nous pouvons utiliser pour enregistrer les messages. Par défaut, ces messages sont affichés sur la console et le niveau de log par défaut est `WARNING`. Nous pouvons configurer le module pour personnaliser son comportement : par exemple, nous pouvons écrire les messages dans un fichier à la place, augmenter ou diminuer le niveau de log et modifier le format du message. Voici un exemple de journalisation simple : # + import logging # log messages to a file, ignoring anything less severe than ERROR logging.basicConfig(filename='myprogram.log', level=logging.ERROR) # these messages should appear in our file logging.error("The washing machine is leaking!") logging.critical("The house is on fire!") # but these ones won't logging.warning("We're almost out of milk.") logging.info("It's sunny today.") logging.debug("I had eggs for breakfast.")
_notebooks/2022-01-02-python-intro-gen-4-1-exceptions.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + [markdown] id="Mf_Ub_nY93w8" # # POGIL 5.1 - Lists # # ## Python for Scientists # + [markdown] id="tHqaWxdO9-gJ" # Python has a wide variety of built-in types for storing anything from numbers to text, like `int`s, `float`s, and `string`s. There's also ways to store combinations of these simple data types in something called a data structure, like `list`s, `tuple`s, and `dict`s. Like the simple data types, each one of these data structures has disadvantages and advantages that you'll learn about here. # + [markdown] id="irLOwBN8-V5L" # ### Content Learning Objectives # + [markdown] id="zhQTp7zW-ZBR" # *After completing this activity, students should be able to:* # # - Identify a list # - Understand how lists and other objects are indexed by default in Python # - Refer to a list and its elements # + [markdown] id="a38Cdkll-8aS" # ### Process Skill Goals # + [markdown] id="KD6NoR_1--uq" # *During the activity, students should make progress toward:* # # - Providing feedback on how well other team members are working # + [markdown] id="7wxBJw3P_IQY" # There are different types of data in a programming language, and they all serve different purposes. For example, consider how we might store a name versus how we might store the price of something. One of these is not like the other, but the ability to store this data is crucial for knowing how to manipulate data in Python. # # Python has four basic datatypes, and these datatypes allow you to store different kinds of data. The datatypes include the boolean, integer, floating-point value, and string. # # A boolean value can only store one state: `True` or `False`. It takes only one bit to store a boolean value, meaning that boolean values are very efficient. However, can you imagine trying to store the price of something in a boolean? # # Instead, we can use numbers. There are two types of numbers: integers and floats. We go over the difference between integers and floating-point numbers in chapter 3 of the Python for Scientists textbook. # # Lastly, if we want to store more than numbers, we need to use a string. A string is a sequence of characters. Again, we cover what a string is in chapter 3. # + [markdown] id="DwfiZ8bH_FI0" # ### Task 1 # + [markdown] id="y9e_rXMTANvd" # **What is the index of the second element of the `primes` array presented above? What is the value at that index value?** # + [markdown] id="uvUW0Z8MAUp9" # # + [markdown] id="Wrh2rrGuAU-A" # ### Task 2 # + [markdown] id="q3dA7E2cAW1d" # **How does the index number compare to the position of the element? You can express your answer in English or in mathematical terms - either is acceptable.** # # *Jupyter Notebook Pro Tip: If you know how to write LaTeX code, you can write math by enclosing your math in two dollar signs, just like LaTeX's math mode.* # # <pre> # $a = 2^{2} = 4$ # </pre> # # $a = 2^{2} = 4$ # + [markdown] id="BhXm-d0QAffZ" # # + [markdown] id="RL7pludbAfxb" # ### Task 3 # + [markdown] id="LMh6BWqaCCT_" # **Type each line of code into the provided Python shell. Write the corresponding output in the space above. If an error occurs, write what type of error occurs. If you were surprised by any of the output, note what was surprising.** # + [markdown] id="GTN16_n6CONA" # ```python # odd = [1, 3, 5, 7] # ``` # + id="WmCE38M6CT36" # + [markdown] id="UopNdQKOCUEe" # # + [markdown] id="tLuzemHGCUzD" # ```python # print(odd) # ``` # + id="psbVGlcDCY79" # + [markdown] id="BQ4w2K8UCZJo" # # + [markdown] id="1S2dbk9FCZtf" # ```python # print(odd[2]) # ``` # + id="9nVCuDmcCd3J" # + [markdown] id="MyesH-DICdVN" # # + [markdown] id="GbtrAiSHCeVh" # ```python # print(odd[4]) # ``` # + id="0uDfu1FVChZx" # + [markdown] id="yY3SEV2aChm3" # # + [markdown] id="lT6rL3QSCh4n" # ```python # print(len(odd)) # ``` # + id="j3JcW625ClZX" # + [markdown] id="NRGXHeTCCk_L" # # + [markdown] id="W_XutfZVClxR" # ```python # number = odd[1] # ``` # + id="WtKfaPY_CpN8" # + [markdown] id="Rhjv_ZocCo3C" # # + [markdown] id="5ERhY26ACplx" # ```python # print(odd) # ``` # + id="7B2Pok90CuAB" # + [markdown] id="hiLqrJLACtdv" # # + [markdown] id="Qs00sSQvCuad" # ```python # print(number) # ``` # + id="j_zUZQDCCwwO" # + [markdown] id="Ne8HFvExCw95" # # + [markdown] id="1cvszc_KCxjb" # ### Task 4 # + [markdown] id="0aJlmJT2C0l9" # **How did you reference the value of the 3rd element of `odd`?** # + [markdown] id="SE57sUONC74Q" # # + [markdown] id="X2sMAaRkC8Ld" # ### Task 5 # + [markdown] id="waw3tYz2C9WZ" # **What did the output of the `len()` function tell you about the list?** # + [markdown] id="MBokPcE2DCip" # # + [markdown] id="Fa3FSPB9DDHF" # ### Task 6 # + [markdown] id="ZikfZ4zCDE-C" # **The output of `print(odd[4])` produced an error. What's wrong with this line?** # + [markdown] id="pfu1bGT6DPXy" # # + [markdown] id="I4GkTh8XDP1p" # ### Task 7 # + [markdown] id="Xn7vonRqDRn8" # **Write and execute a line of Python code that assigns a list of three integers to the variable `run`. You can choose what the integers are.** # + id="mRP5oM0CDa22" # + [markdown] id="SR3cb0E3DbMH" # ### Task 8 # + [markdown] id="5MoBxfMuDcg0" # **Write and execute a statement that assigns the value 100 to the last element of `run`.** # + id="5ZjOm1VPDi_Q" # + [markdown] id="OLhjKxrWDjX0" # ### Task 9 # + [markdown] id="1-ewJ6RyDkqE" # **Write and execute a statement that assigns the first value of `run` to a new variable called `first`.** # + id="IkDkzpcODqjO" # + [markdown] id="-p1v7rWODrRA" # ### Task 10 # + [markdown] id="ZBIOJgKIDsks" # **Double-check your above assignment statements by printing `run` to make sure it did what you wanted it to do, then print `run` to make sure the output is what you expected.** # + id="zNwVFLtCD3Op" # + [markdown] id="mhbtPuzMHpK7" # --- # # End of exercise.
docs/pogil/notebooks/.ipynb_checkpoints/lists-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # Libraries # %matplotlib inline import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from copy import deepcopy from __future__ import print_function # # Versions # !python --version items = [("Numpy", np), ("Pandas", pd), ("Matplotlib", matplotlib), ("Seaborn", sns)] for item in items: print(item[0] + " version " + str(item[1].__version__)) # --- # # Get Data X_train = pd.read_hdf('/Users/davidziganto/Repositories/Synthetic_Dataset_Generation/data/py27/simulated_cleaned_training_data_py27.h5', 'table') y_train = X_train.pop('hired') # # Get X_test & y_test # + import pickle path = "/Users/davidziganto/Repositories/Synthetic_Dataset_Generation/pickle_files/py27/" with open(path + "X_test_py27.pkl", 'rb') as picklefile: X_test = pickle.load(picklefile) with open(path + "y_test_py27.pkl", 'rb') as picklefile: y_test = pickle.load(picklefile) # - # # Machine Learning # This section shows the machine learning pipeline used to generate scoring thresholds. A further discussion of how this information is used will be included in the next notebook. # ### Check Class Weights pos_class_prop = y_train.mean() pos_class_prop # ### ML Libraries from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.naive_bayes import MultinomialNB from sklearn.dummy import DummyClassifier from sklearn.metrics import log_loss, confusion_matrix from sklearn.model_selection import RandomizedSearchCV, GridSearchCV # ### Instantiate Models # + dt = DecisionTreeClassifier(criterion='gini', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=13, max_leaf_nodes=None, min_impurity_split=1e-07, class_weight=None, presort=False) dummy = DummyClassifier(strategy='most_frequent', random_state=99, constant=None) gbc = GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=50, subsample=1.0, criterion='friedman_mse', min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, min_impurity_split=1e-07, init=None, random_state=123, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto') knn = KNeighborsClassifier(n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='euclidean', metric_params=None, n_jobs=-1) lr = LogisticRegression(penalty='l2', dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=10, solver='liblinear', max_iter=100, multi_class='ovr', verbose=0, warm_start=False, n_jobs=-1) nb = MultinomialNB(alpha=1.0, fit_prior=True, class_prior=None) rf = RandomForestClassifier(n_estimators=50, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_split=1e-07, bootstrap=True, oob_score=False, n_jobs=-1, random_state=17, verbose=0, warm_start=False, class_weight=None) # - # ### Setup Parameter Grid For RandomCV # + dt_param_grid = dict(max_depth=[None, 6, 8], min_samples_leaf=range(1,5), class_weight=[None, 'balanced']) gbc_param_grid = dict(loss=['deviance','exponential'], max_depth=range(2,5), learning_rate=[0.001, 0.01, 0.1]) knn_param_grid = dict(n_neighbors=range(1, 15, 2), weights=('uniform', 'distance')) lr_param_grid = dict(penalty=['l1', 'l2'], C=np.geomspace(0.001, 10, num=5), class_weight=[None, 'balanced']) rf_param_grid = dict(n_estimators=[50, 100], max_depth=[None, 8, 10], class_weight=[None, 'balanced']) # - # ### Setup Dictionary For Algo_Report() # + from collections import OrderedDict algo_dict = OrderedDict( ( ("dt",(dt, dt_param_grid)), ("dummy",(dummy)), ("gbc",(gbc, gbc_param_grid)), ("knn",(knn, knn_param_grid)), ("lr",(lr, lr_param_grid)), ("nb",(nb)), ("rf",(rf, rf_param_grid)) ) ) # - # ### Algo_Report() def algo_report(algo_dict, cv=5, search_flag=1): ''' Function that generates in-sample and out-of-sample metrics for numerous machine learning algorithms. Input: algo_dict = dictionary with algorithm name as key and model object & parameter grid as values cv = number of folds for cross validation random_search_flag = {0: use default model paramters; 1: use randomized search} Output: prints a report showing: 1) in-sample negative log-loss value or accuracy (dependent on score function) 2) out-of-sample negative log-loss value or accuracy (dependent on score function) 3) out-of-sample log loss value 4) confusion matrix ''' for k, v in algo_dict.iteritems(): if k == "nb" or k == "dummy": model = v.fit(X_train, y_train) else: if search_flag: model = RandomizedSearchCV(v[0], v[1], cv=cv, scoring='neg_log_loss', random_state=42) model.fit(X_train, y_train) elif search_flag == 2: model = GridSearchCV(v[0], v[1], cv=cv, scoring='neg_log_loss', random_state=42) model.fit(X_train, y_train) else: model = v[0].fit(X_train, y_train) print("[%s]" % k) print("In-Sample: {}\nOut-of_Sample: {}\nLog_loss: {}".format( round(model.score(X_train, y_train),3), round(model.score(X_test, y_test),3), round(log_loss(y_test, model.predict_proba(X_test)),3))) print("\nConfusion Matrix:") print(confusion_matrix(y_test, model.predict(X_test))) print("\n-----------------\n") # ### Results # Results for all three scenarios - using only defaults, using random search, and using grid search - can be found below. # #### Defaults algo_report(algo_dict, cv=10, search_flag=0) # #### Random Search algo_report(algo_dict, cv=10, search_flag=1) # #### Grid Search algo_report(algo_dict, cv=10, search_flag=1) # # Create Models For Pickling # Needs Improvement Model knn_randcv = RandomizedSearchCV(knn, knn_param_grid, cv=10, scoring='neg_log_loss', random_state=42) knn_randcv.fit(X_train, y_train) log_loss(y_test, knn_randcv.predict_proba(X_test)) # Satisfactory Model rf_randcv = RandomizedSearchCV(rf, rf_param_grid, cv=10, scoring='neg_log_loss', random_state=42) rf_randcv.fit(X_train, y_train) log_loss(y_test, rf_randcv.predict_proba(X_test)) # Proficient Model gbc_randcv = RandomizedSearchCV(gbc, gbc_param_grid, cv=10, scoring='neg_log_loss', random_state=42) gbc_randcv.fit(X_train, y_train) log_loss(y_test, gbc_randcv.predict_proba(X_test)) # # Pickle Models & Test Set Data For Auto-Scoring # + import pickle path = '/Users/davidziganto/Repositories/Synthetic_Dataset_Generation/pickle_files/py27/' # Save KNN model with open(path + 'knn_needs_improvement_py27.pkl', 'wb') as picklefile: pickle.dump(knn_randcv, picklefile) # Save Random Forest model with open(path + 'rf_satisfactory_py27.pkl', 'wb') as picklefile: pickle.dump(rf_randcv, picklefile) # Save Gradient Boosted Classifier model with open(path + 'gbc_proficient_py27.pkl', 'wb') as picklefile: pickle.dump(gbc_randcv, picklefile)
python_27_code/.ipynb_checkpoints/5_Simulated_Classification_Dataset_ML_pipeline_py27-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: nlp_env # language: python # name: nlp_env # --- # # Compress NLU model using tflite # + # imports from dialognlu import TransformerNLU from dialognlu.utils.tf_utils import convert_to_tflite_model import ipywidgets as widgets import json # - # ## Load the model from disk # + model_path = "../saved_models/joint_distilbert_model" # specify the model_path print("Loading model ...") nlu = TransformerNLU.load(model_path) # - # ## Compressing model conversion_mode_wid = widgets.Dropdown(options=['hybrid_quantization', 'fp16_quantization', 'normal'], value='hybrid_quantization', description='conversion_mode:') display(conversion_mode_wid) # The compression code save_file_path = model_path + "/model.tflite" conversion_mode = conversion_mode_wid.value print(conversion_mode) convert_to_tflite_model(nlu.model.model, save_file_path, conversion_mode=conversion_mode) print("Done") # ### Note that: This is integrated feature in `model.save()` in case of `TransformerNLU`
notebooks/tflite_compress_nlu_model.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + #default_exp fastai.learner # - #hide from nbdev.showdoc import * # # Learner Errors # > In-place fastai specific errors to ease debugging # + #export from fastdebug.torch import layer_error, device_error from fastai.data.all import * from fastai.optimizer import * from fastai.learner import * from fastai.callback.core import event from fastai.callback.training import ShortEpochCallback from fastai.torch_core import default_device from fastcore.basics import patch from fastcore.meta import delegates # - # This notebook contains a series of various errors that can be used when running with `fastai`. It should be noted here that there is no other imports or magic you need to do to use this section of the library other then: `from fastdebug import *`. It will automatically load in what's needed. # # As a style choice, we are choosing to do the `.*` notation as this loads in not only all of our errors, but also replaces sections of `fastai`'s code to inject some error handling (as we'll see later) # ## Error Types #export def loss_func_error(e:Exception, learn) -> Exception: """ Error that should be run when there is an issue when working with the loss function Raises with a message stating the shapes of the inputs and targs, and the error """ err = f'There was an issue with calculating the loss with `{getattr(learn.loss_func, "__name__", learn.loss_func)}`' err += f'\n\nPrediction shape(s): {[p.shape for p in listify(learn.pred)]}' err += f'\nLabel Shape(s): {[y.shape for y in learn.yb]}' err += f'\nError: {e.args[0]}' e.args = [err] raise e #export def callback_error(e:Exception, cb:str, event_name:str) -> Exception: """ Raises an error from when a Callback event failed, showing what event, the name of the Callback and the trace """ e.args = [f"Exception raised in the {cb} Callback during {event_name}:\n\n{e.args[0]}"] raise e #export def catch_pred_errors(e:Exception, model) -> Exception: "Catches any errors relating to prediction that are either related to the device or model layers. Else raise `e`" if "Input type" in e.args[0]: device_error(e, 'Input', 'Model weights') elif "Expected" in e.args[0]: layer_error(e, model) else: raise e # anything else #export def catch_loss_errors(e:Exception, learn): "Catches any errors that occur with the loss function and its calculation" if "Input type" in e.args[0]: device_error(e, 'Model prediction', 'Truths') else: loss_func_error(e, learn) # ## Modifications and Enhancements to the fastai Source Code and `Learner`: #export @patch def sanity_check(self:Learner, show_table=False): "Performs a short epoch and uses all the callbacks in `self.cbs` on the CPU to ensure nothing is broken" device = getattr(self.dls, 'device', default_device()) if hasattr(self.dls, 'device'): self.dls.device = 'cpu' else: # Using raw torch self.model.to('cpu') self.save('tmp') cbs = [ShortEpochCallback(short_valid=False)] if show_table: with self.no_bar(), self.no_logging(): self.fit(1, cbs=cbs) else: self.fit(1, cbs=cbs) if hasattr(self.dls, 'device'): self.dls.device = device else: self.model.to(device) self.load('tmp') #export @patch @delegates(Learner.sanity_check) def __init__(self:Learner, dls, model, loss_func=None, opt_func=Adam, lr=defaults.lr, splitter=trainable_params, cbs=None, metrics=None, path=None, model_dir='models', wd=None, wd_bn_bias=False, train_bn=True, moms=(0.95,0.85,0.95), sanity_check=False, **kwargs): "Group together a `model`, some `dls` and a `loss_func` to handle training, potentially run a sanity check" path = Path(path) if path is not None else getattr(dls, 'path', Path('.')) if loss_func is None: loss_func = getattr(dls.train_ds, 'loss_func', None) assert loss_func is not None, "Could not infer loss function from the data, please pass a loss function." self.dls,self.model = dls,model store_attr(but='dls,model,cbs') self.training,self.create_mbar,self.logger,self.opt,self.cbs = False,True,print,None,L() self.add_cbs(L(defaults.callbacks)+L(cbs)) self("after_create") if sanity_check: self.sanity_check(**kwargs) show_doc(Learner.__init__) show_doc(Learner.sanity_check) # With `sanity_check`, you can make sure that you've set everything up properly and you won't get any issues before pushing to the GPU. This allows you to quickly ensure that you won't get any `CUDA` device-assist errors, and that the whole training regiment will go well. #export @patch def _do_one_batch(self:Learner): try: self.pred = self.model(*self.xb) except RuntimeError as e: catch_pred_errors(e, self.model) self('after_pred') if len(self.yb): try: self.loss_grad = self.loss_func(self.pred, *self.yb) except Exception as e: catch_loss_errors(e, self) self.loss = self.loss_grad.clone() self('after_loss') if not self.training or not len(self.yb): return self('before_backward') self.loss_grad.backward() self._with_events(self.opt.step, 'step', CancelStepException) self.opt.zero_grad() #export @patch def _call_one(self:Learner, event_name): if not hasattr(event, event_name): raise Exception(f'missing {event_name}') for cb in self.cbs.sorted('order'): try: cb(event_name) except Exception as e: callback_error(e, cb.__repr__(), event_name) #export def module_error(e:AttributeError) -> AttributeError: """ Raises an error when trying to load in a previous `Learner` and custom functions were not available in the namespace """ args = e.args[0] err = 'Custom classes or functions exported with your `Learner` are not available in the namespace currently.\n' err += 'Please re-declare them before calling `load_learner`:\n\n' err += args e.args = [err] raise e #export def load_learner(fname, cpu=True, pickle_module=pickle): "Load a `Learner` object in `fname`, optionally putting it on the `cpu`" distrib_barrier() try: res = torch.load(fname, map_location='cpu' if cpu else None, pickle_module=pickle_module) except AttributeError as e: module_error(e) if hasattr(res, 'to_fp32'): res = res.to_fp32() if cpu: res.dls.cpu() return res # We have a custom `load_learner` function here that can check if everything exported is available when bringing the model in, if not then it'll raise an explicit error
02_fastai.learner.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Indexing time series data in pandas # Quite often the data that we want to analyze has a time based component. Think about data like daily temperatures or rainfall, stock prices, sales data, student attendance, or events like clicks or views of a web application. There is no shortage of sources of data, and new sources are being added all the time. As a result, most pandas users will need to be familiar with time series data at some point. # # A time series is just a pandas ```DataFrame``` or ```Series``` that has a time based index. The values in the time series can be anything else that can be contained in the containers, they are just accessed using date or time values. A time series container can be manipulated in many ways in pandas, but for this article I will focus just on the basics of indexing. Knowing how indexing works first is important for data exploration and use of more advanced features. # # ## DatetimeIndex # In pandas, a ```DatetimeIndex``` is used to provide indexing for pandas ```Series``` and ```DataFrame```s and works just like other ```Index``` types, but provides special functionality for time series operations. We'll cover the common functionality with other ```Index``` types first, then talk about the basics of partial string indexing. # # One word of warning before we get started. It's important for your index to be sorted, or you may get some strange results. # # ## Examples # To show how this functionality works, let's create some sample time series data with different time resolutions. # + import pandas as pd import numpy as np import datetime # this is an easy way to create a DatetimeIndex # both dates are inclusive d_range = pd.date_range("2021-01-01", "2021-01-20") # this creates another DatetimeIndex, 10000 minutes long m_range = pd.date_range("2021-01-01", periods=10000, freq="T") # daily data in a Series daily = pd.Series(np.random.rand(len(d_range)), index=d_range) # minute data in a DataFrame minute = pd.DataFrame(np.random.rand(len(m_range), 1), columns=["value"], index=m_range) # time boundaries not on the minute boundary, add some random jitter mr_range = m_range + pd.Series([pd.Timedelta(microseconds=1_000_000.0 * s) for s in np.random.rand(len(m_range))]) # minute data in a DataFrame, but at a higher resolution minute2 = pd.DataFrame(np.random.rand(len(mr_range), 1), columns=["value"], index=mr_range) # - daily.head() minute.head() minute2.head() # ## Resolution # A ```DatetimeIndex``` has a resolution that indicates to what level the ```Index``` is indexing the data. The three indices created above have distinct resolutions. This will have ramifications in how we index later on. print("daily:", daily.index.resolution) print("minute:", minute.index.resolution) print("randomized minute:", minute2.index.resolution) # ## Typical indexing # Before we get into some of the "special" ways to index a pandas ```Series``` or ```DataFrame``` with a ```DatetimeIndex```, let's just look at some of the typical indexing functionality. # # ### Basics # I've covered the basics of indexing before, so I won't cover too many details here. However it's important to realize that a ```DatetimeIndex``` works just like other indices in pandas, but has extra functionality. (The extra functionality can be more useful and convenient, but just hold tight, those details are next). If you already understand basic indexing, you may want to skim until you get to partial string indexing. If you haven't read my articles on indexing, you should start with the [basics](https://www.wrighters.io/indexing-and-selecting-in-pandas-part-1/) and go from there. # # Indexing a ```DatetimeIndex``` using a ```datetime```-like object will use [exact indexing](https://pandas.pydata.org/docs/user_guide/timeseries.html#exact-indexing). # # ### ```getitem``` a.k.a the array indexing operator (```[]```) # When using ```datetime```-like objects for indexing, we need to match the resolution of the index. # # This ends up looking fairly obvious for our daily time series. daily[pd.Timestamp("2021-01-01")] try: minute[pd.Timestamp("2021-01-01 00:00:00")] except KeyError as ke: print(ke) # This ```KeyError``` is raised because in a ```DataFrame```, using a single argument to the ```[]``` operator will look for a *column*, not a row. We have a single column called ```value``` in our ```DataFrame```, so the code above is looking for a column. Since there isn't a column by that name, there is a ```KeyError```. We will use other methods for indexing rows in a ```DataFrame```. # # ### ```.iloc``` indexing # Since the ```iloc``` indexer is integer offset based, it's pretty clear how it works, not much else to say here. It works the same for all resolutions. daily.iloc[0] minute.iloc[-1] minute2.iloc[4] # ### ```.loc``` indexing # When using ```datetime```-like objects, you need to have exact matches for single indexing. It's important to realize that when you make ```datetime``` or ```pd.Timestamp``` objects, all the fields you don't specify explicitly will default to 0. jan1 = datetime.datetime(2021, 1, 1) daily.loc[jan1] minute.loc[jan1] # the defaults for hour, minute, second make this work try: # we don't have that exact time, due to the jitter minute2.loc[jan1] except KeyError as ke: print("Missing in index: ", ke) # but we do have a value on that day # we could construct it manually to the microsecond if needed jan1_ms = datetime.datetime(2021, 1, 1, 0, 0, 0, microsecond=minute2.index[0].microsecond) minute2.loc[jan1_ms] # ### Slicing # Slicing with integers works as expected, you can read more about regular slicing [here](https://www.wrighters.io/indexing-and-selecting-in-pandas-slicing/). But here's a few examples of "regular" slicing, which works with the array indexing operator (```[]```) or the ```.iloc``` indexer. daily[0:2] # first two, end is not inclusive minute[0:2] # same minute2[1:5:2] # every other minute2.iloc[1:5:2] # works with the iloc indexer as well # Slicing with ```datetime```-like objects also works. Note that the end item is inclusive, and the defaults for hours, minutes, seconds, and microseconds will set the cutoff for the randomized data on minute boundaries (in our case). daily[datetime.date(2021,1,1):datetime.date(2021, 1,3)] # end is inclusive minute[datetime.datetime(2021, 1, 1): datetime.datetime(2021, 1, 1, 0, 2, 0)] minute2[datetime.datetime(2021, 1, 1): datetime.datetime(2021, 1, 1, 0, 2, 0)] # This sort of slicing work with ```[]``` and ```.loc```, but not ```.iloc```, as expected. Remember, ```.iloc``` is for integer offset indexing. minute2.loc[datetime.datetime(2021, 1, 1): datetime.datetime(2021, 1, 1, 0, 2, 0)] try: # no! use integers with iloc minute2.iloc[datetime.datetime(2021, 1, 1): datetime.datetime(2021, 1, 1, 0, 2, 0)] except TypeError as te: print(te) # ### Special indexing with strings # Now things get really interesting and helpful. When working with time series data, partial string indexing can be very helpful and way less cumbersome than working with ```datetime``` objects. I know we started with objects, but now you see that for interactive use and exploration, strings are very helpful. You can pass in a string that can be parsed as a full date, and it will work for indexing. daily["2021-01-04"] minute.loc["2021-01-01 00:03:00"] # Strings also work for slicing. minute.loc["2021-01-01 00:03:00":"2021-01-01 00:05:00"] # end is inclusive # ### Partial String Indexing # Partial strings can also be used, so you only need to specify part of the data. This can be useful for pulling out a single year, month, or day from a longer dataset. daily["2021"] # all items match (since they were all in 2021) daily["2021-01"] # this one as well (and only in January for our data) # You can do this on a ```DataFrame``` as well. minute["2021-01-01"] # See that deprecation warning? You should no longer use ```[]``` for ```DataFrame``` string indexing (as we saw above, ```[]``` should be used for column access, not rows). Depending on whether the value is found in the index or not, you may get an error or a warning. Use ```.loc``` instead so you can avoid the confusion. minute2.loc["2021-01-01"] # If using string slicing, the end point includes *all times in the day*. minute2.loc["2021-01-01":"2021-01-02"] # But if we include times, it will include partial periods, cutting off the end right up to the microsecond if it is specified. minute2.loc["2021-01-01":"2021-01-02 13:32:01"] # ## Slicing vs. exact matching # Our three datasets have different resolutions in their index: day, minute, and microsecond respectively. If we pass in a string indexing parameter and the resolution of the string is *less* accurate than the index, it will be treated as a slice. If it's the same or more accurate, it's treated as an exact match. Let's use our microsecond (```minute2```) and minute (```minute```) resolution data examples. Note that every time you get a slice of the ```DataFrame```, the value returned is a ```DataFrame```. When it's an exact match, it's a ```Series```. minute2.loc["2021-01-01"] # slice - the entire day minute2.loc["2021-01-01 00"] # slice - the first hour of the day minute2.loc["2021-01-01 00:00"] # slice - the first minute of the day minute2.loc["2021-01-01 00:00:00"] # slice - the first minute and second of the day print(str(minute2.index[0])) # note the string representation include the full microseconds minute2.loc[str(minute2.index[0])] # slice - this seems incorrect to me, should return Series not DataFrame minute2.loc[minute2.index[0]] # exact match minute.loc["2021-01-01"] # slice - the entire day minute.loc["2021-01-01 00"] # slice - the first hour of the day minute.loc["2021-01-01 00:00"] # exact match # Note that for a microsecond resolution string match, I don't see an exact match (where the return would be a ```Series```), but instead a slice match (because the return value is a ```DataFrame```). On the minute resolution ```DataFrame``` it worked as I expected. # # ## asof # One way to deal with this sort of issue is to use ```asof```. Often, when you have data that is either randomized in time or may have missing values, getting the most recent value as of a certain time is preffered. You could do this yourself, but it looks little cleaner to use ```asof```. minute2.loc[:"2021-01-01 00:00:03"].iloc[-1] # vs minute2.asof("2021-01-01 00:00:03") # ## truncate # You can also use ```truncate``` which is sort of like slicing. You specify a value of ```before``` or ```after``` (or both) to indicate cutoffs for data. Unlike slicing which includes all values that partially match the date, ```truncate``` assumes 0 for any unspecified values of the date. minute2.truncate(after="2021-01-01 00:00:03") # ## Summary # You can now see that time series data can be indexed a bit differently than other types of ```Index``` in pandas. Understanding time series slicing will allow you to quickly navigate time series data and quickly move on to more advanced time series analysis.
pandas/pandas_indexing_7.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + colab={"base_uri": "https://localhost:8080/"} id="j-b0BLdxHWhz" outputId="6286ee6b-f805-4da3-a0bd-eaae08b00629" # !git clone https://github.com/aryan51k/american_sign_language_reconizer.git # + colab={"base_uri": "https://localhost:8080/"} id="WpRWplPoHeJ5" outputId="ebad8d83-95bc-47b1-addf-16f33df9b5c8" # %cd /content/American-Sign-Language-Recognizer/ # + id="QRvTwegRHlij" import numpy as np import pandas as pd from asl_data import AslDb # + id="axk5mQcmHxQo" asl = AslDb() # + colab={"base_uri": "https://localhost:8080/", "height": 238} id="oS57tVyhH0xn" outputId="279ecbe8-3302-4977-cee5-1eb04cecf674" asl.df.head() # + colab={"base_uri": "https://localhost:8080/"} id="aETbQtieH4CW" outputId="27350fc9-4f25-4bad-a2f8-8a146e3723e8" asl.df.loc[98,1] # + [markdown] id="7pPcCmGGNUBr" # Now getting the coordinates in terms of nose as the origin # + id="-5Qw_faDIG9e" colab={"base_uri": "https://localhost:8080/", "height": 238} outputId="125bba9a-70aa-4606-dea8-245aa23f045a" asl.df['grnd-ry'] = asl.df['right-y'] - asl.df['nose-y'] asl.df.head() # + id="xnJJxLKy9FLr" colab={"base_uri": "https://localhost:8080/", "height": 455} outputId="3507aa90-d545-4923-cef6-9913f46b7c50" asl.df['grnd-ly'] = asl.df['left-y'] - asl.df['nose-y'] asl.df['grnd-rx'] = asl.df['right-x'] - asl.df['nose-x'] asl.df['grnd-lx'] = asl.df['left-x'] - asl.df['nose-x'] asl.df.loc[98] # + colab={"base_uri": "https://localhost:8080/"} id="IMpdESREWGDM" outputId="90a21962-2157-47b3-fd1b-ea84dc42719b" asl.df.loc[98, 75] # + [markdown] id="dLcRYiup93wQ" # ## Now displying the ground truth values for video 98 and frame 1 # + colab={"base_uri": "https://localhost:8080/"} id="O27DN8af-UWa" outputId="6349d32c-00e4-4f83-9a99-055b4d43c571" features_ground = ['grnd-rx','grnd-ry','grnd-lx','grnd-ly'] [asl.df.loc[98,1][v] for v in features_ground] # + colab={"base_uri": "https://localhost:8080/"} id="Q9F-M3O0-f0r" outputId="f862aa3b-2e05-465c-da72-9d112c6b0949" training = asl.build_training(features_ground) print("Training words: {}".format(training.words)) # + colab={"base_uri": "https://localhost:8080/"} id="IhlkJS1qEtEO" outputId="3a511cd5-4ba2-48ae-9daf-ef75331b34fc" training.get_word_Xlengths('BREAK-DOWN') # + colab={"base_uri": "https://localhost:8080/", "height": 175} id="kVhwF_c2Crfg" outputId="d5479af0-9a4c-4f3d-f5ff-740df76296a5" df_means = asl.df.groupby('speaker').mean() df_means # + colab={"base_uri": "https://localhost:8080/", "height": 238} id="bc6QXpMLHUPt" outputId="9f4f7288-5bff-4e63-fcae-07aa1ab743b5" asl.df['left-x-mean']= asl.df['speaker'].map(df_means['left-x']) asl.df.head() # + colab={"base_uri": "https://localhost:8080/", "height": 175} id="DJcIyreQHWb9" outputId="a20879c4-a16b-4af7-f964-db4aeac422de" from asl_utils import test_std_tryit df_std = asl.df.groupby('speaker').std() df_std.head() # + colab={"base_uri": "https://localhost:8080/"} id="7GAdD-llOHv4" outputId="464e9b11-0aaf-4b56-b31e-c27d4c20ed12" asl.df['speaker'].map(df_means['left-x']) # + [markdown] id="ShzDjQoeSnxR" # ## Normalizing using Z-score scaling (X-Xmean)/Xstd # + id="hyBHKI6WNNmF" def normalize(data): mean = asl.df['speaker'].map(df_means[data]) std = asl.df['speaker'].map(df_std[data]) return (asl.df[data] - mean) / std features_norm = ['norm-rx', 'norm-ry', 'norm-lx', 'norm-ly'] asl.df['norm-lx'] = normalize('left-x') asl.df['norm-ly'] = normalize('left-y') asl.df['norm-rx'] = normalize('right-x') asl.df['norm-ry'] = normalize('right-y') # + [markdown] id="myMLXWpQSres" # ## Polar coordinates # # * Summary: to convert from Cartesian Coordinates (x,y) to Polar Coordinates (r,θ): # r = √ ( x2 + y2 ) # θ = tan-1 ( y / x ) # + [markdown] id="ReocewrTTJAu" # Here I have kep the values in terms of inverse of theta # # + id="9l1dJrXgQY_s" features_polar = ['polar-rr', 'polar-rtheta', 'polar-lr', 'polar-ltheta'] rx = asl.df['right-x'] - asl.df['nose-x'] ry = asl.df['right-y'] - asl.df['nose-y'] asl.df['polar-rr'] = np.sqrt(rx**2 + ry**2) asl.df['polar-rtheta'] = np.arctan2(rx, ry) lx = asl.df['left-x'] - asl.df['nose-x'] ly = asl.df['left-y'] - asl.df['nose-y'] asl.df['polar-lr'] = np.sqrt(lx**2 + ly**2) asl.df['polar-ltheta'] = np.arctan2(lx, ly) df_std = asl.df.groupby('speaker').std() df_means = asl.df.groupby('speaker').mean() # + colab={"base_uri": "https://localhost:8080/", "height": 275} id="GNqTSpnvS2Y7" outputId="adae1cd0-648b-48b7-e8c1-774a1cf26a85" asl.df.head() # + id="QLOb83EKTDQF" colab={"base_uri": "https://localhost:8080/", "height": 275} outputId="3223b774-aec9-41c6-8efe-7102f4a9d88a" features_delta_values = ['delta-lx', 'delta-ly', 'delta-rx', 'delta-ry'] asl.df['delta-lx'] = asl.df['left-x'].diff().fillna(0) asl.df['delta-ly'] = asl.df['left-y'].diff().fillna(0) asl.df['delta-rx'] = asl.df['right-x'].diff().fillna(0) asl.df['delta-ry'] = asl.df['right-y'].diff().fillna(0) asl.df.head() # + id="NL6o9Cu8jOo8" features_custom = ['norm-grnd-rx', 'norm-grnd-ry', 'norm-grnd-lx', 'norm-grnd-ly'] addtn_features_custom = ['norm-polar-rr', 'norm-polar-rtheta', 'norm-polar-lr', 'norm-polar-ltheta'] asl.df['norm-grnd-rx'] = normalize('grnd-rx') asl.df['norm-grnd-ry'] = normalize('grnd-ry') asl.df['norm-grnd-lx'] = normalize('grnd-lx') asl.df['norm-grnd-ly'] = normalize('grnd-ly') asl.df['norm-polar-rr'] = normalize('polar-rr') asl.df['norm-polar-lr'] = normalize('polar-lr') asl.df['norm-polar-rtheta'] = normalize('polar-rtheta') asl.df['norm-polar-ltheta'] = normalize('polar-ltheta') # + colab={"base_uri": "https://localhost:8080/", "height": 292} id="KXN92CN3kBC_" outputId="114d5612-2794-4820-d5db-e0eb5f107e30" asl.df.head() # + [markdown] id="hthySU-6kN_D" # ## Creating a function that train the model for single word # + colab={"base_uri": "https://localhost:8080/"} id="y86Kf0GUOXV9" outputId="b4323666-4220-4be4-db63-04e4bea5ccb5" # ! pip install hmmlearn # + [markdown] id="gQhOxedEXGu6" # Here X has array of coordinates for the word specified and the lengths array shows the famelength of the same # + colab={"base_uri": "https://localhost:8080/"} id="95DxvkvyJU2g" outputId="1dbcae1a-6f37-4da7-f1f7-3c5432c9a398" from hmmlearn.hmm import GaussianHMM # import warning def train_a_word(word, hidden_states, features): training = asl.build_training(features) X, length = training.get_word_Xlengths(word) model = GaussianHMM(n_components = hidden_states, n_iter = 1000) model.fit(X, length) logL = model.score(X, length) return model, logL demo = 'BOOK' model, logL = train_a_word(demo, 3, features_ground) print("Number of states trained in model for {} is {}".format(demo, model.n_components)) print("logL = {}".format(logL)) # + colab={"base_uri": "https://localhost:8080/"} id="jJPdZ1ZgOcdP" outputId="82364e7e-36d9-4fd4-a90e-8e285543f5cd" def show_model_stats(word, model): print("Number of states trained in model for {} is {}".format(word, model.n_components)) variance=np.array([np.diag(model.covars_[i]) for i in range(model.n_components)]) for i in range(model.n_components): # for each hidden state print("hidden state #{}".format(i)) print("mean = ", model.means_[i]) print("variance = ", variance[i]) print() show_model_stats(demo, model) # + id="PuDTNUHPXofK" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="e6b9907d-68b2-4c87-86f3-7271a73f26e5" import math from matplotlib import (cm, pyplot as plt, mlab) from scipy.stats import norm def visualize(word, model): """ visualize the input model for a particular word """ variance=np.array([np.diag(model.covars_[i]) for i in range(model.n_components)]) figures = [] for parm_idx in range(len(model.means_[0])): xmin = int(min(model.means_[:,parm_idx]) - max(variance[:,parm_idx])) xmax = int(max(model.means_[:,parm_idx]) + max(variance[:,parm_idx])) fig, axs = plt.subplots(model.n_components, sharex=True, sharey=False) colours = cm.rainbow(np.linspace(0, 1, model.n_components)) for i, (ax, colour) in enumerate(zip(axs, colours)): x = np.linspace(xmin, xmax, 100) mu = model.means_[i,parm_idx] sigma = math.sqrt(np.diag(model.covars_[i])[parm_idx]) ax.plot(x, norm.pdf(x, mu, sigma), c=colour) ax.set_title("{} feature {} hidden state #{}".format(word, parm_idx, i)) ax.grid(True) figures.append(plt) for p in figures: p.show() visualize(demo, model) # + [markdown] id="96WZGv7iwzZ6" # https://rdrr.io/cran/HMMpa/man/AIC_HMM.html # + [markdown] id="l3nFWW5qw00P" # Now I have modified the file my_model_selector and have obtained the required information from here to create the BIC score for the model # + colab={"base_uri": "https://localhost:8080/"} id="S8Ub4GuGXK6g" outputId="fdfefd2f-9d6a-4326-ce52-32941dc7fcac" from my_model_selectors import SelectorConstant training = asl.build_training(features_ground) word = 'VEGETABLE' model = SelectorConstant(training.get_all_sequences(), training.get_all_Xlengths(), word, n_constant=3).select() print("Number of states trained in model for {} is {}".format(word, model.n_components)) # + [markdown] id="y5i9VmHsZI9o" # ## Cross validation folds # If we simply score the model with the Log Likelihood calculated from the feature sequences it has been trained on, we should expect that more complex models will have higher likelihoods. However, that doesn't tell us which would have a better likelihood score on unseen data. The model will likely be overfit as complexity is added. To estimate which topology model is better using only the training data, we can compare scores using cross-validation. One technique for cross-validation is to break the training set into "folds" and rotate which fold is left out of training. The "left out" fold scored. This gives us a proxy method of finding the best model to use on "unseen data". In the following example, a set of word sequences is broken into three folds using the scikit-learn Kfold class object. # + colab={"base_uri": "https://localhost:8080/"} id="nffCJdaZZIuM" outputId="1a37d187-f1c1-4b14-f12d-e60d8440534c" from sklearn.model_selection import KFold training = asl.build_training(features_ground) word = 'VEGETABLE' word_sequence = training.get_word_sequences(word) split_method = KFold(n_splits = 3) for train_split, test_split in split_method.split(word_sequence): print("Train fold indices:{} Test fold indices:{}".format(train_split, test_split)) # + id="YaooLaLTVVny" words_to_train = ['FISH', 'BOOK', 'VEGETABLE', 'FUTURE', 'JOHN'] import timeit # + id="YZw11BSkdS9f" # %load_ext autoreload # %autoreload 2 # + colab={"base_uri": "https://localhost:8080/"} id="pYJO4mjwdXJd" outputId="fc36d0d3-c21a-40c2-afe0-4654b597728e" from my_model_selectors import SelectorCV training = asl.build_training(features_custom) sequences = training.get_all_sequences() Xlengths = training.get_all_Xlengths() for word in words_to_train: start = timeit.default_timer() model = SelectorCV(sequences, Xlengths, word, min_n_components=2, max_n_components=15, random_state = 14).select() end = timeit.default_timer()-start if model is not None: print("Training complete for {} with {} states with time {} seconds".format(word, model.n_components, end)) else: print("Training failed for {}".format(word)) # + colab={"base_uri": "https://localhost:8080/"} id="PernlEXIdZTq" outputId="db19f740-e1d1-4748-f683-8296302d977c" from my_model_selectors import SelectorBIC training = asl.build_training(features_custom) \ sequences = training.get_all_sequences() Xlengths = training.get_all_Xlengths() for word in words_to_train: start = timeit.default_timer() model = SelectorBIC(sequences, Xlengths, word, min_n_components=2, max_n_components=15, random_state = 14).select() end = timeit.default_timer()-start if model is not None: print("Training complete for {} with {} states with time {} seconds".format(word, model.n_components, end)) else: print("Training failed for {}".format(word)) # + colab={"base_uri": "https://localhost:8080/"} id="KxXrmmQ-d1e-" outputId="49ab04f3-1d2a-4040-a79d-6f936c3a71fd" from my_model_selectors import SelectorDIC training = asl.build_training(features_custom) sequences = training.get_all_sequences() Xlengths = training.get_all_Xlengths() for word in words_to_train: start = timeit.default_timer() model = SelectorDIC(sequences, Xlengths, word, min_n_components=2, max_n_components=15, random_state = 14).select() end = timeit.default_timer()-start if model is not None: print("Training complete for {} with {} states with time {} seconds".format(word, model.n_components, end)) else: print("Training failed for {}".format(word)) # + colab={"base_uri": "https://localhost:8080/"} id="8en0EmDnmUaT" outputId="2a85d09f-9439-4855-ff36-a57002905525" from my_model_selectors import SelectorConstant def train_all_words(features, model_selector): training = asl.build_training(features) sequences = training.get_all_sequences() Xlengths = training.get_all_Xlengths() model_dict = {} for word in training.words: model = model_selector(sequences, Xlengths, word, n_constant=3).select() model_dict[word]=model return model_dict models = train_all_words(features_ground, SelectorConstant) print("Number of word models returned = {}".format(len(models))) # + id="d7qTz4lkqQcm" test_set = asl.build_test(features_ground) # + id="Yp3J1kPTqbfD" from my_recognizer import recognize from asl_utils import show_errors # + colab={"base_uri": "https://localhost:8080/"} id="4N2n355jqhTg" outputId="981b180d-f959-4bfb-b0da-54c5f5de2b02" models = train_all_words(features_ground, SelectorBIC) test_set = asl.build_test(features_ground) probability, gausses = recognize(models, test_set) show_errors(gausses, test_set) # + id="a3jFjxe2rqwm"
hmm_asl.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + ## 変数や関数の定義 from pathlib import Path import json from watson_developer_cloud import PersonalityInsightsV3 from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN from collections import OrderedDict import pprint import itertools import get_my_tweets_over200 as tw # 本の文章データ名 books = ["bocchan.txt", "chumonno_oi_ryoriten.txt", "hashire_merosu.txt", "kaijin_nijumenso.txt", "ningen_shikkaku.txt"] # 抽出した本のストーリーを保存するフォルダ stored_path = Path("./extracted_bookdata") # 全ての本の分析結果を保存するJSONファイルの名前 analyzed_all_book_json_name = "analyzed_all_book.json" def get_personality(text): """ Personality Insightsを用いた性格分析の結果を取得する 参考サイト:http://tmngtm.hatenablog.com/entry/2016/10/14/203901 -> return responseで400コードが出てうまくいかず(後で分かったことだが、恐らくContent-Languageをenにしていた...) -> 公式マニュアルを読み解いた ※事前に、pip install --upgrade watson-developer-cloud """ api_version = "" api_username = "" api_password = "" api_url = "https://gateway.watsonplatform.net/personality-insights/api" personality_insights = PersonalityInsightsV3( version = api_version, username = api_username, password = api_password, url = api_url ) profile = personality_insights.profile( content = text, content_type = "text/plain", accept = "application/json", content_language = "ja", accept_language = "en", raw_scores = True, ) return profile def get_personality_old(text): """ 上記参考サイトのコード+少々改変版。 Content-Languageをjaにしていればできてたっぽい。 """ # endpoint url api_url = "https://gateway.watsonplatform.net/personality-insights/api/v2/profile" # username and password for this api api_username = "" api_password = "" # set query query = { "include_raw": "false", "header": "false" } # set header headers = { "Content-Type": "text/plain", # 入力テキストの形式。今回はstringのテキストを渡す設定。 "Content-Language": "en", # 入力言語モードの指定。jaとすると日本語の入力を受け付ける。 "Accept": "application/json", # 応答ファイルの形式。今回はjson形式で受け取る。 "Accept-Language": "en", # 処理言語モードの設定。jaとすると日本語として処理する。 "include_raw": "false" } # set body body = text body = body.encode("utf-8") # 参考サイトのコードに追記 # post response = requests.post( api_url, auth = HTTPBasicAuth(api_username, api_password), params = query, headers = headers, data = body ) return response def convert_dict_to_json(orig_dict, indent = 4): """ 辞書からJSON形式に変換する 参考サイト:https://tmg0525.hatenadiary.jp/entry/2018/03/30/204448 """ return json.dumps(orig_dict, indent = indent) def load_json_as_dict(json_name): """ JSON形式の文字列を辞書として読み込む 参考サイト:https://note.nkmk.me/python-json-load-dump/ """ with open("./" + json_name, "r") as json_file: return json.load(json_file, object_pairs_hook = OrderedDict) def sort_personality(a_book_result): """ a_book_resultを性格の値で降順にソートし、リストとしてreturnする returnされたリストをスライスすれば一部を取得できる 本のカテゴリ分けの時に使う """ return sorted(a_book_result.items(), key = lambda x: x[1], reverse = True) # + ## 本(今回は全5冊)の文章データをPersonality Insightsに入力して分析させる ## その結果を、JSONファイルに変換して保存する ## -> このセルを1回実行しておけば、ファイルを読み込むだけで本の分析結果を利用できる # 全ての本(今回は5冊)の分析結果を格納する # { { book1: { personality_name1: percentile1, personality2: percentile2, ... } }, ... , { book5: { personality5: percentile5, ... } } } # 後でJSONファイルとして保存するため、順序付き辞書を使う # 参考サイト:https://note.nkmk.me/python-collections-ordereddict/ all_book_big5 = OrderedDict() for book in books: book_path = Path(stored_path.name + "/" + book) # Path(Path("./extracted_bookdata") / book) でもOK # 入力となる本の文章データ story = book_path.read_text(encoding="utf-8") # personality insightsに、本の文章データを1つずつ順番に分析させる story_personality_dict = get_personality(story) # 本の性格 personality_name = [big5["name"] for big5 in story_personality_dict["personality"]] # 性格の値。小数点第2位で四捨五入した後、decimal.Decimalからfloatに変換している。 # 参考サイト(四捨五入):https://note.nkmk.me/python-round-decimal-quantize/ personality_percentile = [float(Decimal(str(big5["percentile"])).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)) \ for big5 in story_personality_dict["personality"]] # 1冊の本の分析結果 a_book_big5 = OrderedDict(zip(personality_name, personality_percentile)) # 全体の分析結果の辞書に追加 all_book_big5[book] = a_book_big5 print("finished analyzing {} .".format(book)) # JSONとして出力したくなったらコメントアウト解除 # print(convert_dict_to_json(story_personality_dict, 4)) print("finished analyzing all({}) books.".format(len(books))) # 全ての本の分析結果をJSONファイルとして保存する # このノートブックをシャットダウンしたら、jsonファイルの内容を閲覧できるようになる(それまでは何故か内容が更新されていない) fw = open(analyzed_all_book_json_name, "w") json.dump(all_book_big5, fw, indent = 4) print("registered result of analysis with file: {}".format(analyzed_all_book_json_name)) # + ## 分析結果を基に、本のカテゴリ分けを行う。 # カテゴリの通し番号 serial_numbers = [i + 1 for i in range(10)] # Agreeableness: 協調性, Conscientiousness: 真面目さ, Emotional range: 精神的安定性, Extraversion: 外向性, Openness: 開放性 # 参考サイト:https://note.nkmk.me/python-math-factorial-permutations-combinations/ big5_list = ["Agreeableness", "Conscientiousness", "Emotional range", "Extraversion", "Openness"] # big5から2つの性格を選ぶ組み合わせを列挙する # JSONファイルの内容に合わせて要素をsetに変換する(順番を考慮すると) category_patterns = [set(pat) for pat in itertools.combinations(big5_list, 2)] # 本ごとのカテゴリ分けを記録する辞書 all_book_category_table = OrderedDict() for book in books: # 本の分析結果のJSONファイルをそれぞれ読み込み、値の大きい順にソートする loaded_all_book_big5 = load_json_as_dict(analyzed_all_book_json_name)[book] sorted_result = sort_personality(loaded_all_book_big5) # big5のうち大きい順から2番目までの値の性格名のみを取得し、その本のカテゴリとする(例:{Openness, Extraversion}) # この時、複数の性格の順番を考慮させないために、setで用意する # 2つを組み合わせているため、1つだけの場合よりも幅広くカテゴリ分けできそう book_category = {big5_elm[0] for big5_elm in sorted_result[0:2]} all_book_category_table[book] = book_category pprint.pprint(category_patterns) pprint.pprint(all_book_category_table) print(all_book_category_table["bocchan.txt"] in category_patterns) # + ## 自分のツイートをAPIに入力して結果を見る ## 一番上のセルでget_my_tweets_over200をimport済み # ツイートの取得 tw.userTweets = [] # import元にある、取得したツイートの格納リストの中身をリセットする(これで繰り返し実行してもOK) tw.use_function() print(tw.userTweets) print() print(len(tw.userTweets)) print() userTweets_joined = " ".join(tw.userTweets) print(userTweets_joined) # 自分のツイートをPersonality Insightsに入れて結果を見る result = get_personality(userTweets_joined) print(convert_dict_to_json(result, 4)) # -
main.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] nbsphinx="hidden" # # Random Signals and LTI-Systems # # *This jupyter notebook is part of a [collection of notebooks](../index.ipynb) on various topics of Digital Signal Processing. Please direct questions and suggestions to [<EMAIL>](mailto:<EMAIL>).* # - # ## Introduction # # The response of a system $y[k] = \mathcal{H} \{ x[k] \}$ to a random input signal $x[k]$ is the foundation of statistical signal processing. In the following we limit ourselves to [linear-time invariant (LTI) systems](https://en.wikipedia.org/wiki/LTI_system_theory). # # ![LTI system](LTI_system_td.png) # # In the following it is assumed that the statistical properties of the input signal $x[k]$ are known. For instance, its first- and second-order ensemble averages. It is further assumed that the impulse response $h[k]$ or the transfer function $H(e^{\,\mathrm{j}\,\Omega})$ of the LTI system is given. We are looking for the statistical properties of the output signal $y[k]$ and the joint properties between the input $x[k]$ and output $y[k]$ signal. # ## Stationarity and Ergodicity # # The question arises if the output signal $y[k]$ of an LTI system is (wide-sense) stationary or (wide-sense) ergodic for an input signal $x[k]$ exhibiting the same properties. # # Let's assume that the input signal $x[k]$ is drawn from a stationary random process. According to the [definition of stationarity](../random_signals/stationary_ergodic.ipynb#Definition) the following relation must hold # # \begin{equation} # E\{ f(x[k_1], x[k_2], \dots) \} = E\{ f(x[k_1 + \Delta], x[k_2 + \Delta], \dots) \} # \end{equation} # # where $\Delta \in \mathbb{Z}$ denotes an arbitrary (temporal) shift and $f(\cdot)$ an arbitary mapping function. The condition for time-invariance of a system reads # # \begin{equation} # y[k + \Delta] = \mathcal{H} \{ x[k + \Delta] \} # \end{equation} # # for $y[k] = \mathcal{H} \{ x[k] \}$. Applying the system operator $\mathcal{H}\{\cdot\}$ to the left- and right-hand side of the definition of stationarity for the input signal $x[k]$ and recalling the linearity of the expectation operator $E\{\cdot\}$ yields # # \begin{equation} # E\{ g(y[k_1], y[k_2], \dots) \} = E\{ g(y[k_1 + \Delta], y[k_2 + \Delta], \dots) \} # \end{equation} # # where $g(\cdot)$ denotes an arbitrary mapping function that may differ from $f(\cdot)$. From the equation above, it can be concluded that the output signal of an LTI system for a stationary input signal is also stationary. The same reasoning can also be applied to an [ergodic](../random_signals/stationary_ergodic.ipynb#Ergodic-Random-Processes) input signal. Since both wide-sense stationarity (WSS) and wide-sense ergodicity are special cases of the general case, the derived results hold also here. # # Summarizing, for an input signal $x[k]$ that is # # * (wide-sense) stationary, the output signal $y[k]$ is (wide-sense) stationary and the in- and output is jointly (wide-sense) stationary # * (wide-sense) ergodic, the output signal $y[k]$ is (wide-sense) ergodic and the in- and output is jointly (wide-sense) ergodic # # This implies for instance, that for a WSS input signal $x[k]$ measures like the auto-correlation function (ACF) can also be applied to the output signal $y[k] = \mathcal{H} \{ x[k] \}$ of an LTI system. # ### Example - Response of an LTI system to a random signal # # The following example computes and plots estimates of the linear mean $\mu[k]$ and auto-correlation function (ACF) $\varphi[k_1, k_2]$ for the in- and output of an LTI system. The input $x[k]$ is drawn from a normally distributed white noise process. # + # %matplotlib inline import numpy as np import matplotlib.pyplot as plt L = 64 # number of random samples N = 1000 # number of sample functions # generate input signal (white Gaussian noise) np.random.seed(1) x = np.random.normal(size=(N, L)) # generate output signal h = 2*np.fft.irfft([1,1,1,0,0,0]) y = np.asarray([np.convolve(x[n,:], h, mode='same') for n in range(N)]) # compute and plot results def compute_plot_results(x): # estimate linear mean by ensemble average mu = 1/N * np.sum(x, 0) # estimate the auto-correlation function acf = np.zeros((L, L)) for n in range(L): for m in range(L): acf[n, m] = 1/N * np.sum(x[:, n]*x[:, m], 0) plt.subplot(121) plt.stem(mu) plt.title(r'Estimate of linear mean $\hat{\mu}[k]$') plt.xlabel(r'$k$') plt.ylabel(r'$\hat{\mu}[k]$') plt.axis([0, L, -1.5, 1.5]) plt.subplot(122) plt.pcolor(np.arange(L), np.arange(L), acf, vmin=-2, vmax=2) plt.title(r'Estimate of ACF $\hat{\varphi}[k_1, k_2]$') plt.xlabel(r'$k_1$') plt.ylabel(r'$k_2$') plt.colorbar() plt.autoscale(tight=True) plt.figure(figsize = (10, 5)) plt.gcf().suptitle(r'Input signal $x[k]$', fontsize=12) compute_plot_results(x) plt.figure(figsize = (10, 5)) plt.gcf().suptitle(r'Output signal $y[k]$', fontsize=12) compute_plot_results(y) # - # **Exercise** # # * Are the in- and output signals WSS? # * Can the output signal $y[k]$ be assumed to be white noise? # # Solution: From the shown results it can assumed for the input signal $x[k]$ that the linear mean $\mu_x[k]$ does not depend on the time-index $k$ and that the ACF $\varphi_{xx}[k_1, k_2]$ does only depend on the difference $\kappa = k_1 - k_2$ of both time indexes. The same holds also for the output signal $y[k]$. Hence both the in- and output signal are WSS. Although the input signal $x[k]$ can be assumed to be white noise, the output signal $y[k]$ is not white noise due to its ACF $\varphi_{yy}[k_1, k_2]$. # + [markdown] nbsphinx="hidden" # **Copyright** # # This notebook is provided as [Open Educational Resource](https://en.wikipedia.org/wiki/Open_educational_resources). Feel free to use the notebook for your own purposes. The text is licensed under [Creative Commons Attribution 4.0](https://creativecommons.org/licenses/by/4.0/), the code of the IPython examples under the [MIT license](https://opensource.org/licenses/MIT). Please attribute the work as follows: *<NAME>, Digital Signal Processing - Lecture notes featuring computational examples, 2016-2018*.
random_signals_LTI_systems/introduction.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + executionInfo={"elapsed": 2, "status": "ok", "timestamp": 1639318119384, "user": {"displayName": "Hoon", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj2Mel83Br0O3NTW8TZdtajsACI8PkzYrnpSPdQOA=s64", "userId": "08637906559510914783"}, "user_tz": -540} id="wuVc9NSY_anY" from google.colab import drive import pandas as pd import seaborn as sns; sns.set() import matplotlib.pyplot as plt import numpy as np # + executionInfo={"elapsed": 441, "status": "ok", "timestamp": 1639318134695, "user": {"displayName": "Hoon", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj2Mel83Br0O3NTW8TZdtajsACI8PkzYrnpSPdQOA=s64", "userId": "08637906559510914783"}, "user_tz": -540} id="DFAPWfWm4GYn" # (1) Extraversion, (2) Agreeableness, (3) Conscientiousness, (4) Emotional Stability, or (5) Openness pos_questions = [ # positive questions adding to the trait. 'EXT1','EXT3','EXT5','EXT7','EXT9', 'EST1','EST3','EST5','EST6','EST7','EST8','EST9','EST10', 'AGR2','AGR4','AGR6','AGR8','AGR9','AGR10', 'CSN1','CSN3','CSN5','CSN7','CSN9','CSN10', 'OPN1','OPN3','OPN5','OPN7','OPN8','OPN9','OPN10', ] neg_questions = [ # negative (negating) questions subtracting from the trait. 'EXT2','EXT4','EXT6','EXT8','EXT10', 'EST2','EST4', 'AGR1','AGR3','AGR5','AGR7', 'CSN2','CSN4','CSN6','CSN8', 'OPN2','OPN4','OPN6', ] # + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 3250, "status": "ok", "timestamp": 1639318227430, "user": {"displayName": "Hoon", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj2Mel83Br0O3NTW8TZdtajsACI8PkzYrnpSPdQOA=s64", "userId": "08637906559510914783"}, "user_tz": -540} id="NZJOzKQ2EzAI" outputId="2e7023c6-c1be-41c1-de47-9bc75f8132a1" #user가 설문조사 한 순서 input_order = [ 'EXT1', 'AGR1', 'CSN1', 'EST1', 'OPN1', 'EXT2', 'AGR2', 'CSN2', 'EST2', 'OPN2', 'EXT3', 'AGR3', 'CSN3', 'EST3', 'OPN3', 'EXT4', 'AGR4', 'CSN4', 'EST4', 'OPN4', 'EXT5', 'AGR5', 'CSN5', 'EST5', 'OPN5', 'EXT6', 'AGR6', 'CSN6', 'EST6', 'OPN6', 'EXT7', 'AGR7', 'CSN7', 'EST7', 'OPN7', 'EXT8', 'AGR8', 'CSN8', 'EST8', 'OPN8', 'EXT9', 'AGR9', 'CSN9', 'EST9', 'OPN9', 'EXT10', 'AGR10', 'CSN10', 'EST10', 'OPN10' ] #1~50번 문항 입력 ex)12345543211234553333323455432222225543211211114321 inp = input() input_score = [] for i in range(50): input_score.append(int(inp[i])) # + colab={"base_uri": "https://localhost:8080/", "height": 101} executionInfo={"elapsed": 624, "status": "ok", "timestamp": 1639318230469, "user": {"displayName": "Hoon", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj2Mel83Br0O3NTW8TZdtajsACI8PkzYrnpSPdQOA=s64", "userId": "08637906559510914783"}, "user_tz": -540} id="S_xEgWbCGcCQ" outputId="63159591-8d3b-4ea9-be03-a6d7ef12765a" user = pd.DataFrame([input_score],columns=input_order) user # + executionInfo={"elapsed": 2, "status": "ok", "timestamp": 1639318230990, "user": {"displayName": "Hoon", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj2Mel83Br0O3NTW8TZdtajsACI8PkzYrnpSPdQOA=s64", "userId": "08637906559510914783"}, "user_tz": -540} id="EWnOTkYYf7oa" def scaleMax5(df): #negative 점수 반전 for neg in neg_questions: df[neg] = 6-df[neg] df['EXT_SUM'] = 0 df['EST_SUM'] = 0 df['AGR_SUM'] = 0 df['CSN_SUM'] = 0 df['OPN_SUM'] = 0 for i in range(1,11): df['EXT_SUM'] += df[f'EXT{i}'] df['EST_SUM'] += df[f'EST{i}'] df['AGR_SUM'] += df[f'AGR{i}'] df['CSN_SUM'] += df[f'CSN{i}'] df['OPN_SUM'] += df[f'OPN{i}'] new_df = df.iloc[:,-5:] print("최대점수 5점으로 스케일링") new_df = new_df/10 return new_df # + colab={"base_uri": "https://localhost:8080/", "height": 99} executionInfo={"elapsed": 4, "status": "ok", "timestamp": 1639318232195, "user": {"displayName": "Hoon", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj2Mel83Br0O3NTW8TZdtajsACI8PkzYrnpSPdQOA=s64", "userId": "08637906559510914783"}, "user_tz": -540} id="-4IJitwuIiX9" outputId="20317097-c041-4b59-a87b-6a230118<PASSWORD>" user = scaleMax5(user) user #여기까지. 밑에는 볼 필요 없음
prac/user.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Copyright (c) Microsoft Corporation. All rights reserved. # # Licensed under the MIT License. # # Explain binary classification model predictions with raw feature transformations # _**This notebook showcases how to use the interpret-community repo to help interpret and visualize predictions of a binary classification model.**_ # # # ## Table of Contents # # 1. [Introduction](#Introduction) # 1. [Project](#Project) # 1. [Setup](#Setup) # 1. [Run model explainer locally at training time](#Explain) # 1. Apply feature transformations # 1. Train a binary classification model # 1. Explain the model on raw features # 1. Generate global explanations # 1. Generate local explanations # 1. [Visualize results](#Visualize) # 1. [Next steps](#Next%20steps) # <a id='Introduction'></a> # ## 1. Introduction # # This notebook illustrates how to use interpret-community to help interpret a binary classification model using an IBM dataset with employee attrition data. It uses one-to-one and one-to-many feature transformations from the raw data to engineered features. The one-to-many feature transformations include one hot encoding for categorical features. The one-to-one feature transformations apply standard scaling on numeric features. The interpret-community tabular data explainer in this repo is then used to obtain raw feature importances. # # Three tabular data explainers are demonstrated: # - TabularExplainer (SHAP) # - MimicExplainer (global surrogate) # - PFIExplainer # # | ![Interpretability Toolkit Architecture](./img/interpretability-architecture.png) | # |:--:| # | *Interpretability Toolkit Architecture* | # # <a id='Project'></a> # ## 2. Project # # The goal of this project is to classify employee attrition with scikit-learn and run the model explainer locally: # # 1. Transform raw features to engineered features # 2. Train a SVC classification model using scikit-learn # 3. Run global and local explanation with the full dataset in local mode. # 4. Visualize the global and local explanations with the visualization dashboard. # # <a id='Setup'></a> # ## 3. Setup # # If you are using Jupyter notebooks, the extensions should be installed automatically with the package. # If you are using Jupyter Labs run the following command: # ``` # (myenv) $ jupyter labextension install @jupyter-widgets/jupyterlab-manager # ``` # # <a id='Explain'></a> # ## 4. Run model explainer locally at training time # + from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn.svm import SVC import pandas as pd import numpy as np # Explainers: # 1. SHAP Tabular Explainer from interpret.ext.blackbox import TabularExplainer # OR # 2. Mimic Explainer from interpret.ext.blackbox import MimicExplainer # You can use one of the following four interpretable models as a global surrogate to the black box model from interpret.ext.glassbox import LGBMExplainableModel from interpret.ext.glassbox import LinearExplainableModel from interpret.ext.glassbox import SGDExplainableModel from interpret.ext.glassbox import DecisionTreeExplainableModel # OR # 3. PFI Explainer from interpret.ext.blackbox import PFIExplainer # - # ### Load the IBM employee attrition data # + # get the IBM employee attrition dataset outdirname = 'dataset.6.21.19' try: from urllib import urlretrieve except ImportError: from urllib.request import urlretrieve import zipfile zipfilename = outdirname + '.zip' urlretrieve('https://publictestdatasets.blob.core.windows.net/data/' + zipfilename, zipfilename) with zipfile.ZipFile(zipfilename, 'r') as unzip: unzip.extractall('.') attritionData = pd.read_csv('./WA_Fn-UseC_-HR-Employee-Attrition.csv') # Dropping Employee count as all values are 1 and hence attrition is independent of this feature attritionData = attritionData.drop(['EmployeeCount'], axis=1) # Dropping Employee Number since it is merely an identifier attritionData = attritionData.drop(['EmployeeNumber'], axis=1) attritionData = attritionData.drop(['Over18'], axis=1) # Since all values are 80 attritionData = attritionData.drop(['StandardHours'], axis=1) # Converting target variables from string to numerical values target_map = {'Yes': 1, 'No': 0} attritionData["Attrition_numerical"] = attritionData["Attrition"].apply(lambda x: target_map[x]) target = attritionData["Attrition_numerical"] attritionXData = attritionData.drop(['Attrition_numerical', 'Attrition'], axis=1) # - # Split data into train and test from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(attritionXData, target, test_size = 0.2, random_state=0, stratify=target) # + # Creating dummy columns for each categorical feature categorical = [] for col, value in attritionXData.iteritems(): if value.dtype == 'object': categorical.append(col) # Store the numerical columns in a list numerical numerical = attritionXData.columns.difference(categorical) # - # ### Transform raw features # We can explain raw features by either using `sklearn.compose.ColumnTransformer` or a list of fitted transformer tuples. The cell below uses `sklearn.compose.ColumnTransformer`. # # If you wish to run an example with the list of fitted transformer tuples, comment the cell below and uncomment the cell that follows after. # + from sklearn.compose import ColumnTransformer # We create the preprocessing pipelines for both numeric and categorical data. numeric_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())]) categorical_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='constant', fill_value='missing')), ('onehot', OneHotEncoder(handle_unknown='ignore'))]) transformations = ColumnTransformer( transformers=[ ('num', numeric_transformer, numerical), ('cat', categorical_transformer, categorical)]) # Append classifier to preprocessing pipeline. # Now we have a full prediction pipeline. clf = Pipeline(steps=[('preprocessor', transformations), ('classifier', SVC(C = 1.0, probability=True, gamma='auto'))]) # - ''' ## Fitted Transformer tuples # Uncomment below if sklearn-pandas is not installed #!pip install sklearn-pandas from sklearn_pandas import DataFrameMapper # Impute, standardize the numeric features and one-hot encode the categorical features. numeric_transformations = [([f], Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])) for f in numerical] categorical_transformations = [([f], OneHotEncoder(handle_unknown='ignore', sparse=False)) for f in categorical] transformations = numeric_transformations + categorical_transformations # Append classifier to preprocessing pipeline. # Now we have a full prediction pipeline. clf = Pipeline(steps=[('preprocessor', transformations), ('classifier', SVC(C = 1.0, probability=True, gamma='auto'))]) ''' # ### Train a SVM classification model, which you want to explain model = clf.fit(x_train, y_train) # ### Explain predictions on your local machine # + # 1. Using SHAP TabularExplainer # clf.steps[-1][1] returns the trained classification model explainer = TabularExplainer(clf.steps[-1][1], initialization_examples=x_train, features=attritionXData.columns, classes=["Not leaving", "leaving"], transformations=transformations) # 2. Using MimicExplainer # augment_data is optional and if true, oversamples the initialization examples to improve surrogate model accuracy to fit original model. Useful for high-dimensional data where the number of rows is less than the number of columns. # max_num_of_augmentations is optional and defines max number of times we can increase the input data size. # LGBMExplainableModel can be replaced with LinearExplainableModel, SGDExplainableModel, or DecisionTreeExplainableModel # explainer = MimicExplainer(clf.steps[-1][1], # x_train, # LGBMExplainableModel, # augment_data=True, # max_num_of_augmentations=10, # features=attritionXData.columns, # classes=["Not leaving", "leaving"], # transformations=transformations) # 3. Using PFIExplainer # Use the parameter "metric" to pass a metric name or function to evaluate the permutation. # Note that if a metric function is provided a higher value must be better. # Otherwise, take the negative of the function or set the parameter "is_error_metric" to True. # Default metrics: # F1 Score for binary classification, F1 Score with micro average for multiclass classification and # Mean absolute error for regression # explainer = PFIExplainer(clf.steps[-1][1], # features=x_train.columns, # transformations=transformations, # classes=["Not leaving", "leaving"]) # - # ### Generate global explanations # Explain overall model predictions (global explanation with local component) # + # Passing in test dataset for evaluation examples - note it must be a representative sample of the original data # x_train can be passed as well, but with more examples explanations will take longer although they may be more accurate global_explanation = explainer.explain_global(x_test) # Note: if you used the PFIExplainer in the previous step, use the next line of code instead # global_explanation = explainer.explain_global(x_test, true_labels=y_test) # + # Sorted SHAP values print('ranked global importance values: {}'.format(global_explanation.get_ranked_global_values())) # Corresponding feature names print('ranked global importance names: {}'.format(global_explanation.get_ranked_global_names())) # Feature ranks (based on original order of features) print('global importance rank: {}'.format(global_explanation.global_importance_rank)) # Note: Do not run this cell if using PFIExplainer, it does not support per class explanations # Per class feature names print('ranked per class feature names: {}'.format(global_explanation.get_ranked_per_class_names())) # Per class feature importance values print('ranked per class feature values: {}'.format(global_explanation.get_ranked_per_class_values())) # - # Print out a dictionary that holds the sorted feature importance names and values print('global importance rank: {}'.format(global_explanation.get_feature_importance_dict())) # ### Explain overall model predictions as a collection of local (instance-level) explanations # feature shap values for all features and all data points in the training data print('local importance values: {}'.format(global_explanation.local_importance_values)) # ### Generate local explanations # Explain local data points (individual instances) # + # Note: Do not run this cell if using PFIExplainer, it does not support local explanations # You can pass a specific data point or a group of data points to the explain_local function # E.g., Explain the first data point in the test set instance_num = 1 local_explanation = explainer.explain_local(x_test[:instance_num]) # + # Get the prediction for the first member of the test set and explain why model made that prediction prediction_value = clf.predict(x_test)[instance_num] sorted_local_importance_values = local_explanation.get_ranked_local_values()[prediction_value] sorted_local_importance_names = local_explanation.get_ranked_local_names()[prediction_value] print('local importance values: {}'.format(sorted_local_importance_values)) print('local importance names: {}'.format(sorted_local_importance_names)) # - # <a id='Visualize'></a> # ## 5. Visualize # Load the visualization dashboard. from interpret_community.widget import ExplanationDashboard ExplanationDashboard(global_explanation, model, datasetX=x_test, true_y=y_test) # <a id='Next'></a> # ## Next steps # Learn about other use cases of the interpret-community package: # # 1. [Training time: regression problem](./explain-regression-local.ipynb) # 1. [Training time: binary classification problem](./explain-binary-classification-local.ipynb) # 1. [Training time: multiclass classification problem](./explain-multiclass-classification-local.ipynb) # 1. Explain models with engineered features: # 1. [Advanced feature transformations](./advanced-feature-transformations-explain-local.ipynb)
notebooks/simple-feature-transformations-explain-local.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # [Strings](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str) my_string = 'Python is my favorite programming language!' my_string type(my_string) len(my_string) # ### Respecting [PEP8](https://www.python.org/dev/peps/pep-0008/#maximum-line-length) with long strings long_story = ('Lorem ipsum dolor sit amet, consectetur adipiscing elit.' 'Pellentesque eget tincidunt felis. Ut ac vestibulum est.' 'In sed ipsum sit amet sapien scelerisque bibendum. Sed ' 'sagittis purus eu diam fermentum pellentesque.') long_story # ## `str.replace()` # If you don't know how it works, you can always check the `help`: help(str.replace) my_string.replace('a', '?') print(my_string) my_modified_string = my_string.replace('is', 'will be') print(my_modified_string) # ## `str.format()` secret = '{} is cool'.format('Python') print(secret) print('My name is {} {}, you can call me {}.'.format('John', 'Doe', 'John')) # is the same as: print('My name is {first} {family}, you can call me {first}.'.format(first='John', family='Doe')) # ## `str.join()` pandas = 'pandas' numpy = 'numpy' requests = 'requests' cool_python_libs = ', '.join([pandas, numpy, requests]) print('Some cool python libraries: {}'.format(cool_python_libs)) # Alternatives (not as [Pythonic](http://docs.python-guide.org/en/latest/writing/style/#idioms) and [slower](https://waymoot.org/home/python_string/)): # + cool_python_libs = pandas + ', ' + numpy + ', ' + requests print('Some cool python libraries: {}'.format(cool_python_libs)) cool_python_libs = pandas cool_python_libs += ', ' + numpy cool_python_libs += ', ' + requests print('Some cool python libraries: {}'.format(cool_python_libs)) # - # ## `str.upper(), str.lower(), str.title()` mixed_case = 'PyTHoN hackER' mixed_case.upper() mixed_case.lower() mixed_case.title() # ## `str.strip()` # + ugly_formatted = ' \n \t Some story to tell ' stripped = ugly_formatted.strip() print('ugly: {}'.format(ugly_formatted)) print('stripped: {}'.format(ugly_formatted.strip())) # - # ## `str.split()` sentence = 'three different words' words = sentence.split() print(words) type(words) secret_binary_data = '01001,101101,11100000' binaries = secret_binary_data.split(',') print(binaries) # ## Calling multiple methods in a row ugly_mixed_case = ' ThIS LooKs BAd ' pretty = ugly_mixed_case.strip().lower().replace('bad', 'good') print(pretty) # Note that execution order is from left to right. Thus, this won't work: pretty = ugly_mixed_case.replace('bad', 'good').strip().lower() print(pretty) # ## [Escape characters](http://python-reference.readthedocs.io/en/latest/docs/str/escapes.html#escape-characters) two_lines = 'First line\nSecond line' print(two_lines) indented = '\tThis will be indented' print(indented)
notebooks/beginner/strings.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # 20 News dataset # # This data set is a collection of 20,000 messages, collected from 20 different netnews newsgroups. One thousand messages from each of the twenty newsgroups were chosen at random and partitioned by newsgroup name. The dataset can be found there: http://www.cs.cmu.edu/afs/cs.cmu.edu/project/theo-20/www/data/news20.html # ## 0. Problem solving approach # # Here's how we will solve this classification problem: # # 1. Convert all text samples in the dataset into sequences of word indices. A "word index" would simply be an integer ID for the word. We will only consider the top 20,000 most commonly occuring words in the dataset, and we will truncate the sequences to a maximum length of 1000 words. # # 2. Prepare an "embedding matrix" which will contain at index i the embedding vector for the word of index i in our word index. # # 3. Load this embedding matrix into a Keras Embedding layer, set to be frozen (its weights, the embedding vectors, will not be updated during training). # # 4. Build on top of it a 1D convolutional neural network, ending in a softmax output over our 20 categories. MAX_NUM_WORDS = 20000 MAX_SEQUENCE_LENGTH = 1000 EMBEDDING_DIM = 100 VALIDATION_SPLIT = 0.2 TEXT_DATA_DIR = "dataset/20_newsgroup" GLOVE_DIR = "dataset/glove" # + # Basic packages. import os import sys import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import classification_report # Keras specific packages. from keras import Input from keras import Model from keras import regularizers from keras import optimizers from keras.layers import Dense, Activation, Flatten from keras.layers import Dropout from keras.layers import Conv1D, MaxPooling1D from keras.layers import Embedding from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical # - # ## 1. Text samples conversion. # + # Set the list of text sampels. texts = [] # Dictionary mapping label name to numeric id. labels_index = {} # List of label ids. labels = [] for name in sorted(os.listdir(TEXT_DATA_DIR)): path = os.path.join(TEXT_DATA_DIR, name) if os.path.isdir(path): label_id = len(labels_index) labels_index[name] = label_id for fname in sorted(os.listdir(path)): if fname.isdigit(): fpath = os.path.join(path, fname) if sys.version_info < (3,): f = open(fpath) else: f = open(fpath, encoding='latin-1') t = f.read() i = t.find('\n\n') # skip header if 0 < i: t = t[i:] texts.append(t) f.close() labels.append(label_id) # Display information. print("Dataset information") print("Found {} texts and {} labels".format(len(texts), len(labels))) # - # Then we can format our text samples and labels into tensors that can be fed into a neural network. To do this, we will rely on Keras utilities. # + tokenizer = Tokenizer(nb_words=MAX_NUM_WORDS) tokenizer.fit_on_texts(texts) sequences = tokenizer.texts_to_sequences(texts) word_index = tokenizer.word_index print('Found %s unique tokens.' % len(word_index)) data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH) labels = to_categorical(np.asarray(labels)) print('Shape of data tensor:', data.shape) print('Shape of label tensor:', labels.shape) # split the data into a training set and a validation set indices = np.arange(data.shape[0]) np.random.shuffle(indices) data = data[indices] labels = labels[indices] nb_validation_samples = int(VALIDATION_SPLIT * data.shape[0]) x_train = data[:-nb_validation_samples] y_train = labels[:-nb_validation_samples] x_val = data[-nb_validation_samples:] y_val = labels[-nb_validation_samples:] # - # ## 2. Preparing the pretrained embedding layer. from keras.layers import Embedding # + embeddings_index = {} f = open(os.path.join(GLOVE_DIR, 'glove.6B.100d.txt')) for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embeddings_index[word] = coefs f.close() print('Found %s word vectors.' % len(embeddings_index)) # - embedding_matrix = np.zeros((len(word_index) + 1, EMBEDDING_DIM)) for word, i in word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: # words not found in embedding index will be all-zeros. embedding_matrix[i] = embedding_vector embedding_layer = Embedding(len(word_index) + 1, EMBEDDING_DIM, weights=[embedding_matrix], input_length=MAX_SEQUENCE_LENGTH, trainable=False) len(word_index) # ## 3. Training the model without pretrained embedding # + # Build the embedding layer. #embedding_layer = Embedding(len(word_index) + 1, EMBEDDING_DIM, # embeddings_regularizer = regularizers.l1(0.001), # input_length=MAX_SEQUENCE_LENGTH, # trainable=True) # Set the input. sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype="int32") # Set the embedding layer. embedded_sequences = embedding_layer(sequence_input) # Conv layer 1. x = Conv1D(128, 5, kernel_regularizer=regularizers.l2(0.001))(embedded_sequences) x = Activation("relu")(x) x = MaxPooling1D(5)(x) X = Dropout(0.5)(x) # Conv Layer 2. x = Conv1D(128, 5, kernel_regularizer=regularizers.l2(0.001))(x) x = Activation("relu")(x) x = MaxPooling1D(5)(x) X = Dropout(0.5)(x) # Conv Layer 3. x = Conv1D(128, 5, kernel_regularizer=regularizers.l2(0.001))(x) x = Activation("relu")(x) x = MaxPooling1D(35)(x) X = Dropout(0.5)(x) # Output layer. x = Flatten()(x) x = Dense(128)(x) x = Activation("relu")(x) X = Dropout(0.5)(x) # Softmax layer. preds = Dense(len(labels_index), activation="softmax")(x) # Build the model. model = Model(sequence_input, preds) # Set the optimizer. optim = optimizers.RMSprop(lr=0.001, rho=0.90) # Compile the model. model.compile(loss="categorical_crossentropy", optimizer=optim, metrics=["acc"]) # Set the fitting parameters. fit_params = { "epochs": 10, "batch_size": 64, "validation_data": (x_val, y_val), "shuffle": True } # Print the model. model.summary() # - # Fit the model. history = model.fit(x_train, y_train, **fit_params) # + import matplotlib.pyplot as plt # Visualise the training resuls. plt.figure(figsize=(15,5)) plt.subplot(121) plt.plot(history.history["loss"], color="b", label="tr") plt.plot(history.history["val_loss"], color="r", label="te") plt.ylabel("loss") plt.xlabel("epochs") plt.grid() plt.legend() plt.subplot(122) plt.plot(history.history["acc"], color="b", label="tr") plt.plot(history.history["val_acc"], color="r", label="te") plt.ylabel("acc") plt.xlabel("epochs") plt.grid() plt.legend() plt.show() # - model.summary() # ## 4. Evaluation. # Obtain the predictions for the evaluation set. y_pred = model.predict(x_val) # Handle the predictions. y_pred = np.eye(y_val.shape[1])[np.argmax(y_pred, axis=1).reshape(-1)] # Display the classification report. print(classification_report(y_val, y_pred, target_names=list(labels_index.keys()), digits=4))
20news.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] _cell_guid="3359ce54-1911-43f0-9252-4d8bc0406f80" _uuid="5193e03d52e88b296a8f81f7eefdc0db4628fed1" # # Data Exploration Starter # ## Data Exploration Titanic: Machine Learning from Disaster # ## <NAME> # + [markdown] _cell_guid="d4e1c462-1dfb-4311-b5ab-f79c29f4af63" _uuid="711638889e2115905651f173e2656611c2f06d34" # First thing I want to mention is that this notebook is intended to provide first glance on data and variables. You won't find here any analysis of features interrelation or feature engineering. I intentionally provide only charts that show feature related information (distribution, bar plots and etc) and feature - label relationship. # # I appreciate any constructive criticism and hope my notebook will help you understand data little bit more. # # Please upvote if you think my notebook deserves it. # # Thanks. # # P.S. I think the best way to use my notebook is to quickly read through it and then come back as soon as you need additional information related to any feature. # + [markdown] _cell_guid="96614b9b-22ec-4207-b2e8-994ebafddf8c" _uuid="13409cbc2715c79ad499376efffb15eba5428e5b" # # + _cell_guid="aeb940e4-edcf-4915-8817-1803033b7ea7" _uuid="e57c24ce2df17ab66cf29db4d8c7d3af27bd5281" ### Necessary libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns ### Seaborn style sns.set_style("whitegrid") # + _cell_guid="e2932fa0-8ed6-4b22-b7bb-222d886ca432" _uuid="4f0b49a5e7b47386cf1a087bea170dc1f6d1855e" ### Let's import our data train_data = pd.read_csv('../input/train.csv',index_col='PassengerId') ### and test if everything OK train_data.head() # + _cell_guid="fc7ffb39-08ba-410f-beea-98263f673cf5" _uuid="2e3f8c2249f225df24dc1a7caed47081115fc65f" ### ... check for NAs in sense Pandas understands them train_data.isnull().sum() # + _cell_guid="b059e514-fbff-4b1c-abbb-fa0352d71d33" _uuid="8dc5128e94561b79b7f477dde24bf653cef4995b" ### Now let's prepare lists of numeric and categorical columns # Numeric Features numeric_features = ['Age', 'Fare'] # Categorical Features ordinal_features = ['Pclass', 'SibSp', 'Parch'] nominal_features = ['Sex', 'Embarked'] # + _cell_guid="4ac25dbc-d588-43e4-8f0f-a13b12fce690" _uuid="5a3e8831b31ec51c87c7a185915bc9d61cdc0114" ### Adding new column with beautiful target names train_data['target_name'] = train_data['Survived'].map({0: 'Not Survived', 1: 'Survived'}) # + [markdown] _cell_guid="ea3bd9ef-572f-46e9-ab06-a40e76a11b87" _uuid="35515cadb22070278a7565b40e5a888fb3bdc021" # ### Target Exploration # + _cell_guid="8e094cd6-d3bd-4862-b6dd-64a66d67d447" _uuid="726fbcef5910c6d4309f71343b397fee85f604fa" ### Target variable exploration sns.countplot(train_data.target_name); plt.xlabel('Survived?'); plt.ylabel('Number of occurrences'); plt.show() # + [markdown] _cell_guid="4f8a7c3e-f126-4e18-9885-0f68fe9b2c7e" _uuid="b0517fbc14c48765911471ca4b36fcde7bf22fd2" # ### Corralation between features (variables) # + _cell_guid="a1901889-0b66-4228-ab9c-69e4e1bc9e86" _uuid="d9b3aa4b5ec125a5b700aa3cee8edeb6d2a5a2b7" ### Corralation matrix heatmap # Getting correlation matrix cor_matrix = train_data[numeric_features + ordinal_features].corr().round(2) # Plotting heatmap fig = plt.figure(figsize=(12,12)); sns.heatmap(cor_matrix, annot=True, center=0, cmap = sns.diverging_palette(250, 10, as_cmap=True), ax=plt.subplot(111)); plt.show() # + [markdown] _cell_guid="6f18befc-5279-413d-8edf-51d96317c50e" _uuid="87ab603d3c5cce776b6425c1ed55c2109ad20c1c" # ### Numeric Features Exploration # + _cell_guid="f820b652-e498-4360-bcb5-cf2617305602" _uuid="7740cbd607628d29e9c35749a42c88c0dffbec40" ### Plotting Numeric Features # Looping through and Plotting Numeric features for column in numeric_features: # Figure initiation fig = plt.figure(figsize=(18,12)) ### Distribution plot sns.distplot(train_data[column].dropna(), ax=plt.subplot(221)); # X-axis Label plt.xlabel(column, fontsize=14); # Y-axis Label plt.ylabel('Density', fontsize=14); # Adding Super Title (One for a whole figure) plt.suptitle('Plots for '+column, fontsize=18); ### Distribution per Survived / Not Survived Value # Not Survived hist sns.distplot(train_data.loc[train_data.Survived==0, column].dropna(), color='red', label='Not Survived', ax=plt.subplot(222)); # Survived hist sns.distplot(train_data.loc[train_data.Survived==1, column].dropna(), color='blue', label='Survived', ax=plt.subplot(222)); # Adding Legend plt.legend(loc='best') # X-axis Label plt.xlabel(column, fontsize=14); # Y-axis Label plt.ylabel('Density per Survived / Not Survived Value', fontsize=14); ### Average Column value per Survived / Not Survived Value sns.barplot(x="target_name", y=column, data=train_data, ax=plt.subplot(223)); # X-axis Label plt.xlabel('Survived or Not Survived?', fontsize=14); # Y-axis Label plt.ylabel('Average ' + column, fontsize=14); ### Boxplot of Column per Survived / Not Survived Value sns.boxplot(x="target_name", y=column, data=train_data, ax=plt.subplot(224)); # X-axis Label plt.xlabel('Survived or Not Survived?', fontsize=14); # Y-axis Label plt.ylabel(column, fontsize=14); # Printing Chart plt.show() # + [markdown] _cell_guid="59e9437d-550c-4ee5-8f7c-58740fd54247" _uuid="ca4ea2d8436ccdc681045232b0abe366277831de" # ### Categorical (Ordinal) Features Exploration # + _cell_guid="8cb3ce7e-faaf-4437-a493-f9faa285605e" _uuid="92ed7a5286f650c424f979530c56d6a91dc6a68a" ### Plotting Categorical Features # Looping through and Plotting Categorical features for column in ordinal_features: # Figure initiation fig = plt.figure(figsize=(18,18)) ### Average Column value per Survived / Not Survived Value sns.barplot(x="target_name", y=column, data=train_data, ax=plt.subplot(321)); # X-axis Label plt.xlabel('Survived or Not Survived?', fontsize=14); # Y-axis Label plt.ylabel('Average ' + column, fontsize=14); # Adding Super Title (One for a whole figure) plt.suptitle('Plots for '+column, fontsize=18); ### Boxplot of Column per Survived / Not Survived Value sns.boxplot(x="target_name", y=column, data=train_data, ax=plt.subplot(322)); # X-axis Label plt.xlabel('Survived or Not Survived?', fontsize=14); # Y-axis Label plt.ylabel(column, fontsize=14); ### Number of occurrences per categoty - target pair ax = sns.countplot(x=column, hue="target_name", data=train_data, ax = plt.subplot(312)); # X-axis Label plt.xlabel(column, fontsize=14); # Y-axis Label plt.ylabel('Number of occurrences', fontsize=14); # Setting Legend location plt.legend(loc=1); ### Adding percents over bars # Getting heights of our bars height = [p.get_height() if p.get_height()==p.get_height() else 0 for p in ax.patches] # Counting number of bar groups ncol = int(len(height)/2) # Counting total height of groups total = [height[i] + height[i + ncol] for i in range(ncol)] * 2 # Looping through bars for i, p in enumerate(ax.patches): # Adding percentages ax.text(p.get_x()+p.get_width()/2, height[i]*1.01 + 10, '{:1.0%}'.format(height[i]/total[i]), ha="center", size=14) ### Survived percentage for every value of feature sns.pointplot(x=column, y='Survived', data=train_data, ax = plt.subplot(313)); # X-axis Label plt.xlabel(column, fontsize=14); # Y-axis Label plt.ylabel('Survived Percentage', fontsize=14); # Printing Chart plt.show() # + [markdown] _cell_guid="9500a7d0-3fd0-4a4d-bcda-9c22561578ed" _uuid="680729d4c6ac3033e654a90dc2cbd3a1fa9967a9" # ### Categorical (Nominal) Features Exploration # + _cell_guid="69743b7f-8796-411d-9649-b50c402edadc" _uuid="ccf6532d77dbb2901d2856ed57be3255ddf492c3" ### Plotting Categorical Features # Looping through and Plotting Categorical features for column in nominal_features: # Figure initiation fig = plt.figure(figsize=(18,12)) ### Number of occurrences per categoty - target pair ax = sns.countplot(x=column, hue="target_name", data=train_data, ax = plt.subplot(211)); # X-axis Label plt.xlabel(column, fontsize=14); # Y-axis Label plt.ylabel('Number of occurrences', fontsize=14); # Adding Super Title (One for a whole figure) plt.suptitle('Plots for '+column, fontsize=18); # Setting Legend location plt.legend(loc=1); ### Adding percents over bars # Getting heights of our bars height = [p.get_height() for p in ax.patches] # Counting number of bar groups ncol = int(len(height)/2) # Counting total height of groups total = [height[i] + height[i + ncol] for i in range(ncol)] * 2 # Looping through bars for i, p in enumerate(ax.patches): # Adding percentages ax.text(p.get_x()+p.get_width()/2, height[i]*1.01 + 10, '{:1.0%}'.format(height[i]/total[i]), ha="center", size=14) ### Survived percentage for every value of feature sns.pointplot(x=column, y='Survived', data=train_data, ax = plt.subplot(212)); # X-axis Label plt.xlabel(column, fontsize=14); # Y-axis Label plt.ylabel('Survived Percentage', fontsize=14); # Printing Chart plt.show() # + [markdown] _cell_guid="a7125ff0-0393-447a-b10c-48db4475557b" _uuid="a0226db7a9e67812e6704cb972da6ecdd0c27712" # ### Please upvote if my notebook helped you in any way :)
titanic/titanic-data-exploration-starter.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .r # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: R # language: R # name: ir # --- # # Importação do banco de dados #libPaths() #install.packages("readxl") library(readxl) bd<- read_excel("Planilha de dados_projetos LaNEx_planilha limpa2_080521 (1).xlsx",sheet = 1) head(bd) dim(bd) # # Análise exploratória summary(bd) bd<- bd[,-1] data<- na.omit(bd) dim(data) #140 idosos após remoção dos Nas table(data$Diagnosis) #(93, 21 e 26) str(data) data$Diagnosis<- as.factor(data$Diagnosis) data$Sex<- as.factor(data$Sex) data$Scholarity<- as.factor(data$Scholarity) data$IADL<- as.factor(data$IADL) # # Divisão em amostra de treino e de teste #install.packages("caret") require(caret) set.seed(555) train<- createDataPartition(data$Diagnosis,p=0.7,list=F) data_train<- data[train,] data_test<- data[-train,] table(data_train$Diagnosis) #(66,15,19) table(data_test$Diagnosis) #(27,6,7) # # RFE-RF e RF #install.packages("e1071") require(e1071) #install.packages("randomForest") require(randomForest) set.seed(2) control <- rfeControl(functions=rfFuncs, method="cv", number=5) set.seed(3) results <- rfe(data_train[,2:22], data_train[[1]], sizes=c(2:22),rfeControl=control,metric=ifelse(is.factor(data_train$Diagnosis),"Kappa","RMSE")) print(results) #9 variáveis + diagnosis #list the chosen features predictors(results) #plot the results plot(results, type=c("g", "o"),main="RFE using Random Forest") # ## RF a partir do subset definido pelo RFE-RF data_train_rfe<- data_train[,c("Diagnosis","MMSE", "IADL","GSDT","FMT_DT","FMT_IT","GSST","TMTA","STEP","Age")] data_test_rfe<- data_test[,c("Diagnosis","MMSE", "IADL","GSDT","FMT_DT","FMT_IT","GSST","TMTA","STEP","Age")] head(data_train_rfe) set.seed(4) RF_model1=train(Diagnosis~.,data=data_train_rfe,method='rf',metric=ifelse(is.factor(data_train_rfe$Diagnosis),"Kappa","RMSE"),trControl=trainControl(method='cv',number=5,savePredictions=TRUE)) RF_model1 #Acurácia de 81.08% e kappa= 58,97% plot(RF_model1) #RF_model1$pred #mtry2<- subset(RF_model1$pred,RF_model1$pred[4]==2) #mtry2 RF_model1$finalModel #Acurácia=82% RF_prediction<- predict(RF_model1,data_test_rfe) confusionMatrix(table(data_test_rfe$Diagnosis,RF_prediction)) #Acurácia=80% e Kappa=51.52% confusionMatrix(table(data_test_rfe$Diagnosis,RF_prediction))$byClass #Recall e F1 CCL(NA e NA) varImp(RF_model1) plot(varImp(RF_model1),main="Variables Importance - Random Forest") # # RFE-DT e DT set.seed(22) control2 <- rfeControl(functions=treebagFuncs, method="cv", number=5) set.seed(33) results2 <- rfe(data_train[,2:22], data_train[[1]], sizes=c(2:22), rfeControl=control,metric=ifelse(is.factor(data_train$Diagnosis),"Kappa","RMSE")) print(results2) #9 variáveis + diagnosis #list the chosen features predictors(results2) #plot the results plot(results2, type=c("g", "o"),main="RFE using Decision Tree") # ## DT a partir do subset definido pelo RFE-DT data_train_rfe2<- data_train[,c("Diagnosis","MMSE", "IADL","GSDT","FMT_DT","FMT_IT","GSST","TMTA","Sex","Age")] data_test_rfe2<- data_test[,c("Diagnosis","MMSE", "IADL","GSDT","FMT_DT","FMT_IT","GSST","TMTA","Sex","Age")] head(data_train_rfe2) colnames(data_train_rfe2) <- make.names(colnames(data_train_rfe2)) set.seed(44) Tree_model1=train(Diagnosis~.,data=data_train_rfe2,method='rpart',metric="Kappa",trControl=trainControl(method='cv',number=5,savePredictions=TRUE)) Tree_model1 #Acurácia=81.03% e kappa=57.38% e cp=0 #Tree_model1$pred plot(Tree_model1) Tree_model1$finalModel #install.packages("rpart.plot") require(rpart.plot) rpart.plot(Tree_model1$finalModel,type=0,extra=101,box.palette = "GnBu", branch.lty=3,shadow.col = "gray",nn=T,cex=1) Tree_prediction<- predict(Tree_model1,data_test_rfe2) confusionMatrix(table(data_test_rfe2$Diagnosis,Tree_prediction)) #Acurácia=75% e Kappa=43.10% confusionMatrix(table(data_test_rfe2$Diagnosis,Tree_prediction))$byClass #Recall e F1 CCL(0 e NA) varImp(Tree_model1) plot(varImp(Tree_model1),main="Variables Importance - Decision Tree") # # Aumento de dados (*ROSE*) #install.packages("ROSE") require(ROSE) #sau e ccl data_train$Diagnosis<-as.numeric(data_train$Diagnosis) data_train_ccl<- data_train[data_train$Diagnosis!="3",] #Apenas saudáveis e CCL table(data_train$Diagnosis) #(66,15) data_train_ccl$Diagnosis<- as.factor(data_train_ccl$Diagnosis) set.seed(111) data_train_augmented_rose<- ovun.sample(Diagnosis~.,data=data_train_ccl,method = "over",N=132)$data table(data_train_augmented_rose$Diagnosis) #(66,66) #Sau e DA data_train$Diagnosis<-as.numeric(data_train$Diagnosis) data_train_da<- data_train[data_train$Diagnosis!="2",] #Apenas saudáveis e DA table(data_train_da$Diagnosis) #(66,19) data_train_da$Diagnosis<- as.factor(data_train_da$Diagnosis) set.seed(222) data_train_augmented_rose2<- ovun.sample(Diagnosis~.,data=data_train_da,method = "over",N=132)$data table(data_train_augmented_rose2$Diagnosis) #(66,66) #Unindo DA do fold01_treino_aumentado_rose2 com o fold01_treino_aumentado_rose data_train_augmented_rose2<- data_train_augmented_rose2[data_train_augmented_rose2$Diagnosis!="1",] data_train_augmented_rose_final<- rbind(data_train_augmented_rose,data_train_augmented_rose2) dim(data_train_augmented_rose_final) # 198x22 table(data_train_augmented_rose_final$Diagnosis) #(66,66,66) # ## RF a partir dos dados aumentados set.seed(333) data_train_augmented_rose_final_rfe<- data_train_augmented_rose_final[,c("Diagnosis","MMSE", "IADL","GSDT","FMT_DT","FMT_IT","GSST","TMTA","STEP","Age")] rf_rose<- randomForest(data_train_augmented_rose_final_rfe$Diagnosis~.,data = data_train_augmented_rose_final_rfe) rf_rose #Validação do modelo data_test_augmented_rose_final_rfe<- data_test[,c("Diagnosis","MMSE", "IADL","GSDT","FMT_DT","FMT_IT","GSST","TMTA","STEP","Age")] prediction_rose<- predict(rf_rose,data_test_augmented_rose_final_rfe) Metrics_rose<- confusionMatrix(table(data_test_augmented_rose_final_rfe$Diagnosis,prediction_rose))$byClass Metrics_rose varImp(rf_rose) # ## DT a partir dos dados aumentados set.seed(301) data_train_augmented_rose_final2_rfe<- data_train_augmented_rose_final[,c("Diagnosis","MMSE", "IADL","GSDT","FMT_DT","FMT_IT","GSST","TMTA","Sex","Age")] tree_rose<- rpart(data_train_augmented_rose_final2_rfe$Diagnosis~.,data=data_train_augmented_rose_final2_rfe,method = "class") data_test_augmented_rose_final2_rfe<- data_test[,c("Diagnosis","MMSE", "IADL","GSDT","FMT_DT","FMT_IT","GSST","TMTA","Sex","Age")] prediction_rose_tree<- predict(tree_rose,data_test_augmented_rose_final2_rfe,type="class") Metrics_rose_tree<- confusionMatrix(data_test_augmented_rose_final2_rfe$Diagnosis,prediction_rose_tree)$byClass Metrics_rose_tree rpart.plot(tree_rose,type=0,extra=101,box.palette = "GnBu", branch.lty=3,shadow.col = "gray",nn=T,cex=1) varImp(tree_rose)
analise-artigo-felipe.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="2AHvonepDTeL" colab_type="code" colab={} class PostingCompress: def __init__(self,mode): _dict = {"Gama":self.__toGama,"ContinueBit":self.__toContinueBit} self.mode=_dict[mode] def execute(self,posting): comp_posting=[] for linkList in posting: new_coding=str (self.mode(linkList[0])) for i,item in enumerate(linkList[1:]): new_coding += str (self.mode(item - linkList[i])) comp_posting.append(new_coding) return comp_posting,self.Decompress def Decompress(self,comp_posting): posting = list() if self.mode == self.__toGama: func = self.__fromGama elif self.mode == self.__toContinueBit: func = self.__fromContinueBit for binary in comp_posting: posting.append(func(binary)) return posting def __fromGama(self,binary): unary = True offset = False posting=list() count=0 for i,bit in enumerate(binary): if unary: if bit == "1" : count += 1 continue elif bit == "0" and i == 0:#delete plus one posting.append(int("1",2) -1) continue elif bit == "0" and i !=0: unary = False offset = True if offset: try: #delete plus one posting.append((posting[-1] + int("1" + binary[i+1:i+count+1],2)) -1) except:#delete plus one posting.append(int("1" + binary[i+1:i+count+1],2) -1) offset =False if count != 0: count -= 1 continue else : count=0 unary = True return posting def __fromContinueBit(self,binary): posting=list() for i in range(len(binary) // 8) : try: posting.append(posting[-1] + int(binary[(i)*8 +1:(i+1)*8],2)) except: posting.append(int(binary[(i)*8 +1:(i+1)*8],2)) return posting def __toGama(self,dec): #we should not have zero in GAMA . size=len(bin(dec +1)[2:]) -1 # +1 <---- Gama = size * "1" + "0" + bin(dec + 1)[3:] return Gama def __toContinueBit(self,dec): dec=bin(dec)[2:] result='' while (len(dec) >= 7): temp=dec[-7:] dec=dec[:-7] result = "1" + temp + result res = result if len(result) and len(dec) != 0: res= "0" + ((7 - len(dec)) *"0") + dec + result elif len(dec) != 0 and len(result) == 0: res= "1" + ((7 - len(dec)) *"0") + dec + result return res # + [markdown] id="Vs4bfhqgHScl" colab_type="text" # pc=PostingCompress("Gama") # x=pc.execute([[0,13,54,87,110],[1,5,7,18,38]]) # print(x) # pc.Decompress(x)
Satida/Layers_Source/PostingCompress.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] _cell_guid="477796cc-9a7f-442b-9f56-fe928e10b061" _uuid="8357bdadb815806c1d665dc56f28f0b477a9fc3a" # ## Subplots # # In the previous section, "Styling your plots", we set the title of a plot using a bit of `matplotlib` code. We did this by grabbing the underlying "axis" and then calling `set_title` on that. # # In this section we'll explore another `matplotlib`-based stylistic feature: **subplotting**. # + _cell_guid="fbbe8d34-9c5b-425c-aa00-c2cb71684a63" _uuid="5a5a0b9794ba13949c9755bb59c42f2a81bb6621" import pandas as pd reviews = pd.read_csv("../input/wine-reviews/winemag-data_first150k.csv", index_col=0) reviews.head(3) # + [markdown] _cell_guid="a79a488a-71ed-49be-b15f-01f9c02a66d4" _uuid="516cf05f411aa758959f5627543199558e0a64f1" # ## Subplotting # # Subplotting is a technique for creating multiple plots that live side-by-side in one overall figure. We can use the `subplots` method to create a figure with multiple subplots. `subplots` takes two arguments. The first one controls the number of *rows*, the second one the number of *columns*. # + _cell_guid="27d2a460-c976-4f22-b460-104f63f44626" _uuid="148575c4803a0fde183c3d0645903dfb9a253107" import matplotlib.pyplot as plt fig, axarr = plt.subplots(2, 1, figsize=(12, 8)) # + [markdown] _cell_guid="753dd1b1-e44f-4490-a6da-6c710d0afb9e" _uuid="df8c35d44f7456deb6cc809f091af3a2b764db1d" # Since we asked for a `subplots(2, 1)`, we got a figure with two rows and one column. # # Let's break this down a bit. When `pandas` generates a bar chart, behind the scenes here is what it actually does: # # 1. Generate a new `matplotlib` `Figure` object. # 2. Create a new `matplotlib` `AxesSubplot` object, and assign it to the `Figure`. # 3. Use `AxesSubplot` methods to draw the information on the screen. # 4. Return the result to the user. # # In a similar way, our `subplots` operation above created one overall `Figure` with two `AxesSubplots` vertically nested inside of it. # # `subplots` returns two things, a figure (which we assigned to `fig`) and an array of the axes contained therein (which we assigned to `axarr`). Here are the `axarr` contents: # + _cell_guid="12311f94-fd6a-4483-8710-ce019deff76c" _uuid="f2ffc588b295ebe3f8771828389ca43653ad3dc5" axarr # + [markdown] _cell_guid="a0386abf-4911-4505-846b-abf16248b796" _uuid="6b7c34630a87d79e1467f1728f5844ce2f85f285" # To tell `pandas` which subplot we want a new plot to go in&mdash;the first one or the second one&mdash;we need to grab the proper axis out of the list and pass it into `pandas` via the `ax` parameter: # + _cell_guid="b2b0bdbc-897a-4436-91d1-37c60a1a77ba" _uuid="aedf7693711c0d89d70b4e945c8c77b4b99053ac" fig, axarr = plt.subplots(2, 1, figsize=(12, 8)) reviews['points'].value_counts().sort_index().plot.bar( ax=axarr[0] ) reviews['province'].value_counts().head(20).plot.bar( ax=axarr[1] ) # + [markdown] _cell_guid="ceda04ac-9d62-467b-9896-39686707848e" _uuid="8567844f28bebb1c06beb3c9f0ed1d988492b944" # We are of course not limited to having only a single row. We can create as many subplots as we want, in whatever configuration we need. # # For example: # + _cell_guid="e39d66e6-fb91-4e87-bb32-ece061aef1e3" _uuid="12fb2320aabfd23084a67624abff09c044e6fb35" fig, axarr = plt.subplots(2, 2, figsize=(12, 8)) # + [markdown] _cell_guid="153c7d59-3983-46f4-848d-0427ea848650" _uuid="b2d1af4b4b68fb3c7d7dedb9593b3d23e284c0f0" # If there are multiple columns *and* multiple rows, as above, the axis array becoming a list of lists: # + _cell_guid="80c1089c-bf26-49c7-bdf1-ec77476a1095" _uuid="51d60155336bb70f3eb941895272e9535a9f429b" axarr # + [markdown] _cell_guid="f4dd0de4-4943-4665-b8e3-ff79d1bc8ace" _uuid="5a616c524859f4ecc0901b3b722da0fc9979a3c3" # That means that to plot our data from earlier, we now need a row number, then a column number. # + _cell_guid="b73ac778-b2fc-4be5-9461-a3a2b561abae" _uuid="18600b6237c70d986f912b6c562ef4c665341a71" fig, axarr = plt.subplots(2, 2, figsize=(12, 8)) reviews['points'].value_counts().sort_index().plot.bar( ax=axarr[0][0] ) reviews['province'].value_counts().head(20).plot.bar( ax=axarr[1][1] ) # + [markdown] _cell_guid="1b4994b6-e4b1-4099-a94e-7a7945c165fb" _uuid="1e2312379cae422a28b73994ef0060dbd7fdd079" # Notice that the bar plot of wines by point counts is in the first row and first column (the `[0][0]` position), while the bar plot of wines by origin is in the second row and second column (`[1][1]`). # # By combining subplots with the styles we learned in the last section, we can create appealing-looking panel displays. # + _cell_guid="e66b1c6c-3190-4c75-9ab8-95c93454127f" _uuid="92a2d6d249e681f102131a1fbe89efc622ce2c93" fig, axarr = plt.subplots(2, 2, figsize=(12, 8)) reviews['points'].value_counts().sort_index().plot.bar( ax=axarr[0][0], fontsize=12, color='mediumvioletred' ) axarr[0][0].set_title("Wine Scores", fontsize=18) reviews['variety'].value_counts().head(20).plot.bar( ax=axarr[1][0], fontsize=12, color='mediumvioletred' ) axarr[1][0].set_title("Wine Varieties", fontsize=18) reviews['province'].value_counts().head(20).plot.bar( ax=axarr[1][1], fontsize=12, color='mediumvioletred' ) axarr[1][1].set_title("Wine Origins", fontsize=18) reviews['price'].value_counts().plot.hist( ax=axarr[0][1], fontsize=12, color='mediumvioletred' ) axarr[0][1].set_title("Wine Prices", fontsize=18) plt.subplots_adjust(hspace=.3) import seaborn as sns sns.despine() # + [markdown] _cell_guid="09a6812c-c32f-4e68-81a4-ee831d0cf4ef" _uuid="bececebb0644f2d291f025372d48ce35214d6070" # # Why subplot? # # Why are subplots useful? # # Oftentimes as a part of the exploratory data visualization process you will find yourself creating a large number of smaller charts probing one or a few specific aspects of the data. For example, suppose we're interested in comparing the scores for relatively common wines with those for relatively rare ones. In these cases, it makes logical sense to combine the two plots we would produce into one visual "unit" for analysis and discussion. # # When we combine subplots with the style attributes we explored in the previous notebook, this technique allows us to create extremely attractive and informative panel displays. # # Finally, subplots are critically useful because they enable **faceting**. Faceting is the act of breaking data variables up across multiple subplots, and combining those subplots into a single figure. So instead of one bar chart, we might have, say, four, arranged together in a grid. # # The recommended way to perform faceting is to use the `seaborn` `FacetGrid` facility. This feature is explored in a separate section of this tutorial. # # # Exercises # # Let's test ourselves by answering some questions about the plots we've used in this section. Once you have your answers, click on "Output" button below to show the correct answers. # # 1. A `matplotlib` plot consists of a single X composed of one or more Y. What are X and Y? # 2. The `subplots` function takes which two parameters as input? # 3. The `subplots` function returns what two variables? # + _cell_guid="1f7ad95b-574f-471c-84f9-3ab3108b12a4" _uuid="10d8dd9f02ca749ee91529c36d33c2b2d8528b0d" _kg_hide-output=true _kg_hide-input=true from IPython.display import HTML HTML(""" <ol> <li>The plot consists of one overall figure composed of one or more axes.</li> <li>The subplots function takes the number of rows as the first parameter, and the number of columns as the second.</li> <li>The subplots function returns a figure and an array of axes.</li> </ol> """) # + [markdown] _cell_guid="c64c5a84-92bb-45bc-bc03-31394dfb15df" _uuid="c004cd856969407495cff9b21df30a464fac6d4f" # To put your design skills to the test, try forking this notebook and replicating the plots that follow. To see the answers, hit the "Input" button below to un-hide the code. # + _cell_guid="111d54f4-ead5-48aa-9685-37225d3e60ff" _uuid="4c9402a6985cd16b157995f7650d796d35608d2c" import pandas as pd import matplotlib.pyplot as plt pokemon = pd.read_csv("../input/pokemon/Pokemon.csv") pokemon.head(3) # + [markdown] _cell_guid="0d50dd36-ffff-4c4b-9f39-c1cce30bb463" _uuid="4299993492a455851c533a801b36a5173fed9c77" # (Hint: use `figsize=(8, 8)`) # + _cell_guid="3d017500-f37c-4c90-bb54-04df6155d760" _uuid="d7d6514f2d6b62c0afb629290a4bacd81af33a78" _kg_hide-output=false _kg_hide-input=true fig, axarr = plt.subplots(2, 1, figsize = (8, 8)) # + _cell_guid="f862b3a9-015e-4bbb-8712-e8da1843e7f4" _uuid="b663d346286a8bc55a9c559aaefc215c400ce429" _kg_hide-input=true import seaborn as sns fig, axarr = plt.subplots(2, 1, figsize = (8, 8)) pokemon['Attack'].plot.hist(ax = axarr[0], fontsize=16, color='red', bins=20) axarr[0].set_title("Pokemon Attack Ratings", fontsize=18) pokemon['Defense'].plot.hist(ax = axarr[1], fontsize=16, color='green', bins=20) axarr[1].set_title("Pokemon Defense Ratings", fontsize=18) sns.despine() plt.subplots_adjust(hspace=0.4) # + [markdown] _cell_guid="d95b484e-2c26-485b-8085-eeff1d505a80" _uuid="6ddf98bbe43f2e9674e14f1fcbb8672a027ba6f2" # # Conclusion # # In the previous section we explored some `pandas`/`matplotlib` style parameters. In this section, we dove a little deeper still by exploring subplots. # # Together these two sections conclude our primer on style. Hopefully our plots will now be more legible and informative. # # [Click here to go to the next section, "Multivariate plotting"](https://www.kaggle.com/residentmario/multivariate-plotting/).
pyplot_subplots.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Dealing with categorical features # In this notebook we cover examples of common tasks for treating **categorical data** prior to modeling. Categorical data needs a lot of attention during data pre-processing. This is because most machine learning algorithms don't deal directly with categorical data. Instead we need to **recode** the data from categorical into numeric, and we will see how we do that in this notebook. # # Let's begin by reading some data. We will use a marketing data set of bank customers. You can read more about the data [here](https://archive.ics.uci.edu/ml/datasets/Bank+Marketing). # + import pandas as pd import numpy as np bank = pd.read_csv('data/bank-full.csv', sep = ";") bank.head() # - # We can see that our data contains many categorical columns, including the target itself. Let's check the data types: bank.dtypes # We can use the `select_dtypes` method to limit the data to just the categorical columns. bank.select_dtypes('object').head() # ### Exercise # # Write a loop to obtain counts of unique values for each categorical column in the data. We can use the `value_counts` method to get counts for a column. # ### End of exercise # It turns out there are **two kinds of data types for categorical data** in `pandas`: `object` and `category`. By default, any string column will inherit the `object` type, but we can later convert them to `category` type. Ideally, a `catogory` type is only appropriate for a column with **a limited number pre-defined categories**. This is because the `category` type is a more rigid data type that we can use to impose additional structure on the column. So this only makes sense when the categories are known and few. Let's illustrate that by turning some of the columns in our data into a `category` columns. cat_cols = ['marital', 'default', 'housing', 'loan'] bank[cat_cols] = bank[cat_cols].astype('category') # Why would we want to add additional rigidity? Because this way we can impose some amount of **data integrity**. For example, if `marital` should always be limited to "single", "divorced" or "married" then by converting `marital` into a `category` column we can prevent the data from introducing any other category without first adding it as one of the acceptable categories for this column. bank['marital'].cat.categories # ### Exercise # # Try to change `marital` at the second row to the value "widowed". You should get an error. To fix the error, you need to add "widowed" as one of the acceptable categories. Use the `cat.add_categories` method to add "widowed" as a category and then try again to make sure you don't get an error this time. # Undo your change by reassigning `marital` at the second row to the value "single". Get a count of unique values for `marital` now. Do you notice anything? Explain what and why? # Categorical columns have other useful methods, and their names speak for themselves, such as # `as_ordered`, `as_unordered`, `remove_categories`, `remove_unused_categories`, `rename_categories`, `reorder_categories`, and `set_categories`. It is important to be aware of this functionality and use it when it makes sense. Of course an alternative to using these is to convert the column back to `object` and make all the changes we want and then turn it back into `category`. # ### End of exercise # So we saw that a `category` column has pre-defined categories and a set of methods specific to itself for changing the categories, whereas an `object` column is more a type of **free-form** categorical column where the categories can be changed on the fly and no particular structure is imposed. One way the above distinction matters if when we need to rename the categories for a categorical column. This is sometimes referred to as **recoding** or **remapping**. # ### Exercise # # Let's first begin with an example using `job`, which has type `object`. Rename the category "management" to "managerial". HINT: find all rows where `job` is the string `'management'`, and use `loc` to change those rows to the string `'managerial'`. # The above approach works fine, but it's tedious if we have a lot of changes we want to make. The better way to do it is to create a Python dictionary that maps old values (values we want to change) to new values, then use the `replace` method to replace them all at once. # # Create such a dictionary and use `replace` to make the following changes in the `job` column: # # - rename `'student'` to `'in-school'` # - combine `'housemaid'` and `'services'` into a single group called `'catering'` # - change `unknown` to a missing value, i.e. `np.NaN` (without quotes) # Get a count of unique values for `job` to make sure everything worked. Note that `value_counts()` does not provide count for missing values by default. We need to specify `dropna = False` to include missing vaules in the count. # ### End of exercise # The `replace` method works equally well with a categorical column of type `category`, however **it changes its type to `object`!** So either we have to convert it back to `category`, or we need to use the `rename_categories` method to replace values, which workes very similar to `replace` in that it accepts a dictionary mapping old values to new ones. Here's an example: bank['marital'] = bank['marital'].cat.rename_categories({'married': 'taken'}) bank['marital'].value_counts() # Categorical columns can also be easily generated from numeric columns. For example, let's say we want to have a column called `high_balance` that is `True` when balance exceeds $2,000 and `False` otherwise. Technically this would be a boolean column, but in practice it acts as categorical column. Generating such a column is very easy. We refer to such binary colums as **dummy variables** or **flags** because they single out a group. bank['high_balance'] = bank['balance'] > 2000 # The process of creating a dummy variable **for each category** of a categorical feature is called **one-hot encoding**. Let's see what happens if we one-hot-encode `marital`. bank['marital_taken'] = (bank['marital'] == 'taken').astype('int') bank['marital_single'] = (bank['marital'] == 'single').astype('int') bank['marital_divorced'] = (bank['marital'] == 'divorced').astype('int') bank.filter(like = 'marital').head() # One-hot encoding is a common enough task that we don't need to do it manually like we did above. Instead we can use `pd.get_dummies` to do it in one go. pd.get_dummies(bank['marital'], prefix = 'marital').head() # There's an even more streamlined way to do one-hot encoding, although at first blush it appears less straight-forward, but there is a reason it is set up this way and we will explain that later. Just like normalization, one-hot-encoding is a common pre-processing task and we can turn to the `sklearn` library to do the hard part for us. # + from sklearn.preprocessing import OneHotEncoder bank_cat = bank.select_dtypes('category').copy() # only select columns that have type 'category' onehot = OneHotEncoder(sparse = False) # initialize one-hot-encoder onehot.fit(bank_cat) col_names = onehot.get_feature_names(bank_cat.columns) # this allows us to properly name columns bank_onehot = pd.DataFrame(onehot.transform(bank_cat), columns = col_names) bank_onehot.head() # - # So we can see that one-hot encoding created a **binary feature** for **each category of each categorical column** in the data. Although to be more specific, we limited it to columns whose type is `category` and excluded columns whose type is `object`. This is because one-hot encoding can quickly blow up the number of columns in the data if we are not careful and include categorical columns with lots of categories (also called **high-cardinality** categorical columns). # # What is the point of doing this? The reason we do this is that most machine learning algorithms do not work **directly** with categorical data, so we need to encode the categorical data which turns it into numeric data. One-hot encoding is just one type of encoding, but it is the most common one. # One last note about the `sklearn` pre-processing transformations we learned about in this notebook: If you look at examples online, you may notice that instead of calling `fit` and `transform` separately, you can call `fit_transform` which combines the two steps into one. This may seem reasonable and saves you one extra line of code, but we discourage it. The following exercise will illustrate why, but the main reason will become clear when we talk about machine learning. # ### Exercise # # Let's return to the data, and once again fit a one-hot encoder on it. This time we run it on `job` and `education`. bank_cat = bank[['job', 'education']].copy() onehot = OneHotEncoder(sparse = False) # initialize one-hot-encoder onehot.fit(bank_cat) # We now introduce a change: We replace the value for `job` at the second row with `'data scientist'` (assuming that's a new category). Note that `job` is of type `object`, so we can set it to anything we want. bank_cat.loc[1, 'job'] = 'data scientist' # introduce a category unseen when we ran fit bank_cat.head() # The important point here is that we introduce this additional category **after** we ran `fit` on the one-hot encoder above. # Now let's see what happens if we try to run `transform` on the data to one-hot encode the features. If you run the code below you'll notice that we get an error. What is the error for? col_names = onehot.get_feature_names(bank_cat.columns) bank_onehot = pd.DataFrame(onehot.transform(bank_cat), columns = col_names) bank_onehot.head() # Is it a good thing that we got an error? The answer is it depends: # # - If we are okay with letting new categories slip through, we can return to where we initiated `OneHotEncoder` and change the `handle_unknown = 'ignore'` (default value is `'error'`). Make this change and rerun the code. What is the one-hot encoded value for `job` at the row that we changed? # - If you want to make sure that we preserve **data integrity** so that the data we call `transform` on matches the schema of the data we ran `fit` on, then we want errors like this to stop us in our tracks so we have a change to see why the data changed. # # ### End of exercise # So we saw that using `fit` and `transform`, we can impose a sort of data integrity at training time and enforce it at transform time, and this is true even if the column is of type `object`. This is very similar to what how a column of type `category` works. In fact, if `job` was of type `category` instead of `object`, then we would not have been able to add a new category on the fly, and we would have caught the error pointed in the above exercise earlier.
lesson_5.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import tensorflow as tf import sys from tensorflow import keras from tensorflow.keras import backend as kb from tensorflow.keras import Model from tensorflow.keras.layers import Layer, Dense, Flatten, Conv2D from IPython.display import clear_output from tqdm import tqdm import matplotlib import matplotlib.pyplot as plt import numpy as np import time ## old version functions """ numberOfClasses = 5 numberOfdata = 3 batchsize = numberOfClasses * numberOfdata numberOfBatches = 1000 buffer = [] for i in range(numberOfClasses): buffer.append(np.empty([1, 2])) for idx, output_ in enumerate(outputs_): buffer[int(output_)] = np.concatenate((buffer[int(output_)], [inputs_[idx].numpy()]), axis=0) for i in range(numberOfClasses): buffer[i] = np.delete(buffer[i], 0, axis=0) inputs = np.empty([1, numberOfClasses, numberOfdata, 2]) outputs = np.empty([1, batchsize]) for i in range(numberOfBatches): input_ = np.empty([1, numberOfdata, 2]) output_ = np.empty([1]) for idx in range(numberOfClasses): choice_idx = np.random.choice(buffer[idx].shape[0], 3, replace=False) chosen = buffer[idx][choice_idx] chosen = np.expand_dims(chosen, axis=0) #print(chosen.shape) input_ = np.concatenate((input_, chosen), axis=0) #break # tmp = np.empty(numberOfdata) tmp.fill(idx) output_ = np.concatenate((output_, tmp)) input_ = np.delete(input_, 0, axis=0) output_ = np.delete(output_, 0, axis=0) input_ = np.expand_dims(input_, axis=0) output_ = np.expand_dims(output_, axis=0) inputs = np.concatenate((inputs, input_), axis=0) outputs = np.concatenate((outputs, output_), axis=0) inputs = np.delete(inputs, 0, axis=0) outputs = np.delete(outputs, 0, axis=0) dataset = tf.data.Dataset.from_tensor_slices((inputs, outputs)).shuffle(numberOfBatches, reshuffle_each_iteration=True) trainDataset = dataset.take(int(numberOfBatches * 0.7)) validDataset = dataset.skip(int(numberOfBatches * 0.7)) def DataGenerator(center, length, numberOfdata): fig = plt.figure() # inputs tmp = tf.random.uniform([numberOfdata, 2], maxval = length) a = tf.constant([[center[0] - length/2.0, center[1] - length/2.0]]) b = tf.constant([numberOfdata,1]) bias = tf.tile(a, b) inputs_ = tf.add(tmp, bias) # outputs outputs_ = np.zeros([numberOfdata]) for idx, elem in enumerate(inputs_): if abs(elem[0] - center[0]) < length/4.0 and abs(elem[1] - center[1]) < length/4.0: plt.scatter(elem[0], elem[1], c='m') outputs_[idx] = 4 elif elem[0] > center[0] and elem[1] > center[1]: plt.scatter(elem[0], elem[1], c='r') outputs_[idx] = 0 elif elem[0] > center[0]: plt.scatter(elem[0], elem[1], c='g') outputs_[idx] = 1 elif elem[0] <= center[0] and elem[1] <= center[1]: plt.scatter(elem[0], elem[1], c='b') outputs_[idx] = 2 elif elem[0] <= center[0]: plt.scatter(elem[0], elem[1], c='c') outputs_[idx] = 3 fig.tight_layout() plt.savefig('trainDataset.png') plt.show() return inputs_, outputs_ centerPoint = [0, 0] length = 2 numOfPoint_total = 300 inputs_, outputs_ = DataGenerator(centerPoint, length, numOfPoint_total) #print(inputs_.shape) #print(outputs_.shape) numberOfClasses = 4 batchsize = 32 numberOfBatches = 1000 buffer = [] for i in range(numberOfClasses): buffer.append(np.empty([1, 2])) for idx, output_ in enumerate(outputs_): buffer[int(output_)] = np.concatenate((buffer[int(output_)], [inputs_[idx].numpy()]), axis=0) for i in range(numberOfClasses): buffer[i] = np.delete(buffer[i], 0, axis=0) ratio = separateFairly(batchsize, numberOfClasses) inputs = np.empty([1, batchsize, 2]) outputs = np.empty([1, batchsize]) for i in range(numberOfBatches): input_ = np.empty([1, 2]) output_ = np.empty([1]) for idx in range(numberOfClasses): choice_idx = np.random.choice(buffer[idx].shape[0], ratio[idx], replace=False) chosen = buffer[idx][choice_idx] input_ = np.concatenate((input_, chosen), axis=0) tmp = np.empty(ratio[idx]) tmp.fill(idx) output_ = np.concatenate((output_, tmp)) input_ = np.delete(input_, 0, axis=0) output_ = np.delete(output_, 0, axis=0) input_ = np.expand_dims(input_, axis=0) output_ = np.expand_dims(output_, axis=0) inputs = np.concatenate((inputs, input_), axis=0) outputs = np.concatenate((outputs, output_), axis=0) #break inputs = np.delete(inputs, 0, axis=0) outputs = np.delete(outputs, 0, axis=0) dataset = tf.data.Dataset.from_tensor_slices((inputs, outputs)).shuffle(inputs.shape[0], reshuffle_each_iteration=True) trainDataset = dataset.take(int(numberOfBatches * 0.7)) validDataset = dataset.skip(int(numberOfBatches * 0.7)) class loss_L12(keras.losses.Loss): def __init__(self, name="custom"): super().__init__(name=name) def call(self, y_true, y_pred): avgs = None stds = None for i in range(numberOfClasses): idx = tf.squeeze(tf.where(tf.equal(y_true, i))) tmp = tf.gather(y_pred, idx) avg = tf.reduce_mean(tmp, 0) std = tf.math.reduce_std(tmp, 0) if stds is None: avgs = tf.expand_dims(avg, 0) stds = tf.expand_dims(std, 0) else: avgs = tf.concat([avgs, tf.expand_dims(avg, 0)], 0) stds = tf.concat([stds, tf.expand_dims(std, 0)], 0) tmp = tf.math.reduce_std(avgs, 0) #tf.print(tmp, output_stream=sys.stderr) L1 = 1 / (tf.norm(tmp) + kb.epsilon()) tmp = tf.norm(stds, axis=1) L2 = tf.math.reduce_sum(tmp) #tf.print(L1, output_stream=sys.stderr) #tf.print(L2, output_stream=sys.stderr) loss = tf.math.add(L1, L2) #tf.print(tf.math.is_nan(loss), output_stream=sys.stderr) return loss """ def separateFairly(batchSize, numClasses): ratio = [] for i in range(numClasses): ratio.append(batchSize//numClasses) choice = np.random.choice(numClasses, batchSize - sum(ratio), replace=False) for idx in choice: ratio[idx] += 1 return ratio # + def DataGenerator(center, length, numberOfdata): buffer = {} fig = plt.figure() for i in range(len(center)): tmp = tf.random.uniform([numberOfdata, 2], maxval = length[i]) a = tf.constant([[center[i][0] - length[i]/2.0, center[i][1] - length[i]/2.0]]) inputs_ = tf.add(tmp, a) if answer[i] in buffer.keys(): buffer[answer[i]] = tf.concat([buffer[answer[i]], inputs_], axis=0) else: buffer[answer[i]] = inputs_ for elem in inputs_: plt.scatter(elem[0], elem[1], c=colors[answer[i]]) #print(inputs_.shape) #print(a) return buffer colors = ['r', 'g', 'b', 'c', 'm'] answer = [0, 1, 2, 1, 3] centerPoint = [[-0.5, -0.5], [0.5, 0.5], [0, 0], [-0.5, 0], [-0.4, 0.4]] length = [0.3, 0.4, 0.4, 0.2, 0.3] numOfPoint_total = 50 buffer = DataGenerator(centerPoint, length, numOfPoint_total) # + numberOfClasses = 4 batchsize = 32 numberOfBatches = 1000 ratio = separateFairly(batchsize, numberOfClasses) inputs = np.empty([1, batchsize, 2]) outputs = np.empty([1, batchsize]) for i in range(numberOfBatches): input_ = np.empty([1, 2]) output_ = np.empty([1]) for idx in range(numberOfClasses): choice_idx = np.random.choice(buffer[idx].shape[0], ratio[idx], replace=False) #print(buffer[idx].shape) chosen = tf.gather(buffer[idx], choice_idx)#.numpy() #print(chosen.shape) input_ = np.concatenate((input_, chosen), axis=0) tmp = np.empty(ratio[idx]) tmp.fill(idx) output_ = np.concatenate((output_, tmp)) input_ = np.delete(input_, 0, axis=0) output_ = np.delete(output_, 0, axis=0) input_ = np.expand_dims(input_, axis=0) output_ = np.expand_dims(output_, axis=0) inputs = np.concatenate((inputs, input_), axis=0) outputs = np.concatenate((outputs, output_), axis=0) #break inputs = np.delete(inputs, 0, axis=0) outputs = np.delete(outputs, 0, axis=0) dataset = tf.data.Dataset.from_tensor_slices((inputs, outputs)).shuffle(inputs.shape[0], reshuffle_each_iteration=True) trainDataset = dataset.take(int(numberOfBatches * 0.7)) validDataset = dataset.skip(int(numberOfBatches * 0.7)) # - class custom_weight(Layer): def __init__(self, features=1): super(custom_weight, self).__init__() self.features = features def build(self, input_shape): self.w = self.add_weight( shape=(input_shape[-1], self.features), initializer="random_normal", trainable=True, ) self.b = self.add_weight( shape=(self.features,), initializer="random_normal", trainable=True ) def expandedInput(self): #tf.print(self.w, output_stream=sys.stderr) initial_value = tf.concat([self.w, tf.random.normal([1, 1])], 0) if self.w.trainalbe: self.w = tf.Variable(initial_value=initial_value, trainable=True) else: self.w = tf.Variable(initial_value=initial_value, trainable=False) #initial_value = tf.concat([self.b, tf.random.normal([1])], 0) #self.b = tf.Variable(initial_value=initial_value, trainable=True) def call(self, inputs): return tf.math.tanh(tf.matmul(inputs, self.w) + self.b) # + class MyModel(Model): def __init__(self, numFeatures=3): super(MyModel, self).__init__() self.numFeatures = numFeatures self.depth = 1 def build(self, input_shape): self.Architecture = [] for i in range(self.numFeatures): self.Architecture.append([custom_weight()]) def disableTraining(self, idx, depth): #self.Architecture[idx][depth].disableTraining() self.Architecture[idx][depth].trainalbe = False def expand(self): self.Architecture.append([custom_weight()]) for i in self.Architecture: if len(i) > 1: for j in range(1, len(i)): i[j].expandedInput() self.numFeatures += 1 ## idx for feature index def deeper(self, idx): self.Architecture[idx].append(custom_weight()) self.depth = 1 for i in self.Architecture: if len(i) > self.depth: self.depth = len(i) def call(self, x): for i in range(self.depth): #tf.print(x, output_stream=sys.stderr) tmp = tf.zeros([x.shape[0], 1]) for j, k in enumerate(self.Architecture): #print(j) #print(len(k)) if i < len(k): tmp = tf.concat([tmp, k[i](x)], 1) else: previous = tf.slice(x, [0, j], [x.shape[0], 1]) #tf.print(test, output_stream=sys.stderr) tmp = tf.concat([tmp, previous], 1) x = tmp[:,1:] #tf.print(x, output_stream=sys.stderr) return x model = MyModel(numFeatures=1) # + class loss_L1(keras.losses.Loss): def __init__(self, name="custom"): super().__init__(name=name) def call(self, y_true, y_pred): avgs = None for i in range(numberOfClasses): idx = tf.squeeze(tf.where(tf.equal(y_true, i))) tmp = tf.gather(y_pred, idx) avg = tf.reduce_mean(tmp, 0) if avgs is None: avgs = tf.expand_dims(avg, 0) else: avgs = tf.concat([avgs, tf.expand_dims(avg, 0)], 0) tmp = tf.math.reduce_std(avgs, 0) #L1 = 1 / tf.norm(tmp) L1 = 1 / (tf.norm(tmp) + kb.epsilon()) #tf.print(L1, output_stream=sys.stderr) return L1 class loss_L2(keras.losses.Loss): def __init__(self, name="custom"): super().__init__(name=name) def call(self, y_true, y_pred): stds = None for i in range(numberOfClasses): idx = tf.squeeze(tf.where(tf.equal(y_true, i))) tmp = tf.gather(y_pred, idx) std = tf.math.reduce_std(tmp, 0) if stds is None: stds = tf.expand_dims(std, 0) else: stds = tf.concat([stds, tf.expand_dims(std, 0)], 0) #tf.print(stds, output_stream=sys.stderr) tmp = tf.norm(stds, axis=1) #tf.print(tmp, output_stream=sys.stderr) L2 = tf.math.reduce_sum(tmp) #tf.print(L2, output_stream=sys.stderr) return L2 # + L1 = loss_L1() L2 = loss_L2() optimizer = tf.keras.optimizers.Adam(learning_rate = 0.001) L1_train = tf.keras.metrics.Mean() L2_train = tf.keras.metrics.Mean() @tf.function def train_step(input_, output_): with tf.GradientTape() as tape: #print(input_.shape) predictions = model(input_) l1 = L1(output_, predictions) l2 = L2(output_, predictions) Loss = l1 #+ l2 #Loss = L12(output_, predictions) gradients = tape.gradient(Loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) L1_train(l1) L2_train(l2) L1_valid = tf.keras.metrics.Mean() L2_valid = tf.keras.metrics.Mean() @tf.function def test_step(input_, output_): predictions = model(input_) l1 = L1(output_, predictions) l2 = L2(output_, predictions)# may vary L1_valid(l1) L2_valid(l2) # + EPOCHS = 500 patience = 10 stopped_epoch = 0 best_weights = None best = np.Inf wait = 0 #model.expand() #model.disableTraining(1, 0) #model.disableTraining(2, 0) #model.deeper(1) #model.deeper(2) #model.expand() #model.deeper(1) for epoch in range(EPOCHS): clear_output(wait=True) for input_, output_ in trainDataset: train_step(input_, output_) for input_, output_ in validDataset: test_step(input_, output_) template = '에포크: {}, L1_train: {:.4f}, L2_train: {:.3f}, L1_valid: {:.4f}, L2_valid: {:.3f}' print (template.format(epoch+1, L1_train.result(), L2_train.result(), L1_valid.result(), L2_valid.result())) if np.less(float(L1_valid.result() + L2_valid.result()), best): best = float(L1_valid.result() + L2_valid.result()) best_weights = model.get_weights() wait = 0 else: wait +=1 if wait >= patience: model.set_weights(best_weights) stopped_epoch = epoch print('Early Stopped !') break # + """ ## 1차원 fig= plt.figure() for idx in range(numberOfClasses): #idx = 3 for input_ in buffer[idx]: tmp = np.expand_dims(np.array(input_), axis=0) prediction = tf.squeeze(model(tmp)).numpy() plt.scatter(prediction[0], idx / numberOfClasses, c=colors[idx]) #break Avgs, Stds = findAvgs(numberOfClasses, model) for i in range(numberOfClasses): print('class : ', i, ' Avg : ', Avgs[i], ' Std : ', Stds[i], ' |Std| : ', np.linalg.norm(Stds[i])) print('Acurracy : ', Acc(Avgs, model)) """ """ ## 2차원 fig= plt.figure(figsize=(18,20)) colors = ['r', 'g', 'b', 'c', 'm'] markers = ['.', ',', 'o', 'v', '^'] for idx in range(numberOfClasses): #idx = 0 for input_ in buffer[idx]: tmp = np.expand_dims(np.array(input_), axis=0) prediction = tf.squeeze(model(tmp)).numpy() plt.scatter(prediction[0], prediction[1], c=colors[idx], marker=markers[idx]) #break Avgs, Stds = findAvgs(numberOfClasses, model) for i in range(numberOfClasses): print('class : ', i, ' Avg : ', Avgs[i], ' Std : ', Stds[i], ' |Std| : ', np.linalg.norm(Stds[i])) print('Acurracy : ', Acc(Avgs, model)) """ """ """ ## 3차원 fig= plt.figure(figsize=(18,20)) ax = fig.add_subplot(111, projection='3d') colors = ['r', 'g', 'b', 'c', 'm'] for idx in range(numberOfClasses): if idx != 0: for input_ in buffer[idx]: tmp = np.expand_dims(np.array(input_), axis=0) prediction = tf.squeeze(model(tmp)).numpy() #print(prediction.shape) ax.scatter(prediction[0], prediction[1], prediction[2], c=colors[idx]) #print(prediction) Avgs, Stds = findAvgs(numberOfClasses, model) for i in range(numberOfClasses): print('class : ', i, ' Avg : ', Avgs[i], ' Std : ', Stds[i], ' |Std| : ', np.linalg.norm(Stds[i])) print('Acurracy : ', Acc(Avgs, model)) # + def findAvgs(numberOfClasses, model): Avgs = [] Stds = [] for idx in range(numberOfClasses): predictions = np.empty([1, model.numFeatures]) for input_ in buffer[idx]: tmp = np.expand_dims(np.array(input_), axis=0) #prediction = tf.squeeze(model(tmp)).numpy() prediction = model(tmp).numpy() predictions = np.concatenate((predictions, prediction), axis=0) predictions = np.delete(predictions, 0, axis=0) avg = np.average(predictions, axis=0) std = np.std(predictions, axis=0) Avgs.append(avg) Stds.append(std) return Avgs, Stds def Acc(Avgs, model): total = 0 positive = 0 for idx in range(numberOfClasses): for input_ in buffer[idx]: total += 1 tmp = np.expand_dims(np.array(input_), axis=0) prediction = tf.squeeze(model(tmp)).numpy() answer = None distance_min = np.inf for i, avg in enumerate(Avgs): distance = np.linalg.norm(prediction - avg) if( distance < distance_min): distance_min = distance answer = i if answer == idx: positive += 1 return positive * 100.0 / total # - Avgs, Stds = findAvgs(numberOfClasses, model) for i in range(numberOfClasses): print('class : ', i, ' Avg : ', Avgs[i], ' Std : ', Stds[i], ' |Std| : ', np.linalg.norm(Stds[i])) print('Acurracy : ', Acc(Avgs, model))
.ipynb_checkpoints/DistanceMethod-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Regression # ## 1.Linear models # *** # # * Formulation # # *** # Assume instance $ \mathbf{x} = (x_1, x_2, ... , x_d)^T $, here $T$ means the matrix transpose. Linear model use linear combination of all attributes to do prediction. # # \begin{equation} # f(\mathbf{x}) = w_1x_1 + w_2x_2 + ... + w_dx_d + b, \tag{1} # \end{equation} # # or # # \begin{equation} # f(\mathbf{x}) = \mathbf{w}^T\mathbf{x} + b. \tag{2} # \end{equation} # *** # # * Linear regression # # *** # Use the linear model to obtain the relationship between the dependent variable (test results, $y_i$) and independent variables (selected features, $x_i$). If only one explanatory variable is considered, it is called simple linear regression, for more than one, it is called multiple linear regression. If multiple dependent variables are considered, it is called multivariate linear regression. Let's start with the simple linear regression. # # Given $x_i$ and $y_i$, how to find w and b so that $f(x_i) = wx_i + b \rightarrow y_i$? # We may use the least square approach: # # $(w^* , b^*) = \underset{(w , b)}{\arg\min} \sum\limits_{i=1}^m (f(x_i) - y_i)^2 = \underset{(w , b)}{\arg\min} \sum\limits_{i=1}^m (y_i - wx_i - b)^2$, here $m$ means we have $m$ instances. # # Let's set # $E_{(w, b)} = \sum\limits_{i=1}^m (y_i - wx_i - b)^2$, here $E_{(w, b)}$ is the cost function. # # Perform parameter estimation of least square approach # # \begin{equation} # \frac{\partial E}{\partial w} = 2 \left( w \sum\limits_{i=1}^m x_i^2 - \sum\limits_{i=1}^m (y_i - b)x_i \right) = 0, \tag{3} # \end{equation} # # \begin{equation} # \frac{\partial E}{\partial b} = 2 \left( mb - \sum\limits_{i=1}^m (y_i - wx_i) \right) = 0. \tag{4} # \end{equation} # # We then have # # \begin{equation} # w = \frac{ \sum\limits_{i=1}^m y_i (x_i - \frac{1}{m}\sum\limits_{i=1}^m x_i )}{\sum\limits_{i=1}^m x_i^2 - \frac{1}{m} \left( \sum\limits_{i=1}^m x_i \right)^2}, \tag{5} # \end{equation} # # \begin{equation} # b = \frac{1}{m}\sum\limits_{i=1}^m (y_i - w x_i). \tag{6} # \end{equation} # Similarly, the cost function for multiple variables (let's say d varaibles) is: $E_{(\mathbf{w}, b)} = E_{(w_1, w_2, ..., w_d, b)} = \sum\limits_{i=1}^m (y_i - \mathbf{w}^T\mathbf{x} - b)^2$. Combine coeficients $\mathbf{w}$ and $b$, we obtain a new vector $\hat{\mathbf{w}} = (\mathbf{w} ; b)$. The dataset $\mathbf{XX}$ with the size $m \times (d+1)$ can be read as # # \begin{equation} # \mathbf{XX} = \begin{pmatrix} # x_{11} & x_{12} & ... & x_{1d}\\ # x_{21} & x_{22} & ... & x_{2d}\\ # \vdots & \vdots & \ddots & \vdots \\ # x_{m1} & x_{m2} & ... & x_{md} # \end{pmatrix} = \begin{pmatrix} # \mathbf{x_{1}^T} & 1 \\ # \mathbf{x_{2}^T} & 1 \\ # \vdots & \vdots \\ # \mathbf{x_{m}^T} & 1 # \end{pmatrix}. \tag{7} # \end{equation} # # The label vector is $\mathbf{y} = (y_1; y_2; ...; y_m)$. Based on least square method, we need obtain the following # # \begin{equation} # \mathbf{\hat{w}}^* = \underset{\mathbf{\hat{w}}}{\arg\min} (\mathbf{y} - \mathbf{XX\hat{w}})^T (\mathbf{y} - \mathbf{XX\hat{w}}). \tag{8} # \end{equation} # # Let $E_{\mathbf{\hat{w}}} = (\mathbf{y} - \mathbf{XX\hat{w}})^T (\mathbf{y} - \mathbf{XX\hat{w}})$, then the derivative w.r.t. $\mathbf{\hat{w}}$ is # # \begin{equation} # \frac{\partial E_{\mathbf{\hat{w}}}}{\partial \mathbf{\hat{w}}} = 2\mathbf{XX}^T (\mathbf{XX}\mathbf{\hat{w}} - \mathbf{y}) . \tag{9} # \end{equation} # # We then use Gradient Descent method to iterativly update the unknown coefficients # # \begin{equation} # \mathbf{\hat{w}}^{(n+1)} = \mathbf{\hat{w}}^{(n)} - \left ( \alpha \frac{\partial E_{\mathbf{\hat{w}}}}{\partial \mathbf{\hat{w}}} \right)^n. \tag{10} # \end{equation} # *** # # * Hand-on example # # *** # + import numpy as np import pandas as pd import math as m import matplotlib.pyplot as plt def train_test_split(X, Y, train_size, shuffle): ''' Perform tran/test datasets splitting ''' if shuffle: randomize = np.arange(len(X)) np.random.shuffle(randomize) X = X[randomize] Y = Y[randomize] s_id = int(len(Y) * train_size) X_train, X_test = X[:s_id], X[s_id:] Y_train, Y_test = Y[:s_id], Y[s_id:] return X_train, X_test, Y_train, Y_test def metric_mse(Y_label, Y_pred): ''' Evaluate mean squared error (MSE) ''' return np.mean(np.power(Y_label - Y_pred, 2)) def metric_rmse(Y_label, Y_pred): ''' Evaluate root mean squared error (RMSE) ''' return m.sqrt(np.mean(np.power(Y_label - Y_pred, 2))) def readin_data(path): ''' Evaluate root mean squared error (RMSE) ''' df = pd.read_csv(path) X = df.iloc[:,:-1].values Y = df.iloc[:,1].values return X, Y def generate_dataset_simple(beta, n, std_dev): ''' Generate dataset ''' X = np.random.rand(n) e = np.random.randn(n) * std_dev Y = X * beta + e X = X.reshape((n,1)) return X, Y class LinearRegression() : ''' Linear Regression model. Used to obtain the relationship between dependent variable and independent variables.''' def __init__(self, iterations, learning_rate): self.lr = learning_rate self.it = iterations def fit(self, X, Y): # m instances, d atrributes self.m, self.d = X.shape # weight initialization self.W = np.zeros(self.d+1) self.X = X self.XX = np.ones((self.m, self.d+1)) self.XX[:,:-1] = self.X self.Y = Y for i in range(self.it): self.update_weights() return self def update_weights(self): Y_pred = self.predict(self.XX) # calculate gradients dW = (self.XX.T).dot(Y_pred - self.Y)/self.m # update weights self.W = self.W - self.lr * dW return self def predict(self, X): return X.dot(self.W) def main(): # Import data X, Y = generate_dataset_simple(10, 200, 0.5) # Splitting dataset into train and test set X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size=.5, shuffle=False) # Model Learning model = LinearRegression(learning_rate = 0.01, iterations = 15000) model.fit(X_train, Y_train) # Model Working M, D = X_test.shape TEST = np.ones((M, D+1)) TEST[:,:-1] = X_test Y_pred = model.predict(TEST) # Statistics mse = metric_mse(Y_test, Y_pred) rmse = metric_rmse(Y_test, Y_pred) print('Coefficients: ', 'W = ', model.W[:-1], ', b = ', model.W[-1]) print('MSE = ', mse) print('RMSE = ', rmse) # Visualization plt.scatter( X_test, Y_test, color = 'black', s=8) plt.plot( X_test, Y_pred, color = 'red', linewidth=3) plt.title( 'X_test v.s. Y_test') plt.xlabel( 'X_test') plt.ylabel( 'Y_test') X_actual = np.array([0, 1]) Y_actual = X_actual*10 plt.plot(X_actual, Y_actual, 'c--', linewidth=3) plt.legend(('Regression Line', 'Actual Line'),loc='upper left', prop={'size': 15}) plt.show() if __name__ == '__main__': main() # - # *** # * Additional notes about linear regression # *** # 1. When performing **Gradient Descent** approach, all features/attributes must have similar scale, or **feature scaling** is required to increase Gradient Descent convergence. We may import `from sklearn.preprocessing import StandardScaler`, then use `StandardScaler()`. (refer [feature scaling](https://www.analyticsvidhya.com/blog/2020/04/feature-scaling-machine-learning-normalization-standardization/)) # # 2. To avoid local minimum, and to quickly find the global minimum, make sure the cost function is a **convex function** ($\displaystyle i.e., f(\frac{a+b}{2}) \leq \frac{f(a)+f(b)}{2} $). # # 3. Linear regression assumptions: # - Exogeneity weak. Independent variable X is fixed variable, it is not random variable; # - **Linearity**. $f$ is a linear combination of the parameters/coefficients and the independent variables X. Note that, linearity is a restriction on the parameters, not the independent variables X, e.g., polynomial regression can also be linear regression; # - **Constant variable(Homoscedasticity)**. The variance of residual is the same for any value of independent variables; # - **Independence**. Observations are independent of each other. The errors are uncorrelated with each other; # - **Normality**. For any fixed value of X, Y is normally distributed.
Regression/Regression.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:reinforcement] # language: python # name: conda-env-reinforcement-py # --- import gym from gym import spaces from gym.utils import seeding from tqdm import tqdm import pandas as pd import numpy as np import typing from datetime import datetime import ray # Start up Ray. This must be done before we instantiate any RL agents. ray.init(num_cpus=10, ignore_reinit_error=True, log_to_driver=False,_temp_dir="/rds/general/user/asm119/ephemeral") Thomas_data = "../Thomas/" def load_data( price_source: str, tickers: typing.List[str], start: datetime, end: datetime, features: typing.List[str], ): """Returned price data to use in gym environment""" # Load data # Each dataframe will have columns date and a collection of fields # TODO: DataLoader from mongoDB # Raw price from DB, forward impute on the trading days for missing date # calculate the features (log return, volatility) if price_source in ["csvdata"]: feature_df = [] for t in tickers: df1 = pd.read_csv(Thomas_data + "csvdata/{}.csv".format(t)) df1['datetime'] = pd.to_datetime(df1['datetime']) df1 = df1[(df1['datetime']>=start) & (df1['datetime']<=end)] df1.set_index("datetime",inplace=True) selected_features = ['return','tcost'] + features feature_df.append(df1[selected_features]) ref_df_columns = df1[selected_features].columns # assume all the price_df are aligned and cleaned in the DataLoader merged_df = pd.concat(feature_df, axis=1, join="outer") # Imputer missing values with zeros price_tensor = merged_df['return'].fillna(0.0).values tcost = merged_df['tcost'].fillna(0.0).values return { "dates": merged_df.index, "fields": ref_df_columns, "data": merged_df.fillna(0.0).values, "pricedata": price_tensor, "tcost": tcost, } load_data('csvdata',['SPY','QQQ',], datetime(2010, 5, 4), datetime(2020, 12, 31), ["volatility_20", "skewness_20", "kurtosis_20"] ) ['data'][:10,:] # + from empyrical import max_drawdown, alpha_beta, sharpe_ratio, annual_return from sklearn.preprocessing import StandardScaler class Equitydaily(gym.Env): def __init__(self,env_config): self.tickers = env_config['tickers'] self.lookback = env_config['lookback'] self.random_start = env_config['random_start'] self.trading_days = env_config['trading_days'] # Number of days the algorithm runs before resetting # Load price data, to be replaced by DataLoader class raw_data = load_data(env_config['pricing_source'],env_config['tickers'],env_config['start'],env_config['end'],env_config['features']) # Set the trading dates, features and price data self.dates = raw_data['dates'] self.fields = raw_data['fields'] self.pricedata = raw_data['pricedata'] self.featuredata = raw_data['data'] self.tcostdata = raw_data['tcost'] # Set up historical actions and rewards self.n_assets = len(self.tickers) + 1 self.n_metrics = 2 self.n_assets_fields = len(self.fields) self.n_features = self.n_assets_fields * len(self.tickers) + self.n_assets + self.n_metrics # reward function #self.n_features = self.n_assets_fields * len(self.tickers) # Set up action and observation space # The last asset is cash self.action_space = spaces.Box(low=-1, high=1, shape=(len(self.tickers)+1,), dtype=np.float32) self.observation_space = spaces.Box(low=-np.inf, high=np.inf, shape=(self.lookback,self.n_features,1), dtype=np.float32) self.reset() def step(self, action): # Trade every 10 days # Normalise action space if (self.index - self.start_index) % 10 == 0: normalised_action = action / np.sum(np.abs(action)) self.actions = normalised_action done = False # Rebalance portfolio at close using return of the next date next_day_log_return = self.pricedata[self.index,:] # transaction cost transaction_cost = self.transaction_cost(self.actions,self.position_series[-1]) # Rebalancing self.position_series = np.append(self.position_series, [self.actions], axis=0) # Portfolio return today_portfolio_return = np.sum(self.actions[:-1] * next_day_log_return) + np.sum(transaction_cost) self.log_return_series = np.append(self.log_return_series, [today_portfolio_return], axis=0) # Calculate reward # Need to cast log_return in pd series to use the functions in empyrical recent_series = pd.Series(self.log_return_series)[-100:] #print(recent_series) rolling_volatility = np.std(recent_series) self.metric = today_portfolio_return / rolling_volatility reward = self.metric self.metric_series = np.append(self.metric_series, [self.metric], axis=0) # Check if the end of backtest if self.trading_days is None: done = self.index >= self.pricedata.shape[0]-2 else: done = (self.index - self.start_index) >= self.trading_days # Prepare observation for next day self.index += 1 self.observation = self.get_observation() return self.observation, reward, done, {} def reset(self): self.log_return_series = np.zeros(shape=self.lookback) self.metric_series = np.zeros(shape=self.lookback) self.position_series = np.zeros(shape=(self.lookback,self.n_assets)) self.metric = 0 if self.random_start: num_days = len(self.dates) self.start_index = np.random.randint(self.lookback, num_days - self.trading_days) self.index = self.start_index else: self.start_index = self.lookback self.index = self.lookback self.actions = np.zeros(shape=self.n_assets) self.observation = self.get_observation() return self.observation def get_observation(self): # Can use simple moving average data here last_lookback_day = self.index - self.start_index price_lookback = self.featuredata[last_lookback_day:last_lookback_day + self.lookback,:] metrics = np.vstack((self.log_return_series[last_lookback_day:last_lookback_day + self.lookback], self.metric_series[last_lookback_day:last_lookback_day + self.lookback])).transpose() positions = self.position_series[last_lookback_day:last_lookback_day + self.lookback] scaler = StandardScaler() price_lookback = scaler.fit_transform(price_lookback) observation = np.concatenate((price_lookback, metrics, positions), axis=1) return observation.reshape((observation.shape[0], observation.shape[1], 1)) # 0.05% and spread to model t-cost for institutional portfolios def transaction_cost(self, new_action, old_action): turnover = np.abs(new_action - old_action) fees = 0.9995 - self.tcostdata[self.index,:] fees = np.array(list(fees) + [0.9995]) tcost = turnover * np.log(fees) return tcost # - """ Set the training env to use random starts as made by Pavol, 506 trading days (2 years of trading) and only before the year 2014. Everything after that will be used as a dev set. We use a 60 day look back as used here https://www.oxford-man.ox.ac.uk/wp-content/uploads/2020/06/Deep-Reinforcement-Learning-for-Trading.pdf. This isn't gospel. It's a starting point The conv-net filters had beef with using different look back values for this. Instead I used 150 lookback. Will work on fixing this ^^^ """ agent_training_config = {'pricing_source':'csvdata', 'tickers':['BRK','TLT','QQQ','GLD',], 'lookback':150, 'start':'2008-01-02', 'end':'2013-12-31', 'features':["volatility_20", "skewness_20", "kurtosis_20"], 'random_start': True, 'trading_days':506} EQ_env.reset() _, rw, _, _ = EQ_env.step([ 0.4612986, -0.3883527, -0.45688114, -0.06747285, -0.1717046]) print(rw) # PPO policy from ray.rllib.agents.ppo import PPOTrainer, DEFAULT_CONFIG from ray.tune.logger import pretty_print # + #train the model using only the training data config = DEFAULT_CONFIG.copy() config['num_workers'] = 1 config["num_envs_per_worker"] = 1 config["rollout_fragment_length"] = 20 config["train_batch_size"] = 1200 config["batch_mode"] = "complete_episodes" config['num_sgd_iter'] = 20 config['sgd_minibatch_size'] = 200 config['model']['dim'] = 200 config['model']['conv_filters'] = [[32, [5, 1], 5], [32, [5, 1], 5], [4, [5, 1], 5]] config['num_cpus_per_worker'] = 2 # This avoids running out of resources in the notebook environment when this cell is re-executed config['env_config'] = agent_training_config # - # Check to see if agents can be trained agent = PPOTrainer(config, Equitydaily) best_reward = -np.inf for i in tqdm(range(500)): result = agent.train() if result['episode_reward_mean'] > best_reward + 10: path = agent.save('./sampleagent2') print(path) best_reward = result['episode_reward_mean'] print(best_reward) for i in tqdm(range(500)): result = agent.train() if result['episode_reward_mean'] > best_reward: path = agent.save('./sampleagent2') print(path) best_reward = result['episode_reward_mean'] print(best_reward) for i in tqdm(range(500)): result = agent.train() if result['episode_reward_mean'] > best_reward + 5: path = agent.save('./sampleagent2') print(path) best_reward = result['episode_reward_mean'] print(best_reward) # # Training set run """ Config an environment with the full training set data without random starts """ training_config = {'pricing_source':'csvdata', 'tickers':['BRK','TLT','QQQ','GLD',], 'lookback':150, 'start':'2008-01-02', 'end':'2013-12-31', 'features':["volatility_20", "skewness_20", "kurtosis_20"], 'random_start': False, 'trading_days':506} train_env = Equitydaily(training_config) # + state = train_env.reset() done = False reward_list = [] cum_reward = 0 actions = list() while not done: #action = agent.compute_action(state) action = agent.compute_action(state) state, reward, done, future_price = train_env.step(action) cum_reward += reward actions.append(action) reward_list.append(reward) pd.Series(reward_list).cumsum().plot() # - # # Dev set run dev_config = {'pricing_source':'csvdata', 'tickers':['BRK','TLT','QQQ','GLD',], 'lookback':150, 'start':'2014-01-01', 'end':'2016-12-31', 'features':["volatility_20", "skewness_20", "kurtosis_20"], 'random_start': False, 'trading_days':506} dev_env = Equitydaily(dev_config) # + state = dev_env.reset() done = False reward_list = [] cum_reward = 0 actions = list() while not done: #action = agent.compute_action(state) action = agent.compute_action(state) state, reward, done, future_price = dev_env.step(action) cum_reward += reward actions.append(action) reward_list.append(reward) pd.Series(reward_list).cumsum().plot() # - agent.restore('sampleagent/checkpoint_1/checkpoint-1') for i in range(5): result = agent.train() if result['episode_reward_mean'] > best_reward + 1: path = agent.save('sampleagent') print(path) best_reward = result['episode_reward_mean'] print(best_reward) result # SAC from ray.rllib.agents.sac import SACTrainer, DEFAULT_CONFIG from ray.tune.logger import pretty_print # + config = DEFAULT_CONFIG.copy() config['num_workers'] = 1 config["num_envs_per_worker"] = 1 config["rollout_fragment_length"] = 10 config["train_batch_size"] = 50 config["timesteps_per_iteration"] = 10 config["buffer_size"] = 10000 config["Q_model"]["fcnet_hiddens"] = [10, 10] config["policy_model"]["fcnet_hiddens"] = [10, 10] config["num_cpus_per_worker"] = 2 config["env_config"] = { "pricing_source": "csvdata", "tickers": ["QQQ", "EEM", "TLT", "SHY", "GLD", "SLV"], "lookback": 1, "start": "2007-01-02", "end": "2015-12-31", } # - # Train agent agent = SACTrainer(config, Equitydaily) best_reward = -np.inf for i in range(20): result = agent.train() if result['episode_reward_mean'] > best_reward + 0.01: path = agent.save('sampleagent') print(path) best_reward = result['episode_reward_mean'] print(result['episode_reward_mean']) result # Run environment config agent = PPOTrainer(config, Equitydaily) env = Equitydaily(config['env_config']) agent.restore('checkpoint_1087/checkpoint-1087') # + state = env.reset() done = False reward_list = [] cum_reward = 0 actions = list() while not done: #action = agent.compute_action(state) action = np.array([0,0,0,0,0,0,1]) state, reward, done, _ = env.step(action) cum_reward += reward actions.append(action) reward_list.append(reward) pd.Series(env.log_return_series).cumsum().plot() # - pd.Series(reward_list).plot() pd.DataFrame(actions) # Run environment for RNN environment # + env = Equitydaily({'pricing_source':'Alpaca_Equity_daily', 'tickers':['SPY','QQQ'], 'lookback':50, 'start':'2018-01-02', 'end':'2020-12-31'}) state = env.reset() done = False cum_reward = 0 actions = list() rnn_state = agent.get_policy().get_initial_state() while not done: action, rnn_state, _ = agent.compute_action(state,rnn_state) #action = np.array([1,-1]) state, reward, done, _ = env.step(action) cum_reward += reward actions.append(actions) pd.Series(env.log_return_series).cumsum().plot() # - max_drawdown(pd.Series(env.log_return_series)) annual_return(pd.Series(env.log_return_series)) class Equitydaily_v1(gym.Env): def __init__(self,env_config): self.tickers = env_config['tickers'] self.lookback = env_config['lookback'] # Load price data, to be replaced by DataLoader class raw_data = load_data(env_config['pricing_source'],env_config['tickers'],env_config['start'],env_config['end']) # Set the trading dates, features and price data self.dates = raw_data['dates'] self.fields = raw_data['fields'] self.pricedata = raw_data['pricedata'] self.featuredata = raw_data['data'] self.tcostdata = raw_data['tcost'] # Set up historical actions and rewards self.n_assets = len(self.tickers) + 1 self.n_metrics = 2 self.n_assets_fields = len(self.fields) self.n_features = self.n_assets_fields * len(self.tickers) + self.n_assets + self.n_metrics # reward function # Set up action and observation space # The last asset is cash self.action_space = spaces.Box(low=-1, high=1, shape=(len(self.tickers)+1,), dtype=np.float32) self.observation_space = spaces.Box(low=-np.inf, high=np.inf, shape=(self.lookback,self.n_features), dtype=np.float32) self.reset() def step(self, action): ## Normalise action space normalised_action = action / np.sum(np.abs(action)) done = False # Rebalance portfolio at close using return of the next date next_day_log_return = self.pricedata[self.index,:] # transaction cost transaction_cost = self.transaction_cost(normalised_action,self.position_series[-1]) # Rebalancing self.position_series = np.append(self.position_series, [normalised_action], axis=0) # Portfolio return today_portfolio_return = np.sum(normalised_action[:-1] * next_day_log_return) + np.sum(transaction_cost) self.log_return_series = np.append(self.log_return_series, [today_portfolio_return], axis=0) # Calculate reward # Need to cast log_return in pd series to use the functions in empyrical live_days = self.index - self.lookback burnin = 250 recent_series = pd.Series(self.log_return_series)[-100:] whole_series = pd.Series(self.log_return_series) if live_days > burnin: self.metric = annual_return(whole_series) + 0.5* max_drawdown(whole_series) else: self.metric = annual_return(whole_series) + 0.5* max_drawdown(whole_series) *live_days / burnin reward = self.metric - self.metric_series[-1] #reward = self.metric self.metric_series = np.append(self.metric_series, [self.metric], axis=0) # Check if the end of backtest if self.index >= self.pricedata.shape[0]-2: done = True # Prepare observation for next day self.index += 1 self.observation = self.get_observation() return self.observation, reward, done, {'current_price':next_day_log_return} def reset(self): self.log_return_series = np.zeros(shape=self.lookback) self.metric_series = np.zeros(shape=self.lookback) self.position_series = np.zeros(shape=(self.lookback,self.n_assets)) self.metric = 0 self.index = self.lookback self.observation = self.get_observation() return self.observation def get_observation(self): # Can use simple moving average data here price_lookback = self.featuredata[self.index-self.lookback:self.index,:] metrics = np.vstack((self.log_return_series[self.index-self.lookback:self.index], self.metric_series[self.index-self.lookback:self.index])).transpose() positions = self.position_series[self.index-self.lookback:self.index] observation = np.concatenate((price_lookback, metrics, positions), axis=1) return observation # 0.05% and spread to model t-cost for institutional portfolios def transaction_cost(self,new_action,old_action,): turnover = np.abs(new_action - old_action) fees = 0.9995 - self.tcostdata[self.index,:] tcost = turnover * np.log(fees) return tcost
Aidan/RL_PAVOL_test.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # This notebook reproduces # # > **Fig 11**: Stark states of $n=30$ and 31 states of Ps, with $m=2$ (grey dashed) and $m=29$ (black). In the $n=30$ level, the $m=29$ state is a circular state and experiences no first-order Stark shift and only a very weak second-order shift, as explained in the text. # # from the article # # > #### Prospects for Studies of the Free Fall and Gravitational Quantum States of Antimatter # > # > <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. # > # > *Adv. High En. Phys.*, **2015**, 379642 (2015) [DOI:10.1155/2015/379642](https://dx.doi.org/10.1155/2015/379642) # # This article uses an $|\, n \, l \, m_l \, \rangle$ basis and plots the Stark structure for $m_l=2$ and $m_l=29$. # # The calculation below uses an $|\, n \, l \, S \, J \, M_J \, \rangle$ basis with $S=0$ and plots Stark structure for $M_J = 2$ and $M_J=29$. # packages import os from functools import reduce from hsfs import Hamiltonian, En_h, h, c, constants_info, rad_overlap, mu_me import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl # %matplotlib inline mpl.rcParams['axes.formatter.useoffset'] = False # # Crossed fields, $n=20-21$ # construct matrix n_min = 20 n_max = 21 S = None mat0 = Hamiltonian(n_min=n_min, n_max=n_max, S=S, MJ_max=None) print('Number of basis states:', '%d'%mat0.num_states) # calculate Stark map Bfield=0.1 Efield_vec=[1.0,0.0,0.0] Efield = np.linspace(4.5*10**2, 6.0*10**2, 31) # V /cm sm0 = mat0.stark_map(Efield*1e2, Bfield=Bfield, Efield_vec=Efield_vec, singlet_triplet_coupling=False, cache_matrices=True, load_matrices=False, save_matrices=True, matrices_dir='./saved_matrices/') sm1 = mat0.stark_map(Efield*1e2, Bfield=Bfield, Efield_vec=Efield_vec, singlet_triplet_coupling=True, cache_matrices=True, load_matrices=False, save_matrices=True, matrices_dir='./saved_matrices/') # + fig, ax = plt.subplots(figsize=(9, 7)) indexes = range(mat0.num_states) for ix in indexes: ax.plot(Efield, sm0[:, ix] / (100*h*c*mu_me), ls='-', lw=1.0, alpha=1, c=(0.2, 0.2, 0.8)) indexes = range(mat0.num_states) for ix in indexes: ax.plot(Efield, sm1[:, ix] / (100*h*c*mu_me), ls='--', lw=1.2, alpha=0.8, c=(0.8, 0.2, 0.2)) # format ax.set_xlabel('electric field (V cm$^{-1}$)') ax.set_ylabel('energy / $h c$ (cm$^{-1}$)') ax.set_xlim(450, 600) ax.set_ylim(-266, -260) # output plt.grid() plt.title('Stark map - n,L,S,J,MJ \n' + \ 'n='+str(n_min)+'-'+str(n_max)+ ', ' + \ 'S=' + str(S) + ', ' + \ 'E_vec='+str(Efield_vec) + ', ' + \ 'B='+str(Bfield)) plt.tight_layout() plt.savefig('singlet-triplet-sm.pdf') # - # # Crossed fields, $n=5-6$ # construct matrix n_min = 5 n_max = 6 S = None mat0 = Hamiltonian(n_min=n_min, n_max=n_max, S=S, MJ_max=None) print('Number of basis states:', '%d'%mat0.num_states) # calculate Stark map Bfield=10.0 Efield_vec=[1.0,0.0,0.0] Efield = np.linspace(3.0*10**5, 6.0*10**5, 501) # V /cm sm0 = mat0.stark_map(Efield*1e2, Bfield=Bfield, Efield_vec=Efield_vec, singlet_triplet_coupling=False, cache_matrices=True, load_matrices=False, save_matrices=True, matrices_dir='./saved_matrices/') sm1 = mat0.stark_map(Efield*1e2, Bfield=Bfield, Efield_vec=Efield_vec, singlet_triplet_coupling=True, cache_matrices=True, load_matrices=False, save_matrices=True, matrices_dir='./saved_matrices/') # + fig, ax = plt.subplots(figsize=(9, 7)) # plot #MJ = 0 indexes = range(mat0.num_states) #indexes = mat0.where('J', 11) for ix in indexes: ax.plot(Efield, sm0[:, ix] / (100*h*c*mu_me), ls='-', lw=1.2, alpha=1, c=(0.2, 0.2, 0.8)) #MJ = 1 indexes = range(mat0.num_states) for ix in indexes: ax.plot(Efield, sm1[:, ix] / (100*h*c*mu_me), ls='--', lw=1., alpha=1, c=(0.8, 0.2, 0.2)) # format ax.set_xlabel('electric field (V cm$^{-1}$)') ax.set_ylabel('energy / $h c$ (cm$^{-1}$)') ax.set_xlim(3.0*10**5, 6.0*10**5) ax.set_ylim(-4200, -3700) plt.title('Stark map - n,L,S,J,MJ \n' + \ 'n='+str(n_min)+'-'+str(n_max)+ ', ' + \ 'S=' + str(S) + ', ' + \ 'E_vec='+str(Efield_vec) + ', ' + \ 'B='+str(Bfield)) # output plt.grid() plt.tight_layout() # - constants_info()
notebooks/Stark map - n,L,S,J,MJ.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/DongUk-Park/i_coma/blob/main/California_Colab_Test" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="lQzzKtSUQEyz" # # 캘리포니아 집값 분석 # $price(age) = e^2 * 100 # # + id="OLy2cuiRQXw6" import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # + id="GKd1VALNQkER" train = pd.read_csv('/content/sample_data/california_housing_train.csv') test = pd.read_csv('/content/sample_data/california_housing_test.csv') # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="Tm03u2DCQ6M1" outputId="aff8eb3e-0eb8-4049-d536-1a09d7c09716" test.head() # + colab={"base_uri": "https://localhost:8080/", "height": 364} id="SOsSExsyQ8Lm" outputId="6ec9cb29-bd4d-42f3-db96-9f669492c8ff" train.describe() # + colab={"base_uri": "https://localhost:8080/", "height": 771} id="_Lqkp8r9Q-r-" outputId="ca2157ae-c9ac-472d-9bd3-e78239730926" train.hist(figsize=(15,13) , grid = False , bins = 50) plt.show() # + id="wFBWx15tRG6H" correlation = train.corr() # + colab={"base_uri": "https://localhost:8080/", "height": 691} id="e9KKvVcXRJ7G" outputId="d23d6d27-d137-4347-b7ed-8a52c7345778" plt.figure(figsize = (10,10)) sns.heatmap(correlation , annot = True) plt.show()
California_Colab_Test.ipynb