repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list | possible_versions
list |
---|---|---|---|---|---|
djhn75/RNAEditor
|
[
"5fa841400014ce18e3b6ac6789dbf08897ef45ed"
] |
[
"VariantSet.py"
] |
[
"'''\nCreated on 05.06.2014\n\n@author: david\n'''\nfrom Helper import Helper\nfrom collections import defaultdict, OrderedDict\nimport os\nimport operator\nfrom copy import copy\n#from exceptions import KeyError\nfrom Genome import Genome\nimport collections\nimport numpy as np\nfrom random import shuffle\nimport sys\nfrom pysam import Samfile\nfrom Gene import Gene\n\nclass Variant:\n '''\n reflects a Variant\n '''\n\n def __init__(self, chromosome, position, id, ref, alt, qual, filter, info):\n self.chromosome = chromosome\n self.position = position\n self.id = id\n self.ref = ref\n self.alt = alt\n self.qual = qual\n self.filter = filter\n self.attributes = info\n \n def __iter__(self):\n return self.var\n\nclass VariantSet(object):\n '''\n handles a vcfFile and stores the results internally as a Dictionary with Tuple of (chromosome,pos,ref,alt) as keys and a the VariantObject as value\n '''\n def __init__(self,vcfFile,logFile=None,textField=0):\n self.logFile=logFile\n self.textField=textField\n self.variantDict = self.parseVcf(vcfFile)\n #return self.parseVcfFile_variantSetByChromosome(vcfFile)\n \n def __iter__(self):\n return iter((self.variantDict.values()))\n \n def __add__(self,other):\n newVariantSet = copy(self)\n newDict = {}\n newDict.update(self.variantDict)\n newDict.update(other.variantDict)\n newVariantSet.variantDict=newDict\n return newVariantSet\n \n def readline(self,line):\n '''\n process one line of the vcf file\n <chromosome> <position> <identifier> <reference_base> <alternative_base> <quality> <filter> {attributes}\n '''\n vcfList = line.rstrip().split(\"\\t\")\n \n try:\n vcfList[1] = int(vcfList[1]) #position of SNP\n vcfList[5] = float(vcfList[5]) if vcfList[5] !=\".\" else 0.0\n\n except ValueError:\n raise ValueError(\"Error in line '%s'\" % \" \".join(line))\n\n #parse info\n info = vcfList[7]\n #trim comments\n info=info[:info.find(\"#\")].rstrip()\n \n values = map(lambda x: x.strip(), info.split(\";\"))\n #[:-1])\n \n attributes={}\n for info in values:\n info = map( lambda x: x.strip(), info.split(\"=\"))\n if len(info)>1:\n name, value=info[0], info[1]\n try:\n value=float(value)\n value=int(value)\n except ValueError:\n pass\n except TypeError:\n pass \n \n if name == \"BaseCounts\":\n value=value.replace(\"'\",\"\")\n value=value.replace(\"[\",\"\")\n value=value.replace(\"]\",\"\")\n value = value.split(\",\")\n if name == \"GI\":\n a=[]\n for anno in value.split(\",\"):\n #TODO: Delete the next line later, this is because of a tailing comma which was removed\n if anno==\"\": continue\n gene,segments=anno.split(\":\")\n a.append((gene,set(segments.split(\"|\"))))\n value=a\n attributes[name]=value\n \n vcfList[7]=attributes \n return vcfList\n \n def checkVariantType(self,variants):\n '''\n Checks if the type of the argument is a str or a file\n returns a dictionary of all the variants\n '''\n if type(variants) == dict:\n return variants\n elif type(variants) == file or type(variants) == str:\n variants = self.parseVcf(variants)\n return variants\n \n else: \n raise TypeError(\"variants has wrong type, need variantDict, str or file, %s found\" % type(variants))\n \n def iterator(self,infile):\n while True:\n line = infile.readline()\n if not line: raise StopIteration\n if line.startswith(\"#\"): continue #skip comments\n vcfList=self.readline(line)\n variant = Variant(vcfList[0],vcfList[1],vcfList[2],vcfList[3],vcfList[4],vcfList[5],vcfList[6],vcfList[7])\n yield variant\n \n def getVarPosListByChromosome(self):\n '''\n return: all the variant positions by chromosome\n {\"1\":[4,6,8,45,67],\"2\":[6,9,67,69].....}\n This is only needed for the cluster algorithm later on\n '''\n varPosList=defaultdict(list)\n for v in self.variantDict.values():\n varPosList[v.chromosome].append(v.position)\n \n #make numpy array out of the lists\n for chromosome in varPosList.keys():\n varPosList[chromosome]=np.asarray(varPosList[chromosome])\n return varPosList\n \n def getVariantListByChromosome(self):\n '''\n @return: variants as Dictionary with chromosome as key and a list of VariantObjects as values\n {\"1\":[VariantObject1,VariantObject2....],\"2\":[VariantObject1,VariantObject2....]}\n '''\n variantsByChromosome = defaultdict(list)\n for v in self.variantDict.values():\n variantsByChromosome[v.chromosome].append(v)\n \n #Helper.printTimeDiff(startTime)\n return variantsByChromosome\n \n def parseVcf(self,vcfFile):\n '''\n Imports a given Variant File and returns the variants as Dictionary with Tuple of (chromosome,pos,ref,alt) as key and a the VariantObject as value\n {(1,45435,\"A\",\"G\"):VariantObject1,(1,45435,\"A\",\"G\"):VariantObject1,.....}\n \n '''\n startTime = Helper.getTime()\n Helper.info(\" [%s] Parsing Variant Data from %s\" % (startTime.strftime(\"%c\"),vcfFile),self.logFile,self.textField)\n \n #check correct Type\n if type(vcfFile) == str:\n if os.path.getsize(vcfFile) == 0: #getsize raises OSError if file is not existing\n raise IOError(\"%s File is empty\" % vcfFile)\n vcfFile = open(vcfFile,\"r\")\n elif type(vcfFile) != file:\n raise TypeError(\"Invalid type in 'parseVcfFile' (need string or file, %s found)\" % type(vcfFile)) \n \n variantDict = OrderedDict()\n for v in self.iterator(vcfFile):\n variantDict[(v.chromosome,v.position,v.ref,v.alt)]=v\n #variantDict[(v.chromosome,v.position)]=v\n \n Helper.printTimeDiff(startTime,self.logFile,self.textField)\n return variantDict\n \n def printVariantDict(self,outfile):\n '''\n print the variants from the dictionary to the outfile if defined\n '''\n if type(outfile) == str:\n try:\n outfile=open(outfile,\"w\")\n except IOError:\n Helper.warning(\"Could not open %s to write Variant\" % outfile ,self.logFile,self.textField)\n if type(outfile) != file: \n raise AttributeError(\"Invalid outfile type in 'printVariantDict' (need string or file, %s found)\" % type(outfile))\n \n startTime=Helper.getTime()\n Helper.info(\"[%s] Print Variants to %s\" % (startTime.strftime(\"%c\"),outfile.name),self.logFile,self.textField)\n \n outfile.write(\"\\t\".join([\"#CHROM\", \"POS\", \"ID\", \"REF\", \"ALT\", \"QUAL\", \"FILTER\", \"INFO\", \"\\n\"]))\n for v in self.variantDict.values():\n attributeString=\"\"\n for key in v.attributes.keys():\n if key==\"BaseCounts\":\n attributeString+= \"BaseCounts=\" + \",\".join(v.attributes[\"BaseCounts\"]) + \";\"\n continue \n elif key ==\"GI\":\n a=\"\"\n for anno in v.attributes[\"GI\"]:\n gene,segment = anno\n if gene == \"-\":\n a += gene+\":\"+\"|\".join(segment) \n else:\n if type(gene)==str: #when variantDict was not annotated yet\n a+=gene +\":\"+\"|\".join(segment)+\",\"\n else: \n a+=gene.names[0]+\":\"+\"|\".join(segment)+\",\"\n \n attributeString+=key+\"=\"+a[:-1]+\";\"\n continue\n attributeString+= key+\"=\"+str(v.attributes[key])+\";\"\n outfile.write(\"\\t\".join([v.chromosome,str(v.position),v.id,v.ref,v.alt,str(v.qual),v.filter, attributeString+\"\\n\"])) \n\n\n def topGenes(self,sumDict, fileName,number=20,value=4):\n if number > len(sumDict):\n if len(sumDict)<1:\n Helper.warning(\"no edited genes found\", self.logFile, self.textField)\n return\n Helper.warning(\"The number of top genes you wanted is bigger than the number of edited genes\", self.logFile, self.textField)\n number=len(sumDict)\n if value > 4:\n Helper.error(\"sumDict only hold four values\", self.logFile, self.textField)\n \n \n counts=collections.OrderedDict(sorted(sumDict.items(), key=lambda t: t[1][value],reverse=True)[:number])\n barNameTuple=()\n valueMatrix=[[]]\n for array in counts.values():\n valueMatrix[0].append(array[value])\n for gene in counts.keys():\n barNameTuple+=(gene.names[0],)\n\n if value==0:\n barName=\"3'-UTR\"\n elif value==1:\n barName=\"5'-UTR\"\n elif value==2:\n barName=\"Exonic\"\n elif value==3:\n barName=\"Intronic\"\n elif value==4:\n barName=\"Total\"\n \n yLim=max(max(i) for i in valueMatrix)+1\n Helper.createBarplot(valueMatrix, fileName, barNameTuple, [barName], width=0.35, title=\"Highly Edited Genes\",yLim=yLim,barText=False,yText=\"Editing Counts\")\n\n def printGeneList(self,genome,outfile,printSummary=True):\n '''\n print List of genes with all the variants\n Gene-Variation-File\n \"Gene_ID\",\"gene_Name\",\"SEGMENT\",\"#CHROM\",\"GENE_START\",\"GENE_STOP\",\"VAR_POS\",\"REF\",\"ALT\",\"QUAL\",\"BaseCount(A,C,T,G)\"\n \n Gene Summary File\n \"Gene_ID\",Gene_Name,#3'UTR,#5'UTR,#EXON,'INTRON,#TOTAL\n :param genome: object of class Genome\n :param outfile: \n :param printSummary: boolean wether to print summary-file\n '''\n\n sumDict={}\n \n if type(genome) != Genome:\n raise AttributeError(\"Type of genome is %s, but has to be an object of Genome\" % type(genome))\n \n if type(outfile) == str:\n try:\n outfile=open(outfile,\"w\")\n \n except IOError:\n Helper.warning(\"Could not open %s to write Variant\" % outfile ,self.logFile,self.textField)\n if type(outfile) != file: \n raise AttributeError(\"Invalid outfile type in 'printVariantDict' (need string or file, %s found)\" % type(outfile))\n \n startTime=Helper.getTime()\n Helper.info(\"[%s] Print Genes and Variants to %s\" % (startTime.strftime(\"%c\"),outfile.name),self.logFile,self.textField)\n \n sumFile=open(outfile.name[:outfile.name.rfind(\".\")]+\".summary\",\"w\") \n \n outfile.write(\"\\t\".join([\"#Gene_ID\",\"Name\",\"SEGMENT\",\"#CHROM\",\"GENE_START\",\"GENE_STOP\",\"VAR_ID\",\"VAR_POS\",\n \"REF\",\"ALT\",\"QUAL\",\"#A\",\"#C\",\"#G\",\"#T\",\"Reads_Total\",\"Edited_Reads\",\"Editing_Ratio\",\"\\n\"]))\n \n for v in self.variantDict.values():\n anno = v.attributes[\"GI\"]\n for a in anno:\n gene,segments = a\n totalReads=str(int(sum(map(int,v.attributes[\"BaseCounts\"]))))\n if v.ref ==\"A\" and v.alt == \"G\":\n editedReads=str(v.attributes[\"BaseCounts\"][2])\n ratio=str(round(float(editedReads)/float(totalReads),2))\n elif (v.ref==\"T\" and v.alt==\"C\"):\n editedReads=str(v.attributes[\"BaseCounts\"][1])\n ratio=str(round(float(editedReads)/float(totalReads),2))\n else:\n editedReads=\"0\"\n ratio=\"0\"\n \n \n if gene == \"-\":\n out=[\"-\", \"-\",\",\".join(segments),v.chromosome,\"-\",\"-\",v.id,str(v.position),\n v.ref,v.alt,str(v.qual),\"\\t\".join(v.attributes[\"BaseCounts\"]),totalReads,editedReads,ratio,\"\\n\"]\n outfile.write(\"\\t\".join(out))\n else:\n out=[gene.geneId, gene.names[0],\",\".join(segments),v.chromosome,str(gene.start),str(gene.end),v.id,str(v.position),\n v.ref,v.alt,str(v.qual),\"\\t\".join(v.attributes[\"BaseCounts\"]),totalReads,editedReads,ratio,\"\\n\"]\n outfile.write(\"\\t\".join(out))\n \n #count variations per gene\n if gene not in sumDict:\n sumDict[gene]= [0,0,0,0,0]\n \n for seg in segments:\n if seg == \"3'UTR\":\n sumDict[gene][0]+=1\n elif seg == \"5'UTR\":\n sumDict[gene][1]+=1\n elif seg in (\"coding-exon\",\"noncoding-exon\"):\n sumDict[gene][2]+=1\n elif seg == \"intron\":\n sumDict[gene][3]+=1\n sumDict[gene][4]+=1\n \n \n\n \n #print number of variants per gene\n if printSummary:\n\n \n sumDictGeneIds=set()\n sumFile.write(\"\\t\".join([\"#Gene_ID\",\"Name\",\"#3'UTR\",\"#5'UTR\",\"#EXON\",\"INTRON\",\"#TOTAL\",\"\\n\"]))\n for gene in sumDict.keys():\n numbers=map(str,sumDict[gene])\n if gene==\"-\":\n sumFile.write(\"\\t\".join([\"intergenic\",\"-\"]+[\"-\",\"-\",\"-\",\"-\",numbers[4]]+[\"\\n\"]))\n else:\n sumFile.write(\"\\t\".join([gene.geneId,gene.names[0]]+numbers+[\"\\n\"]))\n sumDictGeneIds.add(gene.geneId) \n #print non effected Genes\n #this was added to have the whole set og genes in the summary file\n #so that it is easier to compare results in Excel\n genesByGeneId=genome.getGenesByGeneID()\n a=set(genesByGeneId.keys())\n b=sumDictGeneIds\n nonEffectedGenes = a-b\n for geneId in nonEffectedGenes:\n gene=genesByGeneId[geneId]\n sumFile.write(\"\\t\".join([gene.geneId,gene.names[0]]+[\"0\",\"0\",\"0\",\"0\",\"0\",]+[\"\\n\"]))\n \n ################################################################\n ############ Draw Barplots with high edited Genes ###########\n ################################################################\n '''\n outdir = outfile.name[:outfile.name.rfind(\"/\")+1]\n tmp=outfile.name[outfile.name.rfind(\"/\")+1:]\n sampleName=tmp[:tmp.find(\".\")\n ]\n fileName=outdir+\"html/\"+sampleName+\".editedGenes(3UTR).png\"\n self.topGenes(sumDict,fileName, 20, 0)\n \n fileName=outdir+\"html/\"+sampleName+\".editedGenes(5UTR).png\"\n self.topGenes(sumDict,fileName, 20, 1)\n \n fileName=outdir+\"html/\"+sampleName+\".editedGenes(Exon).png\"\n self.topGenes(sumDict,fileName, 20, 2)\n \n fileName=outdir+\"html/\"+sampleName+\".editedGenes(Intron).png\"\n self.topGenes(sumDict,fileName, 20, 3)\n \n fileName=outdir+\"html/\"+sampleName+\".editedGenes(Total).png\"\n \n if \"-\" in sumDict.keys():\n del sumDict[\"-\"] #delete intergenics, because we only we only want to show highly edited Genes!!!\n self.topGenes(sumDict,fileName, 20, 4)\n '''\n \n def printClusters(self, outFile):\n \n if type(outFile) == str:\n try:\n outFile=open(outFile,\"w\")\n \n except IOError:\n Helper.warning(\"Could not open %s to write Variant\" % outFile ,self.logFile,self.textField)\n if type(outFile) != file: \n raise AttributeError(\"Invalid outfile type in 'printVariantDict' (need string or file, %s found)\" % type(outFile))\n \n startTime=Helper.getTime()\n Helper.info(\"[%s] Print Clusters to %s\" % (startTime.strftime(\"%c\"),outFile.name),self.logFile,self.textField)\n \n \n outFile.write(\"\\t\".join([\"#Chr\",\"Start\",\"Stop\",\"IslandID\",\"GeneID\",\"Gene Symbol\",\"Cluster Length\",\"Number of Editing_sites\",\"Editing_rate\",\"\\n\"]))\n \n for cluster in self.clusterDict.keys():\n end = max(v.position for v in self.clusterDict[cluster])\n start = min(v.position for v in self.clusterDict[cluster])\n \n length = end - start\n editingRate=float(len(self.clusterDict[cluster]))/float(length)\n geneIdSet=set()\n geneNameSet=set()\n for v in self.clusterDict[cluster]:\n try: \n gene = v.attributes['GI'][0][0]\n if type(gene) == Gene:\n geneIdSet.add(gene.geneId)\n geneNameSet |= set(gene.names)\n #geneList.append(v.attributes['GI'][0][0])\n else:\n geneIdSet.add(\"Intergenic\")\n geneNameSet.add(\"Intergenic\")\n except KeyError:\n geneIdSet.add(\"N/A\") #when variant has no attribute GI\n \n outFile.write(\"\\t\".join([v.chromosome,str(start),str(end),\"Island\"+str(cluster), #Chr\",\"Start\",\"Stop\",\"Cluster Name\",\n \",\".join(map(str,geneIdSet)),\",\".join(map(str,geneNameSet)), #\"GeneID\",\"Gene Symbol\"\n str(length),str(len(self.clusterDict[cluster])),'%1.2f'%float(editingRate),\"\\n\"]))\n \n def getVariantTuble(self,line):\n '''\n returns a tuple of (chromosome, position, alt, ref) from a line of a vcfFile\n '''\n line=line.split(\"\\t\")\n try:\n for alt in line[4].split(\",\"):\n tuple = (line[0],int(line[1]),line[3],alt)\n yield tuple\n except IndexError:\n raise ValueError(\"Error in line '%s'\" % \" \".join(line))\n \n def getVariantByGene(self):\n '''\n Returns a dictionary with geneId as key and all the variants on the gene as values\n The genes are also sorted\n {\"1\":[Gene1,Gene2....]} \n '''\n variantByGene=defaultdict(set)\n \n try:\n for v in self.variantDict.values():\n for anno in v.attributes[\"GI\"]:\n gene,segment = anno\n variantByGene[gene].add(v)\n except KeyError:\n raise KeyError(\"Variant has no attribute GI. Try to run 'annotateVariantDict' before to get GeneInfo\")\n return variantByGene\n \n def deleteOverlapsFromVcf(self,variants):\n '''\n delete the variants from 'variantsA' which also are in 'variantsB'\n '''\n\n variantSetA = set(self.variantDict.keys())\n \n #detrmine type of variantB\n if type(variants) == str:\n variantsB = open(variants)\n elif type(variants) != file:\n raise TypeError(\"variantB has wrong type, need str or file, %s found\" % type(variantsB))\n #TODO: variants could also be another object of VariantsSet\n \n #get Start time\n startTime = Helper.getTime()\n Helper.info(\" [%s] Delete overlapps from %s\" % (startTime.strftime(\"%c\"),variantsB.name),self.logFile,self.textField)\n\n for line in variantsB:\n if line.startswith(\"#\"):\n continue\n for varTuple in self.getVariantTuble(line):\n if varTuple in variantSetA:\n #A.discard(varTuple)\n variantSetA.remove(varTuple)\n del self.variantDict[varTuple]\n \n #calculate duration \n Helper.printTimeDiff(startTime,self.logFile,self.textField)\n \n def getOverlapsFromBed(self,bedFile,getNonOverlaps=False):\n '''\n returns overlaps from bed file features\n :param bedFile: as string or file\n :param getNonOverlaps: boolean\n :return new variantSet of overlaps \n '''\n \n if type(bedFile) == str:\n bedFile = open(bedFile)\n elif type(bedFile) != file:\n raise TypeError(\"bedFile has wrong type, need str or file, %s found\" % type(bedFile))\n \n startTime=Helper.getTime()\n Helper.info(\"[%s] Delete overlaps from %s\" % (startTime.strftime(\"%c\"),bedFile.name) ,self.logFile,self.textField)\n \n variantsByChromosome = self.getVariantListByChromosome() \n overlapps = set()\n for line in bedFile:\n try:\n sl = line.split(\"\\t\") \n #if \"\\t\" in line else line.split(\" \")\n chromosome,start,stop = sl[:3]\n start,stop=(int(start),int(stop))\n except ValueError:\n raise ValueError(\"Error in line '%s'\" % line)\n \n for v in variantsByChromosome[chromosome]:\n if start < v.position < stop:\n overlapps.add((v.chromosome,v.position,v.ref,v.alt))\n \n if getNonOverlaps:\n overlapps = set(self.variantDict.keys()) - overlapps #delete all accept the ones which are overlapping\n \n newSet={}\n for variantTuple in overlapps:\n #del self.variantDict[variantTuple]\n newSet[variantTuple]=self.variantDict[variantTuple]\n \n Helper.printTimeDiff(startTime, self.logFile,self.textField)\n return newSet\n \n def splitByBed(self,bedFile):\n '''\n returns overlaps and nonOverlaps from bed file features\n :param bedFile: as string or file\n :param getNonOverlaps: boolean\n '''\n \n if type(bedFile) == str:\n bedFile = open(bedFile)\n elif type(bedFile) != file:\n raise TypeError(\"bedFile has wrong type, need str or file, %s found\" % type(bedFile))\n \n startTime=Helper.getTime()\n Helper.info(\"[%s] Split Variants by Bed File %s\" % (startTime.strftime(\"%c\"),bedFile.name) ,self.logFile,self.textField)\n \n variantsByChromosome = self.getVariantListByChromosome() \n overlapSet = set()\n i=0\n for line in bedFile:\n \n try:\n sl = line.split(\"\\t\") \n #if \"\\t\" in line else line.split(\" \")\n chromosome,start,stop = sl[:3]\n start,stop=(int(start),int(stop))\n except ValueError:\n raise ValueError(\"Error in line '%s'\" % line)\n \n for v in variantsByChromosome[chromosome]:\n if start < v.position < stop:\n overlapSet.add((v.chromosome,v.position,v.ref,v.alt))\n i+=1\n if i %100000==0:\n Helper.status(\"%s Bed Feautes parsed\" % i, self.logFile,self.textField,\"grey\")\n \n \n Helper.info(\"finished parsing Bed file\", self.logFile,self.textField)\n Helper.printTimeDiff(startTime, self.logFile,self.textField)\n \n #nonOverlapSet = set(self.variantDict.keys()) - overlapSet #delete all accept the ones which are overlapping\n \n \n overlaps = {key: self.variantDict[key] for key in self.variantDict if key in overlapSet}\n \n Helper.info(\"finished creating overlaps\", self.logFile,self.textField)\n Helper.printTimeDiff(startTime, self.logFile,self.textField)\n \n nonOverlaps = {key: self.variantDict[key] for key in self.variantDict if key not in overlapSet}\n \n \"\"\"\n overlaps={}\n for variantTuple in overlapSet:\n #del self.variantDict[variantTuple]\n overlaps[variantTuple]=self.variantDict[variantTuple]\n \n nonOverlaps={}\n for variantTuple in nonOverlapSet:\n nonOverlaps[variantTuple]=self.variantDict\n \"\"\"\n \n Helper.printTimeDiff(startTime, self.logFile,self.textField)\n return overlaps, nonOverlaps\n\n def sortVariantDict(self,variantDict):\n '''\n Sorts a VariantDictionary by the variant position\n :param variantDict:\n '''\n #if type(variantDict) != list:\n # raise TypeError(\"variants has wrong type, need variantDict, %s found\" % type(variantDict))\n for key in variantDict.keys():\n variantDict[key] = sorted(variantDict[key], key=operator.attrgetter('position'))\n\n def annotateVariantDict(self,genome):\n '''\n adds the corresponding Gene and the exact segment wehre the SNP appears\n :param genome: Genome\n '''\n startTime = Helper.getTime()\n Helper.info(\" [%s] Annotating Variants\" % (startTime.strftime(\"%c\")),self.logFile,self.textField)\n for v in self.variantDict.values():\n anno = genome.annotatePosition(v.chromosome,v.position) #[(gene1,segment1;segment2;..)..]\n GI=[]\n for a in anno:\n GI.append(a)\n v.attributes[\"GI\"]=GI\n \n Helper.printTimeDiff(startTime,self.logFile,self.textField)\n \n def createClusters(self,eps=50,minSamples=5):\n \n islandCounter=0\n eps=int(eps)\n minSamples=int(minSamples)\n variantsByChromosome = self.getVariantListByChromosome()\n self.clusterDict=defaultdict(list)\n for chr in variantsByChromosome.keys():\n posList = [v.position for v in variantsByChromosome[chr]] #position of all variants from that chromosome\n \n labels = self.getLabels(posList,eps,minSamples) #actually doing db clustering\n n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n \n \n if n_clusters_ > 0:\n #loop over labels and variants\n tmpDict=defaultdict(list)\n for var,label in zip(variantsByChromosome[chr],labels):\n #clusterdict{1:[var1,var2],2:[var5,var8]}\n if label==-1:\n continue\n \n tmpDict[label].append(var)\n \n #set new label for clusterdict, to avoid overwriting\n for label in tmpDict.keys():\n self.clusterDict[islandCounter]=tmpDict.pop(label)\n islandCounter+=1\n \n def getLabels(self,positionList,eps=10, minSamples=5):\n \"\"\"Perform DBSCAN clustering from vector array.\n \n Parameters\n ----------\n X: array [int1,int1]\n Array of Samples. \n In this case it should be the positions of the variations in the genome per chromosome\n \n eps: float, optional\n The maximum distance between two samples for them to be considered\n as in the same neighborhood.\n \n minSamples: int, optional\n The number of samples in a neighborhood for a point to be considered\n as a core point.\n \n \n Returns\n -------\n core_samples: array [n_core_samples]\n Indices of core samples.\n \n labels : array [n_samples]\n Cluster labels for each point. Noisy samples are given the label -1.\n \n \"\"\"\n if not eps > 0.0:\n raise ValueError(\"eps must be positive.\")\n \n X = np.asarray(positionList)\n n = X.shape[0] #get number of elements (not sure) \n \n index_order=range(n)\n shuffle(index_order)\n \n \n distanceMatrix = self.calculate1dDistanceMatrix(X,eps)\n \n # Calculate neighborhood for all samples. This leaves the original point\n # in, which needs to be considered later (i.e. point i is the\n # neighborhood of point i. While True, its useless information)\n \n #distanceMatrix = [np.where(x <= eps)[0] for x in distanceMatrix]\n \n # Initially, all samples are noise.\n labels = -np.ones(n, dtype=np.int)\n \n # A list of all core samples found.\n core_samples = []\n \n # label_num is the label given to the new cluster\n label_num = 0\n \n # Look at all samples and determine if they are core.\n # If they are then build a new cluster from them.\n for index in index_order:\n # Already classified\n if labels[index] != -1:\n continue\n \n # get neighbors from distanceMatrix or ballTree\n index_neighborhood = []\n \n index_neighborhood = distanceMatrix[index]\n \n \n # Too few samples to be core\n if len(index_neighborhood) < minSamples:\n continue\n \n core_samples.append(index)\n labels[index] = label_num\n # candidates for new core samples in the cluster.\n candidates = [index]\n \n while len(candidates) > 0:\n new_candidates = []\n # A candidate is a core point in the current cluster that has\n # not yet been used to expand the current cluster.\n for c in candidates:\n c_neighborhood = []\n \n c_neighborhood = distanceMatrix[c]\n \n noise = np.where(labels[c_neighborhood] == -1)[0] #indexes of candidate neigbours which do not belong to a cluster yet\n noise = c_neighborhood[noise]\n labels[noise] = label_num\n for neighbor in noise:\n n_neighborhood = []\n \n n_neighborhood = distanceMatrix[neighbor]\n \n # check if its a core point as well\n if len(n_neighborhood) >= minSamples:\n # is new core point\n new_candidates.append(neighbor)\n core_samples.append(neighbor)\n # Update candidates for next round of cluster expansion.\n candidates = new_candidates\n # Current cluster finished.\n # Next core point found will start a new cluster.\n label_num += 1\n #return core_samples, labels\n \n return labels\n \n def calculate1dDistanceMatrix(self,lst,eps):\n '''\n creates a distance matrix for the given vector\n :param lst: vector of samples \n :return: np.array(diffMatrix)\n '''\n if not isinstance(lst, (list, tuple, np.ndarray)):\n raise TypeError(\"Paramer has to be eithe a List or a Tuple found %s\" % type(lst))\n if not all(isinstance(item, (int,float)) for item in lst):\n raise TypeError(\"List should only contain numbers\")\n lst = np.asarray(lst)\n diffMatrix=[]\n\n for l1 in lst:\n diffList=[]\n \n diffList= abs(lst-l1)\n diffList = np.where(diffList<=eps)[0]\n diffMatrix.append(diffList)\n\n return np.asarray(diffMatrix)\n\n def deleteNonEditingBases(self):\n startTime=Helper.getTime()\n Helper.info(\"Delete non Editing Bases (keep only T->C and A->G)\",self.logFile,self.textField)\n \n for varTuple in self.variantDict.keys():\n chr,pos,ref,alt = varTuple\n if (ref ==\"A\" and alt == \"G\") or (ref==\"T\" and alt==\"C\"):\n pass\n else:\n del self.variantDict[varTuple]\n\n def __len__(self):\n return len(self.variantDict)\n \n def removeEdgeMismatches(self,bamFile,minDistance, minBaseQual):\n startTime=Helper.getTime()\n minDistance=int(minDistance)\n counter=0;j=0 \n num_lines = len(self.variantDict)\n Helper.info(\" [%s] remove Missmatches from the first %s bp from read edges\" % (startTime.strftime(\"%c\"),str(minDistance)),self.logFile,self.textField)\n \n bamFile = Samfile(bamFile, \"rb\")\n \n for varKey in self.variantDict.keys():\n variant = self.variantDict[varKey]\n \n counter+=1\n if counter%10000==0:\n Helper.status('%s mm parsed ' % counter ,self.logFile, self.textField,\"grey\")\n \n keepSNP=False\n varPos=variant.position-1\n iter = bamFile.pileup(variant.chromosome, variant.position-1, variant.position)\n #walks up the region wich overlap this position\n for x in iter:\n if x.pos == varPos:\n for pileupread in x.pileups: #walk through the single reads\n if not pileupread.is_del and not pileupread.is_refskip:\n distance=abs(pileupread.alignment.alen-pileupread.query_position) if pileupread.alignment.is_reverse else pileupread.query_position\n if distance >= minDistance:\n #check readBase and Base Quality\n if pileupread.alignment.query_sequence[pileupread.query_position] == variant.alt and pileupread.alignment.query_qualities[pileupread.query_position]>=minBaseQual:\n #if pileupread.alignment.query_sequence[pileupread.query_position] == variant.alt:\n keepSNP=True\n \n if keepSNP==False:\n j+=1\n del self.variantDict[varKey]\n \n Helper.status('%s of %svariants were deleted' % (j,num_lines), self.logFile, self.textField,\"black\") \n Helper.printTimeDiff(startTime, self.logFile, self.textField)\n bamFile.close()"
] |
[
[
"numpy.asarray",
"numpy.where",
"numpy.ones"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
JBris/time_series_anomaly_detection_examples
|
[
"c0bb36be4d20128c3aca911dcce156f7e36ae6da",
"c0bb36be4d20128c3aca911dcce156f7e36ae6da"
] |
[
"python/shampoo_sales/dataset.py",
"python/nasa_bearings/dataset.py"
] |
[
"#!/usr/bin/env python\n\nimport numpy as np\nimport os\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\n\ndef load_date_series():\n dirname = os.path.dirname(os.path.realpath(__file__))\n return pd.read_csv(dirname + '/data/shampoo.csv', header=0, parse_dates=[0], index_col=0, squeeze=True)\n\ndef split_date_series(series):\n # split data into train and test\n X = series.values\n train, test = X[0:-12], X[-12:]\n return train, test\n\n# frame a sequence as a supervised learning problem\ndef timeseries_to_supervised(data, lag=1):\n\tdf = pd.DataFrame(data)\n\tcolumns = [df.shift(i) for i in range(1, lag+1)]\n\tcolumns.append(df)\n\tdf = pd.concat(columns, axis=1)\n\tdf.fillna(0, inplace=True)\n\treturn df\n\n# create a differenced series\ndef difference(dataset, interval=1):\n\tdiff = []\n\tfor i in range(interval, len(dataset)):\n\t\tvalue = dataset[i] - dataset[i - interval]\n\t\tdiff.append(value)\n\treturn pd.Series(diff)\n\n# invert differenced value\ndef inverse_difference(history, yhat, interval=1):\n\treturn yhat + history[-interval]\n\n# scale train and test data to [-1, 1]\ndef scale(train, test):\n\t# fit scaler\n\tscaler = MinMaxScaler(feature_range=(-1, 1))\n\tscaler = scaler.fit(train)\n\t# transform train\n\ttrain = train.reshape(train.shape[0], train.shape[1])\n\ttrain_scaled = scaler.transform(train)\n\t# transform test\n\ttest = test.reshape(test.shape[0], test.shape[1])\n\ttest_scaled = scaler.transform(test)\n\treturn scaler, train_scaled, test_scaled\n\n# inverse scaling for a forecasted value\ndef invert_scale(scaler, X, value):\n\tnew_row = [x for x in X] + [value]\n\tarray = np.array(new_row)\n\tarray = array.reshape(1, len(array))\n\tinverted = scaler.inverse_transform(array)\n\treturn inverted[0, -1]\n",
"#!/usr/bin/env python\n\nimport os\nimport pandas as pd\nfrom sklearn import preprocessing\nfrom sklearn.decomposition import PCA\n\ndef load_data():\n dirname = os.path.dirname(os.path.realpath(__file__))\n return pd.read_csv(dirname + '/data/merged_dataset_BearingTest_2.csv')\n\ndef filter_dataset(df):\n dataset_train = df.loc[ (df['timestamp'] >= '2004-02-12 11:02:39') & (df['timestamp'] < '2004-02-13 23:52:39') ]\n dataset_test = df.loc[df['timestamp'] >= '2004-02-13 23:52:39' ]\n return dataset_train, dataset_test\n\ndef index_timestamps(dataset_train, dataset_test):\n dataset_train.set_index('timestamp')\n dataset_test.set_index('timestamp')\n dataset_train = dataset_train.drop('timestamp', axis=1)\n dataset_test = dataset_test.drop('timestamp', axis=1)\n return dataset_train, dataset_test\n\ndef normalize_data(dataset_train, dataset_test):\n scaler = preprocessing.MinMaxScaler()\n X_train = pd.DataFrame(scaler.fit_transform(dataset_train), \n columns=dataset_train.columns, \n index=dataset_train.index)# Random shuffle training data\n X_train.sample(frac=1)\n\n X_test = pd.DataFrame(scaler.transform(dataset_test), \n columns=dataset_test.columns, \n index=dataset_test.index)\n return X_train, X_test\n\ndef do_PCA(X_train, X_test):\n pca = PCA(n_components=2, svd_solver= 'full')\n \n X_train_PCA = pca.fit_transform(X_train)\n X_train_PCA = pd.DataFrame(X_train_PCA)\n X_train_PCA.index = X_train.index\n\n X_test_PCA = pca.transform(X_test)\n X_test_PCA = pd.DataFrame(X_test_PCA)\n X_test_PCA.index = X_test.index\n return X_train_PCA, X_test_PCA\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"pandas.Series",
"pandas.DataFrame",
"numpy.array",
"sklearn.preprocessing.MinMaxScaler"
],
[
"pandas.read_csv",
"sklearn.decomposition.PCA",
"sklearn.preprocessing.MinMaxScaler",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
psAI-clOps/psAI-clOps
|
[
"48db87c2c0e6b7b7532ff44d9f3338d4f1ed5f2f",
"48db87c2c0e6b7b7532ff44d9f3338d4f1ed5f2f"
] |
[
"vanilla_GAN/infer.py",
"image_classifier/infer.py"
] |
[
"from tensorflow.keras.models import load_model\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\n\ndef test(gen_model_path: str, i: int):\n gen = load_model(gen_model_path)\n noise = np.random.normal(0, 1, (1, 100))\n image = np.squeeze(gen.predict(noise), axis=0)\n plt.imsave(\n \"/Users/vsatpathy/Desktop/off_POCs/cycle_gan/epoch_%d\" % i,\n image.reshape(28, 28),\n format=\"jpg\",\n cmap=\"gray\",\n )\n\n\ngenerator_model_path = (\n \"/Users/vsatpathy/Desktop/docs/training_data/van_gan/generator.h5\"\n)\ntest(gen_model_path=generator_model_path, i=0)\n",
"from tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing.image import load_img\n\nimport numpy as np\nimport os\nimport random\n\n\ndef preprocess(image_path: str, image_shape: tuple = None):\n image_dimensions = (100, 100, 3)\n if image_shape:\n pass\n else:\n image_shape = image_dimensions\n test_inp = image_path\n test_img = np.asarray(load_img(test_inp, target_size=image_shape))\n test_img = np.divide(test_img, 255.0)\n test_img = np.asarray([test_img]).astype(\"float32\")\n return test_img\n\n\ndef predict(folder_path: str, model_path: str):\n image_dimensions = (100, 100, 3)\n full_image_path = os.path.join(folder_path, random.choice(os.listdir(folder_path)))\n model = load_model(model_path)\n image = preprocess(image_path=full_image_path, image_shape=image_dimensions)\n results = model.predict(image)\n print(full_image_path)\n print(np.argmax(results[0]))\n\n\nmodel_path = \"/Users/vsatpathy/Desktop/docs/training_data/intel/image_classifier.h5\"\nfolder_path = (\n \"/Users/vsatpathy/Desktop/off_POCs/intel-image-classification/seg_train/buildings\"\n)\npredict(folder_path=folder_path, model_path=model_path)\n"
] |
[
[
"tensorflow.keras.models.load_model",
"numpy.random.normal"
],
[
"tensorflow.keras.models.load_model",
"tensorflow.keras.preprocessing.image.load_img",
"numpy.asarray",
"numpy.argmax",
"numpy.divide"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.4",
"2.3",
"2.5",
"2.6"
]
}
] |
ezhan94/calibratable-style-consistency
|
[
"460c9a9f6e7350fc3d25f324fcc80762f33a5b16"
] |
[
"scripts/check_dynamics_loss.py"
] |
[
"import argparse\nimport json\nimport os\nimport math\nimport numpy as np\nimport random\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\n\n\nimport sys\nsys.path.append(sys.path[0] + '/..')\n\nfrom lib.models import get_model_class\nfrom util.datasets import load_dataset\n\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import PercentFormatter\n\n\ndef check_selfcon_tvaep_dm(exp_dir, trial_id):\n print('########## Trial {} ##########'.format(trial_id))\n\n # Get trial folder\n trial_dir = os.path.join(exp_dir, trial_id)\n assert os.path.isfile(os.path.join(trial_dir, 'summary.json'))\n\n # Load config\n with open(os.path.join(exp_dir, 'configs', '{}.json'.format(trial_id)), 'r') as f:\n config = json.load(f)\n data_config = config['data_config']\n model_config = config['model_config']\n train_config = config['train_config']\n\n # Load dataset\n dataset = load_dataset(data_config)\n dataset.train()\n loader = DataLoader(dataset, batch_size=train_config['batch_size'], shuffle=False)\n\n # Load best model\n state_dict = torch.load(os.path.join(trial_dir, 'best.pth'), map_location=lambda storage, loc: storage)\n model_class = get_model_class(model_config['name'].lower())\n model_config['label_functions'] = dataset.active_label_functions\n model = model_class(model_config)\n model.filter_and_load_state_dict(state_dict)\n\n if not hasattr(model, 'dynamics_model'):\n return\n\n errors = []\n\n for batch_idx, (states, actions, _) in enumerate(loader):\n states = states.transpose(0,1)\n actions = actions.transpose(0,1)\n\n with torch.no_grad():\n state_change = model.propogate_forward(states[0], actions[0])\n\n diff = torch.abs(state_change - (states[1]-states[0]))\n errors.append(diff.view(-1))\n\n errors = torch.cat(errors).numpy()\n print('Mean: {}'.format(np.mean(errors)))\n print('Median {}'.format(np.median(errors)))\n hist_range = [0.02*i for i in range(30)]\n\n N = len(errors)\n plt.hist(errors, bins=hist_range, weights=np.ones(N)/N, alpha=1, edgecolor='b')\n plt.xlim((0.0, 0.6))\n plt.gca().yaxis.set_major_formatter(PercentFormatter(1))\n plt.xlabel('Absolute Error')\n plt.ylabel('Percentage')\n plt.title('Dynamics model error')\n plt.savefig(os.path.join(trial_dir, 'results', 'dynamics_error.png'))\n plt.clf()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-f', '--exp_folder', type=str,\n required=True, default=None,\n help='folder of experiments from which to load models')\n parser.add_argument('--save_dir', type=str,\n required=False, default='saved',\n help='save directory for experiments from project directory')\n args = parser.parse_args()\n\n # Get exp_directory\n exp_dir = os.path.join(os.getcwd(), args.save_dir, args.exp_folder)\n\n # Load master file\n assert os.path.isfile(os.path.join(exp_dir, 'master.json'))\n with open(os.path.join(exp_dir, 'master.json'), 'r') as f:\n master = json.load(f)\n\n # Check self consistency\n for trial_id in master['summaries']:\n check_selfcon_tvaep_dm(exp_dir, trial_id)\n "
] |
[
[
"torch.abs",
"matplotlib.pyplot.gca",
"matplotlib.ticker.PercentFormatter",
"matplotlib.pyplot.title",
"torch.cat",
"matplotlib.use",
"numpy.median",
"torch.utils.data.DataLoader",
"numpy.ones",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.clf",
"torch.no_grad",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ZM-Zhou/MDE_Platform_Pytorch
|
[
"d86efe061bf14a6eed3352cc45e1437e46c138b1"
] |
[
"_Costfunc/base_confunc.py"
] |
[
"import numpy as np\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\n\r\n##############################################################################\r\n# reprojection loss\r\n##############################################################################\r\ndef compute_reprojection_map(pred, target, ssim=None):\r\n \"\"\"Computes reprojection loss between a batch of predicted\r\n and target images\r\n \"\"\"\r\n abs_diff = torch.abs(target - pred)\r\n l1_loss = abs_diff\r\n\r\n if not ssim:\r\n reprojection_loss = l1_loss\r\n else:\r\n ssim_loss = ssim(pred, target)\r\n reprojection_loss = l1_loss * 0.15 + ssim_loss* 0.85\r\n\r\n return reprojection_loss\r\n\r\n\r\n##############################################################################\r\n# smooth loss\r\n##############################################################################\r\ndef compute_smooth_map(disp, img):\r\n \"\"\"Computes the smoothness loss for a disparity image\r\n The color image is used for edge-aware smoothness\r\n \"\"\"\r\n mean_disp = disp.mean(2, True).mean(3, True)\r\n norm_disp = disp / (mean_disp + 1e-7)\r\n disp = norm_disp\r\n\r\n padh = nn.ReplicationPad2d((0, 0, 1, 0))\r\n padw = nn.ReplicationPad2d((1, 0, 0, 0))\r\n disph = padh(disp)\r\n dispw = padw(disp)\r\n imgh = padh(img)\r\n imgw = padw(img)\r\n\r\n\r\n grad_disp_x = torch.abs(dispw[:, :, :, :-1] - dispw[:, :, :, 1:])\r\n grad_disp_y = torch.abs(disph[:, :, :-1, :] - disph[:, :, 1:, :])\r\n\r\n grad_img_x = torch.mean(torch.abs(imgw[:, :, :, :-1] - imgw[:, :, :, 1:]),\r\n 1, keepdim=True)\r\n grad_img_y = torch.mean(torch.abs(imgh[:, :, :-1, :] - imgh[:, :, 1:, :]),\r\n 1, keepdim=True)\r\n\r\n grad_disp_x *= torch.exp(-grad_img_x)\r\n grad_disp_y *= torch.exp(-grad_img_y)\r\n\r\n return grad_disp_x + grad_disp_y\r\n\r\n\r\n#############################################################################\r\n# Multiview geometry functions\r\n#############################################################################\r\nclass BackprojectDepth(nn.Module):\r\n \"\"\"Layer to transform a depth image into a point cloud\r\n from https://github.com/nianticlabs/monodepth2\r\n \"\"\"\r\n def __init__(self, batch_size, height, width):\r\n super(BackprojectDepth, self).__init__()\r\n\r\n self.batch_size = batch_size\r\n self.height = height\r\n self.width = width\r\n\r\n meshgrid = np.meshgrid(range(self.width), range(self.height),\r\n indexing='xy')\r\n self.id_coords = np.stack(meshgrid, axis=0).astype(np.float32)\r\n self.id_coords = nn.Parameter(torch.from_numpy(self.id_coords),\r\n requires_grad=False)\r\n\r\n self.ones = nn.Parameter(torch.ones(self.batch_size, 1,\r\n self.height * self.width),\r\n requires_grad=False)\r\n\r\n self.pix_coords = torch.unsqueeze(torch.stack(\r\n [self.id_coords[0].view(-1), self.id_coords[1].view(-1)], 0), 0)\r\n self.pix_coords = self.pix_coords.repeat(batch_size, 1, 1)\r\n self.pix_coords = nn.Parameter(torch.cat([self.pix_coords, self.ones],\r\n 1), requires_grad=False)\r\n\r\n def forward(self, depth, inv_K):\r\n cam_points = torch.matmul(inv_K[:, :3, :3], self.pix_coords)\r\n cam_points = depth.view(self.batch_size, 1, -1) * cam_points\r\n cam_points = torch.cat([cam_points, self.ones], 1)\r\n\r\n return cam_points\r\n\r\n\r\nclass Project3D(nn.Module):\r\n \"\"\"Layer which projects 3D points into a camera with intrinsics K\r\n and at position T\r\n from https://github.com/nianticlabs/monodepth2\r\n \"\"\"\r\n def __init__(self, batch_size, height, width, eps=1e-7):\r\n super(Project3D, self).__init__()\r\n\r\n self.batch_size = batch_size\r\n self.height = height\r\n self.width = width\r\n self.eps = eps\r\n\r\n def forward(self, points, K, T):\r\n P = torch.matmul(K, T)[:, :3, :]\r\n\r\n cam_points = torch.matmul(P, points)\r\n\r\n temp = (cam_points[:, 2, :].unsqueeze(1)\r\n + self.eps)\r\n pix_coords = cam_points[:, :2, :] / (cam_points[:, 2, :].unsqueeze(1)\r\n + self.eps)\r\n pix_coords = pix_coords.view(self.batch_size, 2,\r\n self.height, self.width)\r\n pix_coords = pix_coords.permute(0, 2, 3, 1)\r\n pix_coords[..., 0] /= self.width - 1\r\n pix_coords[..., 1] /= self.height - 1\r\n pix_coords = (pix_coords - 0.5) * 2\r\n return pix_coords\r\n\r\n\r\nclass Disp_point(nn.Module):\r\n \"\"\"Layer to transform a disp image into a point cloud\r\n \"\"\"\r\n def __init__(self, batch_size, height, width):\r\n super().__init__()\r\n\r\n self.batch_size = batch_size\r\n self.height = height\r\n self.width = width\r\n self.max_disp = width * 0.3\r\n\r\n meshgrid = np.meshgrid(range(self.width), range(self.height),\r\n indexing='xy')\r\n self.id_coords = np.stack(meshgrid, axis=0).astype(np.float32)\r\n self.id_coords = torch.from_numpy(self.id_coords)\r\n\r\n pix_coords = torch.unsqueeze(torch.stack(\r\n [self.id_coords[0].view(-1), self.id_coords[1].view(-1)], 0), 0)\r\n pix_coords = pix_coords.repeat(batch_size, 1, 1)\r\n self.pix_coords_x = pix_coords[:, 0, ...].unsqueeze(1)\r\n self.pix_coords_y = pix_coords[:, 1, ...].unsqueeze(1)\r\n self.pix_coords_x = nn.Parameter(self.pix_coords_x, requires_grad=False)\r\n self.pix_coords_y = nn.Parameter(self.pix_coords_y, requires_grad=False)\r\n\r\n\r\n def forward(self, disp, T):\r\n disp = disp * self.max_disp\r\n disp = disp.view(self.batch_size, 1, -1)\r\n side = T[:, 0, 3].unsqueeze(1).unsqueeze(1)\r\n pix_coords_x_new = disp * side + self.pix_coords_x\r\n pix_coords_new = torch.cat([pix_coords_x_new, self.pix_coords_y], dim=1)\r\n pix_coords_new = pix_coords_new.view(self.batch_size, 2,\r\n self.height, self.width)\r\n pix_coords_new = pix_coords_new.permute(0, 2, 3, 1)\r\n pix_coords_new[..., 0] /= self.width - 1\r\n pix_coords_new[..., 1] /= self.height - 1\r\n pix_coords_new = (pix_coords_new - 0.5) * 2\r\n\r\n return pix_coords_new\r\n\r\n##############################################################################\r\n# SSIM module\r\n##############################################################################\r\nclass SSIM(nn.Module):\r\n \"\"\"Layer to compute the SSIM loss between a pair of images\r\n from https://github.com/nianticlabs/monodepth2\r\n \"\"\"\r\n def __init__(self):\r\n super(SSIM, self).__init__()\r\n self.mu_x_pool = nn.AvgPool2d(3, 1)\r\n self.mu_y_pool = nn.AvgPool2d(3, 1)\r\n self.sig_x_pool = nn.AvgPool2d(3, 1)\r\n self.sig_y_pool = nn.AvgPool2d(3, 1)\r\n self.sig_xy_pool = nn.AvgPool2d(3, 1)\r\n\r\n self.refl = nn.ReflectionPad2d(1)\r\n\r\n self.C1 = 0.01 ** 2\r\n self.C2 = 0.03 ** 2\r\n\r\n def forward(self, x, y):\r\n x = self.refl(x)\r\n y = self.refl(y)\r\n\r\n mu_x = self.mu_x_pool(x)\r\n mu_y = self.mu_y_pool(y)\r\n\r\n sigma_x = self.sig_x_pool(x ** 2) - mu_x ** 2\r\n sigma_y = self.sig_y_pool(y ** 2) - mu_y ** 2\r\n sigma_xy = self.sig_xy_pool(x * y) - mu_x * mu_y\r\n\r\n SSIM_n = (2 * mu_x * mu_y + self.C1) * (2 * sigma_xy + self.C2)\r\n SSIM_d = (mu_x ** 2 + mu_y ** 2 + self.C1) *\\\r\n (sigma_x + sigma_y + self.C2)\r\n\r\n return torch.clamp((1 - SSIM_n / SSIM_d) / 2, 0, 1)\r\n"
] |
[
[
"torch.abs",
"torch.nn.Parameter",
"torch.nn.ReflectionPad2d",
"torch.ones",
"torch.cat",
"torch.from_numpy",
"numpy.stack",
"torch.exp",
"torch.matmul",
"torch.nn.AvgPool2d",
"torch.clamp",
"torch.nn.ReplicationPad2d"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
herenvarno/gsbn
|
[
"47ed0932b605d8b3cf9661f9308908364ad5892e"
] |
[
"tools/plot/plot_trace_t_fp32.py"
] |
[
"import os\nimport sys\nimport re\nimport glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom google.protobuf import text_format\nsys.path.append(os.path.dirname(os.path.realpath(__file__))+\"/../../build\")\nimport gsbn_pb2\n\n# command: ./plot_trace_t.py <description> <snapshot dir> <projection id> <trace name> <i> <j>\n\nif len(sys.argv) < 7:\n\tprint(\"Arguments wrong! Please retry with command :\")\n\tprint(\"python \"+os.path.realpath(__file__)+\" <network description file> <snapshot file> <projection id> [pij|eij|zi2|zj2|tij|wij]\")\n\texit(-1)\n\t\nnetwork = sys.argv[1]\nsnapshot = sys.argv[2]\nprojection = int(sys.argv[3])\nparameter = sys.argv[4]\ncord_i = int(sys.argv[5])\ncord_j = int(sys.argv[6])\n\n# Read the network\nsolver_param = gsbn_pb2.SolverParam()\ntry:\n\tf = open(network, \"r\")\n\ttext_format.Parse(f.read(), solver_param)\n\tf.close()\nexcept IOError:\n\tprint(sys.argv[1] + \": Could not open file.\")\n\texit(-1)\n\nnet_param = solver_param.net_param\nif projection >= len(net_param.proj_param) or projection < 0 :\n\tprint(\"Error Argument: projection id wrong!\")\n\texit(-1)\n\npop_param_list = net_param.pop_param\npop_param_size = len(pop_param_list)\n\nproj_param = net_param.proj_param[projection]\nsrc_pop = proj_param.src_pop\ndest_pop = proj_param.dest_pop\nif src_pop > pop_param_size or dest_pop > pop_param_size :\n\tprint(\"Error Argument: network description file is wrong!\")\n\texit(-1)\n\nfor i in range(pop_param_size):\n\tif i==src_pop:\n\t\tsrc_pop_dim_hcu = pop_param_list[i].hcu_num;\n\t\tsrc_pop_dim_mcu = pop_param_list[i].mcu_num;\n\tif i==dest_pop:\n\t\tdest_pop_dim_hcu = pop_param_list[i].hcu_num;\n\t\tdest_pop_dim_mcu = pop_param_list[i].mcu_num;\n\t\tdest_pop_slot = pop_param_list[i].slot_num;\n\ndest_pop_dim_conn = src_pop_dim_hcu*src_pop_dim_mcu\nif(dest_pop_slot < dest_pop_dim_conn):\n\tdest_pop_dim_conn = dest_pop_slot\n\nif src_pop_dim_hcu<0 or src_pop_dim_mcu<0 or dest_pop_dim_hcu<0 or dest_pop_dim_mcu<0 or dest_pop_dim_conn<0:\n\tprint(\"Error Argument: network description file is wrong!\")\n\texit(-1)\n\n# READ SNAPSHOT\ntrace=[]\n\nos.chdir(snapshot)\nfor f in glob.glob(\"SolverState*.bin\"):\n\tprint(f)\n\tsolver_state = gsbn_pb2.SolverState()\n\ttry:\n\t\tf = open(f, \"rb\")\n\t\tsolver_state.ParseFromString(f.read())\n\t\tf.close()\n\texcept IOError:\n\t\tprint(sys.argv[1] + \": Could not open snapshot file.\")\n\t\texit(-1)\n\t\n\ttimestamp = solver_state.timestamp\n\tii = np.zeros([dest_pop_dim_hcu*dest_pop_dim_conn])\n\tvector_state_i32_list = solver_state.vector_state_i32\n\tfor i in range(len(vector_state_i32_list)):\n\t\tvector_state_i32 = vector_state_i32_list[i]\n\t\tif vector_state_i32.name==\"ii_\"+str(projection):\n\t\t\tdata = vector_state_i32.data\n\t\t\tfor j in range(len(data)):\n\t\t\t\tii[j]=int(data[j])\n\t\t\n\tif parameter==\"pi\" or parameter==\"ei\" or parameter==\"zi\":\n\t\tvector_state_f32_list = solver_state.vector_state_f32\n\t\tfor i in range(len(vector_state_f32_list)):\n\t\t\tvector_state_f32 = vector_state_f32_list[i]\n\t\t\tif vector_state_f32.name==parameter+\"_\"+str(projection):\n\t\t\t\tdata = vector_state_f32.data\n\t\t\t\tfor j in range(len(data)):\n\t\t\t\t\ty=ii[j]\n\t\t\t\t\tx=j//dest_pop_dim_conn\n\t\t\t\t\tif y==cord_i and x==cord_j and y>=0:\n\t\t\t\t\t\ttrace.append([timestamp, data[j]])\n\t\n\tif parameter==\"pij\" or parameter==\"eij\" or parameter==\"zi2\" or parameter==\"zj2\":\n\t\tvector_state_f32_list = solver_state.vector_state_f32\n\t\tfor i in range(len(vector_state_f32_list)):\n\t\t\tvector_state_f32 = vector_state_f32_list[i]\n\t\t\tif vector_state_f32.name==parameter+\"_\"+str(projection):\n\t\t\t\tdata = vector_state_f32.data\n\t\t\t\tfor j in range(len(data)):\n\t\t\t\t\th=j//dest_pop_dim_mcu\n\t\t\t\t\tw=j%dest_pop_dim_mcu\n\t\t\t\t\ty=ii[h];\n\t\t\t\t\tx=h//dest_pop_dim_conn*dest_pop_dim_mcu+w\n\t\t\t\t\tif y==cord_i and x==cord_j and y>=0:\n\t\t\t\t\t\ttrace.append([timestamp, data[j]])\n\nprint(trace)\ntime=[]\nvalue=[]\ntrace.sort(key=lambda x: x[0])\nfor v in trace:\n\ttime.append(v[0])\n\tvalue.append(v[1])\nprint(time)\nprint(value)\nplt.plot(time, value)\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
surajp92/NIROM_SST
|
[
"1efc2c9ec74015e95195b5039cb0dc062ce44b7b"
] |
[
"post_processing.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 25 17:31:32 2020\n\n@author: suraj\n\"\"\"\nimport numpy as np\n\ndata = np.load('progress_19.npz')\n\npopulation = data['population']\nfitness = data['fitness']\npopulation_old = data['population_old']\n\n#%%\ndata = np.load('results_noaa.npz', allow_pickle=True)\nbest_param_dict = data['best_param_dict']\n\n#%%\naa = best_param_dict[1][:]"
] |
[
[
"numpy.load"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
videodanchik/audio
|
[
"c22962d125e929dd8d4c171e76f5aa48baac3d49"
] |
[
"torchaudio/prototype/emformer.py"
] |
[
"import math\nfrom typing import List, Optional, Tuple\n\nimport torch\n\n\n__all__ = [\"Emformer\"]\n\n\ndef _lengths_to_padding_mask(lengths: torch.Tensor) -> torch.Tensor:\n batch_size = lengths.shape[0]\n max_length = int(torch.max(lengths).item())\n padding_mask = torch.arange(\n max_length, device=lengths.device, dtype=lengths.dtype\n ).expand(batch_size, max_length) >= lengths.unsqueeze(1)\n return padding_mask\n\n\ndef _gen_padding_mask(\n utterance: torch.Tensor,\n right_context: torch.Tensor,\n summary: torch.Tensor,\n lengths: torch.Tensor,\n mems: torch.Tensor,\n left_context_key: Optional[torch.Tensor] = None,\n) -> Optional[torch.Tensor]:\n T = right_context.size(0) + utterance.size(0) + summary.size(0)\n B = right_context.size(1)\n if B == 1:\n padding_mask = None\n else:\n right_context_blocks_length = T - torch.max(lengths).int() - summary.size(0)\n left_context_blocks_length = (\n left_context_key.size(0) if left_context_key is not None else 0\n )\n klengths = (\n lengths\n + mems.size(0)\n + right_context_blocks_length\n + left_context_blocks_length\n )\n padding_mask = _lengths_to_padding_mask(lengths=klengths)\n return padding_mask\n\n\ndef _get_activation_module(activation: str) -> torch.nn.Module:\n if activation == \"relu\":\n return torch.nn.ReLU()\n elif activation == \"gelu\":\n return torch.nn.GELU()\n elif activation == \"silu\":\n return torch.nn.SiLU()\n else:\n raise ValueError(f\"Unsupported activation {activation}\")\n\n\ndef _get_weight_init_gains(\n weight_init_scale_strategy: Optional[str], num_layers: int\n) -> List[Optional[float]]:\n if weight_init_scale_strategy is None:\n return [None for _ in range(num_layers)]\n elif weight_init_scale_strategy == \"depthwise\":\n return [1.0 / math.sqrt(layer_idx + 1) for layer_idx in range(num_layers)]\n elif weight_init_scale_strategy == \"constant\":\n return [1.0 / math.sqrt(2) for layer_idx in range(num_layers)]\n else:\n raise ValueError(\n f\"Unsupported weight_init_scale_strategy value {weight_init_scale_strategy}\"\n )\n\n\ndef _gen_attention_mask_block(\n col_widths: List[int], col_mask: List[bool], num_rows: int, device: torch.device\n) -> torch.Tensor:\n assert len(col_widths) == len(\n col_mask\n ), \"Length of col_widths must match that of col_mask\"\n\n mask_block = [\n torch.ones(num_rows, col_width, device=device)\n if is_ones_col\n else torch.zeros(num_rows, col_width, device=device)\n for col_width, is_ones_col in zip(col_widths, col_mask)\n ]\n return torch.cat(mask_block, dim=1)\n\n\nclass _EmformerAttention(torch.nn.Module):\n r\"\"\"Emformer layer attention module.\n\n Args:\n input_dim (int): input dimension.\n num_heads (int): number of attention heads in each Emformer layer.\n dropout (float, optional): dropout probability. (Default: 0.0)\n weight_init_gain (float or None, optional): scale factor to apply when initializing\n attention module parameters. (Default: ``None``)\n tanh_on_mem (bool, optional): if ``True``, applies tanh to memory elements. (Default: ``False``)\n negative_inf (float, optional): value to use for negative infinity in attention weights. (Default: -1e8)\n \"\"\"\n\n def __init__(\n self,\n input_dim: int,\n num_heads: int,\n dropout: float = 0.0,\n weight_init_gain: Optional[float] = None,\n tanh_on_mem: bool = False,\n negative_inf: float = -1e8,\n ):\n super().__init__()\n\n if input_dim % num_heads != 0:\n raise ValueError(\n f\"input_dim ({input_dim}) is not a multiple of num_heads ({num_heads}).\"\n )\n\n self.input_dim = input_dim\n self.num_heads = num_heads\n self.dropout = dropout\n self.tanh_on_mem = tanh_on_mem\n self.negative_inf = negative_inf\n\n self.scaling = (self.input_dim // self.num_heads) ** -0.5\n\n self.emb_to_key_value = torch.nn.Linear(input_dim, 2 * input_dim, bias=True)\n self.emb_to_query = torch.nn.Linear(input_dim, input_dim, bias=True)\n self.out_proj = torch.nn.Linear(input_dim, input_dim, bias=True)\n\n if weight_init_gain:\n torch.nn.init.xavier_uniform_(\n self.emb_to_key_value.weight, gain=weight_init_gain\n )\n torch.nn.init.xavier_uniform_(\n self.emb_to_query.weight, gain=weight_init_gain\n )\n\n def _gen_key_value(\n self, input: torch.Tensor, mems: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n T, _, _ = input.shape\n summary_length = mems.size(0) + 1\n right_ctx_utterance_block = input[: T - summary_length]\n mems_right_ctx_utterance_block = torch.cat([mems, right_ctx_utterance_block])\n key, value = self.emb_to_key_value(mems_right_ctx_utterance_block).chunk(\n chunks=2, dim=2\n )\n return key, value\n\n def _gen_attention_probs(\n self,\n attention_weights: torch.Tensor,\n attention_mask: torch.Tensor,\n padding_mask: Optional[torch.Tensor],\n ) -> torch.Tensor:\n attention_weights_float = attention_weights.float()\n attention_weights_float = attention_weights_float.masked_fill(\n attention_mask.unsqueeze(0), self.negative_inf\n )\n T = attention_weights.size(1)\n B = attention_weights.size(0) // self.num_heads\n if padding_mask is not None:\n attention_weights_float = attention_weights_float.view(\n B, self.num_heads, T, -1\n )\n attention_weights_float = attention_weights_float.masked_fill(\n padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool), self.negative_inf\n )\n attention_weights_float = attention_weights_float.view(\n B * self.num_heads, T, -1\n )\n attention_probs = torch.nn.functional.softmax(\n attention_weights_float, dim=-1\n ).type_as(attention_weights)\n return torch.nn.functional.dropout(\n attention_probs, p=float(self.dropout), training=self.training\n )\n\n def _forward_impl(\n self,\n utterance: torch.Tensor,\n lengths: torch.Tensor,\n right_context: torch.Tensor,\n summary: torch.Tensor,\n mems: torch.Tensor,\n attention_mask: torch.Tensor,\n left_context_key: Optional[torch.Tensor] = None,\n left_context_val: Optional[torch.Tensor] = None,\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:\n B = utterance.size(1)\n T = right_context.size(0) + utterance.size(0) + summary.size(0)\n\n # Compute query with [right context, utterance, summary].\n query = self.emb_to_query(torch.cat([right_context, utterance, summary]))\n\n # Compute key and value with [mems, right context, utterance].\n key, value = self.emb_to_key_value(\n torch.cat([mems, right_context, utterance])\n ).chunk(chunks=2, dim=2)\n\n if left_context_key is not None and left_context_val is not None:\n right_context_blocks_length = T - torch.max(lengths).int() - summary.size(0)\n key = torch.cat(\n [\n key[: mems.size(0) + right_context_blocks_length],\n left_context_key,\n key[mems.size(0) + right_context_blocks_length:],\n ],\n )\n value = torch.cat(\n [\n value[: mems.size(0) + right_context_blocks_length],\n left_context_val,\n value[mems.size(0) + right_context_blocks_length:],\n ],\n )\n\n # Compute attention weights from query, key, and value.\n reshaped_query, reshaped_key, reshaped_value = [\n tensor.contiguous()\n .view(-1, B * self.num_heads, self.input_dim // self.num_heads)\n .transpose(0, 1)\n for tensor in [query, key, value]\n ]\n attention_weights = torch.bmm(\n reshaped_query * self.scaling, reshaped_key.transpose(1, 2)\n )\n\n # Compute padding mask.\n padding_mask = _gen_padding_mask(\n utterance, right_context, summary, lengths, mems, left_context_key\n )\n\n # Compute attention probabilities.\n attention_probs = self._gen_attention_probs(\n attention_weights, attention_mask, padding_mask\n )\n\n # Compute attention.\n attention = torch.bmm(attention_probs, reshaped_value)\n assert attention.shape == (\n B * self.num_heads,\n T,\n self.input_dim // self.num_heads,\n )\n attention = attention.transpose(0, 1).contiguous().view(T, B, self.input_dim)\n\n # Apply output projection.\n output_right_context_mems = self.out_proj(attention)\n\n summary_length = summary.size(0)\n output_right_context = output_right_context_mems[: T - summary_length]\n output_mems = output_right_context_mems[T - summary_length:]\n if self.tanh_on_mem:\n output_mems = torch.tanh(output_mems)\n else:\n output_mems = torch.clamp(output_mems, min=-10, max=10)\n\n return output_right_context, output_mems, key, value\n\n def forward(\n self,\n utterance: torch.Tensor,\n lengths: torch.Tensor,\n right_context: torch.Tensor,\n summary: torch.Tensor,\n mems: torch.Tensor,\n attention_mask: torch.Tensor,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n r\"\"\"Forward pass for training.\n\n B: batch size;\n D: feature dimension of each frame;\n T: number of utterance frames;\n R: number of right context frames;\n S: number of summary elements;\n M: number of memory elements.\n\n Args:\n utterance (torch.Tensor): utterance frames, with shape (T, B, D).\n lengths (torch.Tensor): with shape (B,) and i-th element representing\n number of valid frames for i-th batch element in ``utterance``.\n right_context (torch.Tensor): right context frames, with shape (R, B, D).\n summary (torch.Tensor): summary elements, with shape (S, B, D).\n mems (torch.Tensor): memory elements, with shape (M, B, D).\n attention_mask (torch.Tensor): attention mask for underlying attention module.\n\n Returns:\n torch.Tensor and torch.Tensor:\n torch.Tensor\n output frames corresponding to utterance and right_context, with shape (T + R, B, D).\n torch.Tensor\n updated memory elements, with shape (M, B, D).\n \"\"\"\n output, output_mems, _, _ = self._forward_impl(\n utterance, lengths, right_context, summary, mems, attention_mask\n )\n return output, output_mems[:-1]\n\n @torch.jit.export\n def infer(\n self,\n utterance: torch.Tensor,\n lengths: torch.Tensor,\n right_context: torch.Tensor,\n summary: torch.Tensor,\n mems: torch.Tensor,\n left_context_key: torch.Tensor,\n left_context_val: torch.Tensor,\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:\n r\"\"\"Forward pass for inference.\n\n B: batch size;\n D: feature dimension of each frame;\n T: number of utterance frames;\n R: number of right context frames;\n S: number of summary elements;\n M: number of memory elements.\n\n Args:\n utterance (torch.Tensor): utterance frames, with shape (T, B, D).\n lengths (torch.Tensor): with shape (B,) and i-th element representing\n number of valid frames for i-th batch element in ``utterance``.\n right_context (torch.Tensor): right context frames, with shape (R, B, D).\n summary (torch.Tensor): summary elements, with shape (S, B, D).\n mems (torch.Tensor): memory elements, with shape (M, B, D).\n left_context_key (torch.Tensor): left context attention key computed from preceding invocation.\n left_context_val (torch.Tensor): left context attention value computed from preceding invocation.\n\n Returns:\n torch.Tensor, torch.Tensor, torch.Tensor, and torch.Tensor:\n torch.Tensor\n output frames corresponding to utterance and right_context, with shape (T + R, B, D).\n torch.Tensor\n updated memory elements, with shape (M, B, D).\n torch.Tensor\n attention key computed for left context and utterance.\n torch.Tensor\n attention value computed for left context and utterance.\n \"\"\"\n query_dim = right_context.size(0) + utterance.size(0) + summary.size(0)\n key_dim = (\n right_context.size(0)\n + utterance.size(0)\n + mems.size(0)\n + left_context_key.size(0)\n )\n attention_mask = torch.zeros(query_dim, key_dim).to(\n dtype=torch.bool, device=utterance.device\n )\n attention_mask[-1, : mems.size(0)] = True\n output, output_mems, key, value = self._forward_impl(\n utterance,\n lengths,\n right_context,\n summary,\n mems,\n attention_mask,\n left_context_key=left_context_key,\n left_context_val=left_context_val,\n )\n return (\n output,\n output_mems,\n key[mems.size(0) + right_context.size(0):],\n value[mems.size(0) + right_context.size(0):],\n )\n\n\nclass _EmformerLayer(torch.nn.Module):\n r\"\"\"Emformer layer that constitutes Emformer.\n\n Args:\n input_dim (int): input dimension.\n num_heads (int): number of attention heads.\n ffn_dim: (int): hidden layer dimension of feedforward network.\n dropout (float, optional): dropout probability. (Default: 0.0)\n activation (str, optional): activation function to use in feedforward network.\n Must be one of (\"relu\", \"gelu\", \"silu\"). (Default: \"relu\")\n left_context_length (int, optional): length of left context. (Default: 0)\n segment_length (int, optional): length of each input segment. (Default: 128)\n max_memory_size (int, optional): maximum number of memory elements to use. (Default: 0)\n weight_init_gain (float or None, optional): scale factor to apply when initializing\n attention module parameters. (Default: ``None``)\n tanh_on_mem (bool, optional): if ``True``, applies tanh to memory elements. (Default: ``False``)\n negative_inf (float, optional): value to use for negative infinity in attention weights. (Default: -1e8)\n \"\"\"\n\n def __init__(\n self,\n input_dim: int,\n num_heads: int,\n ffn_dim: int,\n dropout: float = 0.0,\n activation: str = \"relu\",\n left_context_length: int = 0,\n segment_length: int = 128,\n max_memory_size: int = 0,\n weight_init_gain: Optional[float] = None,\n tanh_on_mem: bool = False,\n negative_inf: float = -1e8,\n ):\n super().__init__()\n\n self.attention = _EmformerAttention(\n input_dim=input_dim,\n num_heads=num_heads,\n dropout=dropout,\n weight_init_gain=weight_init_gain,\n tanh_on_mem=tanh_on_mem,\n negative_inf=negative_inf,\n )\n self.dropout = torch.nn.Dropout(dropout)\n self.memory_op = torch.nn.AvgPool1d(\n kernel_size=segment_length, stride=segment_length, ceil_mode=True\n )\n\n activation_module = _get_activation_module(activation)\n self.pos_ff = torch.nn.Sequential(\n torch.nn.LayerNorm(input_dim),\n torch.nn.Linear(input_dim, ffn_dim),\n activation_module,\n torch.nn.Dropout(dropout),\n torch.nn.Linear(ffn_dim, input_dim),\n torch.nn.Dropout(dropout),\n )\n self.layer_norm_input = torch.nn.LayerNorm(input_dim)\n self.layer_norm_output = torch.nn.LayerNorm(input_dim)\n\n self.left_context_length = left_context_length\n self.segment_length = segment_length\n self.max_memory_size = max_memory_size\n self.input_dim = input_dim\n\n self.use_mem = max_memory_size > 0\n\n def _init_state(\n self, batch_size: int, device: Optional[torch.device]\n ) -> List[torch.Tensor]:\n empty_memory = torch.zeros(\n self.max_memory_size, batch_size, self.input_dim, device=device\n )\n left_context_key = torch.zeros(\n self.left_context_length, batch_size, self.input_dim, device=device\n )\n left_context_val = torch.zeros(\n self.left_context_length, batch_size, self.input_dim, device=device\n )\n past_length = torch.zeros(1, batch_size, dtype=torch.int32, device=device)\n return [empty_memory, left_context_key, left_context_val, past_length]\n\n def _unpack_state(\n self, utterance: torch.Tensor, mems: torch.Tensor, state: List[torch.Tensor]\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n past_length = state[3][0][0].item()\n past_left_context_length = min(self.left_context_length, past_length)\n past_mem_length = min(\n self.max_memory_size, math.ceil(past_length / self.segment_length)\n )\n pre_mems = state[0][self.max_memory_size - past_mem_length:]\n lc_key = state[1][self.left_context_length - past_left_context_length:]\n lc_val = state[2][self.left_context_length - past_left_context_length:]\n return pre_mems, lc_key, lc_val\n\n def _pack_state(\n self,\n next_k: torch.Tensor,\n next_v: torch.Tensor,\n update_length: int,\n mems: torch.Tensor,\n state: List[torch.Tensor],\n ) -> List[torch.Tensor]:\n new_k = torch.cat([state[1], next_k])\n new_v = torch.cat([state[2], next_v])\n state[0] = torch.cat([state[0], mems])[-self.max_memory_size:]\n state[1] = new_k[new_k.shape[0] - self.left_context_length:]\n state[2] = new_v[new_v.shape[0] - self.left_context_length:]\n state[3] = state[3] + update_length\n return state\n\n def _process_attention_output(\n self,\n rc_output: torch.Tensor,\n utterance: torch.Tensor,\n right_context: torch.Tensor,\n ) -> torch.Tensor:\n result = self.dropout(rc_output) + torch.cat([right_context, utterance])\n result = self.pos_ff(result) + result\n result = self.layer_norm_output(result)\n return result\n\n def _apply_pre_attention_layer_norm(\n self, utterance: torch.Tensor, right_context: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n layer_norm_input = self.layer_norm_input(torch.cat([right_context, utterance]))\n return (\n layer_norm_input[right_context.size(0):],\n layer_norm_input[: right_context.size(0)],\n )\n\n def _apply_post_attention_ffn(\n self, rc_output: torch.Tensor, utterance: torch.Tensor, right_context: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n rc_output = self._process_attention_output(rc_output, utterance, right_context)\n return rc_output[right_context.size(0):], rc_output[: right_context.size(0)]\n\n def _apply_attention_forward(\n self,\n utterance: torch.Tensor,\n lengths: torch.Tensor,\n right_context: torch.Tensor,\n mems: torch.Tensor,\n attention_mask: Optional[torch.Tensor],\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n if attention_mask is None:\n raise ValueError(\n \"attention_mask must be not None when for_inference is False\"\n )\n\n if self.use_mem:\n summary = self.memory_op(utterance.permute(1, 2, 0)).permute(2, 0, 1)\n else:\n summary = torch.empty(0).to(dtype=utterance.dtype, device=utterance.device)\n rc_output, next_m = self.attention(\n utterance=utterance,\n lengths=lengths,\n right_context=right_context,\n summary=summary,\n mems=mems,\n attention_mask=attention_mask,\n )\n return rc_output, next_m\n\n def _apply_attention_infer(\n self,\n utterance: torch.Tensor,\n lengths: torch.Tensor,\n right_context: torch.Tensor,\n mems: torch.Tensor,\n state: Optional[List[torch.Tensor]],\n ) -> Tuple[torch.Tensor, torch.Tensor, List[torch.Tensor]]:\n if state is None:\n state = self._init_state(utterance.size(1), device=utterance.device)\n pre_mems, lc_key, lc_val = self._unpack_state(utterance, mems, state)\n if self.use_mem:\n summary = self.memory_op(utterance.permute(1, 2, 0)).permute(2, 0, 1)\n summary = summary[:1]\n else:\n summary = torch.empty(0).to(dtype=utterance.dtype, device=utterance.device)\n rc_output, next_m, next_k, next_v = self.attention.infer(\n utterance=utterance,\n lengths=lengths,\n right_context=right_context,\n summary=summary,\n mems=pre_mems,\n left_context_key=lc_key,\n left_context_val=lc_val,\n )\n state = self._pack_state(next_k, next_v, utterance.size(0), mems, state)\n return rc_output, next_m, state\n\n def forward(\n self,\n utterance: torch.Tensor,\n lengths: torch.Tensor,\n right_context: torch.Tensor,\n mems: torch.Tensor,\n attention_mask: torch.Tensor,\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n r\"\"\"Forward pass for training.\n\n B: batch size;\n D: feature dimension of each frame;\n T: number of utterance frames;\n R: number of right context frames;\n M: number of memory elements.\n\n Args:\n utterance (torch.Tensor): utterance frames, with shape (T, B, D).\n lengths (torch.Tensor): with shape (B,) and i-th element representing\n number of valid frames for i-th batch element in ``utterance``.\n right_context (torch.Tensor): right context frames, with shape (R, B, D).\n mems (torch.Tensor): memory elements, with shape (M, B, D).\n attention_mask (torch.Tensor): attention mask for underlying attention module.\n\n Returns:\n torch.Tensor, torch.Tensor, and torch.Tensor:\n torch.Tensor\n encoded utterance frames, with shape (T, B, D).\n torch.Tensor\n updated right context frames, with shape (R, B, D).\n torch.Tensor\n updated memory elements, with shape (M, B, D).\n \"\"\"\n (\n layer_norm_utterance,\n layer_norm_right_context,\n ) = self._apply_pre_attention_layer_norm(utterance, right_context)\n rc_output, output_mems = self._apply_attention_forward(\n layer_norm_utterance,\n lengths,\n layer_norm_right_context,\n mems,\n attention_mask,\n )\n output_utterance, output_right_context = self._apply_post_attention_ffn(\n rc_output, utterance, right_context\n )\n return output_utterance, output_right_context, output_mems\n\n @torch.jit.export\n def infer(\n self,\n utterance: torch.Tensor,\n lengths: torch.Tensor,\n right_context: torch.Tensor,\n state: Optional[List[torch.Tensor]],\n mems: torch.Tensor,\n ) -> Tuple[torch.Tensor, torch.Tensor, List[torch.Tensor], torch.Tensor]:\n r\"\"\"Forward pass for inference.\n\n B: batch size;\n D: feature dimension of each frame;\n T: number of utterance frames;\n R: number of right context frames;\n M: number of memory elements.\n\n Args:\n utterance (torch.Tensor): utterance frames, with shape (T, B, D).\n lengths (torch.Tensor): with shape (B,) and i-th element representing\n number of valid frames for i-th batch element in ``utterance``.\n right_context (torch.Tensor): right context frames, with shape (R, B, D).\n state (List[torch.Tensor] or None): list of tensors representing layer internal state\n generated in preceding invocation of ``infer``.\n mems (torch.Tensor): memory elements, with shape (M, B, D).\n\n Returns:\n torch.Tensor, torch.Tensor, List[torch.Tensor], and torch.Tensor:\n torch.Tensor\n encoded utterance frames, with shape (T, B, D).\n torch.Tensor\n updated right context frames, with shape (R, B, D).\n List[torch.Tensor]\n list of tensors representing layer internal state\n generated in current invocation of ``infer``.\n torch.Tensor\n updated memory elements, with shape (M, B, D).\n \"\"\"\n (\n layer_norm_utterance,\n layer_norm_right_context,\n ) = self._apply_pre_attention_layer_norm(utterance, right_context)\n rc_output, output_mems, output_state = self._apply_attention_infer(\n layer_norm_utterance, lengths, layer_norm_right_context, mems, state\n )\n output_utterance, output_right_context = self._apply_post_attention_ffn(\n rc_output, utterance, right_context\n )\n return output_utterance, output_right_context, output_state, output_mems\n\n\nclass Emformer(torch.nn.Module):\n r\"\"\"Implements the Emformer architecture introduced in\n *Emformer: Efficient Memory Transformer Based Acoustic Model for Low Latency Streaming Speech Recognition*\n [:footcite:`shi2021emformer`].\n\n Args:\n input_dim (int): input dimension.\n num_heads (int): number of attention heads in each Emformer layer.\n ffn_dim (int): hidden layer dimension of each Emformer layer's feedforward network.\n num_layers (int): number of Emformer layers to instantiate.\n dropout (float, optional): dropout probability. (Default: 0.0)\n activation (str, optional): activation function to use in each Emformer layer's\n feedforward network. Must be one of (\"relu\", \"gelu\", \"silu\"). (Default: \"relu\")\n left_context_length (int, optional): length of left context. (Default: 0)\n right_context_length (int, optional): length of right context. (Default: 0)\n segment_length (int, optional): length of each input segment. (Default: 128)\n max_memory_size (int, optional): maximum number of memory elements to use. (Default: 0)\n weight_init_scale_strategy (str, optional): per-layer weight initialization scaling\n strategy. Must be one of (\"depthwise\", \"constant\", ``None``). (Default: \"depthwise\")\n tanh_on_mem (bool, optional): if ``True``, applies tanh to memory elements. (Default: ``False``)\n negative_inf (float, optional): value to use for negative infinity in attention weights. (Default: -1e8)\n\n Examples:\n >>> emformer = Emformer(512, 8, 2048, 20)\n >>> input = torch.rand(128, 400, 512) # batch, num_frames, feature_dim\n >>> lengths = torch.randint(1, 200, (128,)) # batch\n >>> output = emformer(input, lengths)\n >>> output, lengths, states = emformer.infer(input, lengths, None)\n \"\"\"\n\n def __init__(\n self,\n input_dim: int,\n num_heads: int,\n ffn_dim: int,\n num_layers: int,\n dropout: float = 0.0,\n activation: str = \"relu\",\n left_context_length: int = 0,\n right_context_length: int = 0,\n segment_length: int = 128,\n max_memory_size: int = 0,\n weight_init_scale_strategy: str = \"depthwise\",\n tanh_on_mem: bool = False,\n negative_inf: float = -1e8,\n ):\n super().__init__()\n\n self.use_mem = max_memory_size > 0\n self.memory_op = torch.nn.AvgPool1d(\n kernel_size=segment_length, stride=segment_length, ceil_mode=True,\n )\n\n weight_init_gains = _get_weight_init_gains(\n weight_init_scale_strategy, num_layers\n )\n self.emformer_layers = torch.nn.ModuleList(\n [\n _EmformerLayer(\n input_dim,\n num_heads,\n ffn_dim,\n dropout=dropout,\n activation=activation,\n left_context_length=left_context_length,\n segment_length=segment_length,\n max_memory_size=max_memory_size,\n weight_init_gain=weight_init_gains[layer_idx],\n tanh_on_mem=tanh_on_mem,\n negative_inf=negative_inf,\n )\n for layer_idx in range(num_layers)\n ]\n )\n\n self.left_context_length = left_context_length\n self.right_context_length = right_context_length\n self.segment_length = segment_length\n self.max_memory_size = max_memory_size\n\n def _gen_right_context(self, input: torch.Tensor) -> torch.Tensor:\n right_context_blocks = []\n T, B, D = input.shape\n num_segs = math.ceil((T - self.right_context_length) / self.segment_length)\n right_context_blocks = []\n for seg_idx in range(num_segs - 1):\n start = (seg_idx + 1) * self.segment_length\n end = start + self.right_context_length\n right_context_blocks.append(input[start:end])\n right_context_blocks.append(input[T - self.right_context_length:])\n return torch.cat(right_context_blocks)\n\n def _gen_attention_mask_col_widths(\n self, seg_idx: int, utterance_length: int\n ) -> List[int]:\n num_segs = math.ceil(utterance_length / self.segment_length)\n rc = self.right_context_length\n lc = self.left_context_length\n rc_start = seg_idx * rc\n rc_end = rc_start + rc\n seg_start = max(seg_idx * self.segment_length - lc, 0)\n seg_end = min((seg_idx + 1) * self.segment_length, utterance_length)\n rc_length = self.right_context_length * num_segs\n\n if self.use_mem:\n m_start = max(seg_idx - self.max_memory_size, 0)\n mem_length = num_segs - 1\n col_widths = [\n m_start, # before memory\n seg_idx - m_start, # memory\n mem_length - seg_idx, # after memory\n rc_start, # before right context\n rc, # right context\n rc_length - rc_end, # after right context\n seg_start, # before query segment\n seg_end - seg_start, # query segment\n utterance_length - seg_end, # after query segment\n ]\n else:\n col_widths = [\n rc_start, # before right context\n rc, # right context\n rc_length - rc_end, # after right context\n seg_start, # before query segment\n seg_end - seg_start, # query segment\n utterance_length - seg_end, # after query segment\n ]\n\n return col_widths\n\n def _gen_attention_mask(self, input: torch.Tensor) -> torch.Tensor:\n utterance_length, batch_size, _ = input.shape\n num_segs = math.ceil(utterance_length / self.segment_length)\n\n rc_mask = []\n query_mask = []\n summary_mask = []\n\n if self.use_mem:\n num_cols = 9\n # memory, right context, query segment\n rc_q_cols_mask = [idx in [1, 4, 7] for idx in range(num_cols)]\n # right context, query segment\n s_cols_mask = [idx in [4, 7] for idx in range(num_cols)]\n masks_to_concat = [rc_mask, query_mask, summary_mask]\n else:\n num_cols = 6\n # right context, query segment\n rc_q_cols_mask = [idx in [1, 4] for idx in range(num_cols)]\n s_cols_mask = None\n masks_to_concat = [rc_mask, query_mask]\n\n for seg_idx in range(num_segs):\n col_widths = self._gen_attention_mask_col_widths(seg_idx, utterance_length)\n\n rc_mask_block = _gen_attention_mask_block(\n col_widths, rc_q_cols_mask, self.right_context_length, input.device\n )\n rc_mask.append(rc_mask_block)\n\n query_mask_block = _gen_attention_mask_block(\n col_widths,\n rc_q_cols_mask,\n min(\n self.segment_length,\n utterance_length - seg_idx * self.segment_length,\n ),\n input.device,\n )\n query_mask.append(query_mask_block)\n\n if s_cols_mask is not None:\n summary_mask_block = _gen_attention_mask_block(\n col_widths, s_cols_mask, 1, input.device\n )\n summary_mask.append(summary_mask_block)\n\n attention_mask = (\n 1 - torch.cat([torch.cat(mask) for mask in masks_to_concat])\n ).to(torch.bool)\n return attention_mask\n\n def forward(\n self, input: torch.Tensor, lengths: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n r\"\"\"Forward pass for training.\n\n B: batch size;\n T: number of frames;\n D: feature dimension of each frame.\n\n Args:\n input (torch.Tensor): utterance frames right-padded with right context frames, with\n shape (B, T, D).\n lengths (torch.Tensor): with shape (B,) and i-th element representing\n number of valid frames for i-th batch element in ``input``.\n\n Returns:\n torch.Tensor and torch.Tensor:\n torch.Tensor\n output frames, with shape (B, T - ``right_context_length``, D).\n torch.Tensor\n output lengths, with shape (B,) and i-th element representing\n number of valid frames for i-th batch element in output frames.\n \"\"\"\n input = input.permute(1, 0, 2)\n right_context = self._gen_right_context(input)\n utterance = input[: input.size(0) - self.right_context_length]\n attention_mask = self._gen_attention_mask(utterance)\n mems = (\n self.memory_op(utterance.permute(1, 2, 0)).permute(2, 0, 1)[:-1]\n if self.use_mem\n else torch.empty(0).to(dtype=input.dtype, device=input.device)\n )\n output = utterance\n for layer in self.emformer_layers:\n output, right_context, mems = layer(\n output, lengths, right_context, mems, attention_mask\n )\n return output.permute(1, 0, 2), lengths\n\n @torch.jit.export\n def infer(\n self,\n input: torch.Tensor,\n lengths: torch.Tensor,\n states: Optional[List[List[torch.Tensor]]] = None,\n ) -> Tuple[torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:\n r\"\"\"Forward pass for inference.\n\n B: batch size;\n T: number of frames;\n D: feature dimension of each frame.\n\n Args:\n input (torch.Tensor): utterance frames right-padded with right context frames, with\n shape (B, T, D).\n lengths (torch.Tensor): with shape (B,) and i-th element representing\n number of valid frames for i-th batch element in ``input``.\n states (List[List[torch.Tensor]] or None, optional): list of lists of tensors\n representing Emformer internal state generated in preceding invocation of ``infer``. (Default: ``None``)\n\n Returns:\n torch.Tensor, torch.Tensor, and List[List[torch.Tensor]]:\n torch.Tensor\n output frames, with shape (B, T - ``right_context_length``, D).\n torch.Tensor\n output lengths, with shape (B,) and i-th element representing\n number of valid frames for i-th batch element in output frames.\n List[List[torch.Tensor]]\n output states; list of lists of tensors representing Emformer internal state\n generated in current invocation of ``infer``.\n \"\"\"\n input = input.permute(1, 0, 2)\n right_context_start_idx = input.size(0) - self.right_context_length\n right_context = input[right_context_start_idx:]\n utterance = input[:right_context_start_idx]\n output_lengths = torch.clamp(lengths - self.right_context_length, min=0)\n mems = (\n self.memory_op(utterance.permute(1, 2, 0)).permute(2, 0, 1)\n if self.use_mem\n else torch.empty(0).to(dtype=input.dtype, device=input.device)\n )\n output = utterance\n output_states: List[List[torch.Tensor]] = []\n for layer_idx, layer in enumerate(self.emformer_layers):\n output, right_context, output_state, mems = layer.infer(\n output,\n output_lengths,\n right_context,\n None if states is None else states[layer_idx],\n mems,\n )\n output_states.append(output_state)\n\n return output.permute(1, 0, 2), output_lengths, output_states\n"
] |
[
[
"torch.nn.Dropout",
"torch.clamp",
"torch.nn.GELU",
"torch.ones",
"torch.max",
"torch.cat",
"torch.zeros",
"torch.nn.functional.softmax",
"torch.empty",
"torch.arange",
"torch.nn.LayerNorm",
"torch.tanh",
"torch.nn.Linear",
"torch.bmm",
"torch.nn.init.xavier_uniform_",
"torch.nn.ReLU",
"torch.nn.SiLU",
"torch.nn.AvgPool1d"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
KirillRnd/gcc-nmf
|
[
"2bf235e9da0d04f603b8d6d383e3c25c4dc428ff"
] |
[
"gccNMF/realtime/gccNMFInterface.py"
] |
[
"'''\nThe MIT License (MIT)\n\nCopyright (c) 2017 Sean UN Wood\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n@author: Sean UN Wood\n'''\n\nimport logging\nfrom os import listdir\nfrom os.path import join, isdir\nfrom collections import OrderedDict\n\nimport numpy as np\nfrom pyqtgraph.Qt import QtGui, QtCore\nimport pyqtgraph as pg\n\nfrom gccNMF.realtime.gccNMFProcessor import TARGET_MODE_BOXCAR, TARGET_MODE_MULTIPLE, TARGET_MODE_WINDOW_FUNCTION\n\nBUTTON_WIDTH = 50\n \nclass RealtimeGCCNMFInterfaceWindow(QtGui.QMainWindow):\n def __init__(self, audioPath, numTDOAs, gccPHATNLAlpha, gccPHATNLEnabled, dictionariesW, dictionarySize, dictionarySizes, dictionaryType, numHUpdates,\n gccPHATHistory, inputSpectrogramHistory, outputSpectrogramHistory, coefficientMaskHistories,\n togglePlayAudioProcessQueue, togglePlayAudioProcessAck,\n togglePlayGCCNMFProcessQueue, togglePlayGCCNMFProcessAck,\n tdoaParamsGCCNMFProcessQueue, tdoaParamsGCCNMFProcessAck,\n toggleSeparationGCCNMFProcessQueue, toggleSeparationGCCNMFProcessAck):\n super(RealtimeGCCNMFInterfaceWindow, self).__init__()\n \n self.audioPath = audioPath\n logging.info('Loading interface with audio path: %s' % self.audioPath)\n self.initAudioFiles()\n \n self.numTDOAs = numTDOAs\n self.tdoaIndexes = np.arange(numTDOAs)\n self.dictionariesW = getVisualizedDictionariesW(dictionariesW)\n self.dictionaryTypes = self.dictionariesW.keys()\n \n self.dictionarySize = dictionarySize\n self.dictionarySizes = dictionarySizes\n self.dictionaryType = dictionaryType\n self.numHUpdates = numHUpdates\n self.targetTDOAIndex = self.numTDOAs / 2.0\n self.targetTDOAEpsilon = self.numTDOAs / 10.0\n self.gccPHATNLAlpha = gccPHATNLAlpha\n self.gccPHATNLEnabled = gccPHATNLEnabled\n \n self.gccPHATPlotTimer = QtCore.QTimer()\n self.gccPHATPlotTimer.timeout.connect(self.updateGCCPHATPlot)\n \n self.gccPHATHistory = gccPHATHistory\n self.gccPHATHistorySize = gccPHATHistory.size()\n self.inputSpectrogramHistory = inputSpectrogramHistory\n self.outputSpectrogramHistory = outputSpectrogramHistory\n self.coefficientMaskHistories = coefficientMaskHistories\n \n self.togglePlayAudioProcessQueue = togglePlayAudioProcessQueue\n self.togglePlayAudioProcessAck = togglePlayAudioProcessAck\n self.togglePlayGCCNMFProcessQueue = togglePlayGCCNMFProcessQueue\n self.togglePlayGCCNMFProcessAck = togglePlayGCCNMFProcessAck\n self.tdoaParamsGCCNMFProcessQueue = tdoaParamsGCCNMFProcessQueue\n self.tdoaParamsGCCNMFProcessAck = tdoaParamsGCCNMFProcessAck\n self.toggleSeparationGCCNMFProcessQueue = toggleSeparationGCCNMFProcessQueue\n self.toggleSeparationGCCNMFProcessAck = toggleSeparationGCCNMFProcessAck\n \n self.playIconString = 'Play'\n self.pauseIconString = 'Pause'\n self.separationOffIconString = 'Disabled'\n self.separationOnIconString = 'Enabled'\n '''self.playIconString = u'\\u23F5'\n self.pauseIconString = u'\\u23F8'\n self.separationOffIconString = u'\\u21F6 | \\u21F6'\n self.separationOnIconString = u'\\u21F6 | \\u2192'''\n \n self.targetModeIconStrings = {TARGET_MODE_BOXCAR: u'\\u168B',\n TARGET_MODE_MULTIPLE: u'\\u168D',\n TARGET_MODE_WINDOW_FUNCTION: u'\\u1109'}\n self.rollingImages = True\n \n self.initWindow()\n self.initControlWidgets()\n self.initVisualizationWidgets()\n self.initWindowLayout()\n \n #self.show()\n self.showMaximized()\n \n def keyPressEvent(self, event):\n key = event.key()\n \n if key == QtCore.Qt.Key_Escape:\n if self.isFullScreen():\n self.showNormal()\n else:\n self.close()\n if key == QtCore.Qt.Key_W and QtGui.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:\n self.close()\n elif key == QtCore.Qt.Key_Return or key == QtCore.Qt.Key_Enter or key == QtCore.Qt.Key_Space:\n self.togglePlay()\n elif key == QtCore.Qt.Key_F and QtGui.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:\n if self.isFullScreen():\n self.showNormal()\n #self.showMaximized()\n else:\n self.showFullScreen()\n elif key == QtCore.Qt.Key_I and QtGui.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:\n self.toggleInfoViews()\n elif key == QtCore.Qt.Key_1 and QtGui.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:\n self.inputSpectrogramWidget.setVisible(self.inputSpectrogramWidget.isHidden())\n elif key == QtCore.Qt.Key_2 and QtGui.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:\n self.outputSpectrogramWidget.setVisible(self.outputSpectrogramWidget.isHidden())\n elif key == QtCore.Qt.Key_3 and QtGui.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:\n self.dictionaryWidget.setVisible(self.dictionaryWidget.isHidden())\n elif key == QtCore.Qt.Key_4 and QtGui.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:\n self.coefficientMaskWidget.setVisible(self.coefficientMaskWidget.isHidden())\n elif key == QtCore.Qt.Key_5 and QtGui.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:\n self.gccPHATHistoryWidget.setVisible(self.gccPHATHistoryWidget.isHidden())\n elif key == QtCore.Qt.Key_0 and QtGui.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:\n self.rollingImages = not self.rollingImages\n \n super(QtGui.QMainWindow, self).keyPressEvent(event)\n \n def closeEvent(self, event):\n logging.info('RealtimeGCCNMFInterfaceWindow: closing...')\n self.gccPHATPlotTimer.stop()\n \n def initAudioFiles(self):\n if isdir(self.audioPath):\n audioDirectory = self.audioPath\n self.audioFilePaths = [join(audioDirectory, fileName) for fileName in listdir(audioDirectory) if fileName.endswith('wav')]\n elif self.audioPath.endswith('.wav'):\n self.audioFilePaths = [self.audioPath]\n else:\n raise IOError('Unable to find wav files at: %s' % self.audioPath)\n self.selectedFileIndex = 0\n \n def initWindow(self):\n self.setWindowTitle('Real-time GCC-NMF')\n \n self.mainWidget = QtGui.QWidget()\n self.setCentralWidget(self.mainWidget)\n self.backgroundColor = self.mainWidget.palette().color(QtGui.QPalette.Background)\n self.borderColor = 'k'\n self.mainWidget.setStyleSheet('QSplitter::handle {image: url(images/notExists.png); background-color: #D8D8D8}')\n \n self.mainLayout = QtGui.QGridLayout()\n self.mainWidget.setLayout(self.mainLayout)\n self.mainWidget.setAutoFillBackground(True)\n p = QtGui.QPalette(self.mainWidget.palette())\n p.setColor(self.mainWidget.backgroundRole(), QtCore.Qt.black)\n self.mainWidget.setPalette(p)\n \n self.mainLayout.setContentsMargins(0, 0, 0, 0)\n self.mainLayout.setSpacing(1)\n \n def initWindowLayout(self):\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(1)\n sizePolicy.setVerticalStretch(1)\n \n self.infoLabelWidgets = []\n def addWidgetWithLabel(widget, label, fromRow, fromColumn, rowSpan=1, columnSpan=1):\n labeledWidget = QtGui.QWidget()\n widgetLayout = QtGui.QVBoxLayout()\n widgetLayout.setContentsMargins(0, 0, 0, 0)\n widgetLayout.setSpacing(1)\n labeledWidget.setLayout(widgetLayout)\n \n labelWidget = QtGui.QLabel(label)\n labelWidget.setContentsMargins(0, 3, 0, 1)\n labelWidget.setAutoFillBackground(True)\n labelWidget.setAlignment(QtCore.Qt.AlignCenter)\n #labelWidget.setStyleSheet('QLabel { border-top-width: 10px }') \n self.infoLabelWidgets.append(labelWidget)\n \n widgetLayout.addWidget(labelWidget)\n widgetLayout.addWidget(widget)\n labeledWidget.setSizePolicy(sizePolicy)\n self.mainLayout.addWidget(labeledWidget, fromRow, fromColumn, rowSpan, columnSpan)\n \n addWidgetWithLabel(self.inputSpectrogramWidget, 'Input Spectrogram', 0, 1)\n addWidgetWithLabel(self.outputSpectrogramWidget, 'Output Spectrogram', 1, 1)\n addWidgetWithLabel(self.controlsWidget, 'GCC-NMF Masking Function', 0, 2)\n addWidgetWithLabel(self.gccPHATHistoryWidget, 'GCC PHAT Angular Spectrogram', 0, 3)\n addWidgetWithLabel(self.dictionaryWidget, 'NMF Dictionary', 1, 2)\n addWidgetWithLabel(self.coefficientMaskWidget, 'NMF Dictionary Mask', 1, 3)\n #for widget in self.infoLabelWidgets:\n # widget.hide()\n #map(lambda widget: widget.hide(), self.infoLabelWidgets)\n \n def initControlWidgets(self):\n self.initMaskFunctionControls()\n self.initMaskFunctionPlot()\n self.initNMFControls()\n self.initUIControls()\n \n controlWidgetsLayout = QtGui.QVBoxLayout()\n controlWidgetsLayout.addWidget(self.gccPHATPlotWidget)\n controlWidgetsLayout.addLayout(self.maskFunctionControlslayout)\n self.addSeparator(controlWidgetsLayout)\n controlWidgetsLayout.addLayout(self.nmfControlsLayout)\n self.addSeparator(controlWidgetsLayout)\n controlWidgetsLayout.addWidget(self.uiConrolsWidget)\n \n self.controlsWidget = QtGui.QWidget()\n self.controlsWidget.setLayout(controlWidgetsLayout)\n self.controlsWidget.setAutoFillBackground(True)\n \n def initMaskFunctionControls(self):\n self.maskFunctionControlslayout = QtGui.QHBoxLayout()\n labelsLayout = QtGui.QVBoxLayout()\n slidersLayout = QtGui.QVBoxLayout()\n self.maskFunctionControlslayout.addLayout(labelsLayout)\n self.maskFunctionControlslayout.addLayout(slidersLayout)\n def addSlider(label, changedFunction, minimum, maximum, value):\n labelsLayout.addWidget(QtGui.QLabel(label))\n slider = QtGui.QSlider(QtCore.Qt.Horizontal)\n slider.setMinimum(minimum)\n slider.setMaximum(maximum)\n slider.setValue(value)\n slider.sliderReleased.connect(changedFunction)\n slidersLayout.addWidget(slider)\n return slider\n \n self.targetModeWindowTDOASlider = addSlider('Center:', self.tdoaRegionChanged, 0, 100, 50)\n self.targetModeWindowWidthSlider = addSlider('Width:', self.tdoaRegionChanged, 1, 101, 50)\n self.targetModeWindowBetaSlider = addSlider('Shape:', self.tdoaRegionChanged, 0, 100, 50)\n self.targetModeWindowNoiseFloorSlider = addSlider('Floor:', self.tdoaRegionChanged, 0, 100, 0)\n \n def initMaskFunctionPlot(self):\n self.gccPHATPlotWidget = self.createGraphicsLayoutWidget(self.backgroundColor, contentMargins=(6, 12, 18, 10))\n self.gccPHATPlotItem = self.gccPHATPlotWidget.addPlot()\n self.gccPHATPlotItem.getViewBox().setBackgroundColor((255, 255, 255, 150))\n self.gccPHATPlot = self.gccPHATPlotItem.plot()\n self.gccPHATPlot.setPen((0, 0, 0))\n self.gccPHATPlotItem.hideAxis('left')\n self.gccPHATPlotItem.hideAxis('bottom')\n self.gccPHATPlotItem.hideButtons()\n self.gccPHATPlotItem.setXRange(0, self.numTDOAs - 1)\n \n self.targetTDOARegion = pg.LinearRegionItem([self.targetTDOAIndex - self.targetTDOAEpsilon, self.targetTDOAIndex + self.targetTDOAEpsilon],\n bounds=[0, self.numTDOAs - 1], movable=True)\n self.targetTDOARegion.sigRegionChangeFinished.connect(self.tdoaRegionChanged)\n \n self.targetWindowFunctionPen = pg.mkPen((0, 0, 204, 255), width=2) # , style=QtCore.Qt.DashLine)\n self.targetWindowFunctionPlot = TargetWindowFunctionPlot(self.targetTDOARegion, self.targetModeWindowTDOASlider, self.targetModeWindowBetaSlider, self.targetModeWindowNoiseFloorSlider, self.targetModeWindowWidthSlider, self.numTDOAs, pen=self.targetWindowFunctionPen)\n self.gccPHATPlotItem.addItem(self.targetWindowFunctionPlot)\n self.targetWindowFunctionPlot.updateData()\n \n def initNMFControls(self):\n self.nmfControlsLayout = QtGui.QHBoxLayout()\n self.nmfControlsLayout.addStretch(1)\n self.nmfControlsLayout.addWidget(QtGui.QLabel('Dictionary Size:'))\n self.dictionarySizeDropDown = QtGui.QComboBox()\n for dictionarySize in self.dictionarySizes:\n self.dictionarySizeDropDown.addItem( str(dictionarySize) )\n self.dictionarySizeDropDown.setMaximumWidth(75)\n self.dictionarySizeDropDown.setCurrentIndex(self.dictionarySizes.index(self.dictionarySize))\n self.dictionarySizeDropDown.currentIndexChanged.connect(self.dictionarySizeChanged)\n self.nmfControlsLayout.addWidget(self.dictionarySizeDropDown)\n self.nmfControlsLayout.addStretch(1)\n \n self.nmfControlsLayout.addWidget(QtGui.QLabel('Num Updates:'))\n self.numHUpdatesSpinBox = QtGui.QSpinBox()\n self.nmfControlsLayout.addWidget(self.numHUpdatesSpinBox)\n self.nmfControlsLayout.addStretch(1)\n \n def initUIControls(self):\n self.uiConrolsWidget = QtGui.QWidget()\n buttonBarWidgetLayout = QtGui.QHBoxLayout(spacing=0)\n buttonBarWidgetLayout.setContentsMargins(0, 0, 0, 0)\n buttonBarWidgetLayout.setSpacing(0)\n self.uiConrolsWidget.setLayout(buttonBarWidgetLayout)\n \n def addButton(label, widget=None, function=None):\n button = QtGui.QPushButton(label)\n if function is None:\n button.clicked.connect(lambda: widget.setVisible(widget.isHidden()))\n else:\n button.clicked.connect(function)\n button.setStyleSheet('QPushButton {'\n 'border-color: black;'\n 'border-width: 5px;}')\n buttonBarWidgetLayout.addWidget(button)\n return button\n\n addButton('Info', function=self.toggleInfoViews)\n self.toggleSeparationButton = addButton(self.separationOnIconString, function=self.toggleSeparation)\n self.playPauseButton = addButton(self.playIconString, function=self.togglePlay)\n\n def initVisualizationWidgets(self):\n self.inputSpectrogramWidget = self.createGraphicsLayoutWidget(self.backgroundColor)\n inputSpectrogramViewBox = self.inputSpectrogramWidget.addViewBox()\n self.inputSpectrogramHistoryImageItem = pg.ImageItem(self.inputSpectrogramHistory.values) # , border=self.borderColor)\n inputSpectrogramViewBox.addItem(self.inputSpectrogramHistoryImageItem)\n inputSpectrogramViewBox.setRange(xRange=(0, self.inputSpectrogramHistory.values.shape[1]), yRange=(0, self.inputSpectrogramHistory.values.shape[0]), padding=0)\n \n self.outputSpectrogramWidget = self.createGraphicsLayoutWidget(self.backgroundColor)\n outputSpectrogramViewBox = self.outputSpectrogramWidget.addViewBox()\n self.outputSpectrogramHistoryImageItem = pg.ImageItem(self.outputSpectrogramHistory.values) # , border=self.borderColor)\n outputSpectrogramViewBox.addItem(self.outputSpectrogramHistoryImageItem)\n outputSpectrogramViewBox.setRange(xRange=(0, self.outputSpectrogramHistory.values.shape[1] - 1), yRange=(0, self.outputSpectrogramHistory.values.shape[0] - 1), padding=0)\n \n self.gccPHATHistoryWidget = self.createGraphicsLayoutWidget(self.backgroundColor)\n gccPHATHistoryViewBox = self.gccPHATHistoryWidget.addViewBox() # invertY=True)\n self.gccPHATImageItem = pg.ImageItem(self.gccPHATHistory.values) # , border=self.borderColor)\n gccPHATHistoryViewBox.addItem(self.gccPHATImageItem)\n gccPHATHistoryViewBox.setRange(xRange=(0, self.gccPHATHistory.values.shape[1] - 1), yRange=(0, self.gccPHATHistory.values.shape[0] - 1), padding=0)\n \n dictionarySize = self.dictionarySizes[self.dictionarySizeDropDown.currentIndex()]\n self.coefficientMaskWidget = self.createGraphicsLayoutWidget(self.backgroundColor)\n self.coefficientMaskViewBox = self.coefficientMaskWidget.addViewBox()\n self.coefficientMaskHistory = self.coefficientMaskHistories[dictionarySize]\n self.coefficientMaskHistoryImageItem = pg.ImageItem() # , border=self.borderColor)\n self.coefficientMaskViewBox.addItem(self.coefficientMaskHistoryImageItem)\n \n self.dictionaryWidget = self.createGraphicsLayoutWidget(self.backgroundColor)\n self.dictionaryViewBox = self.dictionaryWidget.addViewBox()\n self.dictionaryImageItem = pg.ImageItem() # 1 - visualizedDictionary)#, border=self.borderColor)\n self.dictionaryViewBox.addItem(self.dictionaryImageItem)\n self.dictionarySizeChanged(False)\n\n def addSeparator(self, layout, lineStyle=QtGui.QFrame.HLine):\n separator = QtGui.QFrame()\n separator.setFrameShape(lineStyle)\n separator.setFrameShadow(QtGui.QFrame.Sunken)\n layout.addWidget(separator) \n \n def createGraphicsLayoutWidget(self, backgroundColor, border=None, contentMargins=(0, 0, 0, 0)):\n graphicsLayoutWidget = pg.GraphicsLayoutWidget(border=border)\n graphicsLayoutWidget.setBackground(backgroundColor)\n graphicsLayoutWidget.ci.layout.setContentsMargins(*contentMargins)\n graphicsLayoutWidget.ci.layout.setSpacing(0)\n return graphicsLayoutWidget\n \n def updateGCCPHATPlot(self):\n gccPHATValues = np.squeeze(np.mean(self.gccPHATHistory.values, axis=-1))\n gccPHATValues -= min(gccPHATValues)\n gccPHATValues /= max(gccPHATValues)\n self.gccPHATPlot.setData(y=gccPHATValues)\n if self.rollingImages:\n self.gccPHATImageItem.setImage(-self.gccPHATHistory.getUnraveledArray().T)\n self.inputSpectrogramHistoryImageItem.setImage(self.inputSpectrogramHistory.getUnraveledArray().T)\n self.outputSpectrogramHistoryImageItem.setImage(self.outputSpectrogramHistory.getUnraveledArray().T)\n self.coefficientMaskHistoryImageItem.setImage(self.coefficientMaskHistory.getUnraveledArray().T, levels=[0, 1])\n else:\n self.gccPHATImageItem.setImage(-self.gccPHATHistory.values.T)\n self.inputSpectrogramHistoryImageItem.setImage(self.inputSpectrogramHistory.values.T)\n self.outputSpectrogramHistoryImageItem.setImage(self.outputSpectrogramHistory.values.T)\n self.coefficientMaskHistoryImageItem.setImage(self.coefficientMaskHistory.values.T, levels=[0, 1])\n \n def toggleInfoViews(self):\n isHidden = self.infoLabelWidgets[0].isHidden()\n for view in self.infoLabelWidgets:\n view.setVisible(isHidden)\n #map(lambda view: view.setVisible(isHidden), self.infoLabelWidgets) \n \n def togglePlay(self):\n playing = self.playPauseButton.text() == self.playIconString\n logging.info('GCCNMFInterface: setting playing: %s' % playing)\n \n self.playPauseButton.setText(self.pauseIconString if playing else self.playIconString)\n \n if playing:\n QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)\n self.tdoaRegionChanged()\n self.updateTogglePlayParamsGCCNMFProcess()\n self.updateTogglePlayParamsAudioProcess(playing)\n QtGui.QApplication.restoreOverrideCursor()\n else:\n self.updateTogglePlayParamsAudioProcess(playing)\n\n self.gccPHATPlotTimer.start(100) if playing else self.gccPHATPlotTimer.stop()\n \n def toggleSeparation(self):\n separationEnabled = self.toggleSeparationButton.text() == self.separationOffIconString\n logging.info('GCCNMFInterface: toggleSeparation(): now %s' % separationEnabled)\n \n self.toggleSeparationButton.setText(self.separationOnIconString if separationEnabled else self.separationOffIconString)\n self.queueParams(self.toggleSeparationGCCNMFProcessQueue,\n self.toggleSeparationGCCNMFProcessAck,\n {'separationEnabled': separationEnabled},\n 'separationEnabledParameters')\n \n def numHUpdatesChanged(self):\n numHUpdates = int(self.numHUpdatesTextBox.text())\n logging.info('GCCNMFInterface: setting numHUpdates: %d' % numHUpdates)\n \n self.queueParams(self.togglePlayGCCNMFProcessQueue,\n self.togglePlayGCCNMFProcessAck,\n {'numHUpdates': numHUpdates},\n 'gccNMFProcessTogglePlayParameters')\n\n def updateFileNameAudioProcess(self):\n self.queueParams(self.togglePlayAudioProcessQueue,\n self.togglePlayAudioProcessAck,\n {'fileName': self.selectedFilePath},\n 'audioProcessParameters')\n \n def updateTogglePlayParamsAudioProcess(self, playing):\n self.queueParams(self.togglePlayAudioProcessQueue,\n self.togglePlayAudioProcessAck,\n {'fileName': self.audioFilePaths[self.selectedFileIndex],\n 'start' if playing else 'stop': ''},\n 'audioProcessParameters')\n\n def updateTogglePlayParamsGCCNMFProcess(self):\n self.queueParams(self.togglePlayGCCNMFProcessQueue,\n self.togglePlayGCCNMFProcessAck,\n {'numTDOAs': self.numTDOAs,\n 'dictionarySize': int(self.dictionarySizeDropDown.currentText())},\n 'gccNMFProcessTogglePlayParameters')\n \n def tdoaRegionChanged(self):\n self.queueParams(self.tdoaParamsGCCNMFProcessQueue,\n self.tdoaParamsGCCNMFProcessAck,\n {'targetTDOAIndex': self.targetWindowFunctionPlot.getTDOA(),\n 'targetTDOAEpsilon': self.targetWindowFunctionPlot.getWindowWidth(), # targetTDOAEpsilon,\n 'targetTDOABeta': self.targetWindowFunctionPlot.getBeta(),\n 'targetTDOANoiseFloor': self.targetWindowFunctionPlot.getNoiseFloor()},\n 'gccNMFProcessTDOAParameters (region)')\n self.targetWindowFunctionPlot.updateData()\n \n def dictionarySizeChanged(self, changeGCCNMFProcessor=True):\n self.dictionarySize = self.dictionarySizes[self.dictionarySizeDropDown.currentIndex()]\n logging.info('GCCNMFInterface: setting dictionarySize: %d' % self.dictionarySize)\n \n visualizedDictionary = self.dictionariesW[self.dictionaryType][self.dictionarySize]\n self.dictionaryImageItem.setImage(visualizedDictionary)\n self.dictionaryViewBox.setXRange(0, visualizedDictionary.shape[0] - 1, padding=0)\n self.dictionaryViewBox.setYRange(0, visualizedDictionary.shape[1] - 1, padding=0)\n \n self.coefficientMaskHistory = self.coefficientMaskHistories[self.dictionarySize]\n self.coefficientMaskViewBox.setXRange(0, self.coefficientMaskHistory.values.shape[1] - 1, padding=0)\n self.coefficientMaskViewBox.setYRange(0, self.coefficientMaskHistory.values.shape[0] - 1, padding=0)\n \n if changeGCCNMFProcessor:\n self.queueParams(self.togglePlayGCCNMFProcessQueue,\n self.togglePlayGCCNMFProcessAck,\n {'dictionarySize': self.dictionarySize},\n 'gccNMFProcessTogglePlayParameters')\n\n def dictionaryTypeChanged(self):\n dictionaryType = self.dictionaryTypes[self.dictionaryTypeDropDown.currentIndex()]\n logging.info('GCCNMFInterface: setting dictionarySize: %s' % dictionaryType)\n \n self.queueParams(self.togglePlayGCCNMFProcessQueue,\n self.togglePlayGCCNMFProcessAck,\n {'dictionaryType': dictionaryType},\n 'gccNMFProcessTogglePlayParameters')\n\n def queueParams(self, queue, ack, params, label='params'):\n ack.clear()\n logging.debug('GCCNMFInterface: putting %s' % label)\n queue.put(params)\n logging.debug('GCCNMFInterface: put %s' % label)\n ack.wait()\n logging.debug('GCCNMFInterface: ack received')\n \ndef generalizedGaussian(x, alpha, beta, mu):\n return np.exp( - (np.abs(x-mu) / alpha) ** beta )\n \nclass TargetWindowFunctionPlot(pg.PlotDataItem):\n def __init__(self, tdoaRegionItem, targetModeWindowTDOASlider, targetModeWindowBetaSlider, targetModeWindowNoiseFloorSlider, targetModeWindowWidthSlider, numTDOAs, *args, **kwargs):\n super(TargetWindowFunctionPlot, self).__init__(*args, **kwargs)\n \n self.tdoaRegionItem = tdoaRegionItem\n self.targetModeWindowTDOASlider = targetModeWindowTDOASlider\n self.targetModeWindowBetaSlider = targetModeWindowBetaSlider\n self.targetModeWindowNoiseFloorSlider = targetModeWindowNoiseFloorSlider\n self.targetModeWindowWidthSlider = targetModeWindowWidthSlider\n\n self.targetModeWindowTDOASlider.valueChanged.connect(self.updateData)\n self.targetModeWindowBetaSlider.valueChanged.connect(self.updateData)\n self.targetModeWindowNoiseFloorSlider.valueChanged.connect(self.updateData)\n self.targetModeWindowWidthSlider.valueChanged.connect(self.updateData)\n self.numTDOAs = numTDOAs\n self.tdoas = np.arange(self.numTDOAs).astype(np.float32)\n \n def updateData(self):\n mu = self.getTDOA()\n alpha = self.getWindowWidth()\n beta = self.getBeta()\n noiseFloor = self.getNoiseFloor()\n data = generalizedGaussian(self.tdoas, alpha, beta, mu)\n data -= min(data)\n data = data / max(data) * (1 - noiseFloor) + noiseFloor \n self.setData(self.tdoas, data)\n \n def getBeta(self):\n lnBeta = self.targetModeWindowBetaSlider.value() / 100.0\n lnBeta *= 10.0\n lnBeta -= 5.0\n beta = np.exp(lnBeta)\n return beta\n \n def getNoiseFloor(self):\n noiseFloorValue = self.targetModeWindowNoiseFloorSlider.value() / 100.0\n return noiseFloorValue\n \n def getWindowWidth(self):\n windowWidth = self.targetModeWindowWidthSlider.value() / 100.0 * self.numTDOAs\n return windowWidth\n \n def getTDOA(self):\n tdoa = self.targetModeWindowTDOASlider.value() / 100.0 * self.numTDOAs\n return tdoa\n \ndef getVisualizedDictionariesW(dictionariesW):\n visualizedDictionariesW = OrderedDict()\n for dictionaryType, dictionaries in dictionariesW.items():\n currentDictionaries = OrderedDict()\n for dictionarySize, dictionary in dictionaries.items():\n visualizedDictionary = dictionary.copy()\n visualizedDictionary /= np.max(visualizedDictionary)\n visualizedDictionary **= (1 / 3.0)\n visualizedDictionary = 1 - visualizedDictionary\n currentDictionaries[dictionarySize] = visualizedDictionary\n visualizedDictionariesW[dictionaryType] = currentDictionaries\n return visualizedDictionariesW\n"
] |
[
[
"numpy.abs",
"numpy.arange",
"numpy.max",
"numpy.mean",
"numpy.exp"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
id9502/RLFrame
|
[
"a6fe99c6578e74f74767720b9212365e10f0cefd"
] |
[
"examples/mcpo_rlbench.py"
] |
[
"#!/usr/bin/env python3\nimport os\nimport sys\nimport torch\n\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n\nfrom core.logger import Logger\nfrom core.filter.zfilter import ZFilter\nfrom core.algorithm.mcpo import mcpo_step\nfrom core.agent import Agent_sync as Agent\nfrom core.model import PolicyWithValue as Policy\nfrom core.common import ParamDict, ARGConfig, ARG\nfrom core.utilities import running_time, model_dir, loadInitConfig\nfrom environment import FakeRLBench\n\n\ndefault_config = ARGConfig(\n \"PyTorch MC-PO example\",\n ARG(\"env name\", \"ReachTarget\", critical=True, fields=[\"naming\"],\n desc=\"name of the environment to run\"),\n ARG(\"action mode\", \"delta joint position\", critical=True, fields=[\"naming\"],\n desc=\"name of the action mode, (default: {})\"),\n ARG(\"tag\", \"new_r\", fields=[\"naming\"],\n desc=\"tag of this experiment\"),\n ARG(\"short\", \"mcpo\", critical=True, fields=[\"naming\"],\n desc=\"short name of this method\"),\n ARG(\"seed\", 1, critical=True, fields=[\"naming\"], desc=\"random seed (default: {})\"),\n\n ARG(\"load name\", \"~final.pkl\", desc=\"name of pre-trained model\"),\n ARG(\"demo path\", \"RLBench/1000_djp_ReachTarget.demo.pkl\", desc=\"demo package path\"),\n # ---- model parameters ---- #\n ARG(\"activation\", \"tanh\", critical=True,\n desc=\"activation function name('tanh', 'sigmoid', 'relu')\"),\n ARG(\"gamma\", 0.99, critical=True, key_name=\"advantage gamma\", fields=[\"policy init\"],\n desc=\"discount factor (default: {})\"),\n ARG(\"tau\", 0.95, critical=True, key_name=\"advantage tau\", fields=[\"policy init\"],\n desc=\"gae (default: {})\"),\n ARG(\"damping\", 1.e-2, critical=True, desc=\"damping (default: {})\"),\n ARG(\"l2 reg\", 1.e-3, critical=True, desc=\"l2 regularization regression (default: {})\"),\n ARG(\"lr\", 1.e-4, critical=True, desc=\"Learning rate (default: {})\"),\n ARG(\"max kl\", 1.e-2, critical=True, desc=\"max kl value (default: {})\"),\n ARG(\"bc method\", \"l2\", critical=True, desc=\"method for determining distance (default: {})\"),\n ARG(\"constraint\", -6.e-3, critical=True, desc=\"constraint limit of behavior discrepancy (default: {})\"),\n ARG(\"constraint factor\", 1.e-3, critical=True, desc=\"constraint limit growth along iter (default: {})\"),\n ARG(\"constraint max\", 10., critical=True, desc=\"constraint max growth along iter (default: {})\"),\n ARG(\"use zfilter\", True, critical=True, desc=\"filter the state when running (default {})\"),\n\n # ---- program config ---- #\n ARG(\"batch size\", 32, desc=\"batch size per update (default: {})\"),\n ARG(\"max iter\", 5000, desc=\"maximal number of training iterations (default: {})\"),\n ARG(\"eval batch size\", 4, desc=\"batch size used for evaluations (default: {})\"),\n ARG(\"eval interval\", 1, desc=\"interval between evaluations (default: {})\"),\n ARG(\"save interval\", 50, desc=\"interval between saving (default: {}, 0, means never save)\"),\n ARG(\"threads\", 4, desc=\"number of threads for agent (default: {})\"),\n ARG(\"gpu threads\", 2, desc=\"number of threads for agent (default: {})\"),\n ARG(\"gpu\", (0, 1, 2, 3), desc=\"tuple of available GPUs, empty for cpu only\"),\n)\n\n\ndef train_loop(cfg, agent, logger):\n curr_iter, max_iter, eval_iter, eval_batch_sz, batch_sz, save_iter, demo_loader =\\\n cfg.require(\"current training iter\", \"max iter\", \"eval interval\",\n \"eval batch size\", \"batch size\", \"save interval\", \"demo loader\")\n\n training_cfg = ParamDict({\n \"policy state dict\": agent.policy().getStateDict(),\n \"filter state dict\": agent.filter().getStateDict(),\n \"trajectory max step\": 64,\n \"batch size\": batch_sz,\n \"fixed environment\": False,\n \"fixed policy\": False,\n \"fixed filter\": False\n })\n validate_cfg = ParamDict({\n \"policy state dict\": None,\n \"filter state dict\": None,\n \"trajectory max step\": 64,\n \"batch size\": eval_batch_sz,\n \"fixed environment\": False,\n \"fixed policy\": True,\n \"fixed filter\": True\n })\n\n # we use the entire demo set without sampling\n demo_trajectory = demo_loader.generate_all()\n if demo_trajectory is None:\n print(\"Warning: No demo loaded, fall back compatible with TRPO method\")\n else:\n print(\"Info: Demo loaded successfully\")\n demo_actions = []\n demo_states = []\n for p in demo_trajectory:\n demo_actions.append(torch.as_tensor([t['a'] for t in p], dtype=torch.float32, device=agent.policy().device))\n demo_states.append(torch.as_tensor([t['s'] for t in p], dtype=torch.float32, device=agent.policy().device))\n demo_states = torch.cat(demo_states, dim=0)\n demo_actions = torch.cat(demo_actions, dim=0)\n demo_trajectory = [demo_states, demo_actions]\n\n for i_iter in range(curr_iter, max_iter):\n\n s_time = float(running_time(fmt=False))\n\n \"\"\"sample new batch and perform MCPO update\"\"\"\n batch_train, info_train = agent.rollout(training_cfg)\n\n demo_batch = None\n if demo_trajectory is not None:\n filter_dict = agent.filter().getStateDict()\n errsum, mean, n_step = filter_dict[\"zfilter errsum\"], filter_dict[\"zfilter mean\"], filter_dict[\"zfilter n_step\"]\n errsum = torch.as_tensor(errsum, dtype=torch.float32, device=agent.policy().device)\n mean = torch.as_tensor(mean, dtype=torch.float32, device=agent.policy().device)\n std = torch.sqrt(errsum / (n_step - 1)) if n_step > 1 else mean\n demo_batch = ((demo_trajectory[0] - mean) / (std + 1e-8), demo_trajectory[1])\n\n mcpo_step(cfg, batch_train, agent.policy(), demo_batch)\n\n e_time = float(running_time(fmt=False))\n\n logger.train()\n info_train[\"duration\"] = e_time - s_time\n info_train[\"epoch\"] = i_iter\n logger(info_train)\n\n cfg[\"current training iter\"] = i_iter + 1\n cfg[\"policy state dict\"] = training_cfg[\"policy state dict\"] = validate_cfg[\"policy state dict\"] = agent.policy().getStateDict()\n cfg[\"filter state dict\"] = training_cfg[\"filter state dict\"] = validate_cfg[\"filter state dict\"] = agent.filter().getStateDict()\n\n if i_iter % eval_iter == 0:\n batch_eval, info_eval = agent.rollout(validate_cfg)\n\n logger.train(False)\n info_eval[\"duration\"] = e_time - s_time\n info_eval[\"epoch\"] = i_iter\n logger(info_eval)\n\n if i_iter != 0 and i_iter % save_iter == 0:\n file_name = os.path.join(model_dir(cfg), f\"I_{i_iter}.pkl\")\n cfg.save(file_name)\n print(f\"Saving current step at {file_name}\")\n\n file_name = os.path.join(model_dir(cfg), f\"final.pkl\")\n cfg.save(file_name)\n print(f\"Total running time: {running_time(fmt=True)}, result saved at {file_name}\")\n\n\ndef main(cfg):\n env_name, action_mode, use_zf, gamma, tau, policy_state, filter_state =\\\n cfg.require(\"env name\", \"action mode\", \"use zfilter\", \"advantage gamma\", \"advantage tau\", \"policy state dict\", \"filter state dict\")\n\n logger = Logger()\n logger.init(cfg)\n\n filter_op = ZFilter(gamma, tau, enable=use_zf)\n env = FakeRLBench(env_name, action_mode=action_mode)\n policy = Policy(cfg, env.info())\n agent = Agent(cfg, env, policy, filter_op)\n\n # ---- start training ---- #\n if policy_state is not None:\n agent.policy().reset(policy_state)\n if filter_state is not None:\n agent.filter().reset(filter_state)\n\n train_loop(cfg, agent, logger)\n\n print(\"Done\")\n\n\nif __name__ == '__main__':\n import torch.multiprocessing as multiprocessing\n multiprocessing.set_start_method('spawn')\n\n default_config.parser()\n\n train_cfg = loadInitConfig(default_config)\n\n main(train_cfg)\n\n exit(0)\n"
] |
[
[
"torch.sqrt",
"torch.multiprocessing.set_start_method",
"torch.cat"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sehomi/pyCFTrackers
|
[
"4dbd550fbac78f4e7e35fdb4a1761b5b0cf9b096",
"4dbd550fbac78f4e7e35fdb4a1761b5b0cf9b096",
"4dbd550fbac78f4e7e35fdb4a1761b5b0cf9b096",
"4dbd550fbac78f4e7e35fdb4a1761b5b0cf9b096"
] |
[
"ltr/models/target_classifier/residual_modules.py",
"cftracker/ldes.py",
"cftracker/dat.py",
"ltr/models/loss/bbr_loss.py"
] |
[
"import torch\nimport torch.nn as nn\nimport math\nimport ltr.models.layers.filter as filter_layer\nimport ltr.models.layers.activation as activation\nfrom ltr.models.layers.distance import DistanceMap\nfrom pytracking import TensorList\n\n\nclass LinearFilterLearnGen(nn.Module):\n def __init__(self, feat_stride=16, init_filter_reg=1e-2, init_gauss_sigma=1.0, num_dist_bins=5, bin_displacement=1.0,\n mask_init_factor=4.0, score_act='bentpar', act_param=None, mask_act='sigmoid'):\n super().__init__()\n\n self.filter_reg = nn.Parameter(init_filter_reg * torch.ones(1))\n self.feat_stride = feat_stride\n self.distance_map = DistanceMap(num_dist_bins, bin_displacement)\n\n # Distance coordinates\n d = torch.arange(num_dist_bins, dtype=torch.float32).reshape(1,-1,1,1) * bin_displacement\n if init_gauss_sigma == 0:\n init_gauss = torch.zeros_like(d)\n init_gauss[0,0,0,0] = 1\n else:\n init_gauss = torch.exp(-1/2 * (d / init_gauss_sigma)**2)\n\n self.label_map_predictor = nn.Conv2d(num_dist_bins, 1, kernel_size=1, bias=False)\n self.label_map_predictor.weight.data = init_gauss - init_gauss.min()\n\n mask_layers = [nn.Conv2d(num_dist_bins, 1, kernel_size=1, bias=False)]\n if mask_act == 'sigmoid':\n mask_layers.append(nn.Sigmoid())\n init_bias = 0.0\n elif mask_act == 'linear':\n init_bias = 0.5\n else:\n raise ValueError('Unknown activation')\n self.target_mask_predictor = nn.Sequential(*mask_layers)\n self.target_mask_predictor[0].weight.data = mask_init_factor * torch.tanh(2.0 - d) + init_bias\n\n self.spatial_weight_predictor = nn.Conv2d(num_dist_bins, 1, kernel_size=1, bias=False)\n self.spatial_weight_predictor.weight.data.fill_(1.0)\n\n if score_act == 'bentpar':\n self.score_activation = activation.BentIdentPar(act_param)\n elif score_act == 'relu':\n self.score_activation = activation.LeakyReluPar()\n else:\n raise ValueError('Unknown activation')\n\n\n def forward(self, meta_parameter: TensorList, feat, bb, sample_weight=None, is_distractor=None):\n filter = meta_parameter[0]\n\n num_images = feat.shape[0]\n num_sequences = feat.shape[1] if feat.dim() == 5 else 1\n filter_sz = (filter.shape[-2], filter.shape[-1])\n\n # Compute scores\n scores = filter_layer.apply_filter(feat, filter)\n\n # Compute distance map\n center = ((bb[..., :2] + bb[..., 2:] / 2) / self.feat_stride).reshape(-1, 2).flip((1,))\n if is_distractor is not None:\n center[is_distractor.reshape(-1), :] = 99999\n dist_map = self.distance_map(center, scores.shape[-2:])\n\n # Compute label map masks and weight\n label_map = self.label_map_predictor(dist_map).reshape(num_images, num_sequences, dist_map.shape[-2], dist_map.shape[-1])\n target_mask = self.target_mask_predictor(dist_map).reshape(num_images, num_sequences, dist_map.shape[-2], dist_map.shape[-1])\n spatial_weight = self.spatial_weight_predictor(dist_map).reshape(num_images, num_sequences, dist_map.shape[-2], dist_map.shape[-1])\n\n if sample_weight is None:\n sample_weight = math.sqrt(1.0 / num_images) * spatial_weight\n elif isinstance(sample_weight, torch.Tensor):\n sample_weight = sample_weight.sqrt().reshape(-1, 1, 1, 1) * spatial_weight\n\n # Compute data residual\n scores_act = self.score_activation(scores, target_mask)\n data_residual = sample_weight * (scores_act - label_map)\n\n # Compute regularization residual. Put batch in second dimension\n reg_residual = self.filter_reg*filter.reshape(1, num_sequences, -1)\n\n return TensorList([data_residual, reg_residual])\n\n\nclass LinearFilterHinge(nn.Module):\n def __init__(self, feat_stride=16, init_filter_reg=1e-2, hinge_threshold=-999, activation_leak=0.0, score_act='bentpar', act_param=None):\n super().__init__()\n\n self.filter_reg = nn.Parameter(init_filter_reg * torch.ones(1))\n self.feat_stride = feat_stride\n self.hinge_threshold = hinge_threshold\n self.activation_leak = activation_leak\n\n if score_act == 'bentpar':\n self.score_activation = activation.BentIdentPar(act_param)\n elif score_act == 'relu':\n self.score_activation = activation.LeakyReluPar()\n else:\n raise ValueError('Unknown activation')\n\n\n def forward(self, meta_parameter: TensorList, feat, bb=None, train_label=None, sample_weight=None, is_distractor=None):\n assert isinstance(meta_parameter, TensorList)\n\n filter = meta_parameter[0]\n\n num_images = feat.shape[0]\n num_sequences = feat.shape[1] if feat.dim() == 5 else 1\n\n # Compute scores\n scores = filter_layer.apply_filter(feat, filter)\n\n if sample_weight is None:\n sample_weight = math.sqrt(1.0 / num_images)\n elif isinstance(sample_weight, torch.Tensor):\n sample_weight = sample_weight.sqrt()\n else:\n raise NotImplementedError()\n\n # Compute data residual\n target_mask = ((train_label > self.hinge_threshold).float() + self.activation_leak).clamp(max=1.0)\n scores_act = self.score_activation(scores, target_mask)\n data_residual = sample_weight * (scores_act - target_mask * train_label)\n\n # Compute regularization residual. Put batch in second dimension\n reg_residual = self.filter_reg*filter.view(1, num_sequences, -1)\n\n return TensorList([data_residual, reg_residual])\n",
"import numpy as np\r\nfrom numpy.matlib import repmat\r\nimport cv2\r\nfrom scipy.ndimage import map_coordinates\r\nfrom lib.utils import cos_window,gaussian2d_rolled_labels\r\nfrom lib.fft_tools import fft2,ifft2\r\nfrom cftracker.base import BaseCF\r\nfrom cftracker.feature import extract_hog_feature,extract_cn_feature,extract_cn_feature_byw2c\r\nfrom skimage.feature.peak import peak_local_max\r\nfrom lib.utils import APCE\r\n\r\ndef mod_one(a, b):\r\n y = np.mod(a - 1, b) + 1\r\n return y\r\n\r\ndef cf_confidence(response_cf):\r\n peak_loc_indices = peak_local_max(response_cf, min_distance=1,indices=True)\r\n max_peak_val=0\r\n secondmax_peak_val=0\r\n max_peak_val_indice=[0,0]\r\n secondmax_peak_val_indice=[0,0]\r\n for indice in peak_loc_indices:\r\n if response_cf[indice]>max_peak_val:\r\n max_peak_val_indice=indice\r\n max_peak_val=response_cf[indice]\r\n elif response_cf[indice]>secondmax_peak_val:\r\n secondmax_peak_val_indice=indice\r\n secondmax_peak_val=response_cf[indice]\r\n pass\r\n\r\ndef confidence_cf_apce(response_cf):\r\n apce=APCE(response_cf)\r\n conf=np.clip(apce/50,a_min=0,a_max=1)\r\n return conf\r\n\r\n\r\n# max val at the bottom right loc\r\ndef gaussian2d_rolled_labels_staple(sz, sigma):\r\n halfx, halfy = int(np.floor((sz[0] - 1) / 2)), int(np.floor((sz[1] - 1) / 2))\r\n x_range = np.arange(-halfx, halfx + 1)\r\n y_range = np.arange(-halfy, halfy + 1)\r\n i, j = np.meshgrid(y_range, x_range)\r\n i_mod_range = mod_one(i, sz[1])\r\n j_mod_range = mod_one(j, sz[0])\r\n labels = np.zeros((sz[1], sz[0]))\r\n labels[i_mod_range - 1, j_mod_range - 1] = np.exp(-(i ** 2 + j ** 2) / (2 * sigma ** 2))\r\n return labels\r\n\r\n\r\ndef crop_filter_response(response_cf, response_sz):\r\n h, w = response_cf.shape[:2]\r\n half_width = int(np.floor(response_sz[0] / 2))\r\n half_height = int(np.floor(response_sz[1] / 2))\r\n range_i, range_j = np.arange(-half_height, half_height + 1), np.arange(-half_width, half_width + 1)\r\n i, j = np.meshgrid(mod_one(range_i, h), mod_one(range_j, w))\r\n new_responses = response_cf[i - 1, j - 1]\r\n return new_responses.T\r\n\r\n# pad [h,w] format\r\ndef pad(img,pad):\r\n h,w=img.shape[:2]\r\n delta=(int((pad[0]-h)/2),int((pad[1]-w)/2))\r\n c=img.shape[2]\r\n r=np.zeros((pad[0],pad[1],c))\r\n idy=[delta[0],delta[0]+h]\r\n idx=[delta[1],delta[1]+w]\r\n r[idy[0]:idy[1], idx[0]:idx[1], :] = img\r\n return r\r\n\r\ndef parameters_to_projective_matrix(p):\r\n \"\"\"\r\n :param p: [s,rot,x,y]\r\n :return:\r\n \"\"\"\r\n s,rot,x,y=p\r\n R=np.array([[np.cos(rot),-np.sin(rot)],\r\n [np.sin(rot),np.cos(rot)]])\r\n T=np.diag([1.,1.,1.])\r\n T[:2,:2]=s*R\r\n T[0,2]=x\r\n T[1,2]=y\r\n return T\r\n\r\n\r\ndef getLKcorner(warp_p,sz):\r\n template_nx,template_ny=sz\r\n nx=(sz[0]-1)/2\r\n ny=(sz[1]-1)/2\r\n tmplt_pts=np.array([[-nx,-ny],\r\n [-nx,template_ny-ny],\r\n [template_nx-nx,template_ny-ny],\r\n [template_nx-nx,-ny]]).T\r\n if warp_p.shape[0]==2:\r\n M=np.concatenate((warp_p,np.array([0,0,1])),axis=0)\r\n M[0,0]=M[0,0]+1\r\n M[1,1]=M[1,1]+1\r\n else:\r\n M=warp_p\r\n warp_pts=M.dot(np.concatenate((tmplt_pts,np.ones((1,4))),axis=0))\r\n c=np.array([[(1+template_nx)/2],[(1+template_ny)/2],[1]])\r\n warp_pts=warp_pts[:2,:]\r\n return warp_pts\r\n\r\ndef PSR(response,rate):\r\n max_response=np.max(response)\r\n h,w=response.shape\r\n k=4/(h*w)\r\n yy,xx=np.unravel_index(np.argmax(response, axis=None),response.shape)\r\n idx=np.arange(w)-xx\r\n idy=np.arange(h)-yy\r\n idx=repmat(idx,h,1)\r\n idy=repmat(idy,w,1).T\r\n t=idx**2+idy**2\r\n delta=1-np.exp(-k*t.astype(np.float32))\r\n r=(max_response-response)/delta\r\n r[np.isnan(r)]=np.inf\r\n return np.min(r)\r\n\r\n\r\ndef get_center_likelihood(likelihood_map, sz):\r\n h,w=likelihood_map.shape[:2]\r\n n1= h - sz[1] + 1\r\n n2= w - sz[0] + 1\r\n sat=cv2.integral(likelihood_map)\r\n i,j=np.arange(n1),np.arange(n2)\r\n i,j=np.meshgrid(i,j)\r\n sat1=sat[i,j]\r\n sat2=np.roll(sat, -sz[1], axis=0)\r\n sat2=np.roll(sat2, -sz[0], axis=1)\r\n sat2=sat2[i,j]\r\n sat3=np.roll(sat, -sz[1], axis=0)\r\n sat3=sat3[i,j]\r\n sat4=np.roll(sat, -sz[0], axis=1)\r\n sat4=sat4[i,j]\r\n center_likelihood=((sat1+sat2-sat3-sat4)/(sz[0] * sz[1])).T\r\n def fillzeros(im,sz):\r\n res=np.zeros((sz[1],sz[0]))\r\n msz=((sz[0]-im.shape[1])//2,(sz[1]-im.shape[0])//2)\r\n res[msz[1]:msz[1]+im.shape[0],msz[0]:msz[0]+im.shape[1]]=im\r\n return res\r\n center_likelihood=fillzeros(center_likelihood,(w,h))\r\n return center_likelihood\r\n\r\nclass LDES(BaseCF):\r\n def __init__(self,config):\r\n super(LDES).__init__()\r\n self.kernel_type=config.kernel_type\r\n self.padding=config.padding\r\n self.lambda_ = config.lambda_\r\n self.output_sigma_factor = config.output_sigma_factor\r\n self.interp_factor = config.interp_factor\r\n self.cell_size = config.cell_size\r\n\r\n self.min_image_sample_size =config.min_image_sample_size\r\n self.max_image_sample_size = config.max_image_sample_size\r\n\r\n self.fixed_model_sz = config.fixed_model_sz\r\n self.is_rotation = config.is_rotation\r\n self.is_BGD = config.is_BGD\r\n self.is_subpixel = config.is_subpixel\r\n self.interp_n = config.interp_n\r\n\r\n self.learning_rate_scale = config.learning_rate_scale\r\n self.scale_sz_window = config.scale_sz_window\r\n\r\n # color histogram\r\n self.inter_patch_rate = config.inter_patch_rate\r\n self.nbin = config.nbin\r\n self.color_update_rate = config.color_update_rate\r\n self.merge_factor = config.merge_factor\r\n\r\n self.polygon=config.polygon\r\n self.vis=False\r\n self.sigma=config.sigma\r\n self.adaptive_merge_factor=config.adaptive_merge_factor\r\n self.theta=config.theta\r\n\r\n def init(self, first_frame, region):\r\n #file = h5py.File('../lib/w2crs.mat', 'r')\r\n #self.w2c = file['w2crs']\r\n self.use_color_hist=not(np.all(first_frame[:,:,0]==first_frame[:,:,1]))\r\n assert len(first_frame.shape)==3 and first_frame.shape[2]==3\r\n region = np.array(region).astype(np.int64)\r\n if len(region)==4:\r\n x0, y0, w, h = tuple(region)\r\n rot=0\r\n self._center = (x0 + w / 2, y0 + h / 2)\r\n target_sz = (w, h)\r\n elif len(region)==8:\r\n corners=region.reshape((4,2))\r\n pos=np.mean(corners,axis=0)\r\n pos=pos.T\r\n dist12=np.sqrt(np.sum((corners[1,:]-corners[2,:])**2))\r\n dist03=np.sqrt(np.sum((corners[0,:]-corners[3,:])**2))\r\n dist10=np.sqrt(np.sum((corners[1,:]-corners[0,:])**2))\r\n dist23=np.sqrt(np.sum((corners[2,:]-corners[3,:])**2))\r\n target_sz=((dist10+dist23)/2,(dist12+dist03)/2)\r\n self._center=(pos[0],pos[1])\r\n A=np.array([0.,-1.])\r\n B=np.array([region[4]-region[2],region[3]-region[5]])\r\n rot1=np.arccos(A.dot(B)/(np.linalg.norm(A)*np.linalg.norm(B)))*2/np.pi\r\n if np.prod(B)<0:\r\n rot1=-rot1\r\n C=np.array([region[6]-region[0],region[1]-region[7]])\r\n rot2=np.arccos(A.dot(C)/(np.linalg.norm(A)*np.linalg.norm(C)))*2/np.pi\r\n if np.prod(C)<0:\r\n rot2=-rot2\r\n rot=(rot1+rot2)/2\r\n else:\r\n raise ValueError()\r\n\r\n self.bin_mapping=self.get_bin_mapping(self.nbin)\r\n\r\n self.window_sz=(int(np.floor(target_sz[0] * (1 + self.padding))), int(np.floor(target_sz[1] * (1 + self.padding))))\r\n search_area= self.window_sz[0] * self.window_sz[1]\r\n self.sc=search_area/np.clip(search_area,a_min=self.min_image_sample_size,a_max=self.max_image_sample_size)\r\n self.window_sz0=(int(np.round(self.window_sz[0] / self.sc)), int(np.round(self.window_sz[1] / self.sc)))\r\n feature_sz=(self.window_sz0[0] // self.cell_size, self.window_sz0[1] // self.cell_size)\r\n self.window_sz0=(feature_sz[0] * self.cell_size, feature_sz[1] * self.cell_size)\r\n\r\n self.sc= (self.window_sz[0] / self.window_sz0[0],self.window_sz[1]/self.window_sz0[1])\r\n self.cell_size=int(np.round((self.window_sz0[0] / feature_sz[0])))\r\n self.rot=rot\r\n self.avg_dim= (self.window_sz[0] + self.window_sz[1]) / 4\r\n self.window_sz_search=(int(np.floor(self.window_sz[0]+self.avg_dim)),int(np.floor(self.window_sz[1]+self.avg_dim)))\r\n self.window_sz_search0=(int(np.floor(self.window_sz_search[0]/self.sc[0])),int(np.floor(self.window_sz_search[1]/self.sc[1])))\r\n cell_size_search=self.cell_size\r\n feature_sz0=(int(np.floor(self.window_sz_search0[0]/cell_size_search)),\r\n int(np.floor(self.window_sz_search0[1]/cell_size_search)))\r\n residual=(feature_sz0[0]-feature_sz[0],feature_sz0[1]-feature_sz[1])\r\n feature_sz0=(feature_sz0[0]+residual[0]%2,feature_sz0[1]+residual[1]%2)\r\n self.window_sz_search0=(feature_sz0[0]*cell_size_search,\r\n feature_sz0[1]*cell_size_search)\r\n self.sc=(self.window_sz_search[0]/self.window_sz_search0[0],\r\n self.window_sz_search[1]/self.window_sz_search0[1])\r\n self.target_sz0=(int(np.round(target_sz[0]/self.sc[0])),\r\n int(np.round(target_sz[1]/self.sc[1])))\r\n self.output_sigma=np.sqrt(target_sz[0]*target_sz[1])*self.output_sigma_factor/self.cell_size\r\n self.y=gaussian2d_rolled_labels_staple((int(np.round(self.window_sz0[0]/self.cell_size)),\r\n int(np.round(self.window_sz0[1]/self.cell_size))),\r\n self.output_sigma)\r\n self.yf=fft2(self.y)\r\n self.cos_window=cos_window((self.y.shape[1],self.y.shape[0]))\r\n self.cos_window_search=cos_window((int(np.floor(self.window_sz_search0[0]/cell_size_search)),\r\n int(np.floor(self.window_sz_search0[1]/cell_size_search))))\r\n # scale setttings\r\n avg_dim=(target_sz[0]+target_sz[1])/2.5\r\n self.scale_sz=((target_sz[0]+avg_dim)/self.sc[0],\r\n (target_sz[1]+avg_dim)/self.sc[1])\r\n self.scale_sz0=self.scale_sz\r\n self.cos_window_scale=cos_window((self.scale_sz_window[0]//self.cell_size,self.scale_sz_window[1]//self.cell_size))\r\n self.mag=self.scale_sz_window[1]/np.log(np.sqrt((self.scale_sz_window[0]**2+\r\n self.scale_sz_window[1]**2)/4))\r\n\r\n self.cell_size=cell_size_search\r\n tmp_sc = 1.\r\n tmp_rot = 0.\r\n self.logupdate(1,first_frame,self._center,tmp_sc,tmp_rot)\r\n x,y=self._center\r\n x=np.clip(x,a_min=0,a_max=first_frame.shape[1]-1)\r\n y=np.clip(y,a_min=0,a_max=first_frame.shape[0]-1)\r\n self._center=(x,y)\r\n\r\n\r\n\r\n def update(self,current_frame,vis=False,FI=None,do_learning=True):\r\n\r\n # self.vis=vis\r\n self.vis=True\r\n\r\n ## this section is added to get search zone based on camera orientation\r\n ## if the estimated search zone is provided through FI\r\n if FI is None:\r\n search_zone_center=self._center\r\n else:\r\n search_zone_center=(int(FI[0]+FI[2]/2),int(FI[1]+FI[3]/2))\r\n\r\n pos,tmp_sc,tmp_rot,cscore,sscore=self.tracking(current_frame,search_zone_center,0)\r\n\r\n if self.is_BGD:\r\n #print('cscore:',cscore,' sscore:',sscore)\r\n cscore=(1-self.interp_n)*cscore+self.interp_n*sscore\r\n iter=0\r\n mcscore=0\r\n mpos=None\r\n msc = None\r\n mrot = None\r\n while iter<5:\r\n if np.floor(self.sc[0]*tmp_sc*self.window_sz0[0])+np.floor(self.sc[1]*tmp_sc*self.window_sz0[1])<10:\r\n tmp_sc=1.\r\n self.sc=(self.sc[0]*tmp_sc,self.sc[1]*tmp_sc)\r\n self.rot=self.rot+tmp_rot\r\n if cscore>=mcscore:\r\n msc=self.sc\r\n mrot=self.rot\r\n mpos=pos\r\n mcscore=cscore\r\n else:\r\n break\r\n #print('iter:',iter)\r\n pos,tmp_sc,tmp_rot,cscore,sscore=self.tracking(current_frame,pos,iter)\r\n cscore=(1-self.interp_n)*cscore+self.interp_n*sscore\r\n iter+=1\r\n if msc is not None:\r\n pos = mpos\r\n self.sc = msc\r\n self.rot = mrot\r\n\r\n ## do not update template when target is lost\r\n if not do_learning:\r\n x, y = pos\r\n x = np.clip(x, a_min=0, a_max=current_frame.shape[1]-1)\r\n y = np.clip(y, a_min=0, a_max=current_frame.shape[0]-1)\r\n self._center=(x,y)\r\n target_sz=(self.sc[0]*self.target_sz0[0],self.sc[1]*self.target_sz0[1])\r\n box=[x-target_sz[0]/2,y-target_sz[1]/2,target_sz[0],target_sz[1]]\r\n return box\r\n\r\n self.logupdate(0,current_frame,pos,tmp_sc,tmp_rot)\r\n x, y = pos\r\n x = np.clip(x, a_min=0, a_max=current_frame.shape[1]-1)\r\n y = np.clip(y, a_min=0, a_max=current_frame.shape[0]-1)\r\n self._center=(x,y)\r\n target_sz=(self.sc[0]*self.target_sz0[0],self.sc[1]*self.target_sz0[1])\r\n box=[x-target_sz[0]/2,y-target_sz[1]/2,target_sz[0],target_sz[1]]\r\n aff=[]\r\n if self.is_rotation:\r\n T=parameters_to_projective_matrix([1,self.rot,self._center[0],self._center[1]])\r\n aff=getLKcorner(T,target_sz)\r\n \"\"\"\r\n import copy\r\n show_img=copy.deepcopy(current_frame)\r\n tl=(int(aff[0,0]),int(aff[1,0]))\r\n tr=(int(aff[0,1]),int(aff[1,1]))\r\n br=(int(aff[0,2]),int(aff[1,2]))\r\n bl=(int(aff[0,3]),int(aff[1,3]))\r\n show_img=cv2.line(show_img,tl,tr,color=(255,0,0))\r\n show_img=cv2.line(show_img,tr,br,color=(255,0,0))\r\n show_img=cv2.line(show_img,br,bl,color=(255,0,0))\r\n show_img=cv2.line(show_img,bl,tl,color=(255,0,0))\r\n cv2.imshow('show_img',show_img)\r\n cv2.waitKey(1)\r\n \"\"\"\r\n self.aff=aff\r\n if self.polygon is True:\r\n aff=aff[:,[0,3,2,1]]\r\n reg=aff.T.flatten()\r\n return reg\r\n else:\r\n return box\r\n\r\n def logupdate(self,init,img,pos,tmp_sc,tmp_rot):\r\n tmp=np.floor(self.sc[0]*tmp_sc*self.window_sz0[0])+np.floor(self.sc[1]*tmp_sc*self.window_sz0[1])\r\n if tmp<10:\r\n tmp_sc=1.\r\n self.sc=(self.sc[0]*tmp_sc,self.sc[1]*tmp_sc)\r\n self.rot=self.rot+tmp_rot\r\n self.window_sz=(int(np.floor(self.sc[0]*self.window_sz0[0])),\r\n int(np.floor(self.sc[1]*self.window_sz0[1])))\r\n self.window_sz_search=(int(np.floor(self.sc[0]*self.window_sz_search0[0])),\r\n int(np.floor(self.sc[1]*self.window_sz_search0[1])))\r\n # compute the current CF model\r\n # sampling the image\r\n if self.is_rotation:\r\n patch=self.get_affine_subwindow(img, pos, self.sc, self.rot, self.window_sz0)\r\n else:\r\n patchO=cv2.getRectSubPix(img,self.window_sz,pos)\r\n patch=cv2.resize(patchO,self.window_sz0,interpolation=cv2.INTER_CUBIC)\r\n x=self.get_features(patch,self.cell_size)\r\n x=x*self.cos_window[:,:,None]\r\n xf=fft2(x)\r\n #kf=np.sum(xf*np.conj(xf),axis=2)/xf.size\r\n kf=self._kernel_correlation(xf,xf,self.kernel_type)\r\n alphaf=self.yf/(kf+self.lambda_)\r\n\r\n if self.is_rotation:\r\n # here is not similarity transformation\r\n patchL=self.get_affine_subwindow(img, pos,[1.,1.], self.rot, (int(np.floor(self.sc[0]* self.scale_sz[0])),\r\n int(np.floor(self.sc[1]*self.scale_sz[1]))))\r\n else:\r\n patchL=cv2.getRectSubPix(img,(int(np.floor(self.sc[0]*self.scale_sz[0])),\r\n int(np.floor(self.sc[1]*self.scale_sz[1]))),pos)\r\n patchL=cv2.resize(patchL,self.scale_sz_window,cv2.INTER_CUBIC)\r\n # get logpolar space and apply feature extraction\r\n patchLp=cv2.logPolar(patchL.astype(np.float32),(patchL.shape[1]//2,patchL.shape[0]//2),self.mag,flags=cv2.INTER_LINEAR + cv2.WARP_FILL_OUTLIERS)\r\n\r\n patchLp=extract_hog_feature(patchLp,self.cell_size)\r\n #patchLp = patchLp * self.cos_window_scale[:, :, None]\r\n\r\n # updating color histogram probabilities\r\n sz=(patch.shape[1],patch.shape[0])\r\n\r\n #is_color=True\r\n if self.use_color_hist:\r\n pos_in=((sz[0])/2-1,(sz[1])/2-1)\r\n lab_patch=patch\r\n inter_patch=cv2.getRectSubPix(lab_patch.astype(np.uint8),(int(round(sz[0]*self.inter_patch_rate)),int(round(sz[1]*self.inter_patch_rate))),pos_in)\r\n self.interp_patch=inter_patch\r\n pl=self.get_color_space_hist(lab_patch,self.nbin)\r\n pi=self.get_color_space_hist(inter_patch,self.nbin)\r\n interp_factor_scale=self.learning_rate_scale\r\n if init==1: # first_frame\r\n self.model_alphaf=alphaf\r\n self.model_xf=xf\r\n self.model_patchLp=patchLp\r\n if self.use_color_hist:\r\n self.pl=pl\r\n self.pi=pi\r\n\r\n else:\r\n # CF model\r\n self.model_alphaf=(1-self.interp_factor)*self.model_alphaf+self.interp_factor*alphaf\r\n self.model_xf=(1-self.interp_factor)*self.model_xf+self.interp_factor*xf\r\n self.model_patchLp= (1 - interp_factor_scale) * self.model_patchLp + interp_factor_scale * patchLp\r\n if self.use_color_hist:\r\n self.pi=(1-self.color_update_rate)*self.pi+self.color_update_rate*pi\r\n self.pl=(1-self.color_update_rate)*self.pl+self.color_update_rate*pl\r\n\r\n\r\n def tracking(self,img,pos,polish):\r\n \"\"\"\r\n obtain a subwindow for detecting at the positiono from last frame, and convert to Fourier domain\r\n find a proper window size\r\n :param img:\r\n :param pos:\r\n :param iter:\r\n :return:\r\n \"\"\"\r\n\r\n large_num=0\r\n if polish>large_num:\r\n w_sz0=self.window_sz0\r\n c_w=self.cos_window\r\n else:\r\n w_sz0=self.window_sz_search0\r\n c_w=self.cos_window_search\r\n if self.is_rotation:\r\n patch=self.get_affine_subwindow(img, pos, self.sc, self.rot, w_sz0)\r\n else:\r\n sz_s=(int(np.floor(self.sc[0]*w_sz0[0])),int(np.floor(self.sc[1]*w_sz0[1])))\r\n patchO=cv2.getRectSubPix(img,sz_s,pos)\r\n patch=cv2.resize(patchO,w_sz0,cv2.INTER_CUBIC)\r\n\r\n z=self.get_features(patch,self.cell_size)\r\n z=z*c_w[:,:,None]\r\n zf=fft2(z)\r\n ssz=(zf.shape[1],zf.shape[0],zf.shape[2])\r\n # calculate response of the classifier at all shifts\r\n wf=np.conj(self.model_xf)*self.model_alphaf[:,:,None]/np.size(self.model_xf)\r\n if polish<=large_num:\r\n w=pad(np.real(ifft2(wf)),(ssz[1],ssz[0]))\r\n wf=fft2(w)\r\n\r\n tmp_sz=ssz\r\n # compute convolution for each feature block in the Fourier domain\r\n # use general compute here for easy extension in future\r\n\r\n rff=np.sum(wf*zf,axis=2)\r\n rff_real=cv2.resize(rff.real,(tmp_sz[0],tmp_sz[1]),cv2.INTER_NEAREST)\r\n rff_imag=cv2.resize(rff.imag,(tmp_sz[0],tmp_sz[1]),cv2.INTER_NEAREST)\r\n rff=rff_real+1.j*rff_imag\r\n response_cf=np.real(ifft2(rff))\r\n #response_cf=np.fft.fftshift(response_cf,axes=(0,1))\r\n response_cf=crop_filter_response(response_cf,(response_cf.shape[1],response_cf.shape[0]))\r\n\r\n response_color=np.zeros_like(response_cf)\r\n\r\n if self.use_color_hist:\r\n object_likelihood=self.get_colour_map(patch,self.pl,self.pi,self.bin_mapping)\r\n response_color=get_center_likelihood(object_likelihood,self.target_sz0)\r\n response_color=cv2.resize(response_color,(response_cf.shape[1],response_cf.shape[0]),cv2.INTER_CUBIC)\r\n\r\n # adaptive merge factor\r\n if self.adaptive_merge_factor is True:\r\n cf_conf=confidence_cf_apce(response_cf)\r\n adaptive_merge_factor=self.merge_factor*self.theta+(1-self.theta)*(1-cf_conf)\r\n response=(1-adaptive_merge_factor)*response_cf+adaptive_merge_factor*response_color\r\n else:\r\n response=(1-self.merge_factor)*response_cf+self.merge_factor*response_color\r\n if self.vis is True:\r\n self.score=response\r\n self.crop_size=self.window_sz\r\n # sub-pixel search\r\n pty,ptx=np.unravel_index(np.argmax(response, axis=None),response.shape)\r\n\r\n if self.is_subpixel:\r\n slobe=2\r\n idy=np.arange(pty-slobe,pty+slobe+1)\r\n idx=np.arange(ptx-slobe,ptx+slobe+1)\r\n idy=np.clip(idy,a_min=0,a_max=response.shape[0]-1)\r\n idx=np.clip(idx,a_min=0,a_max=response.shape[1]-1)\r\n weight_patch=response[idy,:][:,idx]\r\n s=np.sum(weight_patch)+2e-16\r\n pty=np.sum(np.sum(weight_patch,axis=1)*idy)/s\r\n ptx=np.sum(np.sum(weight_patch,axis=0)*idx)/s\r\n cscore=PSR(response,0.1)\r\n\r\n # update the translation status\r\n dy=pty-(response.shape[0])//2\r\n dx=ptx-(response.shape[1])//2\r\n\r\n self.trans=[dy,dx]\r\n\r\n if self.is_rotation:\r\n sn,cs=np.sin(self.rot),np.cos(self.rot)\r\n pp=np.array([[self.sc[1]*cs,-self.sc[0]*sn],\r\n [self.sc[1]*sn,self.sc[0]*cs]])\r\n x,y=pos\r\n delta=self.cell_size*np.array([[dy,dx]]).dot(pp)\r\n x+=delta[0,1]\r\n y+=delta[0,0]\r\n pos=(x,y)\r\n patchL=self.get_affine_subwindow(img, pos, [1.,1.], self.rot, (int(np.floor(self.sc[0]* self.scale_sz[0])),\r\n int(np.floor(self.sc[1]*self.scale_sz[1]))))\r\n else:\r\n x,y=pos\r\n pos=(x+self.sc[0]*self.cell_size*dx,y+self.sc[1]*self.cell_size*dy)\r\n patchL=cv2.getRectSubPix(img,(int(np.floor(self.sc[0]*self.scale_sz[0])),\r\n int(np.floor(self.sc[1]*self.scale_sz[1]))),pos)\r\n patchL=cv2.resize(patchL,self.scale_sz_window,cv2.INTER_CUBIC)\r\n patchLp=cv2.logPolar(patchL.astype(np.float32),(patchL.shape[1]//2,patchL.shape[0]//2),self.mag,flags=cv2.INTER_LINEAR + cv2.WARP_FILL_OUTLIERS)\r\n patchLp=extract_hog_feature(patchLp,self.cell_size)\r\n #patchLp = patchLp * self.cos_window_scale[:, :, None]\r\n tmp_sc,tmp_rot,sscore=self.estimate_scale(self.model_patchLp, patchLp, self.mag)\r\n tmp_sc=np.clip(tmp_sc,a_min=0.6,a_max=1.4)\r\n if tmp_rot>1 or tmp_rot<-1:\r\n tmp_rot=0\r\n return pos, tmp_sc, tmp_rot, cscore, sscore\r\n\r\n def estimate_scale(self,model,obser,mag):\r\n def phase_correlation(src1,src2):\r\n s1f=fft2(src1)\r\n s2f=fft2(src2)\r\n num=s2f*np.conj(s1f)\r\n d=np.sqrt(num*np.conj(num))+2e-16\r\n Cf=np.sum(num/d,axis=2)\r\n C=np.real(ifft2(Cf))\r\n C=np.fft.fftshift(C,axes=(0,1))\r\n #mscore=np.max(C)\r\n mscore=PSR(C,0.1)\r\n pty,ptx=np.unravel_index(np.argmax(C, axis=None), C.shape)\r\n slobe_y=slobe_x=1\r\n idy=np.arange(pty-slobe_y,pty+slobe_y+1).astype(np.int64)\r\n idx=np.arange(ptx-slobe_x,ptx+slobe_x+1).astype(np.int64)\r\n idy=np.clip(idy,a_min=0,a_max=C.shape[0]-1)\r\n idx=np.clip(idx,a_min=0,a_max=C.shape[1]-1)\r\n weight_patch=C[idy,:][:,idx]\r\n\r\n s=np.sum(weight_patch)+2e-16\r\n pty=np.sum(np.sum(weight_patch,axis=1)*idy)/s\r\n ptx=np.sum(np.sum(weight_patch,axis=0)*idx)/s\r\n pty=pty-(src1.shape[0])//2\r\n ptx=ptx-(src1.shape[1])//2\r\n return ptx,pty,mscore\r\n\r\n ptx,pty,mscore=phase_correlation(model,obser)\r\n rotate=pty*np.pi/(np.floor(obser.shape[1]/2))\r\n scale = np.exp(ptx/mag)\r\n return scale,rotate,mscore\r\n\r\n def get_features(self,img,cell_size):\r\n hog_feature=extract_hog_feature(img.astype(np.uint8),cell_size)\r\n #resized_img=cv2.resize(img,(hog_feature.shape[1],hog_feature.shape[0]),cv2.INTER_CUBIC).astype(np.uint8)\r\n #cn_feature=extract_cn_feature(resized_img,1)\r\n cn_feature=extract_cn_feature(img,cell_size)\r\n return np.concatenate((hog_feature,cn_feature),axis=2)\r\n\r\n def get_color_space_hist(self,patch,n_bins):\r\n histogram=cv2.calcHist([patch.astype(np.uint8)],[0,1,2],None,[n_bins,n_bins,n_bins],[0,256,0,256,0,256])\r\n return histogram\r\n\r\n def get_colour_map(self,patch,bg_hist,fg_hist,bin_mapping):\r\n frame_bin = cv2.LUT(patch.astype(np.uint8), bin_mapping).astype(np.int64)\r\n P_fg = fg_hist[frame_bin[:, :, 0], frame_bin[:, :, 1], frame_bin[:, :, 2]]\r\n P_bg=bg_hist[frame_bin[:,:,0],frame_bin[:,:,1],frame_bin[:,:,2]]\r\n not_na=np.where(P_bg!=0)\r\n P_O=0.5*np.ones_like(P_fg)\r\n P_O[not_na]=P_fg[not_na]/P_bg[not_na]\r\n return P_O\r\n\r\n def get_bin_mapping(self,num_bins):\r\n bin_mapping = np.zeros((256,))\r\n for i in range(bin_mapping.shape[0]):\r\n bin_mapping[i] = (np.floor(i / (256 / num_bins)))\r\n return bin_mapping.astype(np.int)\r\n\r\n\r\n def get_affine_subwindow(self,img, pos,sc, rot, window_sz):\r\n def simiparam2mat(tx,ty,rot,s):\r\n sn,cs=np.sin(rot),np.cos(rot)\r\n p=[tx,ty,s[0]*cs,-s[1]*sn,s[0]*sn,s[1]*cs]\r\n return p\r\n\r\n def interp2(img, Xq, Yq):\r\n wimg = map_coordinates(img, [Xq.ravel(), Yq.ravel()], order=1, mode='wrap')\r\n wimg = wimg.reshape(Xq.shape)\r\n return wimg\r\n\r\n def mwarpimg(img,p,sz):\r\n imsz=img.shape\r\n w,h=sz\r\n x,y=np.meshgrid(np.arange(1,w+1)-w//2,np.arange(1,h+1)-h//2)\r\n tmp1=np.zeros((h*w,3))\r\n tmp1[:,0]=1\r\n tmp1[:,1]=x.flatten()\r\n tmp1[:,2]=y.flatten()\r\n tmp2=np.array([[p[0],p[1]],[p[2],p[4]],[p[3],p[5]]])\r\n tmp3=tmp1.dot(tmp2)\r\n tmp3=np.clip(tmp3,a_min=1,a_max=None)\r\n tmp3[:, 0] = np.clip(tmp3[:, 0], a_min=None,a_max=imsz[1])\r\n tmp3[:, 1] = np.clip(tmp3[:, 1], a_min=None,a_max=imsz[0])\r\n pos=np.reshape(tmp3,(h,w,2))\r\n c=img.shape[2]\r\n wimg=np.zeros((sz[1],sz[0],c))\r\n pos=pos-1\r\n for i in range(c):\r\n wimg[:,:,i]=interp2(img[:,:,i],pos[:,:,1],pos[:,:,0])\r\n return wimg\r\n x,y=pos\r\n param0=simiparam2mat(x,y,rot,sc)\r\n out=mwarpimg(img.astype(np.float32),param0,window_sz).astype(np.uint8)\r\n #cv2.imshow('affine_window',out.astype(np.uint8))\r\n #cv2.waitKey(1)\r\n return out\r\n\r\n\r\n def _kernel_correlation(self, xf, yf, kernel='gaussian'):\r\n if kernel== 'gaussian':\r\n N=xf.shape[0]*xf.shape[1]\r\n xx=(np.dot(xf.flatten().conj().T,xf.flatten())/N)\r\n yy=(np.dot(yf.flatten().conj().T,yf.flatten())/N)\r\n xyf=xf*np.conj(yf)\r\n xy=np.sum(np.real(ifft2(xyf)),axis=2)\r\n kf = fft2(np.exp(-1 / self.sigma ** 2 * np.clip(xx+yy-2*xy,a_min=0,a_max=None) / np.size(xf)))\r\n elif kernel== 'linear':\r\n kf= np.sum(xf*np.conj(yf),axis=2)/np.size(xf)\r\n else:\r\n raise NotImplementedError\r\n return kf\r\n",
"\"\"\"\nPython re-implementation of \"In Defense of Color-based Model-free Tracking\"\n@inproceedings{Possegger2015In,\n title={In Defense of Color-based Model-free Tracking},\n author={Possegger, Horst and Mauthner, Thomas and Bischof, Horst},\n booktitle={Computer Vision & Pattern Recognition},\n year={2015},\n}\n\"\"\"\nimport numpy as np\nimport cv2\nfrom cftracker.base import BaseCF\nfrom lib.utils import cos_window\nimport copy\nfrom cftracker.config.dat_config import DATConfig\n\nclass DAT(BaseCF):\n def __init__(self):\n super(DAT).__init__()\n self.config=DATConfig()\n self.target_pos_history=[]\n self.target_sz_history=[]\n\n def init(self,first_frame,bbox):\n bbox=np.array(bbox).astype(np.int64)\n x,y,w,h=tuple(bbox)\n self._scale_factor=min(1,round(10*self.config.img_scale_target_diagonal/cv2.norm(np.array([w,h])))/10.)\n self._center=(self._scale_factor*(x+(w-1)/2),self._scale_factor*(y+(h-1)/2))\n self.w,self.h=int(w*self._scale_factor),int(h*self._scale_factor)\n self._target_sz=(self.w,self.h)\n\n img=cv2.resize(first_frame,None,fx=self._scale_factor,fy=self._scale_factor)\n if self.config.color_space=='lab':\n img=cv2.cvtColor(img,cv2.COLOR_BGR2Lab)\n elif self.config.color_space=='hsv':\n img=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n img[:, :, 0] = (img[:, :, 0] * 256 / 180)\n img = img.astype(np.uint8)\n else:\n pass\n\n surr_sz=(int(np.floor(self.config.surr_win_factor*self.w)),int(np.floor(self.config.surr_win_factor*self.h)))\n surr_rect=pos2rect(self._center,surr_sz,(img.shape[1],img.shape[0]))\n obj_rect_surr=pos2rect(self._center,self._target_sz,(img.shape[1],img.shape[0]))\n obj_rect_surr=(obj_rect_surr[0]-surr_rect[0],\n obj_rect_surr[1]-surr_rect[1],\n obj_rect_surr[2],obj_rect_surr[3])\n surr_win=get_sub_window(img,self._center,surr_sz)\n self.bin_mapping=get_bin_mapping(self.config.num_bins)\n self.prob_lut_,prob_map=get_foreground_background_probs(surr_win,obj_rect_surr,\n self.config.num_bins,self.bin_mapping)\n self._prob_lut_distractor=copy.deepcopy(self.prob_lut_)\n self._prob_lut_masked=copy.deepcopy(self.prob_lut_)\n self.adaptive_threshold_=get_adaptive_threshold(prob_map,obj_rect_surr)\n self.target_pos_history.append((self._center[0]/self._scale_factor,self._center[1]/self._scale_factor))\n self.target_sz_history.append((self._target_sz[0]/self._scale_factor,self._target_sz[1]/self._scale_factor))\n\n def update(self,current_frame,vis=False):\n img_preprocessed=cv2.resize(current_frame,None,fx=self._scale_factor,fy=self._scale_factor)\n if self.config.color_space=='lab':\n img=cv2.cvtColor(img_preprocessed,cv2.COLOR_BGR2Lab)\n elif self.config.color_space=='hsv':\n img=cv2.cvtColor(img_preprocessed,cv2.COLOR_BGR2HSV)\n img[:,:,0]=(img[:,:,0]*256/180)\n img=img.astype(np.uint8)\n else:\n img=img_preprocessed\n prev_pos=self.target_pos_history[-1]\n prev_sz=self.target_sz_history[-1]\n if self.config.motion_estimation_history_size>0:\n prev_pos=prev_pos+get_motion_prediciton(self.target_pos_history,self.config.motion_estimation_history_size)\n target_pos=(prev_pos[0]*self._scale_factor,prev_pos[1]*self._scale_factor)\n target_sz=(prev_sz[0]*self._scale_factor,prev_sz[1]*self._scale_factor)\n search_sz_w=int(np.floor(target_sz[0]+self.config.search_win_padding*max(target_sz[0],target_sz[1])))\n search_sz_h=int(np.floor(target_sz[1]+self.config.search_win_padding*max(target_sz[0],target_sz[1])))\n search_sz=(search_sz_w,search_sz_h)\n search_rect=pos2rect(target_pos,search_sz)\n self.crop_size=(search_rect[2],search_rect[3])\n search_win,padded_search_win=get_subwindow_masked(img,target_pos,search_sz)\n #Apply probability LUT\n pm_search=get_foreground_prob(search_win,self.prob_lut_,self.bin_mapping)\n if self.config.distractor_aware is True:\n pm_search_dist=get_foreground_prob(search_win,self._prob_lut_distractor,self.bin_mapping)\n pm_search=(pm_search+pm_search_dist)/2\n pm_search=pm_search*padded_search_win\n window=cos_window(search_sz)\n hypotheses,vote_scores,dist_scores=get_nms_rects(pm_search,target_sz,self.config.nms_scale,\n self.config.nms_overlap,self.config.nms_score_factor,\n window,self.config.nms_include_center_vote)\n\n candidate_centers=[]\n candidate_scores=[]\n for i in range(len(hypotheses)):\n candidate_centers.append((hypotheses[i][0]+hypotheses[i][2]/2,\n hypotheses[i][1]+hypotheses[i][3]/2))\n candidate_scores.append(vote_scores[i]*dist_scores[i])\n best_candidate=np.argmax(np.array(candidate_scores))\n target_pos=candidate_centers[best_candidate]\n\n distractors=[]\n distractor_overlap=[]\n if len(hypotheses)>1:\n target_rect=pos2rect(target_pos,target_sz,(pm_search.shape[1],pm_search.shape[0]))\n for i in range(len(hypotheses)):\n if i!=best_candidate:\n distractors.append(hypotheses[i])\n distractor_overlap.append(cal_iou(target_rect,distractors[-1]))\n if vis:\n self.score=pm_search\n\n\n target_pos_img=(target_pos[0]+search_rect[0],target_pos[1]+search_rect[1])\n if self.config.prob_lut_update_rate>0:\n surr_sz=(int(self.config.surr_win_factor*target_sz[0]),int(self.config.surr_win_factor*target_sz[1]))\n surr_rect=pos2rect(target_pos_img,surr_sz,(img.shape[1],img.shape[0]))\n obj_rect_surr=pos2rect(target_pos_img,target_sz,(img.shape[1],img.shape[0]))\n obj_rect_surr=(obj_rect_surr[0]-surr_rect[0],obj_rect_surr[1]-surr_rect[1],obj_rect_surr[2],obj_rect_surr[3])\n surr_win=get_sub_window(img,target_pos_img,surr_sz)\n prob_lut_bg,_=get_foreground_background_probs(surr_win,obj_rect_surr,self.config.num_bins)\n\n if self.config.distractor_aware is True:\n if len(distractors)>1:\n obj_rect=pos2rect(target_pos,target_sz,(search_win.shape[1],search_win.shape[0]))\n prob_lut_dist=get_foreground_distractor_probs(search_win,obj_rect,distractors,self.config.num_bins)\n self._prob_lut_distractor=(1-self.config.prob_lut_update_rate)*self._prob_lut_distractor+\\\n self.config.prob_lut_update_rate*prob_lut_dist\n else:\n self._prob_lut_distractor=(1-self.config.prob_lut_update_rate)*self._prob_lut_distractor+\\\n self.config.prob_lut_update_rate*prob_lut_bg\n if len(distractors)==0 or np.max(distractor_overlap)<0.1:\n self.prob_lut_=(1-self.config.prob_lut_update_rate)*self.prob_lut_+self.config.prob_lut_update_rate*prob_lut_bg\n prob_map=get_foreground_prob(surr_win,self.prob_lut_,self.bin_mapping)\n dist_map=get_foreground_prob(surr_win,self._prob_lut_distractor,self.bin_mapping)\n prob_map=0.5*prob_map+0.5*dist_map\n else:\n self.prob_lut_=(1-self.config.prob_lut_update_rate)*self.prob_lut_+self.config.prob_lut_update_rate*prob_lut_bg\n prob_map=get_foreground_prob(surr_win,self.prob_lut_,self.bin_mapping)\n self.adaptive_threshold_=get_adaptive_threshold(prob_map,obj_rect_surr)\n\n target_pos=(target_pos[0]+search_rect[0],target_pos[1]+search_rect[1])\n target_pos_original=(target_pos[0]/self._scale_factor,target_pos[1]/self._scale_factor)\n target_sz_original=(target_sz[0]/self._scale_factor,target_sz[1]/self._scale_factor)\n self.target_pos_history.append(target_pos_original)\n self.target_sz_history.append(target_sz_original)\n self._scale_factor=min(1,round(10*self.config.img_scale_target_diagonal/cv2.norm(target_sz_original))/10)\n return [target_pos_original[0]-target_sz_original[0]/2,target_pos_original[1]-target_sz_original[1]/2,\n target_sz_original[0],target_sz_original[1]]\n\n\ndef pos2rect(center,obj_sz,win_sz=None):\n obj_w,obj_h=obj_sz\n cx,cy=center\n rect=(int(round(cx-obj_w/2)),int(round(cy-obj_h/2)),obj_w,obj_h)\n if win_sz is not None:\n border=(0,0,win_sz[0]-1,win_sz[1]-1)\n rect=intersect_of_rects(border,rect)\n return rect\n\ndef get_foreground_background_probs(frame,obj_rect,num_bins,bin_mapping=None):\n frame=frame.astype(np.uint8)\n\n surr_hist = cv2.calcHist([frame],[0, 1, 2], None, [num_bins,num_bins,num_bins],\n [0, 256, 0, 256, 0, 256])\n x,y,w,h=obj_rect\n if x+w>frame.shape[1]-1:\n w=(frame.shape[1]-1)-x\n if y+h>frame.shape[0]-1:\n h=(frame.shape[0]-1)-y\n x=int(max(x,0))\n y=int(max(y,0))\n obj_win=frame[y:y+h+1,x:x+w+1]\n\n obj_hist = cv2.calcHist([obj_win], [0, 1, 2], None, [num_bins, num_bins, num_bins], [0, 256, 0, 256, 0, 256])\n prob_lut = (obj_hist + 1) / (surr_hist + 2)\n prob_map = None\n if bin_mapping is not None:\n frame_bin = cv2.LUT(frame, bin_mapping).astype(np.int64)\n prob_map = prob_lut[frame_bin[:, :, 0], frame_bin[:, :, 1], frame_bin[:, :, 2]]\n\n return prob_lut,prob_map\n\ndef get_bin_mapping(num_bins):\n bin_mapping=np.zeros((256,))\n for i in range(bin_mapping.shape[0]):\n bin_mapping[i]=(np.floor(i/(256/num_bins)))\n return bin_mapping.astype(np.uint8)\n\ndef get_adaptive_threshold(prob_map, obj_rect, config=DATConfig()):\n x,y,w,h=obj_rect\n w+=1\n w=int(min(prob_map.shape[1]-x,w))\n h+=1\n h=int(min(prob_map.shape[0]-y,h))\n obj_prob_map=prob_map[y:y+h,x:x+w]\n bins=21\n H_obj=cv2.calcHist([obj_prob_map],[0],None,[bins],[-0.025,1.025],accumulate=False)\n H_obj=H_obj/np.sum(H_obj)\n cum_H_obj=copy.deepcopy(H_obj)\n for i in range(1,cum_H_obj.shape[0]):\n cum_H_obj[i,0]+=cum_H_obj[i-1,0]\n H_dist=cv2.calcHist([prob_map],[0],None,[bins],[-0.025,1.025],accumulate=False)\n H_dist=H_dist-H_obj\n H_dist=H_dist/np.sum(H_dist)\n cum_H_dist=copy.deepcopy(H_dist)\n for i in range(1,cum_H_dist.shape[0]):\n cum_H_dist[i,0]+=cum_H_dist[i-1,0]\n k=np.zeros_like(cum_H_obj)\n for i in range(k.shape[0]-1):\n k[i,0]=cum_H_obj[i+1,0]-cum_H_obj[i,0]\n # not sure\n\n x=np.abs(cum_H_obj-(1-cum_H_dist))+(cum_H_obj<(1-cum_H_dist))+(1-k)\n i=np.argmin(x)\n #print(i)\n threshold=max(0.4,min(0.7,config.adapt_thresh_prob_bins[i]))\n return threshold\n\ndef get_motion_prediciton(points,max_num_frames):\n predx,predy=0,0\n if len(points)>=3:\n max_num_frames=max_num_frames+2\n A1=0.8\n A2=-1\n V=copy.deepcopy(points[int(max(0,len(points)-max_num_frames)):len(points)])\n Px=[]\n Py=[]\n for i in range(2,len(V)):\n x=A1*(V[i][0]-V[i-2][0])+A2*(V[i-1][0]-V[i-2][0])\n y=A1*(V[i][1]-V[i-2][1]+A2*(V[i-1][1]-V[i-2][1]))\n Px.append(x)\n Py.append(y)\n predx=sum(Px)/len(Px)\n predy=sum(Py)/len(Py)\n return (predx,predy)\n\ndef get_subwindow_masked(img,pos,sz):\n tl=(int(np.floor(pos[0])+1-np.floor(sz[0]/2)),int(np.floor(pos[1])+1-np.floor(sz[1]/2)))\n out=get_sub_window(img,pos,sz)\n bbox=(tl[0],tl[1],sz[0],sz[1])\n bbox2=(0,0,img.shape[1]-1,img.shape[0]-1)\n bbox=intersect_of_rects(bbox,bbox2)\n bbox=(bbox[0]-tl[0],bbox[1]-tl[1],bbox[2],bbox[3])\n mask=np.zeros((sz[1],sz[0]),dtype=np.uint8)\n mask[bbox[1]:bbox[1]+bbox[3],bbox[0]:bbox[0]+bbox[2]]=1\n return out,mask\n\n\n\ndef intersect_of_rects(rect1,rect2):\n tl = (max(rect1[0], rect2[0]), max(rect1[1], rect2[1]))\n br = (min(rect1[0] + rect1[2], rect2[0] + rect2[2]), min(rect1[1] + rect1[3], rect2[1] + rect2[3]))\n inter = (int(tl[0]), int(tl[1]), int(br[0] - tl[0]), int(br[1] - tl[1]))\n return inter\n\ndef cal_iou(rect1,rect2):\n inter=intersect_of_rects(rect1,rect2)\n iou=(inter[2]*inter[3])/(rect1[2]*rect1[3]+rect2[2]*rect2[3]-inter[2]*inter[3])\n return iou\n\ndef get_foreground_prob(frame,prob_lut,bin_mapping):\n frame_bin=cv2.LUT(frame,bin_mapping).astype(np.int64)\n prob_map = prob_lut[frame_bin[:, :, 0], frame_bin[:, :, 1], frame_bin[:, :, 2]]\n return prob_map\n\ndef get_nms_rects(prob_map,obj_sz,scale,overlap,score_frac,dist_map,include_inner):\n\n height,width=prob_map.shape[:2]\n rect_sz=(int(np.floor(obj_sz[0]*scale)),int(np.floor(obj_sz[1]*scale)))\n o_x,o_y=0,0\n if include_inner is True:\n o_x=int(np.round(max(1,rect_sz[0]*0.2)))\n o_y=int(np.round(max(1,rect_sz[1]*0.2)))\n stepx=int(max(1,int(np.round(rect_sz[0]*(1-overlap)))))\n stepy=int(max(1,int(np.round(rect_sz[1]*(1-overlap)))))\n posx,posy=[],[]\n for i in range(0,width-rect_sz[0],stepx):\n posx.append(i)\n for i in range(0,height-rect_sz[1],stepy):\n posy.append(i)\n posx,posy=np.arange(0,width-rect_sz[0],stepx),np.arange(0,height-rect_sz[1],stepy)\n x,y=np.meshgrid(posx,posy)\n r=x.flatten()+rect_sz[0]\n b=y.flatten()+rect_sz[1]\n r[r>width-1]=width-1\n b[b>height-1]=height-1\n boxes=[x.flatten(),y.flatten(),r-x.flatten(),b-y.flatten()]\n boxes=np.array(boxes).T\n if include_inner is True:\n boxes_inner=[x.flatten()+o_x,y.flatten()+o_y,(r-2*o_x)-x.flatten(),(b-2*o_y)-y.flatten()]\n boxes_inner=np.array(boxes_inner).T\n\n bl=np.array([b,x.flatten()]).T\n br=np.array([b,r]).T\n tl=np.array([y.flatten(),x.flatten()]).T\n tr=np.array([y.flatten(),r]).T\n\n if include_inner is True:\n rect_sz_inner=(rect_sz[0]-2*o_x,rect_sz[1]-2*o_y)\n bl_inner=np.array([b-o_y,x.flatten()+o_x]).T\n br_inner=np.array([b-o_y,r-o_x]).T\n tl_inner=np.array([y.flatten()+o_y,x.flatten()+o_x]).T\n tr_inner=np.array([y.flatten()+o_y,r-o_x]).T\n int_prob_map=cv2.integral(prob_map)\n int_dist_map=cv2.integral(dist_map)\n v_scores=int_prob_map[br[:,0],br[:,1]]-int_prob_map[bl[:,0],bl[:,1]]-int_prob_map[tr[:,0],tr[:,1]]+int_prob_map[tl[:,0],tl[:,1]]\n d_scores=int_dist_map[br[:,0],br[:,1]]-int_dist_map[bl[:,0],bl[:,1]]-int_dist_map[tr[:,0],tr[:,1]]+int_dist_map[tl[:,0],tl[:,1]]\n if include_inner is True:\n scores_inner = int_prob_map[br_inner[:,0],br_inner[:,1]] - int_prob_map[bl_inner[:,0],bl_inner[:,1]] -\\\n int_prob_map[tr_inner[:,0],tr_inner[:,1]] + int_prob_map[tl_inner[:,0],tl_inner[:,1]]\n v_scores=v_scores/(rect_sz[0]*rect_sz[1])+scores_inner/(rect_sz_inner[0]*rect_sz_inner[1])\n\n top_rects = []\n top_vote_scores = []\n top_dist_scores = []\n midx=np.argmax(v_scores)\n ms=v_scores[midx]\n best_score=ms\n\n while ms>score_frac*best_score:\n box_mid=tuple(boxes[midx])\n prob_map[box_mid[1]:box_mid[1]+box_mid[3],box_mid[0]:box_mid[0]+box_mid[2]]=0\n top_rects.append(tuple(boxes[midx]))\n top_vote_scores.append(v_scores[midx])\n top_dist_scores.append(d_scores[midx])\n boxes=np.delete(boxes,midx,axis=0)\n if include_inner is True:\n boxes_inner=np.delete(boxes_inner,midx,axis=0)\n bl=np.delete(bl,midx,axis=0)\n br=np.delete(br,midx,axis=0)\n tl=np.delete(tl,midx,axis=0)\n tr=np.delete(tr,midx,axis=0)\n\n if include_inner is True:\n bl_inner = np.delete(bl_inner, midx, axis=0)\n br_inner = np.delete(br_inner, midx, axis=0)\n tl_inner = np.delete(tl_inner, midx, axis=0)\n tr_inner = np.delete(tr_inner, midx, axis=0)\n\n int_prob_map=cv2.integral(prob_map)\n int_dist_map=cv2.integral(dist_map)\n v_scores = int_prob_map[br[:, 0], br[:, 1]] - int_prob_map[bl[:, 0], bl[:, 1]] - int_prob_map[\n tr[:, 0], tr[:, 1]] + int_prob_map[tl[:, 0], tl[:, 1]]\n d_scores = int_dist_map[br[:, 0], br[:, 1]] - int_dist_map[bl[:, 0], bl[:, 1]] - int_dist_map[\n tr[:, 0], tr[:, 1]] + int_dist_map[tl[:, 0], tl[:, 1]]\n if include_inner is True:\n scores_inner = int_prob_map[br_inner[:, 0], br_inner[:, 1]] - int_prob_map[bl_inner[:, 0], bl_inner[:, 1]] - \\\n int_prob_map[tr_inner[:, 0], tr_inner[:, 1]] + int_prob_map[tl_inner[:, 0], tl_inner[:, 1]]\n v_scores = v_scores / (rect_sz[0] * rect_sz[1]) + scores_inner / (rect_sz_inner[0] * rect_sz_inner[1])\n\n midx=np.argmax(v_scores)\n ms=v_scores[midx]\n\n return top_rects,top_vote_scores,top_dist_scores\n\ndef get_foreground_distractor_probs(frame,obj_rect,distractors,num_bins):\n Md=np.zeros((frame.shape[0],frame.shape[1]),dtype=np.uint8)\n Mo=np.zeros((frame.shape[0],frame.shape[1]),dtype=np.uint8)\n for i in range(len(distractors)):\n x,y,w,h=distractors[i]\n Md[y:y+h,x:x+w]=1\n Mo[obj_rect[1]:obj_rect[1]+obj_rect[3],obj_rect[0]:obj_rect[0]+obj_rect[2]]=1\n obj_hist=cv2.calcHist([frame],[0,1,2],Mo,[num_bins,num_bins,num_bins],[0,256,0,256,0,256])\n dist_hist=cv2.calcHist([frame],[0,1,2],Md,[num_bins,num_bins,num_bins],[0,256,0,256,0,256])\n prob_lut=(obj_hist*len(distractors)+1)/(dist_hist+obj_hist*len(distractors)+2)\n return prob_lut\n\ndef get_sub_window(frame,center,sz):\n h,w=frame.shape[:2]\n lt=(int(min(w-1,max(-sz[0]+1,center[0]-np.floor(sz[0]/2+1)))),\n int(min(h-1,max(-sz[1]+1,center[1]-np.floor(sz[1]/2+1)))))\n rb=(lt[0]+sz[0]-1,lt[1]+sz[1]-1)\n border=(-min(0,lt[0]),-min(lt[1],0),\n max(rb[0]-w+1,0),max(rb[1]-h+1,0))\n lt_limit=(max(lt[0],0),max(lt[1],0))\n rb_limit=(min(rb[0]+1,w),min(rb[1]+1,h))\n sub_window=frame[lt_limit[1]:rb_limit[1],lt_limit[0]:rb_limit[0]]\n if border!=(0,0,0,0):\n sub_window=cv2.copyMakeBorder(sub_window,border[1],border[3],border[0],border[2],cv2.BORDER_REPLICATE)\n return sub_window\n",
"import torch\nimport torch.nn as nn\n\n\nclass GIoULoss(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, pred, target, weights=None):\n if pred.dim() == 4:\n pred = pred.unsqueeze(0)\n\n pred = pred.permute(0, 1, 3, 4, 2).reshape(-1, 4) # nf x ns x x 4 x h x w\n target = target.permute(0, 1, 3, 4, 2).reshape(-1, 4) #nf x ns x 4 x h x w\n\n pred_left = pred[:, 0]\n pred_top = pred[:, 1]\n pred_right = pred[:, 2]\n pred_bottom = pred[:, 3]\n\n target_left = target[:, 0]\n target_top = target[:, 1]\n target_right = target[:, 2]\n target_bottom = target[:, 3]\n\n target_area = (target_left + target_right) * \\\n (target_top + target_bottom)\n pred_area = (pred_left + pred_right) * \\\n (pred_top + pred_bottom)\n\n w_intersect = torch.min(pred_left, target_left) + torch.min(pred_right, target_right)\n g_w_intersect = torch.max(pred_left, target_left) + torch.max(\n pred_right, target_right)\n h_intersect = torch.min(pred_bottom, target_bottom) + torch.min(pred_top, target_top)\n g_h_intersect = torch.max(pred_bottom, target_bottom) + torch.max(pred_top, target_top)\n ac_union = g_w_intersect * g_h_intersect + 1e-7\n area_intersect = w_intersect * h_intersect\n area_union = target_area + pred_area - area_intersect + 1e-7\n ious = (area_intersect) / (area_union)\n gious = ious - (ac_union - area_union) / ac_union\n\n losses = 1 - gious\n\n if weights is not None and weights.sum() > 0:\n weights = weights.permute(0, 1, 3, 4, 2).reshape(-1) # nf x ns x x 1 x h x w\n loss_mean = losses[weights>0].mean()\n ious = ious[weights>0]\n else:\n loss_mean = losses.mean()\n\n return loss_mean, ious\n"
] |
[
[
"torch.nn.Sequential",
"torch.ones",
"torch.nn.Conv2d",
"torch.zeros_like",
"torch.nn.Sigmoid",
"torch.exp",
"torch.tanh",
"torch.arange"
],
[
"numpy.diag",
"numpy.sqrt",
"numpy.fft.fftshift",
"numpy.concatenate",
"numpy.max",
"numpy.all",
"numpy.round",
"numpy.zeros_like",
"numpy.mean",
"numpy.exp",
"numpy.where",
"numpy.roll",
"numpy.ones_like",
"numpy.clip",
"numpy.reshape",
"numpy.arange",
"numpy.sin",
"numpy.size",
"numpy.argmax",
"numpy.matlib.repmat",
"numpy.zeros",
"numpy.min",
"numpy.isnan",
"numpy.floor",
"numpy.meshgrid",
"numpy.array",
"numpy.sum",
"numpy.conj",
"numpy.cos",
"numpy.linalg.norm",
"numpy.ones",
"numpy.prod",
"numpy.mod"
],
[
"numpy.abs",
"numpy.arange",
"numpy.round",
"numpy.max",
"numpy.delete",
"numpy.argmax",
"numpy.argmin",
"numpy.zeros_like",
"numpy.floor",
"numpy.array",
"numpy.meshgrid",
"numpy.zeros",
"numpy.sum"
],
[
"torch.min",
"torch.max"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nikunjpansari/stochastic-optimization
|
[
"a01e95e9168dd8f87751c29f94bb382f83567e71"
] |
[
"ClinicalTrials/ClinicalTrialsDriverScriptSolutionQ5.py"
] |
[
"\"\"\"\nClinical Trials Driver Script class\n\nRaluca Cobzaru (c) 2018\n\n\"\"\"\n\nfrom collections import namedtuple\nimport numpy as np\nimport scipy\nimport pandas as pd\nfrom ClinicalTrialsModel import ClinicalTrialsModel\nfrom ClinicalTrialsPolicy import ClinicalTrialsPolicy\nimport matplotlib.pyplot as plt\nimport time\n\nif __name__ == \"__main__\":\n\ttime_total = time.time()\n\tnp.random.seed(2345678173)\n\t# initializes a policy object and a model object, then runs the policy on the model\n\tpolicy_names = ['model_A', 'model_B', 'model_C', 'model_C_extension']\n\tstate_names = ['potential_pop', 'success', 'failure', 'l_response']\n\t# extracts data from given data set; defines initial state\n\tfile = 'Parameters.xlsx'\n\traw_data = pd.ExcelFile(file)\n\tdata = raw_data.parse('Parameters')\n\tinitial_state = {'potential_pop': float(data.iat[0, 0]),\n\t\t\t\t\t 'success': data.iat[1, 0],\n\t\t\t\t\t 'failure': float(data.iat[2, 0]),\n\t\t\t\t\t 'l_response': float(data.iat[3, 0]),\n\t\t\t\t\t 'theta_stop_low': data.iat[4, 0],\n\t\t\t\t\t 'theta_stop_high': data.iat[5, 0],\n\t\t\t\t\t 'alpha': data.iat[6, 0],\n\t\t\t\t\t 'K': int(data.iat[7, 0]),\n\t\t\t\t\t 'N': int(data.iat[8, 0]),\n\t\t\t\t\t 'trial_size': int(data.iat[9, 0]),\n\t\t\t\t\t 'patient_cost': data.iat[10, 0],\n\t\t\t\t\t 'program_cost': data.iat[11, 0],\n\t\t\t\t\t 'success_rev': data.iat[12, 0],\n\t\t\t\t\t 'sampling_size': int(data.iat[13, 0]),\n\t\t\t\t\t 'enroll_min': int(data.iat[14, 0]),\n\t\t\t\t\t 'enroll_max': int(data.iat[15, 0]),\n\t\t\t\t\t 'enroll_step': int(data.iat[16, 0]),\n\t\t\t\t\t 'H': int(data.iat[17, 0]),\n\t\t\t\t\t 'true_l_response': data.iat[18, 0],\n\t\t\t\t\t 'true_succ_rate': data.iat[19, 0]}\n\tmodel_name = data.iat[20, 0]\n\tnumIterations = int(data.iat[21,0])\n\t\n\tdecision_names = ['enroll', 'prog_continue', 'drug_success']\n\t\n\t################################################################\n\t#Solution Q5\n\ttheta_list = list(np.arange(.77,.79,0.005))\n\ttheta_avg=[]\n\tfor theta in theta_list:\n\t\tinitial_state.update({'theta_stop_low':theta})\n\t\tavg_policy_value = 0\n\t\tfor i in range(0,numIterations):\n\n\t\t\tM = ClinicalTrialsModel(state_names, decision_names, initial_state, False)\n\t\t\tP = ClinicalTrialsPolicy(M, policy_names)\n\t\t\tt = 0\n\t\t\tstop = False\n\t\t\tpolicy_info = {'model_A': [-1, stop],\n\t\t\t\t\t\t\t'model_B': [-1, stop],\n\t\t\t\t\t\t\t'model_C': [-1, stop],\n\t\t\t\t\t\t\t'model_C_extension': [-1, stop]}\n\t\t\tpolicy_value = P.run_policy(policy_info, model_name, t)\n\t\t\tavg_policy_value += policy_value\n\t\t\tprint(\"Finished run policy for iteration {} - Value: {} and Avg_value: {:,}\".format(i,policy_value,avg_policy_value/(i+1)))\n\n\t\tavg_policy_value = avg_policy_value/numIterations\n\t\tprint(\"Theta {} - Average values after {} iterations is {:,}\".format(initial_state['theta_stop_low'],numIterations,avg_policy_value))\n\t\ttheta_avg.append(avg_policy_value)\n\n\tprint(theta_list)\n\tprint(theta_avg)\n\tplt.plot(theta_list,theta_avg,'bo')\n\tplt.show()\n\t#End Solution Q5\n\t###############################################################\n\t\n\n\t\n\n\tprint(\"Total elapsed time {:.2f} secs\".format(time.time()-time_total))\n\t\n\tpass"
] |
[
[
"numpy.random.seed",
"numpy.arange",
"matplotlib.pyplot.plot",
"pandas.ExcelFile",
"matplotlib.pyplot.show"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
aditi2795/NOPaxos
|
[
"c650eda207090534b34f6521ed3d420f36ba186f"
] |
[
"bench/createFig8.py"
] |
[
"# Arguments in order: protocol, #replicas, #threads per client, #client machines\n# EX: python ./bench/runBench.py unreplicated 5 1 1\n# To run with batching, use protocol \"batch\"\nimport sys, string\nimport subprocess\nimport os\nfrom runBench import runTest\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FormatStrFormatter\n\nclientMachines = 5\naverageRuns = 3 \nprotocols = [\"nopaxos\", \"unreplicated\", \"vr\", \"batch\", \"fastpaxos\"]\nmaxThreads = {\"unreplicated\": 12, \"vr\": 5, \"batch\": 20, \"fastpaxos\": 4,\n \"nopaxos\": 12}\nlegend = {\"nopaxos\": \"NOPaxos\", \"unreplicated\": \"Unreplicated\", \"vr\": \"Paxos\",\n \"batch\": \"Batching\", \"fastpaxos\": \"Fast Paxos\"}\nnumReplicasList = [3, 5, 7, 9]\nfor protocol in protocols:\n throughputList = []\n for numReplicas in numReplicasList:\n avgThroughput = 0\n totRuns = 0\n for i in range(averageRuns):\n throughput, latency,_ = runTest(protocol, numReplicas,\n maxThreads[protocol], clientMachines)\n if throughput == -1 and latency == -1:\n continue\n totRuns += 1\n avgThroughput += throughput\n avgThroughput /= float(totRuns) \n avgThroughput /= 1000 # change units to thousands\n throughputList.append(avgThroughput)\n plt.plot(numReplicasList, throughputList, label=legend[protocol], linestyle='-',\n marker='o')\nplt.legend()\nplt.xlabel(\"Number of Replicas\")\nplt.ylabel(\"Throughput (ops/sec)\")\nplt.gca().yaxis.set_major_formatter(FormatStrFormatter('%dK'))\nplt.ylim([0,180])\nplt.title(\"NOPAXOS Figure 8 replication\")\nplt.savefig('Figure8.png')\n\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.ticker.FormatStrFormatter",
"matplotlib.pyplot.ylabel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
chunxiaosz/CNTK
|
[
"a7453ed0791ae797bcf9e8d8fbc287332a430db4"
] |
[
"bindings/python/cntk/ops/tests/reshaping_test.py"
] |
[
"# Copyright (c) Microsoft. All rights reserved.\n\n# Licensed under the MIT license. See LICENSE.md file in the project root\n# for full license information.\n# ==============================================================================\n\n\"\"\"\nUnit tests for reshaping operations.\n\"\"\"\n\nfrom __future__ import division\nimport numpy as np\nimport cntk as C\nimport pytest\nfrom .ops_test_utils import unittest_helper, _test_unary_op, _test_binary_op, \\\n AA, precision, PRECISION_TO_TYPE, cntk_device\nimport cntk as C\nfrom cntk import Value\nfrom cntk.axis import Axis\nfrom cntk.internal import sanitize_dtype_cntk\nfrom .. import constant\n\n\nRESHAPE_TEST_CASES = [\n #(input_shape, output_shape, expected_output_shape)\n ((2, 3), (3, 2), (3, 2)),\n ((2, 3), (6, 1), (6, 1)),\n ((2, 3), (6, 1), (6, 1)),\n ((6, 1), (2, 3), (2, 3)),\n ((2, 3, 5), (5, 6), (5, 6)),\n ((2, 3, 5), (C.InferredDimension, 6), (5, 6)),\n ((2, 3, 5), (5, C.InferredDimension), (5, 6)),\n]\n\[email protected](\"input_shape, output_shape, expected_output_shape\",\n RESHAPE_TEST_CASES)\ndef test_op_reshape(input_shape, output_shape, expected_output_shape, device_id, precision):\n # Reshaping is just moving the input values to different indexes of the result tensor.\n # If we compute the gradients on the unmodified tensor, reshape would get 1 for all inputs\n # For testing the gradients we want to have different gradients for each input index otherwise we can't\n # test if they get wrongly permuted during test. To this end we multiply\n # the reshaping result with itself.\n dev = cntk_device(device_id)\n from .. import reshape, element_times\n\n num_tensor_elements = np.multiply.reduce(input_shape)\n input_tensor = np.arange(\n num_tensor_elements, dtype=PRECISION_TO_TYPE[precision]).reshape(input_shape)\n input_reshaped = input_tensor.reshape(expected_output_shape)\n\n a = C.input_variable(shape=input_tensor.shape,\n dtype=sanitize_dtype_cntk(PRECISION_TO_TYPE[precision]),\n needs_gradient=True,\n name='a')\n\n a_reshaped = reshape(a, output_shape)\n\n const_input_reshaped = constant(input_reshaped, device=dev)\n input_op = element_times(a_reshaped, const_input_reshaped)\n\n expected_forward = [input_reshaped**2]\n expected_backward = {a: input_tensor}\n\n # create batch\n input_tensor.shape = (1,) + input_tensor.shape\n\n forward_input = {a: input_tensor}\n\n unittest_helper(input_op,\n forward_input, expected_forward, expected_backward,\n device_id=device_id, precision=precision)\n\nRESHAPE_SUBSHAPE_TEST_CASES = [\n #(input_shape, replacement_shape, begin_axis, end_axis, expected_output_shape)\n ((2, 3), (3, 2), 0, Axis.new_leading_axis(), (3, 2)),\n ((2, 3), (1), 0, 0, (1, 2, 3)),\n ((2, 3), (1, 1), Axis.new_leading_axis(),Axis.new_leading_axis(), (2, 3, 1, 1)),\n ((2, 3, 5), (C.InferredDimension), 0, Axis(2), (6, 5)),\n ((2, 3, 5), (C.InferredDimension), Axis(-3), -1, (6, 5)),\n ((6, 5), (2, C.InferredDimension), 0, 1, (2, 3, 5)),\n]\n\[email protected](\"input_shape, replacement_shape, begin_axis, end_axis, expected_output_shape\", RESHAPE_SUBSHAPE_TEST_CASES)\ndef test_op_reshape_subshape(input_shape, replacement_shape, begin_axis, end_axis, expected_output_shape, device_id, precision):\n # Reshaping is just moving the input values to different indexes of the result tensor.\n # If we compute the gradients on the unmodified tensor, reshape would get 1 for all inputs\n # For testing the gradients we want to have different gradients for each input index otherwise we can't\n # test if they get wrongly permuted during test. To this end we multiply\n # the reshaping result with itself.\n dev = cntk_device(device_id)\n from cntk.internal import sanitize_dtype_cntk\n from .. import reshape, element_times\n\n num_tensor_elements = np.multiply.reduce(input_shape)\n input_tensor = np.arange(\n num_tensor_elements, dtype=PRECISION_TO_TYPE[precision]).reshape(input_shape)\n input_reshaped = input_tensor.reshape(expected_output_shape)\n\n a = C.input_variable(shape=input_tensor.shape,\n dtype=sanitize_dtype_cntk(PRECISION_TO_TYPE[precision]),\n needs_gradient=True,\n name='a')\n\n a_reshaped = reshape(a, replacement_shape, begin_axis, end_axis)\n\n const_input_reshaped = constant(input_reshaped, device=dev)\n input_op = element_times(a_reshaped, const_input_reshaped)\n\n expected_forward = [input_reshaped**2]\n expected_backward = {a: input_tensor}\n\n # create batch\n input_tensor.shape = (1,) + input_tensor.shape\n\n forward_input = {a: input_tensor}\n\n unittest_helper(input_op,\n forward_input, expected_forward, expected_backward,\n device_id=device_id, precision=precision)\n\n# Test that reshape accumulates the gradient in its input operand\n# instead of overwriting the input operand gradient\ndef test_op_reshape_gradient_accumulation(device_id, precision):\n from .. import reshape\n\n input_shape = (2,3)\n output_shape = (3,2)\n expected_output_shape = (3,2)\n\n num_tensor_elements = np.multiply.reduce(input_shape)\n input_tensor = np.arange(\n num_tensor_elements, dtype=PRECISION_TO_TYPE[precision])\n input_reshaped = input_tensor.reshape(expected_output_shape)\n\n a = C.input_variable(shape=input_tensor.shape,\n dtype=sanitize_dtype_cntk(PRECISION_TO_TYPE[precision]),\n needs_gradient=True,\n name='a')\n\n a_reshaped1 = reshape(a, output_shape)\n a_reshaped2 = reshape(a, output_shape)\n\n input_op = a_reshaped1 + a_reshaped2\n\n resulting_multiplicative_factor = 2\n expected_forward = [input_reshaped * resulting_multiplicative_factor]\n\n # create batch\n input_tensor.shape = (1,) + input_tensor.shape\n expected_backward = {a: np.full(input_tensor.shape, resulting_multiplicative_factor, dtype=PRECISION_TO_TYPE[precision])}\n\n forward_input = {a: input_tensor}\n\n unittest_helper(input_op,\n forward_input, expected_forward, expected_backward,\n device_id=device_id, precision=precision)\n\n\ndef test_op_reshape_parameter():\n from .. import reshape, parameter\n\n param_shape = (4,2)\n param_value = np.random.random(param_shape)\n param = parameter(init=param_value)\n param_new_shape = (8,1)\n param_reshaped = reshape(param, param_new_shape)\n\n expected_forward = np.copy(param_value).reshape(param_new_shape)\n state, result = param_reshaped.forward({}, [param_reshaped.output],\n [param_reshaped.output])\n assert np.allclose(result[param_reshaped.output], expected_forward)\n\n grad = param_reshaped.backward(state, np.ones(param_new_shape), [param])\n assert np.allclose(grad[param], np.ones(param_shape))\n\n\nSLICE_TEST_CASES_STATIC = [\n #(input_data, slice_params(beg_index, end_index, axis), expected_result)\n ([[1, 2], [-3, 4]], (1, 2, 0, 1), [[-3, 4]]),\n ([[1,2],[-3,4]], (1,2,1, 1), [[2],[4]]),\n ([[1,2],[-3,4]], (0,2,1, -1), [[2, 1],[4, -3]]),\n ([[1,2],[-3,4]], (0,2,0, 2), [[1, 2]]),\n\t([[1,2],[-3,4], [-2,5], [7,8], [-9,6]], (0,5,0,2), [[1,2],[-2,5],[-9,6]]),\n\t([[1,2],[-3,4], [-2,5], [7,8], [-9,6]], (0,5,0,-2), [[-9,6],[-2,5],[1,2]])\n]\n\[email protected](\"input_data, slice_params, expected_result\",\n SLICE_TEST_CASES_STATIC)\ndef test_op_slice(input_data, slice_params, expected_result, device_id, precision):\n\n input_data = AA(input_data, dtype=PRECISION_TO_TYPE[precision])\n\n def _ax_slices(x, beg_index, end_index, axis, strides):\n '''\n Creates a NumPy slicing array from slice operator's arguments\n '''\n ax_slices = []\n for i in range(0, len(x.shape)):\n if i == axis:\n if end_index >= x.shape[i]:\n ax_slices.append(slice(beg_index, None, abs(strides)))\n else:\n ax_slices.append(slice(beg_index, end_index, abs(strides)))\n else:\n ax_slices.append(slice(None)) # corresponds to ':'\n return ax_slices\n\n # Backward pass test\n # ==================\n # The gradient of the slice operator is a tensor of the same shape as the\n # input tensor, having 1 for elements that were taken and 0 for elements\n # that were dropped.\n\n def grad_slice(x, beg_index, end_index, axis, strides):\n res = np.zeros_like(x)\n ax_slices = _ax_slices(x, beg_index, end_index, axis, strides)\n res[ax_slices] = x[ax_slices]\n res[res != 0] = 1\n return res\n\n expected_forward = AA([expected_result], dtype=PRECISION_TO_TYPE[precision])\n expected_backward = {\n 'arg': [grad_slice(np.asarray(input_data), *slice_params)]\n }\n\n _test_unary_op(precision, device_id, C.slice, input_data,\n expected_forward, expected_backward,\n {'begin_index': slice_params[0],\n 'end_index': slice_params[1],\n 'axis': slice_params[2],\n 'strides': slice_params[3]})\n\nSLICE_OVERLOAD_TEST_CASES_STATIC = [\n # (input_data, slices, axis, expected_result)\n\n ([[1, 2, 3], [-4, 5, 6]],\n # Selecting from row 1 the column 2\n (1, 2),\n [[6]]),\n\n # slicing with a list of indices\n ([[1, 2, 3], [-4, 5, 6]],\n # Selecting from both rows columns 1 and 2\n (0, [1, 2]),\n [[2, 3]]),\n]\n\n\[email protected](\"input_data, slices, expected_result\",\n SLICE_OVERLOAD_TEST_CASES_STATIC)\ndef test_op_slice_overload(input_data, slices, expected_result,\n device_id, precision):\n\n dtype = PRECISION_TO_TYPE[precision]\n input_data = AA(input_data, dtype=dtype)\n\n # Backward pass test\n # ==================\n # The gradient of the slice operator is a tensor of the same shape as the\n # input tensor, having 1 for elements that were taken and 0 for elements\n # that were dropped.\n\n def grad_slice(x, slices):\n res = np.zeros_like(x)\n res[slices] = 1\n return res\n\n value = AA(input_data, dtype=dtype)\n\n expected_forward = AA([expected_result], dtype=dtype)\n expected_backward = [grad_slice(input_data, slices)]\n\n a = C.input_variable(shape=value.shape,\n dtype=sanitize_dtype_cntk(dtype),\n needs_gradient=True,\n name='a')\n\n f = a+0\n\n # create batch\n value.shape = (1,) + value.shape\n\n input_op = f[slices]\n\n forward_input = {a: value}\n expected_backward = {a: expected_backward}\n unittest_helper(input_op,\n forward_input, expected_forward, expected_backward,\n device_id=device_id, precision=precision)\n\nSLICE_TEST_CASES_DYNAMIC = [\n #(input_data, slice_params(beg_index, end_index), expected_result)\n # Note that input_data contains sequences\n ([[[1, 2, 3]], [[-4, 5, 6]], [[7, 8, 9]]],\n (0, 2),\n [[[1, 2, 3]], [[-4, 5, 6]]]),\n ([[[1, 2, 3], [11, 12, 13]], [[-4, 5, 6], [-14, 15, 16]], [[7, 8, 9], [17, 18, 19]]],\n (0, 2),\n [[[1, 2, 3], [11, 12, 13]], [[-4, 5, 6], [-14, 15, 16]]]),\n ([[[1, 2, 3], [11, 12, 13]], [[-4, 5, 6], [-14, 15, 16]], [[7, 8, 9], [17, 18, 19]]],\n (1, 2),\n [[-4, 5, 6], [-14, 15, 16]]),\n]\n\n\[email protected](\"input_data, slice_params, expected_result\",\n SLICE_TEST_CASES_DYNAMIC)\ndef test_op_slice_sequence(input_data, slice_params, expected_result,\n device_id, precision):\n input_data = AA(input_data, dtype=PRECISION_TO_TYPE[precision])\n\n t = Axis.new_unique_dynamic_axis('t')\n sample_shape = input_data.shape[1:]\n a = C.sequence.input_variable(shape=sample_shape,\n dtype=sanitize_dtype_cntk(PRECISION_TO_TYPE[precision]),\n needs_gradient=True,\n sequence_axis=t,\n name='a')\n\n result = C.sequence.slice(a,\n begin_index=slice_params[0],\n end_index=slice_params[1])\n\n def grad_slice(x, beg_index, end_index):\n res = np.zeros_like(x)\n res[beg_index:end_index] = 1\n return res\n\n\n expected_forward = AA([expected_result],\n dtype=PRECISION_TO_TYPE[precision])\n expected_backward = {\n a: [grad_slice(np.asarray(input_data), *slice_params)]\n }\n\n # create batch\n input_data.shape = (1,) + input_data.shape\n\n forward_input = {a: input_data}\n unittest_helper(result,\n forward_input, expected_forward, expected_backward,\n device_id=device_id, precision=precision)\n\nSPLICE_TEST_CASES = [\n #(input_data1, input_data2, axis, expected_result)\n ([1], [2], 0, [1, 2]),\n ([1], [2], -1, [1, 2]),\n ([1], [2], Axis.new_leading_axis(), [[1], [2]]),\n ([1], [2], -2, [[1], [2]]),\n ([[1, 2], [4, 5]], [[10, 20], [30, 40], [50, 60]], 0,\n [[1, 2], [4, 5], [10, 20], [30, 40], [50, 60]]),\n ([[1, 2], [4, 5]], [[10, 20, 30], [40, 50, 60]], 1,\n [[1, 2, 10, 20, 30], [4, 5, 40, 50, 60]]),\n ([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[10, 20], [30, 40]], 0,\n [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[10, 20], [30, 40]]]),\n]\n\n\[email protected](\"input_data1, input_data2, axis, expected_result\",\n SPLICE_TEST_CASES)\ndef test_op_splice(input_data1, input_data2, axis, expected_result, device_id, precision):\n # FIXME This test currently fails in C++ with\n # RuntimeError: Node 'splice_ab' (RowStack operation): Attempted to\n # type-cast node to struct Microsoft::MSR::CNTK::INumInputs, which is not\n # possible.\n\n input_data1 = AA(input_data1, dtype=PRECISION_TO_TYPE[precision])\n input_data2 = AA(input_data2, dtype=PRECISION_TO_TYPE[precision])\n\n def test_splice(shape1, shape2):\n a = C.input_variable(shape=shape1,\n dtype=sanitize_dtype_cntk(PRECISION_TO_TYPE[precision]),\n needs_gradient=True,\n name='a')\n b = C.input_variable(shape=shape2,\n dtype=sanitize_dtype_cntk(PRECISION_TO_TYPE[precision]),\n needs_gradient=True,\n name='b')\n\n # create batch\n input_data1.shape = (1,) + input_data1.shape\n input_data2.shape = (1,) + input_data2.shape\n\n # splice using the operator\n root_op = C.splice(a, b, axis=axis, name='splice_ab')\n\n forward_input = {a: input_data1, b: input_data2}\n\n # Backward pass test\n # ==================\n # The gradient of the splice operator is all ones in the shape of the input\n\n def grad_splice(x):\n return np.ones_like(x)\n\n expected_forward = [expected_result]\n expected_backward = {\n a: grad_splice(np.asarray(input_data1)),\n b: grad_splice(np.asarray(input_data2))\n }\n\n unittest_helper(root_op,\n forward_input, expected_forward, expected_backward,\n device_id=device_id, precision=precision)\n\n test_splice(input_data1.shape, input_data2.shape)\n # test with free dimension axis\n if axis is int and axis >= 0:\n input_shape1 = list(input_data1.shape)\n input_shape2 = list(input_data2.shape)\n\n input_shape1[axis] = C.FreeDimension\n input_shape2[axis] = C.FreeDimension\n test_splice(input_shape1, input_shape2)\n\n\ndef test_swapaxes_0d_1d_operands():\n x1 = C.input_variable(())\n with pytest.raises(ValueError):\n swapaxes_0d = C.swapaxes(x1)\n\n x2 = C.input_variable(2)\n with pytest.raises(ValueError):\n swapaxes_1d = C.swapaxes(x2)\n\n\ndef test_transpose():\n a = np.arange(120, dtype=np.float32).reshape(2, 3, 4, 5)\n from itertools import permutations\n for p in permutations(range(4)):\n assert np.array_equal(C.transpose(a, p).eval(), np.transpose(a, p))\n # test permutations over odd number of axes just in case\n b = a.reshape(6, 4, 5)\n for p in permutations(range(3)):\n assert np.array_equal(C.transpose(b, p).eval(), np.transpose(b, p))\n # test negative numbers\n for p in permutations(range(3)):\n q = [i - 3 for i in p]\n assert np.array_equal(C.transpose(b, q).eval(), np.transpose(b, q))\n\ndef test_transpose_backward():\n shape = (2, 3, 4)\n p = (2, 0, 1)\n x0 = np.arange(np.prod(shape), dtype=np.float32).reshape(*shape)\n shapet = tuple(shape[i] for i in p)\n x = C.input_variable(shape, needs_gradient=True)\n y = C.reduce_sum(C.cos(C.transpose(x, p)))\n xt = C.input_variable(shapet, needs_gradient=True)\n yt = C.reduce_sum(C.cos(xt))\n g = np.squeeze(y.grad({x:x0}))\n gt = np.squeeze(yt.grad({xt:np.transpose(x0, p)}))\n assert np.allclose(np.transpose(g, p), gt)\n\n\ndef test_op_reshape_free_dimension(device_id):\n dev = cntk_device(device_id)\n x = C.input_variable((C.FreeDimension, 2, 2))\n\n x_reshaped_1 = C.reshape(x, (-1,), 0, 2)\n data = [[[1, 2], [3, 4]]]\n result = x_reshaped_1.eval({x : np.asarray(data, dtype=np.float32)})\n assert np.array_equal(result[0], data[0])\n data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\n result = x_reshaped_1.eval({x : np.asarray(data, dtype=np.float32)})\n assert np.array_equal(result[0], np.reshape(data, (4, 2)))\n\n x_reshaped_2 = C.reshape(x, (-1,), 1, 3)\n data = [[[1, 2], [3, 4]]]\n result = x_reshaped_2.eval({x : np.asarray(data, dtype=np.float32)})\n assert np.array_equal(result[0], np.reshape(data, (1, 4)))\n data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\n result = x_reshaped_2.eval({x : np.asarray(data, dtype=np.float32)})\n assert np.array_equal(result[0], np.reshape(data, (2, 4)))\n\nRESHAPE_MULTIPLE_FREE_DIMENSION_TEST_CASES = [\n #(input_shape, replacement_shape, expected_output_shape)\n ((2, 3), (3, -1), (1, 3, 2)),\n ((4, 5, 7), (5, -1, 4), (1, 5, 7, 4)),\n ((3, 4, 2), (12, 2), (1, 12, 2)),\n]\n\[email protected](\"input_shape, replacement_shape, expected_output_shape\", RESHAPE_MULTIPLE_FREE_DIMENSION_TEST_CASES)\ndef test_op_reshape_multiple_free_dimensions(input_shape, replacement_shape, expected_output_shape, device_id, precision):\n dev = cntk_device(device_id)\n from cntk.internal import sanitize_dtype_cntk\n from .. import reshape, element_times\n\n num_tensor_elements = np.multiply.reduce(input_shape)\n input_tensor = np.arange(\n num_tensor_elements, dtype=PRECISION_TO_TYPE[precision]).reshape(input_shape)\n input_reshaped = input_tensor.reshape(expected_output_shape)\n\n a = C.input_variable(shape=tuple([C.FreeDimension]*len(input_tensor.shape)),\n dtype=sanitize_dtype_cntk(PRECISION_TO_TYPE[precision]),\n needs_gradient=True,\n name='a')\n\n a_reshaped = reshape(a, replacement_shape)\n\n const_input_reshaped = constant(input_reshaped, device=dev)\n input_op = element_times(a_reshaped, const_input_reshaped)\n\n expected_forward = [input_reshaped**2]\n expected_backward = {a: input_tensor}\n\n # create batch\n input_tensor.shape = (1,) + input_tensor.shape\n\n forward_input = {a: input_tensor}\n\n unittest_helper(input_op,\n forward_input, expected_forward, expected_backward,\n device_id=device_id, precision=precision)\n\ndef test_gather_op(device_id, precision):\n a_data = [AA([[0],[1]], dtype=PRECISION_TO_TYPE[precision]),\n AA([[3],[4]], dtype=PRECISION_TO_TYPE[precision])]\n a = C.input_variable((2,1))\n r_data = np.arange(12).reshape(6,2).astype('f')\n r = C.parameter(shape=r_data.data, init=r_data)\n res = C.gather(r, a).eval({a:a_data})\n expectd = np.asarray([[[[0., 1.]],[[2., 3.]]],[[[6., 7.]],[[8.,9.]]]])\n assert np.array_equal(res, expectd)\n\n grads = C.gather(r, a).grad({a:a_data}, [r])\n expectd_grad = np.asarray([[1,1],[1,1],[0,0],[1,1],[1,1],[0,0]], dtype=np.float32)\n assert np.array_equal(grads, expectd_grad)\n\n b_data = [AA([[0,2],[1,3]], dtype=PRECISION_TO_TYPE[precision]),\n AA([[2,4],[3,5]], dtype=PRECISION_TO_TYPE[precision])]\n b = C.input_variable((2,2))\n res2 = C.gather(r, b).eval({b:b_data})\n\n expectd2 = np.asarray([[[[0., 1.],[4.,5.]],[[2., 3.],[6., 7.]]],[[[4., 5.],[8.,9.]],[[6., 7.], [10., 11.]]]])\n assert np.array_equal(res2, expectd2)\n\n #the following small model is to test the memory reuse issue of gather node.\n x = C.input((3, 4))\n x1 = C.to_sequence(x)\n w = C.parameter((5, 6), init=1)\n z = C.gather(w, x1)\n assert z.shape == (4, 6)\n #need the unpack node to trigger memory reuse.\n f = C.sequence.unpack(z, 0, no_mask_output=True)\n y = C.input((3, 4, 6))\n loss = C.reduce_mean(C.square(f - y), axis=-1)\n loss = C.reduce_mean(loss, axis=C.Axis.all_axes())\n\n g = C.constant(0, shape=w.shape)\n u = C.assign(w, g + 1)\n learner = C.cntk_py.universal_learner([w], [g], u)\n trainer = C.trainer.Trainer(loss, [loss], [learner])\n indices = np.asarray([[[1, 2, 1, 2]]])\n input = np.repeat(np.repeat(indices, 3, axis=1), 10, axis=0)\n lable = np.full((10, 3, 4, 6), 2)\n trainer.train_minibatch({x: input, y: lable})\n # the 2nd and 3rd rows should be udpated by gradients.\n assert np.mean(w.value[1, :]) < 1\n assert np.mean(w.value[2, :]) < 1\n # the other three rows should keep as 1\n assert np.isclose(np.mean(w.value[0, :]), 1)\n assert np.isclose(np.mean(w.value[3, :]), 1)\n assert np.isclose(np.mean(w.value[4, :]), 1)\n\n\ndef test_gather_op_with_axis(device_id, precision):\n data = np.array([ [1.0, 1.2, 1.9], [2.3, 3.4, 3.9], [4.5, 5.7, 5.9], ]).astype(PRECISION_TO_TYPE[precision])\n indices = np.array([ 0, 2]).astype(PRECISION_TO_TYPE[precision]).astype(PRECISION_TO_TYPE[precision])\n output = np.array([ [1.0, 1.9], [2.3, 3.9], [4.5, 5.9], ]).astype(PRECISION_TO_TYPE[precision])\n x = C.constant(data)\n i = C.constant(indices)\n y = C.gather(x, i, axis=1)\n z = y.eval({}, device=cntk_device(device_id))\n assert np.allclose(output, z)\n\n\ndef test_convert_dynamic_axis():\n #test fix batch size\n batch_size = 4\n a = C.parameter(shape=(batch_size, 2, 3), init=1)\n dynamic_a = C.to_batch(a)\n assert len(dynamic_a.dynamic_axes) == 1\n assert dynamic_a.shape == (2, 3)\n\n x = C.input_variable((2, 3))\n y = x * dynamic_a\n\n #test grad\n data = np.arange(batch_size * 2 * 3).reshape(batch_size, 2, 3).astype('f')\n assert np.array_equal(y.grad({x:data}, [a]), data)\n\n const_a = C.unpack_batch(y)\n assert len(const_a.dynamic_axes) == 0\n assert const_a.shape == (C.FreeDimension, 2, 3)\n\n f = C.assign(a, const_a)\n f.eval({x:data})\n assert np.array_equal(a.value, data)\n\n #test reshape with batch axis\n x = C.input_variable((2,3))\n const_x = C.unpack_batch(x)\n assert len(const_x.dynamic_axes) == 0\n assert const_x.shape == (C.FreeDimension, 2, 3)\n\n const_y = C.reshape(const_x, (-1, 3))\n assert const_y.shape == (C.FreeDimension, 3)\n y = C.to_batch(const_y)\n assert len(y.dynamic_axes) == 1\n assert y.shape == (3,)\n\n z = y * 2\n expected = data.reshape((8, 3)) * 2\n assert np.array_equal(z.eval({x:data}), expected)\n\n #test inferred dimension\n x = C.input_variable((C.InferredDimension, 3))\n const_x = C.unpack_batch(x)\n assert len(const_x.dynamic_axes) == 0\n assert const_x.shape == (C.FreeDimension, C.InferredDimension, 3)\n\n const_y = const_x * 2\n y = C.to_batch(const_y)\n assert len(y.dynamic_axes) == 1\n assert y.shape == (C.InferredDimension, 3)\n\ndef test_pad():\n x = C.constant(value=np.arange(6).reshape((2,3)))\n pad1 = C.pad(x, [(1, 1), (2, 2)]).eval()\n expect1 = np.lib.pad([[0, 1, 2], [3, 4, 5]], ((1, 1), (2, 2)), 'constant')\n assert np.array_equal(pad1, expect1)\n\n pad2 = C.pad(x, [(1, 1), (2, 2)], mode=1).eval()\n expect2 = np.lib.pad([[0, 1, 2], [3, 4, 5]], ((1, 1), (2, 2)), 'reflect')\n assert np.array_equal(pad2, expect2)\n\n pad3 = C.pad(x, [(1, 1), (2, 2)], mode=2).eval()\n expect3 = np.lib.pad([[0, 1, 2], [3, 4, 5]], ((1, 1), (2, 2)), 'symmetric')\n assert np.array_equal(pad3, expect3)\n\n #test inferred dimension and free dimension\n x = C.input((C.InferredDimension, 3))\n data = np.arange(12).reshape((2, 2, 3))\n pad4 = C.pad(x, [(1, 1), (2, 2)], mode=1).eval({x:data})\n expect4 = np.lib.pad([[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]],\n ((0,0),(1,1),(2,2)), 'reflect')\n assert np.array_equal(pad4, expect4)\n\n x = C.input((C.FreeDimension, 3))\n pad5 = C.pad(x, [(1, 1), (2, 2)], mode=2).eval({x: data})\n expect5 = np.lib.pad([[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]],\n ((0, 0), (1, 1), (2, 2)), 'symmetric')\n assert np.array_equal(pad5, expect5)\n\n #test grad\n x = C.parameter(init=np.arange(6).reshape((2,3)))\n p = C.pad(x, mode=C.ops.SYMMETRIC_PAD, pattern=[(1, 0), (2, 1)])\n grad = p.grad({}, [x])\n expect_grad = np.asarray([[4., 4., 4.],[2., 2., 2.]])\n assert np.array_equal(grad, expect_grad)\n\n p2 = C.pad(x, mode=C.ops.REFLECT_PAD, pattern=[(1, 1), (2, 2)])\n grad2 = p2.grad({}, [x])\n expect_grad2 = np.asarray([[4., 6., 4.], [4., 6., 4.]])\n assert np.array_equal(grad2, expect_grad2)\n\ndef test_crop():\n # Small network.\n node_input = C.input_variable((1, 5, 5))\n node_referent = C.input_variable((1, 5, 5))\n node_output = C.layers.Sequential([\n C.layers.Convolution2D(filter_shape = (3, 3),\n num_filters = 1,\n init = 1,\n strides = (2, 2),\n pad = True,\n bias = False),\n C.layers.MaxPooling(filter_shape = (3, 3),\n strides = (2, 2),\n pad = True),\n C.layers.ConvolutionTranspose(filter_shape = (4, 4),\n num_filters = 1,\n strides = (4, 4),\n init = 1,\n bias = False)])(node_input)\n\n # Input data.\n input_map = {\n node_input: -np.arange(25).reshape(1, 1, 5, 5).astype(np.float32),\n node_referent: np.zeros([1, 1, 5, 5]).astype(np.float32)\n }\n\n # Expected cropped output.\n expected = [-12, -12, -12, -24, -24] * 3 + [-63, -63, -63, -81, -81] * 2\n expected = np.asarray(expected, dtype = np.float32).reshape(1, 1, 5, 5)\n\n # Test crop with explicitly specified offsets.\n cropped = C.crop_manual(node_output, node_referent, 1, 1).eval(input_map)\n assert np.array_equal(cropped, expected)\n\n # Test crop with automatically computed offsets where inputs\n # have common ancestor.\n cropped = C.crop_automatic(node_output, node_input).eval(input_map)\n assert np.array_equal(cropped, expected)\n\n # Test crop with automatically computed offsets where inputs do not\n # have common ancestor.\n cropped = C.crop_automatic_with_ancestors(\n node_output, node_referent, node_input, node_referent).eval(input_map)\n assert np.array_equal(cropped, expected)\n\n\[email protected](\"axis\", [-2, -1])\ndef test_topk(axis, device_id, precision):\n def sliceit(x, axis):\n if axis not in (-2, -1):\n raise ValueError(\"unknown axis %d\"%axis)\n if axis == -1:\n return x[..., -1:-4:-1]\n elif axis == -2:\n return x[..., -1:-4:-1, :]\n\n def check_topk_values_and_indices(top, y, x):\n vals = top[y.outputs[0]]\n idxs = top[y.outputs[1]]\n for vi,xi in zip(vals, x):\n assert np.allclose(vi, sliceit(np.sort(xi, axis=axis), axis))\n for idxi,xi in zip(idxs, x):\n assert np.allclose(idxi, sliceit(np.argsort(xi, axis=axis), axis))\n\n dt = PRECISION_TO_TYPE[precision]\n dev = cntk_device(device_id)\n\n p = C.parameter((10, 20, 30), dtype=dt)\n np.random.seed(90210)\n p.value = p.value + np.random.randn(*p.shape)\n y = C.top_k(p, 3, axis=axis)\n top = y.eval({}) # for now run this on the device where the parameter is\n assert np.allclose(top[y.outputs[0]], sliceit(np.sort(p.value, axis=axis), axis))\n assert np.allclose(top[y.outputs[1]], sliceit(np.argsort(p.value, axis=axis), axis))\n\n q = C.input_variable((5, 6), dtype=dt)\n q0 = np.random.randn(2, 5, 6).astype(dt)\n y = C.top_k(q, 3, axis=axis)\n top = y.eval({q:q0}, device=dev)\n check_topk_values_and_indices(top, y, q0)\n\n q = C.sequence.input_variable((5, 6), dtype=dt)\n q0 = [np.random.randn(4-i, 5, 6).astype(dt) for i in range(2)]\n y = C.top_k(q, 3, axis=axis)\n top = y.eval({q:q0}, device=dev)\n check_topk_values_and_indices(top, y, q0)\n\n\ndef test_topk_backward(device_id, precision):\n def check_grad_last_axis(input, root, indices, output):\n d = input.shape[-1]\n k = indices.shape[-1]\n expected_output = np.zeros_like(input).reshape(-1,d)\n ind = np.reshape(indices, (-1,k))\n r = np.reshape(root,(-1,k))\n assert ind.shape[0] == r.shape[0] == expected_output.shape[0]\n for i in range(expected_output.shape[0]):\n for j in range(k):\n expected_output[i,int(ind[i,j])] = r[i,j]\n expected_output = expected_output.reshape(input.shape)\n assert np.allclose(output, expected_output)\n\n dt = PRECISION_TO_TYPE[precision]\n dev = cntk_device(device_id)\n\n axis=-1\n h = C.placeholder()\n p = C.parameter((4, 5, 6))\n p.value = p.value + np.random.randn(*p.shape)\n y = C.top_k(h, 3, axis=axis)\n y.replace_placeholder(p)\n dy, top = y.forward({}, y.outputs, set([y.outputs[0]]))\n indices = top[y.outputs[1]]\n root = np.ones_like(indices)\n root = root + np.arange(np.prod(root.shape)).reshape(*root.shape)\n cg = y.backward(dy, {y.outputs[0]:root}, set([p]))[p]\n check_grad_last_axis(p.value, root, indices, cg)\n\n q = C.sequence.input_variable((5,6), needs_gradient=True)\n q0 = [np.random.randn(4-i,5,6).astype(dt) for i in range(2)]\n y = C.top_k(q, 3, axis=axis)\n dy, top = y.forward({q:q0}, y.outputs, set([y.outputs[0]]), device=dev)\n indices = top[y.outputs[1]]\n root = [np.ones_like(i) + 100 * k + np.arange(np.prod(i.shape)).reshape(*i.shape) for k,i in enumerate(indices)]\n cg = y.backward(dy, {y.outputs[0]:root}, set([q]))[q]\n for i in range(2):\n check_grad_last_axis(q0[i], root[i], indices[i], cg[i])\n\n\nDEPTH_TO_SPACE_TEST_CASES = [\n ((2, 3), 8, 2, #(image_shape, num_channels, block_size)\n [[[[ 0., 1., 0., 1., 0., 1.],# output\n [ 2., 3., 2., 3., 2., 3.],\n [ 0., 1., 0., 1., 0., 1.],\n [ 2., 3., 2., 3., 2., 3.]],\n [[ 4., 5., 4., 5., 4., 5.],\n [ 6., 7., 6., 7., 6., 7.],\n [ 4., 5., 4., 5., 4., 5.],\n [ 6., 7., 6., 7., 6., 7.]]]]),\n\n ((4, 5), 9, 3, #(image_shape, num_channels, block_size)\n [[[[ 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2.], # output\n [ 3., 4., 5., 3., 4., 5., 3., 4., 5., 3., 4., 5., 3., 4., 5.],\n [ 6., 7., 8., 6., 7., 8., 6., 7., 8., 6., 7., 8., 6., 7., 8.],\n [ 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2.],\n [ 3., 4., 5., 3., 4., 5., 3., 4., 5., 3., 4., 5., 3., 4., 5.],\n [ 6., 7., 8., 6., 7., 8., 6., 7., 8., 6., 7., 8., 6., 7., 8.],\n [ 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2.],\n [ 3., 4., 5., 3., 4., 5., 3., 4., 5., 3., 4., 5., 3., 4., 5.],\n [ 6., 7., 8., 6., 7., 8., 6., 7., 8., 6., 7., 8., 6., 7., 8.],\n [ 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2.],\n [ 3., 4., 5., 3., 4., 5., 3., 4., 5., 3., 4., 5., 3., 4., 5.],\n [ 6., 7., 8., 6., 7., 8., 6., 7., 8., 6., 7., 8., 6., 7., 8.]]]]),\n]\[email protected](\"image_shape, num_channels, block_size, output_ref\", DEPTH_TO_SPACE_TEST_CASES)\ndef test_depth_to_space(image_shape, num_channels, block_size, output_ref, device_id, precision):\n dev = cntk_device(device_id)\n from cntk.internal import sanitize_dtype_cntk\n\n input_val = np.array(np.reshape(range(num_channels), (num_channels, 1, 1)), dtype=PRECISION_TO_TYPE[precision])\n input_val = np.tile(input_val, (1,) + image_shape)\n img = C.input_variable((num_channels,) + image_shape, dtype=sanitize_dtype_cntk(PRECISION_TO_TYPE[precision]))\n depth_to_space_op = C.depth_to_space(img, block_size)\n output_test = depth_to_space_op.eval({ img : input_val })\n\n assert np.array_equal(output_test, output_ref)\n\n# space_to_depth is tested as a roundtrip, i.e. first a tensor is shuffled using depth_to_space\n# and its output is provided as the input to space_to_depth. The output os space_to_depth is\n# checked against the original input tensor for equality.\nSPACE_TO_DEPTH_TEST_CASES = [\n #(image_shape, num_channels, block_size)\n ((2, 3), 8, 2),\n ((4, 5), 9, 3),\n]\[email protected](\"image_shape, num_channels, block_size\", SPACE_TO_DEPTH_TEST_CASES)\ndef test_space_to_depth(image_shape, num_channels, block_size, device_id, precision):\n dev = cntk_device(device_id)\n from cntk.internal import sanitize_dtype_cntk\n\n input_val = np.random.randint(low=0, high=100, size=(num_channels,) + image_shape).astype(PRECISION_TO_TYPE[precision])\n img = C.input_variable((num_channels,) + image_shape, dtype=sanitize_dtype_cntk(PRECISION_TO_TYPE[precision]))\n depth_to_space_op = C.depth_to_space(img, block_size)\n space_to_depth_op = C.space_to_depth(depth_to_space_op, block_size)\n output_val = np.squeeze(space_to_depth_op.eval({ img : input_val }), 0)\n\n assert np.array_equal(output_val, input_val)\n\n\ndef test_data_resize():\n batch_size = 8\n w = C.parameter(shape=(3, 2), name='w1')\n x = C.input_variable(shape=[3], name='x')\n y = C.softmax(C.times(x, w))\n y = C.unpack_batch(y)\n y = C.reshape(y, [batch_size * 2])\n loss = C.reduce_mean(-C.log(y))\n\n learning_rate = 0.01\n lr_schedule = C.learning_rate_schedule(learning_rate, C.UnitType.minibatch)\n learner = C.sgd(y.parameters, lr_schedule, gradient_clipping_threshold_per_sample=1.0)\n trainer = C.Trainer(y, (loss), [learner])\n\n features = np.random.randn(batch_size, 3)\n trainer.train_minibatch({x: features})\n\n\nSQUEEZE_TEST_CASES = [((1,1,1), ax) for ax in [-3,-2,-1,0,1,2,None]] + [((1,3), ax) for ax in [0,-2,None]] + [((1,2,1), ax) for ax in [-3,-1,(0,2),None]]\n\n\[email protected](\"operand_shape, axis\", SQUEEZE_TEST_CASES)\ndef test_squeeze(operand_shape, axis, device_id, precision):\n operand = np.arange(np.prod(operand_shape)).reshape(operand_shape).astype('f')\n expected = np.squeeze(operand, axis)\n\n expected_forward = [expected]\n expected_backward = {\n 'arg': [np.ones_like(operand)],\n }\n\n from .. import squeeze, placeholder\n p = C.placeholder()\n squeeze_with_axis = C.squeeze(p, axis)\n _test_unary_op(precision, device_id, squeeze_with_axis, operand,\n expected_forward, expected_backward)\n\n\[email protected](\"operand_shape, axis\", SQUEEZE_TEST_CASES)\ndef test_expand_dims(operand_shape, axis, device_id, precision):\n if axis is None or isinstance(axis, tuple):\n return\n operand = np.arange(np.prod(operand_shape)).reshape(operand_shape).astype('f')\n expected = np.expand_dims(operand, axis)\n\n expected_forward = [expected]\n expected_backward = {\n 'arg': [np.ones_like(operand)],\n }\n\n from .. import expand_dims, placeholder\n p = C.placeholder()\n expand_dims_with_axis = C.expand_dims(p, axis)\n _test_unary_op(precision, device_id, expand_dims_with_axis, operand,\n expected_forward, expected_backward)\n"
] |
[
[
"numpy.expand_dims",
"numpy.asarray",
"numpy.squeeze",
"numpy.random.randn",
"numpy.zeros_like",
"numpy.mean",
"numpy.random.randint",
"numpy.ones_like",
"numpy.allclose",
"numpy.reshape",
"numpy.arange",
"numpy.full",
"numpy.copy",
"numpy.repeat",
"numpy.zeros",
"numpy.lib.pad",
"numpy.transpose",
"numpy.argsort",
"numpy.array",
"numpy.multiply.reduce",
"numpy.random.random",
"numpy.array_equal",
"numpy.random.seed",
"numpy.tile",
"numpy.sort",
"numpy.ones",
"numpy.prod"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sharanmayank/ShillingAttack
|
[
"783f135a4fcc709e7ce478c2e6f2e7e6c5ad2ace"
] |
[
"Leg-UP/models/recommender/Recommender.py"
] |
[
"# -*- coding: utf-8 -*-\n# @Time : 2020/11/27 17:20\n# @Author : chensi\n# @File : Recommender.py\n# @Software : PyCharm\n# @Desciption : None\n\nimport os\n# os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\"\n\n# def available_GPU():\n# import subprocess\n# import numpy as np\n# nDevice = int(subprocess.getoutput(\"nvidia-smi -L | grep GPU |wc -l\"))\n# total_GPU_str = subprocess.getoutput(\"nvidia-smi -q -d Memory | grep -A4 GPU | grep Total | grep -o '[0-9]\\+'\")\n# total_GPU = total_GPU_str.split('\\n')\n# total_GPU = np.array([int(device_i) for device_i in total_GPU])\n# avail_GPU_str = subprocess.getoutput(\"nvidia-smi -q -d Memory | grep -A4 GPU | grep Free | grep -o '[0-9]\\+'\")\n# avail_GPU = avail_GPU_str.split('\\n')\n# avail_GPU = np.array([int(device_i) for device_i in avail_GPU])\n# avail_GPU = avail_GPU / total_GPU\n# return np.argmax(avail_GPU)\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1, 2, 3\"\n\n\n# try:\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(available_GPU())\n# except:\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = '0'\n\nimport random\nimport numpy as np\nimport torch\n\ntf = None\ntry:\n import tensorflow.compat.v1 as tf\n\n tf.disable_v2_behavior()\nexcept:\n import tensorflow as tf\n\nseed = 1234\nrandom.seed(seed)\nnp.random.seed(seed)\ntf.set_random_seed(seed)\ntorch.manual_seed(seed)\ntorch.cuda.manual_seed_all(seed)\n\nfrom utils.data_loader import DataLoader\nimport numpy as np\nimport pandas as pd\nimport argparse, scipy, math\nimport surprise\nfrom surprise import Dataset, Reader, accuracy\nfrom surprise.model_selection import PredefinedKFold\n\n\nclass Recommender(object):\n\n def __init__(self):\n self.args = self.parse_args()\n # 路径\n self.train_path = self.args.train_path\n self.test_path = self.args.test_path\n self.model_path = self.args.model_path\n self.target_prediction_path_prefix = self.args.target_prediction_path_prefix\n # 攻击\n self.target_id_list = list(map(int, self.args.target_ids.split(',')))\n self.topk_list = list(map(int, self.args.topk.split(',')))\n #\n # os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(self.args.cuda_id)\n pass\n\n @staticmethod\n def parse_args():\n\n parser = argparse.ArgumentParser(description=\"Run Recommender.\")\n parser.add_argument('--data_set', type=str, default='ml100k') # , required=True)\n # 路径\n parser.add_argument('--train_path', type=str,\n default='./data/ml100k/ml100k_train.dat') # , required=True)\n parser.add_argument('--test_path', type=str,\n default='./data/ml100k/ml100k_test.dat') # , required=True)\n parser.add_argument('--model_path', type=str,\n default='./results/model_saved/automotive/automotive_NeuMF_AUSHplus_round_119') # , required=True)\n parser.add_argument('--target_prediction_path_prefix', type=str,\n default='./results/performance/mid_results/ml100k_Recommender') # , required=True)\n\n # 攻击\n parser.add_argument('--target_ids', type=str, default='0') # , required=True)\n parser.add_argument('--topk', type=str, default='5,10,20,50')\n #\n parser.add_argument('--cuda_id', type=int, default=0)\n return parser\n\n def prepare_data(self):\n self.dataset_class = DataLoader(self.train_path, self.test_path)\n\n self.train_data_df, self.test_data_df, self.n_users, self.n_items = self.dataset_class.load_file_as_dataFrame()\n self.train_matrix, _ = self.dataset_class.dataFrame_to_matrix(self.train_data_df, self.n_users, self.n_items)\n self.test_matrix, _ = self.dataset_class.dataFrame_to_matrix(self.test_data_df, self.n_users, self.n_items)\n pass\n\n def build_network(self):\n print('build Recommender model graph.')\n raise NotImplemented\n\n def train(self):\n print('train.')\n raise NotImplemented\n\n def test(self):\n print('test.')\n raise NotImplemented\n\n def execute(self):\n print('generate target item performace on a trained Recommender model.')\n raise NotImplemented\n\n def save(self, path):\n saver = tf.train.Saver()\n saver.save(self.sess, path)\n\n def restore(self, path):\n saver = tf.train.Saver()\n saver.restore(self.sess, path)\n\n def predict(self, user_id, item_id):\n raise NotImplemented\n\n def generate_target_result(self):\n train_data_array = self.train_matrix.toarray()\n for target_id in self.target_id_list:\n # mask掉已评分用户以及未评分用户的已评分商品\n mask = np.zeros_like(train_data_array)\n mask[np.where(train_data_array[:, target_id])[0]] = float('inf')\n # 找到测试数据\n test_uids, test_iids = np.where((train_data_array + mask) == 0)\n # 预测\n test_predRatings = self.predict(test_uids, test_iids)\n # 构建dataframe\n predResults = pd.DataFrame({'user_id': test_uids,\n 'item_id': test_iids,\n 'rating': test_predRatings\n })\n # 为每个未评分计算预测分和HR\n predResults_target = np.zeros([len(predResults.user_id.unique()), len(self.topk_list) + 2])\n for idx, (user_id, pred_result) in enumerate(predResults.groupby('user_id')):\n pred_value = pred_result[pred_result.item_id == target_id].rating.values[0]\n sorted_recommend_list = pred_result.sort_values('rating', ascending=False).item_id.values\n new_line = [user_id, pred_value] + [1 if target_id in sorted_recommend_list[:k] else 0 for k in\n self.topk_list]\n predResults_target[idx] = new_line\n np.save('%s_%d' % (self.target_prediction_path_prefix, target_id), predResults_target)\n\n\nclass AutoRec(Recommender):\n def __init__(self):\n super(AutoRec, self).__init__()\n self.restore_model = self.args.restore_model\n self.learning_rate = self.args.learning_rate\n self.epochs = self.args.epoch\n self.batch_size = self.args.batch_size\n self.reg_rate = self.args.reg_rate\n self.verbose = self.args.verbose\n self.T = self.args.T\n #\n self.hidden_neuron = self.args.hidden_neuron\n #\n print(\"AutoRec.\", end=' ')\n\n @staticmethod\n def parse_args():\n parser = Recommender.parse_args()\n #\n parser.add_argument('--restore_model', type=int, default=0)\n parser.add_argument('--learning_rate', type=float, default=0.001)\n parser.add_argument('--reg_rate', type=float, default=0.1)\n parser.add_argument('--epoch', type=int, default=500)\n parser.add_argument('--batch_size', type=int, default=500)\n parser.add_argument('--verbose', type=int, default=1)\n parser.add_argument('--T', type=int, default=5)\n parser.add_argument('--display_step', type=int, default=1000)\n #\n parser.add_argument('--hidden_neuron', type=int, default=500)\n #\n return parser\n\n def prepare_data(self):\n super(AutoRec, self).prepare_data()\n self.train_data_array = self.train_matrix.toarray()\n self.train_data_mask_array = scipy.sign(self.train_data_array)\n\n def build_network(self):\n raise NotImplemented\n\n def predict(self, user_id, item_id):\n raise NotImplemented\n\n def train(self):\n raise NotImplemented\n\n def test(self):\n raise NotImplemented\n\n def execute(self):\n # 数据准备\n self.prepare_data()\n\n # tensorflow session\n config = tf.ConfigProto()\n # config.gpu_options.allow_growth = True\n with tf.Session(config=config) as sess:\n self.sess = sess\n\n self.build_network()\n\n\n init = tf.global_variables_initializer()\n sess.run(init)\n\n\n if self.restore_model:\n self.restore(self.model_path)\n print(\"loading done.\")\n\n\n else:\n loss_prev = float('inf')\n for epoch in range(self.epochs):\n loss_cur = self.train()\n if self.verbose and epoch % self.T == 0:\n print(\"epoch:\\t\", epoch, \"\\tloss:\\t\", loss_cur)\n if abs(loss_cur - loss_prev) < math.exp(-5):\n break\n loss_prev = loss_cur\n\n\n self.save(self.model_path)\n print(\"training done.\")\n\n\n rmse, mae = self.test()\n print(\"RMSE : %.4f,\\tMAE : %.4f\" % (rmse, mae))\n\n self.generate_target_result()\n\n return\n\n\nclass IAutoRec(AutoRec):\n def __init__(self):\n super(IAutoRec, self).__init__()\n print(\"IAutoRec.\", end=' ')\n\n @staticmethod\n def parse_args():\n parser = AutoRec.parse_args()\n # return parser.parse_args()\n\n args, _ = parser.parse_known_args()\n return args\n\n def prepare_data(self):\n super(IAutoRec, self).prepare_data()\n\n def build_network(self):\n # placeholder\n self.rating_matrix = tf.placeholder(dtype=tf.float32, shape=[self.n_users, None])\n self.rating_matrix_mask = tf.placeholder(dtype=tf.float32, shape=[self.n_users, None])\n self.keep_rate_net = tf.placeholder(tf.float32)\n self.keep_rate_input = tf.placeholder(tf.float32)\n\n # Variable\n V = tf.Variable(tf.random_normal([self.hidden_neuron, self.n_users], stddev=0.01))\n W = tf.Variable(tf.random_normal([self.n_users, self.hidden_neuron], stddev=0.01))\n\n mu = tf.Variable(tf.random_normal([self.hidden_neuron], stddev=0.01))\n b = tf.Variable(tf.random_normal([self.n_users], stddev=0.01))\n\n # forward\n layer_1 = tf.nn.dropout(tf.sigmoid(tf.expand_dims(mu, 1) + tf.matmul(V, self.rating_matrix)),\n self.keep_rate_net)\n self.layer_2 = tf.matmul(W, layer_1) + tf.expand_dims(b, 1)\n\n # backward\n self.loss = tf.reduce_mean(tf.square(\n tf.norm(tf.multiply((self.rating_matrix - self.layer_2), self.rating_matrix_mask)))) + self.reg_rate * (\n tf.square(tf.norm(W)) + tf.square(tf.norm(V)))\n self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.loss)\n\n def predict(self, user_id, item_id):\n self.reconstruction = self.sess.run(self.layer_2, feed_dict={self.rating_matrix: self.train_data_array,\n self.rating_matrix_mask: self.train_data_mask_array,\n self.keep_rate_net: 1})\n return self.reconstruction[user_id, item_id]\n\n def train(self):\n total_batch = int(self.n_items / self.batch_size)\n idxs = np.random.permutation(self.n_items) # shuffled ordering\n loss = []\n for i in range(total_batch):\n batch_set_idx = idxs[i * self.batch_size: (i + 1) * self.batch_size]\n\n _, loss_ = self.sess.run(\n [self.optimizer, self.loss],\n feed_dict={\n self.rating_matrix: self.train_matrix[:, batch_set_idx].toarray(),\n self.rating_matrix_mask: scipy.sign(self.train_matrix[:, batch_set_idx].toarray()),\n self.keep_rate_net: 1 # 0.95\n })\n\n loss.append(loss_)\n return np.mean(loss)\n\n def test(self):\n self.reconstruction = self.sess.run(self.layer_2,\n feed_dict={self.rating_matrix: self.train_data_array,\n self.rating_matrix_mask: self.train_data_mask_array,\n self.keep_rate_net: 1})\n test_data = self.test_matrix.toarray()\n test_data_mask = test_data > 0\n test_data_num = np.sum(test_data_mask)\n #\n mae_matrix = np.abs(test_data - self.reconstruction) * test_data_mask\n rmse_matrix = mae_matrix ** 2\n rmse, mae = np.sum(rmse_matrix) / test_data_num, np.sum(mae_matrix) / test_data_num\n return rmse, mae\n\n def execute(self):\n super(IAutoRec, self).execute()\n\n\nclass UAutoRec(AutoRec):\n def __init__(self):\n super(UAutoRec, self).__init__()\n #\n self.layer = self.args.layer\n #\n print(\"UAutoRec.\", end=' ')\n\n @staticmethod\n def parse_args():\n parser = AutoRec.parse_args()\n #\n parser.add_argument('--layer', type=int, default=1)\n #\n # return parser.parse_args()\n\n args, _ = parser.parse_known_args()\n return args\n\n def prepare_data(self):\n super(UAutoRec, self).prepare_data()\n\n def build_network(self):\n # placeholder\n self.rating_matrix = tf.placeholder(dtype=tf.float32, shape=[self.n_items, None])\n self.rating_matrix_mask = tf.placeholder(dtype=tf.float32, shape=[self.n_items, None])\n if self.layer == 1:\n # Variable\n V = tf.Variable(tf.random_normal([self.hidden_neuron, self.n_items], stddev=0.01))\n W = tf.Variable(tf.random_normal([self.n_items, self.hidden_neuron], stddev=0.01))\n\n mu = tf.Variable(tf.random_normal([self.hidden_neuron], stddev=0.01))\n b = tf.Variable(tf.random_normal([self.n_items], stddev=0.01))\n layer_1 = tf.sigmoid(tf.expand_dims(mu, 1) + tf.matmul(V, self.rating_matrix))\n self.layer_2 = tf.matmul(W, layer_1) + tf.expand_dims(b, 1)\n Loss_norm = tf.square(tf.norm(W)) + tf.square(tf.norm(V))\n elif self.layer == 3:\n V_1 = tf.Variable(tf.random_normal([self.hidden_neuron, self.n_items], stddev=0.01))\n V_2 = tf.Variable(tf.random_normal([self.hidden_neuron // 2, self.hidden_neuron], stddev=0.01))\n V_3 = tf.Variable(tf.random_normal([self.hidden_neuron, self.hidden_neuron // 2], stddev=0.01))\n W = tf.Variable(tf.random_normal([self.n_items, self.hidden_neuron], stddev=0.01))\n mu_1 = tf.Variable(tf.random_normal([self.hidden_neuron], stddev=0.01))\n mu_2 = tf.Variable(tf.random_normal([self.hidden_neuron // 2], stddev=0.01))\n mu_3 = tf.Variable(tf.random_normal([self.hidden_neuron], stddev=0.01))\n b = tf.Variable(tf.random_normal([self.n_items], stddev=0.01))\n #\n layer_1 = tf.sigmoid(tf.matmul(V_1, self.rating_matrix) + tf.expand_dims(mu_1, 1))\n layer_2 = tf.sigmoid(tf.matmul(V_2, layer_1) + tf.expand_dims(mu_2, 1))\n layer_3 = tf.sigmoid(tf.matmul(V_3, layer_2) + tf.expand_dims(mu_3, 1))\n self.layer_2 = tf.matmul(W, layer_3) + tf.expand_dims(b, 1)\n Loss_norm = tf.square(tf.norm(W)) + tf.square(tf.norm(V_1)) + tf.square(tf.norm(V_3)) + tf.square(\n tf.norm(V_3))\n self.loss = tf.reduce_mean(tf.square(\n tf.norm(tf.multiply((self.rating_matrix - self.layer_2),\n self.rating_matrix_mask)))) + self.reg_rate + Loss_norm\n\n self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.loss)\n\n def predict(self, user_id, item_id):\n self.reconstruction = self.sess.run(self.layer_2,\n feed_dict={self.rating_matrix: self.train_data_array.transpose(),\n self.rating_matrix_mask: self.train_data_mask_array.transpose()})\n return self.reconstruction.transpose()[user_id, item_id]\n\n def train(self):\n total_batch = int(self.n_users / self.batch_size)\n idxs = np.random.permutation(self.n_users) # shuffled ordering\n loss = []\n for i in range(total_batch):\n batch_set_idx = idxs[i * self.batch_size: (i + 1) * self.batch_size]\n\n _, loss_ = self.sess.run(\n [self.optimizer, self.loss],\n feed_dict={self.rating_matrix: self.train_data_array.transpose()[:, batch_set_idx],\n self.rating_matrix_mask: self.train_data_mask_array.transpose()[:, batch_set_idx]\n })\n\n loss.append(loss_)\n return np.mean(loss)\n\n def test(self):\n self.reconstruction = self.sess.run(self.layer_2,\n feed_dict={self.rating_matrix: self.train_data_array.transpose(),\n self.rating_matrix_mask:\n self.train_data_mask_array.transpose()})\n test_data = self.test_matrix.toarray().transpose()\n test_data_mask = test_data > 0\n test_data_num = np.sum(test_data_mask)\n #\n mae_matrix = np.abs(test_data - self.reconstruction) * test_data_mask\n rmse_matrix = mae_matrix ** 2\n rmse, mae = np.sum(rmse_matrix) / test_data_num, np.sum(mae_matrix) / test_data_num\n return rmse, mae\n\n def execute(self):\n super(UAutoRec, self).execute()\n\n\nclass NeuMF(Recommender):\n def __init__(self):\n super(NeuMF, self).__init__()\n self.restore_model = self.args.restore_model\n self.learning_rate = self.args.learning_rate\n self.epochs = self.args.epoch\n self.batch_size = self.args.batch_size\n self.reg_rate = self.args.reg_rate\n self.verbose = self.args.verbose\n self.T = self.args.T\n #\n self.num_factor = self.args.num_factor\n self.num_factor_mlp = self.args.num_factor_mlp\n self.hidden_dimension = self.args.hidden_dimension\n #\n print(\"NeuMF.\")\n\n @staticmethod\n def parse_args():\n parser = Recommender.parse_args()\n #\n parser.add_argument('--restore_model', type=int, default=0)\n parser.add_argument('--learning_rate', type=float, default=0.5)\n parser.add_argument('--reg_rate', type=float, default=0.01)\n parser.add_argument('--epoch', type=int, default=50)\n parser.add_argument('--batch_size', type=int, default=256)\n #\n parser.add_argument('--num_factor', type=int, default=10)\n parser.add_argument('--num_factor_mlp', type=int, default=64)\n parser.add_argument('--hidden_dimension', type=int, default=10)\n #\n parser.add_argument('--verbose', type=int, default=1)\n parser.add_argument('--T', type=int, default=5)\n parser.add_argument('--display_step', type=int, default=1000)\n #\n # return parser.parse_args()\n\n args, _ = parser.parse_known_args()\n return args\n\n def build_network(self):\n # self.num_neg_sample = num_neg_sample\n self.user_id = tf.placeholder(dtype=tf.int32, shape=[None], name='user_id')\n self.item_id = tf.placeholder(dtype=tf.int32, shape=[None], name='item_id')\n self.y = tf.placeholder(dtype=tf.float32, shape=[None], name='y')\n\n self.P = tf.Variable(tf.random_normal([self.n_users, self.num_factor], stddev=0.01), dtype=tf.float32)\n self.Q = tf.Variable(tf.random_normal([self.n_items, self.num_factor], stddev=0.01), dtype=tf.float32)\n\n self.mlp_P = tf.Variable(tf.random_normal([self.n_users, self.num_factor_mlp], stddev=0.01), dtype=tf.float32)\n self.mlp_Q = tf.Variable(tf.random_normal([self.n_items, self.num_factor_mlp], stddev=0.01), dtype=tf.float32)\n\n user_latent_factor = tf.nn.embedding_lookup(self.P, self.user_id)\n item_latent_factor = tf.nn.embedding_lookup(self.Q, self.item_id)\n mlp_user_latent_factor = tf.nn.embedding_lookup(self.mlp_P, self.user_id)\n mlp_item_latent_factor = tf.nn.embedding_lookup(self.mlp_Q, self.item_id)\n\n _GMF = tf.multiply(user_latent_factor, item_latent_factor)\n\n regularizer = tf.keras.regularizers.l2(self.reg_rate)\n layer_1 = tf.layers.dense(\n inputs=tf.concat([mlp_item_latent_factor, mlp_user_latent_factor], axis=1),\n units=self.num_factor_mlp * 2,\n kernel_initializer=tf.random_normal_initializer,\n activation=tf.nn.relu,\n kernel_regularizer=regularizer)\n\n layer_2 = tf.layers.dense(\n inputs=layer_1,\n units=self.hidden_dimension * 8,\n activation=tf.nn.relu,\n kernel_initializer=tf.random_normal_initializer,\n kernel_regularizer=regularizer)\n\n layer_3 = tf.layers.dense(\n inputs=layer_2,\n units=self.hidden_dimension * 4,\n activation=tf.nn.relu,\n kernel_initializer=tf.random_normal_initializer,\n kernel_regularizer=regularizer)\n\n layer_4 = tf.layers.dense(\n inputs=layer_3,\n units=self.hidden_dimension * 2,\n activation=tf.nn.relu,\n kernel_initializer=tf.random_normal_initializer,\n kernel_regularizer=regularizer)\n\n _MLP = tf.layers.dense(\n inputs=layer_4,\n units=self.hidden_dimension,\n activation=tf.nn.relu,\n kernel_initializer=tf.random_normal_initializer,\n kernel_regularizer=regularizer)\n\n # self.pred_y = tf.nn.sigmoid(tf.reduce_sum(tf.concat([_GMF, _MLP], axis=1), 1))\n self.pred_rating = tf.reduce_sum(tf.concat([_GMF, _MLP], axis=1), 1)\n\n self.loss = tf.reduce_sum(tf.square(self.y - self.pred_rating)) \\\n + tf.losses.get_regularization_loss() + \\\n self.reg_rate * (tf.nn.l2_loss(self.P) + tf.nn.l2_loss(self.Q) +\n tf.nn.l2_loss(self.mlp_P) + tf.nn.l2_loss(self.mlp_Q))\n #\n self.optimizer = tf.train.AdagradOptimizer(self.learning_rate).minimize(self.loss)\n\n return self\n\n def prepare_data(self):\n super(NeuMF, self).prepare_data()\n #\n self.train_matrix_coo = self.train_matrix.tocoo()\n #\n self.user = self.train_matrix_coo.row.reshape(-1)\n self.item = self.train_matrix_coo.col.reshape(-1)\n self.rating = self.train_matrix_coo.data\n\n def train(self):\n self.num_training = len(self.rating)\n total_batch = int(self.num_training / self.batch_size)\n idxs = np.random.permutation(self.num_training) # shuffled ordering\n user_random = list(self.user[idxs])\n item_random = list(self.item[idxs])\n rating_random = list(self.rating[idxs])\n # train\n loss = []\n for i in range(total_batch):\n batch_user = user_random[i * self.batch_size:(i + 1) * self.batch_size]\n batch_item = item_random[i * self.batch_size:(i + 1) * self.batch_size]\n batch_rating = rating_random[i * self.batch_size:(i + 1) * self.batch_size]\n\n _, loss_ = self.sess.run(\n [self.optimizer, self.loss],\n feed_dict={self.user_id: batch_user,\n self.item_id: batch_item,\n self.y: batch_rating})\n\n loss.append(loss_)\n return np.mean(loss)\n\n def test(self):\n test_data = self.test_matrix.todok()\n #\n uids = np.array(list(test_data.keys()))[:, 0]\n iids = np.array(list(test_data.keys()))[:, 1]\n ground_truth = np.array(list(test_data.values()))\n #\n pred_rating = self.predict(uids, iids)\n #\n rmse = np.sqrt(np.mean((pred_rating - ground_truth) ** 2))\n mae = np.mean(np.abs(pred_rating - ground_truth))\n return rmse, mae\n\n def predict(self, user_ids, item_ids):\n if len(user_ids) < self.batch_size:\n return self.sess.run(self.pred_rating,\n feed_dict={\n self.user_id: user_ids,\n self.item_id: item_ids}\n )\n # predict by batch\n total_batch = math.ceil(len(user_ids) / self.batch_size)\n user_ids, item_ids = list(user_ids), list(item_ids)\n pred_rating = []\n for i in range(total_batch):\n batch_user = user_ids[i * self.batch_size:(i + 1) * self.batch_size]\n batch_item = item_ids[i * self.batch_size:(i + 1) * self.batch_size]\n # predict\n batch_pred_rating = self.sess.run(self.pred_rating,\n feed_dict={\n self.user_id: batch_user,\n self.item_id: batch_item}\n )\n pred_rating += list(batch_pred_rating)\n return pred_rating\n\n def restore_user_embedding(self):\n # 数据准备\n self.prepare_data()\n self.n_users += 50\n # ================\n\n attackers = ['AUSHplus_Dis_xiaorong', 'AUSHplus', 'SegmentAttacker', 'BandwagonAttacker',\n 'AverageAttacker', 'RandomAttacker',\n 'AUSH', 'RecsysAttacker',\n 'DCGAN', 'WGAN']\n #\n targets = [62] # [119, 422, 594, 884, 1593]\n with tf.Session() as sess:\n self.sess = sess\n\n self.build_network()\n\n sess.run(tf.global_variables_initializer())\n\n for target in targets:\n for attacker in attackers:\n self.model_path = './results/model_saved/ml100k/ml100k_NeuMF_%s_%d' % (attacker, target)\n if not os.path.exists(self.model_path + '.meta'):\n continue\n\n self.restore(self.model_path)\n print(\"loading done.\")\n user_embedding, user_embedding_mlp = self.sess.run([self.P, self.mlp_P])\n save_path = self.model_path + '_user_embed'\n save_path = save_path.replace('model_saved', 'performance\\mid_results')\n np.save(save_path, user_embedding)\n np.save(save_path + '_mlp', user_embedding_mlp)\n return\n\n def execute(self):\n\n self.prepare_data()\n # ================\n\n # tensorflow session\n config = tf.ConfigProto()\n # config.gpu_options.allow_growth = True\n with tf.Session(config=config) as sess:\n self.sess = sess\n\n self.build_network()\n\n\n init = tf.global_variables_initializer()\n sess.run(init)\n\n\n if self.restore_model:\n self.restore(self.model_path)\n print(\"loading done.\")\n\n\n else:\n loss_prev = float('inf')\n for epoch in range(self.epochs):\n loss_cur = self.train()\n if True: # self.verbose and epoch % self.T == 0:\n print(\"epoch:\\t\", epoch, \"\\tloss:\\t\", loss_cur, flush=True)\n if abs(loss_cur - loss_prev) < math.exp(-5):\n break\n loss_prev = loss_cur\n\n\n self.save(self.model_path)\n print(\"training done.\")\n\n\n rmse, mae = self.test()\n print(\"RMSE : %.4f,\\tMAE : %.4f\" % (rmse, mae))\n\n self.generate_target_result()\n\n return\n\n\nclass NNMF(Recommender):\n def __init__(self):\n super(NNMF, self).__init__()\n\n self.restore_model = self.args.restore_model\n self.learning_rate = self.args.learning_rate\n self.epochs = self.args.epoch\n self.batch_size = self.args.batch_size\n self.reg_rate = self.args.reg_rate\n self.verbose = self.args.verbose\n self.T = self.args.T\n #\n self.num_factor_1 = self.args.num_factor_1\n self.num_factor_2 = self.args.num_factor_2\n self.hidden_dimension = self.args.hidden_dimension\n #\n print(\"NNMF.\")\n\n @staticmethod\n def parse_args():\n parser = Recommender.parse_args()\n #\n parser.add_argument('--restore_model', type=int, default=0)\n parser.add_argument('--learning_rate', type=float, default=0.001)\n parser.add_argument('--reg_rate', type=float, default=0.1)\n parser.add_argument('--epoch', type=int, default=500)\n parser.add_argument('--batch_size', type=int, default=500)\n #\n parser.add_argument('--num_factor_1', type=int, default=100)\n parser.add_argument('--num_factor_2', type=int, default=10)\n parser.add_argument('--hidden_dimension', type=int, default=50)\n #\n parser.add_argument('--verbose', type=int, default=1)\n parser.add_argument('--T', type=int, default=5)\n parser.add_argument('--display_step', type=int, default=1000)\n #\n # return parser.parse_args()\n\n args, _ = parser.parse_known_args()\n return args\n\n def prepare_data(self):\n super(NNMF, self).prepare_data()\n #\n self.train_matrix_coo = self.train_matrix.tocoo()\n #\n self.user = self.train_matrix_coo.row.reshape(-1)\n self.item = self.train_matrix_coo.col.reshape(-1)\n self.rating = self.train_matrix_coo.data\n\n def build_network(self):\n print(\"num_factor_1=%d, num_factor_2=%d, hidden_dimension=%d\" % (\n self.num_factor_1, self.num_factor_2, self.hidden_dimension))\n\n # placeholder\n self.user_id = tf.placeholder(dtype=tf.int32, shape=[None], name='user_id')\n self.item_id = tf.placeholder(dtype=tf.int32, shape=[None], name='item_id')\n self.y = tf.placeholder(\"float\", [None], 'rating')\n\n # Variable\n P = tf.Variable(tf.random_normal([self.n_users, self.num_factor_1], stddev=0.01))\n Q = tf.Variable(tf.random_normal([self.n_items, self.num_factor_1], stddev=0.01))\n\n U = tf.Variable(tf.random_normal([self.n_users, self.num_factor_2], stddev=0.01))\n V = tf.Variable(tf.random_normal([self.n_items, self.num_factor_2], stddev=0.01))\n\n # forward\n input = tf.concat(values=[tf.nn.embedding_lookup(P, self.user_id),\n tf.nn.embedding_lookup(Q, self.item_id),\n tf.multiply(tf.nn.embedding_lookup(U, self.user_id),\n tf.nn.embedding_lookup(V, self.item_id))\n ], axis=1)\n\n # tf1->tf2\n # regularizer = tf.contrib.layers.l2_regularizer(scale=self.reg_rate)\n regularizer = tf.keras.regularizers.l2(self.reg_rate)\n layer_1 = tf.layers.dense(inputs=input, units=2 * self.num_factor_1 + self.num_factor_2,\n bias_initializer=tf.random_normal_initializer,\n kernel_initializer=tf.random_normal_initializer, activation=tf.sigmoid,\n kernel_regularizer=regularizer)\n layer_2 = tf.layers.dense(inputs=layer_1, units=self.hidden_dimension, activation=tf.sigmoid,\n bias_initializer=tf.random_normal_initializer,\n kernel_initializer=tf.random_normal_initializer,\n kernel_regularizer=regularizer)\n layer_3 = tf.layers.dense(inputs=layer_2, units=self.hidden_dimension, activation=tf.sigmoid,\n bias_initializer=tf.random_normal_initializer,\n kernel_initializer=tf.random_normal_initializer,\n kernel_regularizer=regularizer)\n layer_4 = tf.layers.dense(inputs=layer_3, units=self.hidden_dimension, activation=tf.sigmoid,\n bias_initializer=tf.random_normal_initializer,\n kernel_initializer=tf.random_normal_initializer,\n kernel_regularizer=regularizer)\n output = tf.layers.dense(inputs=layer_4, units=1, activation=None,\n bias_initializer=tf.random_normal_initializer,\n kernel_initializer=tf.random_normal_initializer,\n kernel_regularizer=regularizer)\n self.pred_rating = tf.reshape(output, [-1])\n\n # backward\n self.loss = tf.reduce_sum(tf.square(self.y - self.pred_rating)) \\\n + tf.losses.get_regularization_loss() + self.reg_rate * (\n tf.norm(U) + tf.norm(V) + tf.norm(P) + tf.norm(Q))\n self.optimizer = tf.train.RMSPropOptimizer(learning_rate=self.learning_rate).minimize(self.loss)\n\n def train(self):\n self.num_training = len(self.rating)\n total_batch = int(self.num_training / self.batch_size)\n idxs = np.random.permutation(self.num_training) # shuffled ordering\n user_random = list(self.user[idxs])\n item_random = list(self.item[idxs])\n rating_random = list(self.rating[idxs])\n # train\n loss = []\n for i in range(total_batch):\n batch_user = user_random[i * self.batch_size:(i + 1) * self.batch_size]\n batch_item = item_random[i * self.batch_size:(i + 1) * self.batch_size]\n batch_rating = rating_random[i * self.batch_size:(i + 1) * self.batch_size]\n\n _, loss_ = self.sess.run(\n [self.optimizer, self.loss],\n feed_dict={self.user_id: batch_user,\n self.item_id: batch_item,\n self.y: batch_rating})\n\n loss.append(loss_)\n return np.mean(loss)\n\n def test(self):\n test_data = self.test_matrix.todok()\n #\n uids = np.array(list(test_data.keys()))[:, 0]\n iids = np.array(list(test_data.keys()))[:, 1]\n ground_truth = np.array(list(test_data.values()))\n #\n pred_rating = self.predict(uids, iids)\n #\n rmse = np.sqrt(np.mean((pred_rating - ground_truth) ** 2))\n mae = np.mean(np.abs(pred_rating - ground_truth))\n return rmse, mae\n\n def predict(self, user_ids, item_ids):\n if len(user_ids) < self.batch_size:\n return self.sess.run(self.pred_rating,\n feed_dict={\n self.user_id: user_ids,\n self.item_id: item_ids}\n )\n # predict by batch\n total_batch = math.ceil(len(user_ids) / self.batch_size)\n user_ids, item_ids = list(user_ids), list(item_ids)\n pred_rating = []\n for i in range(total_batch):\n batch_user = user_ids[i * self.batch_size:(i + 1) * self.batch_size]\n batch_item = item_ids[i * self.batch_size:(i + 1) * self.batch_size]\n # predict\n batch_pred_rating = self.sess.run(self.pred_rating,\n feed_dict={\n self.user_id: batch_user,\n self.item_id: batch_item}\n )\n pred_rating += list(batch_pred_rating)\n return pred_rating\n\n def execute(self):\n\n self.prepare_data()\n\n # tensorflow session\n config = tf.ConfigProto()\n # config.gpu_options.allow_growth = True\n with tf.Session(config=config) as sess:\n self.sess = sess\n\n self.build_network()\n\n init = tf.global_variables_initializer()\n sess.run(init)\n\n if self.restore_model:\n self.restore(self.model_path)\n print(\"loading done.\")\n\n else:\n loss_prev = float('inf')\n for epoch in range(self.epochs):\n loss_cur = self.train()\n if self.verbose and epoch % self.T == 0:\n print(\"epoch:\\t\", epoch, \"\\tloss:\\t\", loss_cur)\n if abs(loss_cur - loss_prev) < math.exp(-5):\n break\n loss_prev = loss_cur\n\n self.save(self.model_path)\n print(\"training done.\")\n\n rmse, mae = self.test()\n print(\"RMSE : %.4f,\\tMAE : %.4f\" % (rmse, mae))\n\n self.generate_target_result()\n\n return\n\n\nclass NRR(Recommender):\n def __init__(self):\n super(NRR, self).__init__()\n self.restore_model = self.args.restore_model\n self.learning_rate = self.args.learning_rate\n self.epochs = self.args.epoch\n self.batch_size = self.args.batch_size\n self.reg_rate = self.args.reg_rate\n self.verbose = self.args.verbose\n self.T = self.args.T\n #\n self.num_factor_user = self.args.num_factor_user\n self.num_factor_item = self.args.num_factor_item\n self.d = self.args.d\n self.hidden_dimension = self.args.hidden_dimension\n #\n print(\"NRR.\")\n\n @staticmethod\n def parse_args():\n parser = Recommender.parse_args()\n #\n parser.add_argument('--restore_model', type=int, default=0)\n parser.add_argument('--learning_rate', type=float, default=0.001)\n parser.add_argument('--reg_rate', type=float, default=0.1)\n parser.add_argument('--epoch', type=int, default=500)\n parser.add_argument('--batch_size', type=int, default=256)\n #\n parser.add_argument('--num_factor_user', type=int, default=40)\n parser.add_argument('--num_factor_item', type=int, default=40)\n parser.add_argument('--d', type=int, default=50)\n parser.add_argument('--hidden_dimension', type=int, default=40)\n #\n parser.add_argument('--verbose', type=int, default=1)\n parser.add_argument('--T', type=int, default=5)\n parser.add_argument('--display_step', type=int, default=1000)\n #\n # return parser.parse_args()\n\n args, _ = parser.parse_known_args()\n return args\n\n def build_network(self):\n\n # model dependent arguments\n self.user_id = tf.placeholder(dtype=tf.int32, shape=[None], name='user_id')\n self.item_id = tf.placeholder(dtype=tf.int32, shape=[None], name='item_id')\n self.y = tf.placeholder(\"float\", [None], 'rating')\n\n U = tf.Variable(tf.random_normal([self.n_users, self.num_factor_user], stddev=0.01))\n V = tf.Variable(tf.random_normal([self.n_items, self.num_factor_item], stddev=0.01))\n b = tf.Variable(tf.random_normal([self.d]))\n\n user_latent_factor = tf.nn.embedding_lookup(U, self.user_id)\n item_latent_factor = tf.nn.embedding_lookup(V, self.item_id)\n\n W_User = tf.Variable(tf.random_normal([self.num_factor_user, self.d], stddev=0.01))\n W_Item = tf.Variable(tf.random_normal([self.num_factor_item, self.d], stddev=0.01))\n\n input = tf.matmul(user_latent_factor, W_User) + tf.matmul(item_latent_factor, W_Item) + b\n\n regularizer = tf.keras.regularizers.l2(self.reg_rate)\n layer_1 = tf.layers.dense(inputs=input, units=self.d, bias_initializer=tf.random_normal_initializer,\n kernel_initializer=tf.random_normal_initializer, activation=tf.sigmoid,\n kernel_regularizer=regularizer)\n layer_2 = tf.layers.dense(inputs=layer_1, units=self.hidden_dimension, activation=tf.sigmoid,\n bias_initializer=tf.random_normal_initializer,\n kernel_initializer=tf.random_normal_initializer,\n kernel_regularizer=regularizer)\n layer_3 = tf.layers.dense(inputs=layer_2, units=self.hidden_dimension, activation=tf.sigmoid,\n bias_initializer=tf.random_normal_initializer,\n kernel_initializer=tf.random_normal_initializer,\n kernel_regularizer=regularizer)\n layer_4 = tf.layers.dense(inputs=layer_3, units=self.hidden_dimension, activation=tf.sigmoid,\n bias_initializer=tf.random_normal_initializer,\n kernel_initializer=tf.random_normal_initializer,\n kernel_regularizer=regularizer)\n output = tf.layers.dense(inputs=layer_4, units=1, activation=None,\n bias_initializer=tf.random_normal_initializer,\n kernel_initializer=tf.random_normal_initializer,\n kernel_regularizer=regularizer)\n self.pred_rating = tf.reshape(output, [-1])\n\n # print(np.shape(output))\n reg_losses = tf.reduce_sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))\n self.loss = tf.reduce_sum(tf.square(self.y - self.pred_rating)) \\\n + tf.losses.get_regularization_loss() + self.reg_rate * (\n tf.norm(U) + tf.norm(V) + tf.norm(b) + tf.norm(W_Item) + tf.norm(W_User))\n self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.loss)\n\n def prepare_data(self):\n super(NRR, self).prepare_data()\n #\n self.train_matrix_coo = self.train_matrix.tocoo()\n #\n self.user = self.train_matrix_coo.row.reshape(-1)\n self.item = self.train_matrix_coo.col.reshape(-1)\n self.rating = self.train_matrix_coo.data\n\n def train(self):\n self.num_training = len(self.rating)\n total_batch = int(self.num_training / self.batch_size)\n idxs = np.random.permutation(self.num_training) # shuffled ordering\n user_random = list(self.user[idxs])\n item_random = list(self.item[idxs])\n rating_random = list(self.rating[idxs])\n\n # train\n loss = []\n for i in range(total_batch):\n batch_user = user_random[i * self.batch_size:(i + 1) * self.batch_size]\n batch_item = item_random[i * self.batch_size:(i + 1) * self.batch_size]\n batch_rating = rating_random[i * self.batch_size:(i + 1) * self.batch_size]\n\n _, loss_ = self.sess.run([self.optimizer, self.loss],\n feed_dict={self.user_id: batch_user,\n self.item_id: batch_item,\n self.y: batch_rating})\n\n loss.append(loss_)\n return np.mean(loss)\n\n def test(self):\n test_data = self.test_matrix.todok()\n #\n uids = np.array(list(test_data.keys()))[:, 0]\n iids = np.array(list(test_data.keys()))[:, 1]\n ground_truth = np.array(list(test_data.values()))\n #\n pred_rating = self.predict(uids, iids)\n #\n rmse = np.sqrt(np.mean((pred_rating - ground_truth) ** 2))\n mae = np.mean(np.abs(pred_rating - ground_truth))\n return rmse, mae\n\n def predict(self, user_ids, item_ids):\n if len(user_ids) < self.batch_size:\n return self.sess.run(self.pred_rating,\n feed_dict={\n self.user_id: user_ids,\n self.item_id: item_ids}\n )\n # predict by batch\n total_batch = math.ceil(len(user_ids) / self.batch_size)\n user_ids, item_ids = list(user_ids), list(item_ids)\n pred_rating = []\n for i in range(total_batch):\n batch_user = user_ids[i * self.batch_size:(i + 1) * self.batch_size]\n batch_item = item_ids[i * self.batch_size:(i + 1) * self.batch_size]\n # predict\n batch_pred_rating = self.sess.run(self.pred_rating,\n feed_dict={\n self.user_id: batch_user,\n self.item_id: batch_item}\n )\n pred_rating += list(batch_pred_rating)\n return pred_rating\n\n def execute(self):\n\n self.prepare_data()\n\n # tensorflow session\n config = tf.ConfigProto()\n # config.gpu_options.allow_growth = True\n with tf.Session(config=config) as sess:\n self.sess = sess\n\n self.build_network()\n\n init = tf.global_variables_initializer()\n sess.run(init)\n\n if self.restore_model:\n self.restore(self.model_path)\n print(\"loading done.\")\n\n else:\n loss_prev = float('inf')\n for epoch in range(self.epochs):\n loss_cur = self.train()\n if True: # self.verbose and epoch % self.T == 0:\n print(\"epoch:\\t\", epoch, \"\\tloss:\\t\", loss_cur)\n if abs(loss_cur - loss_prev) < math.exp(-5):\n break\n loss_prev = loss_cur\n\n self.save(self.model_path)\n print(\"training done.\")\n\n rmse, mae = self.test()\n print(\"RMSE : %.4f,\\tMAE : %.4f\" % (rmse, mae))\n\n self.generate_target_result()\n\n return\n\n\nclass RecommenderOnSurprice(Recommender):\n\n def __init__(self):\n super(RecommenderOnSurprice, self).__init__()\n\n print(\"CF build by surprise.\")\n\n def prepare_data(self):\n super(RecommenderOnSurprice, self).prepare_data()\n\n reader = Reader(line_format='user item rating', sep='\\t', rating_scale=(1, 5))\n data = Dataset.load_from_folds([(self.train_path, self.test_path)], reader=reader)\n trainset, testset = None, None\n pkf = PredefinedKFold()\n for trainset_, testset_ in pkf.split(data):\n trainset, testset = trainset_, testset_\n self.trainset, self.testset = trainset, testset\n\n def build_network(self):\n print('build_network')\n self.model = None\n raise NotImplemented\n\n def predict(self, user_ids, item_ids):\n fn_pred = lambda x: self.model.predict(str(x[0]), str(x[1]), r_ui=0).est\n pred_ratings = list(map(fn_pred, zip(user_ids, item_ids)))\n return pred_ratings\n\n def train(self):\n self.model.fit(self.trainset)\n return\n\n def test(self):\n preds = self.model.test(self.testset)\n rmse = accuracy.rmse(preds, verbose=True)\n print(\"RMSE : %.4f\" % (rmse))\n return\n\n def execute(self):\n\n self.prepare_data()\n\n self.build_network()\n\n self.train()\n\n self.test()\n\n self.generate_target_result()\n return\n\n\nclass KNN(RecommenderOnSurprice):\n def __init__(self):\n super(KNN, self).__init__()\n self.user_based = self.args.user_based\n self.dis_method = self.args.dis_method\n self.k = self.args.k\n print(\"KNN.\")\n\n @staticmethod\n def parse_args():\n parser = Recommender.parse_args()\n #\n parser.add_argument('--user_based', type=int, default=0) # 1\n parser.add_argument('--dis_method', type=str, default='msd')\n parser.add_argument('--k', type=int, default=50) # 20\n #\n\n args, _ = parser.parse_known_args()\n return args\n\n def build_network(self):\n sim_options = {'user_based': self.user_based, 'name': self.dis_method}\n self.model = surprise.KNNBasic(sim_options=sim_options, k=self.k)\n\n\nclass NMF(RecommenderOnSurprice):\n def __init__(self):\n super(NMF, self).__init__()\n self.n_factors = self.args.n_factors\n print(\"NMF.\")\n\n @staticmethod\n def parse_args():\n parser = Recommender.parse_args()\n #\n parser.add_argument('--n_factors', type=int, default=25)\n\n # return parser.parse_args()\n args, _ = parser.parse_known_args()\n return args\n\n def build_network(self):\n self.model = surprise.NMF(n_factors=self.n_factors)\n\n\nclass SVD(RecommenderOnSurprice):\n def __init__(self):\n super(SVD, self).__init__()\n self.n_factors = self.args.n_factors\n print('SVD.')\n\n @staticmethod\n def parse_args():\n parser = Recommender.parse_args()\n #\n parser.add_argument('--n_factors', type=int, default=25)\n #\n # return parser.parse_args()\n\n args, _ = parser.parse_known_args()\n return args\n\n def build_network(self):\n self.model = surprise.SVD(n_factors=self.n_factors)\n\n\nclass SlopeOne(RecommenderOnSurprice):\n def __init__(self):\n super(SlopeOne, self).__init__()\n # self.n_factors = self.args.n_factors\n print('SlopeOne.')\n\n @staticmethod\n def parse_args():\n parser = Recommender.parse_args()\n #\n # parser.add_argument('--n_factors', type=int, default=25)\n #\n # return parser.parse_args()\n\n args, _ = parser.parse_known_args()\n return args\n\n def build_network(self):\n self.model = surprise.SlopeOne()\n\n\nclass CoClustering(RecommenderOnSurprice):\n def __init__(self):\n super(CoClustering, self).__init__()\n print('CoClustering.')\n\n @staticmethod\n def parse_args():\n parser = Recommender.parse_args()\n\n args, _ = parser.parse_known_args()\n return args\n\n def build_network(self):\n self.model = surprise.CoClustering()\n"
] |
[
[
"tensorflow.concat",
"pandas.DataFrame",
"tensorflow.nn.l2_loss",
"numpy.mean",
"numpy.zeros_like",
"torch.cuda.manual_seed_all",
"tensorflow.train.AdamOptimizer",
"numpy.where",
"tensorflow.disable_v2_behavior",
"tensorflow.get_collection",
"tensorflow.keras.regularizers.l2",
"tensorflow.layers.dense",
"numpy.save",
"tensorflow.ConfigProto",
"tensorflow.Session",
"tensorflow.square",
"tensorflow.train.Saver",
"tensorflow.matmul",
"tensorflow.train.AdagradOptimizer",
"tensorflow.norm",
"tensorflow.train.RMSPropOptimizer",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.set_random_seed",
"tensorflow.nn.embedding_lookup",
"numpy.sum",
"tensorflow.multiply",
"numpy.abs",
"numpy.random.seed",
"tensorflow.losses.get_regularization_loss",
"torch.manual_seed",
"tensorflow.reshape",
"tensorflow.expand_dims",
"numpy.random.permutation",
"scipy.sign",
"tensorflow.random_normal"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
MatthewRicks/hand_eye_calibration
|
[
"1454db380aee79139cae185d288d7450dedf52e4"
] |
[
"hand_eye_calibration/bin/tf_to_csv.py"
] |
[
"#!/usr/bin/env python\nimport argparse\nimport math\nimport sys\nimport time\n\nimport numpy as np\n\nimport rosbag\nimport rospy\nimport tf\nfrom tf2_msgs.msg import TFMessage\nimport warnings\n\nimport tf.transformations as tfs\n\n\ndef write_transformation_to_csv_file(bag_file, target_frame, source_frame,\n csv_file_name):\n print(\"Loading tfs into Transformer...\")\n tf_tree = tf.Transformer(True, rospy.Duration(3600.0))\n bag = rosbag.Bag(bag_file)\n\n for topic, msg, t in bag.read_messages(topics=['/tf']):\n for msg_tf in msg.transforms:\n tf_tree.setTransform(msg_tf)\n bag.close()\n\n print(\"Listening to tf transformation from \", source_frame, \" to \",\n target_frame)\n # Reopen bag\n bag = rosbag.Bag(bag_file)\n init = True\n tf_counter = 0\n tf_frequency_estimated = 0.\n tf_interval_estimated = 0.\n tf_previous_timestamp = 0.\n start_time_tf_message = rospy.Time()\n end_time_tf_message = rospy.Time()\n csv_file = open(csv_file_name, 'w')\n print(\"Looking up transforms and writing to csv file...\")\n for topic, msg, t in bag.read_messages():\n if topic == \"/tf\" and msg.transforms:\n for single_tf in msg.transforms:\n # TODO(ff): Fix this logic, as if the source frame is child frame, we\n # can't get this frame.\n if single_tf.child_frame_id == source_frame:\n # if single_tf.header.frame_id == source_frame:\n try:\n (translation,\n hamilton_quaternion) = tf_tree.lookupTransform(\n target_frame, source_frame, single_tf.header.stamp)\n # rot_mat = tf.transformations.quaternion_matrix(hamilton_quaternion)[:3, :3]\n # translation = np.matmul(rot_mat.T, translation)\n except (tf.LookupException, tf.ConnectivityException,\n tf.ExtrapolationException):\n # Only start counting if we already did at least one successful tf\n # lookup\n if tf_counter > 0:\n tf_counter += 1\n continue\n\n # Initialize start time to first successful tf message lookup.\n if init:\n start_time_tf_message = single_tf.header.stamp\n init = False\n\n ##############################################################################\n # We invert the tranformation to find the pose of the camera (static) with respect to the robot base\n ht = tfs.quaternion_matrix(hamilton_quaternion)\n ht[0:3,-1] = np.array(translation).T\n inverse = tfs.inverse_matrix(ht)\n hamilton_quaternion = tfs.quaternion_from_matrix(inverse)\n translation = inverse[0:3,-1]\n ################################################################################\n\n # Write to csv file.\n quaternion = np.array(hamilton_quaternion)\n csv_file.write(\n str(single_tf.header.stamp.to_sec()) + ', ' +\n str(translation[0]) + ', ' + str(translation[1]) + ', ' +\n str(translation[2]) + ', ' + str(quaternion[0]) + ', ' +\n str(quaternion[1]) + ', ' + str(quaternion[2]) + ', ' +\n str(quaternion[3]) + '\\n')\n\n # Update end time.\n end_time_tf_message = single_tf.header.stamp\n tf_counter += 1\n\n # Check if there was a drop in the tf frequency.\n if tf_counter > 3:\n tf_frequency_estimated = tf_counter / (\n end_time_tf_message - start_time_tf_message).to_sec()\n\n # Check if there has been a drop.\n tf_interval_estimated = 1. / tf_frequency_estimated\n tf_interval_measured = (single_tf.header.stamp.to_sec() -\n tf_previous_timestamp.to_sec())\n\n # Drop pose if the tf interval is zero.\n if tf_interval_measured < 1e-8:\n tf_previous_timestamp = single_tf.header.stamp\n continue\n\n # If the interval deviates from the frequency by more than x\n # percent, print a warning.\n tf_interval_deviation_percent = abs(\n tf_interval_estimated -\n tf_interval_measured) / tf_interval_estimated * 100.\n if (tf_interval_deviation_percent > 50.0):\n seconds_from_start_time = (\n single_tf.header.stamp.to_sec() -\n start_time_tf_message.to_sec())\n print(\"There might have been a drop in the tf after {:.3f}s.\".format(\n seconds_from_start_time))\n print(\"\\tThe interval deviated by {:.2f}%, interval: {:.6f}\".format(\n tf_interval_deviation_percent, tf_interval_measured))\n print(\"\\tCurrent frequency estimate: {:.2f}Hz\".format(\n tf_frequency_estimated))\n\n tf_previous_timestamp = single_tf.header.stamp\n\n # Output final estimated frequency.\n if tf_counter > 3:\n tf_frequency_estimated = tf_counter / (\n end_time_tf_message - start_time_tf_message).to_sec()\n print(\"Final estimate of tf topic frequency: \", \"{0:.2f}\".format(\n tf_frequency_estimated), \"Hz\")\n\n print(\"Exported \", tf_counter, \" tf poses.\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('--bag', required=True, help='Rosbag to parse.')\n parser.add_argument(\n '--tf_source_frame', required=True, help='Name of tf source frame.')\n parser.add_argument(\n '--tf_target_frame', required=True, help='Name of tf target frame.')\n parser.add_argument(\n '--csv_output_file', required=True, help='Path to output csv file')\n\n args = parser.parse_args()\n\n print(\"tf_to_csv.py: export tf to csv from bag: \", args.bag, \"...\")\n\n write_transformation_to_csv_file(args.bag, args.tf_target_frame,\n args.tf_source_frame,\n args.csv_output_file)\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jeffdshen/oneshotNN
|
[
"d50be01032336a17e07b80752bbdd7a8d716b0ab"
] |
[
"common.py"
] |
[
"from abc import abstractmethod\nfrom abc import ABCMeta\nimport prettytensor as pt\nimport tensorflow as tf\n\n\nclass Model(metaclass=ABCMeta):\n def __init__(self, inputs, labels):\n self.inputs = inputs\n self.labels = labels\n self.model = self._make(inputs, labels)\n self.softmax = self.model.softmax\n self.loss = self.model.loss\n self._phase = self._phases(self.model)\n\n def phase(self, p):\n if p in self._phase:\n return self._phase[p]\n\n if p == pt.Phase.test:\n self._phase[p] = self.model.softmax.evaluate_classifier(self.labels, phase=pt.Phase.test)\n elif p == pt.Phase.train:\n self._phase[p] = pt.apply_optimizer(self._optimizer(), losses=[self.model.loss])\n\n return self._phase[p]\n\n def _phases(self, model):\n return {\n pt.Phase.infer: model.softmax,\n }\n\n def _optimizer(self):\n return tf.train.GradientDescentOptimizer(0.01)\n\n @abstractmethod\n def _make(self, input, labels):\n return\n"
] |
[
[
"tensorflow.train.GradientDescentOptimizer"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
realfastvla/rfpipe
|
[
"47ae24972d8aace0d44c6be2bced8b4768e5efa2"
] |
[
"tests/test_search.py"
] |
[
"from __future__ import print_function, division, absolute_import, unicode_literals\nfrom builtins import bytes, dict, object, range, map, input, str\nfrom future.utils import itervalues, viewitems, iteritems, listvalues, listitems\nfrom io import open\n\nimport rfpipe, rfpipe.search\nimport pytest\nfrom astropy import time\nimport numpy as np\n\n\[email protected](scope=\"module\")\ndef st():\n inprefs = {'flaglist': [], 'npix_max': 128, 'uvres': 500, 'nthread': 1,\n 'fftmode': 'fftw', 'searchtype': 'imagek', 'sigma_image1': 6.}\n t0 = time.Time.now().mjd\n meta = rfpipe.metadata.mock_metadata(t0, t0+0.05/(24*3600), 10, 4, 32*4,\n 2, 5e3, datasource='sim', antconfig='D')\n return rfpipe.state.State(inmeta=meta, inprefs=inprefs)\n\n\[email protected](scope=\"module\")\ndef data(st):\n segment = 0\n return rfpipe.source.read_segment(st, segment)\n\n\ndef test_prepsearch(st, data):\n segment = 0\n data[:, :, 10:12] = 0j # test zeroed channels\n cc = rfpipe.pipeline.prep_and_search(st, segment, data)\n assert len(cc) == 0\n\n\ndef test_excess(st, data):\n segment = 0\n st.prefs.max_candfrac = 0.01\n data += 1.\n cc = rfpipe.pipeline.prep_and_search(st, segment, data)\n st.prefs.max_candfrac = 0.2\n assert len(cc) == 0\n\n\ndef test_nosearch(st, data):\n segment = 0\n st.prefs.searchtype = None\n cc = rfpipe.pipeline.prep_and_search(st, segment, data)\n st.prefs.searchtype = 'imagek'\n assert len(cc) == 0\n\n\ndef test_dm_singlemulti(st, data):\n dm = 100\n datap = rfpipe.source.data_prep(st, 0, data)\n delay = rfpipe.util.calc_delay(st.freq, st.freq.max(), dm,\n st.inttime)\n data1 = rfpipe.search.dedisperse(datap, delay, parallel=False)\n data2 = rfpipe.search.dedisperse(datap, delay, parallel=True)\n data3 = rfpipe.search.dedisperse(datap, delay, parallel=False)\n\n assert np.allclose(data1, data2)\n assert np.allclose(data3, data2)\n\n\ndef test_resample_singlemulti(st, data):\n dt = 2\n datap = rfpipe.source.data_prep(st, 0, data)\n data1 = rfpipe.search.resample(datap, dt, parallel=False)\n data2 = rfpipe.search.resample(datap, dt, parallel=True)\n data3 = rfpipe.search.resample(datap, dt, parallel=False)\n\n assert np.allclose(data1, data2)\n assert np.allclose(data3, data2)\n\n\ndef test_dmresample_single(st, data):\n dm = 100\n dt = 2\n datap = rfpipe.source.data_prep(st, 0, data)\n delay = rfpipe.util.calc_delay(st.freq, st.freq.max(), dm,\n st.inttime)\n\n data1 = rfpipe.search.dedisperse(datap, delay, parallel=False)\n data2 = rfpipe.search.resample(data1, dt, parallel=False)\n data3 = rfpipe.search.dedisperseresample(datap, delay, dt, parallel=False,\n resamplefirst=False)\n assert np.allclose(data3, data2)\n\n\ndef test_dmresample_multi1(st, data):\n dm = 100\n dt = 1\n datap = rfpipe.source.data_prep(st, 0, data)\n delay = rfpipe.util.calc_delay(st.freq, st.freq.max(), dm,\n st.inttime)\n\n data1 = rfpipe.search.dedisperse(datap, delay, parallel=True)\n data2 = rfpipe.search.resample(data1, dt, parallel=True)\n data3 = rfpipe.search.dedisperseresample(datap, delay, dt, parallel=True,\n resamplefirst=False)\n assert np.allclose(data3, data2)\n\n\ndef test_dmresample_multi2(st, data):\n dm = 100\n dt = 2\n datap = rfpipe.source.data_prep(st, 0, data)\n delay = rfpipe.util.calc_delay(st.freq, st.freq.max(), dm,\n st.inttime)\n\n data1 = rfpipe.search.dedisperse(datap, delay, parallel=True)\n data2 = rfpipe.search.resample(data1, dt, parallel=True)\n data3 = rfpipe.search.dedisperseresample(datap, delay, dt, parallel=True,\n resamplefirst=False)\n assert np.allclose(data3, data2)\n\n\ndef test_dmresample_singlemulti1(st, data):\n dm = 100\n dt = 1\n datap = rfpipe.source.data_prep(st, 0, data)\n delay = rfpipe.util.calc_delay(st.freq, st.freq.max(), dm,\n st.inttime)\n\n data1 = rfpipe.search.dedisperseresample(datap, delay, dt, parallel=False)\n data2 = rfpipe.search.dedisperseresample(datap, delay, dt, parallel=True)\n data3 = rfpipe.search.dedisperseresample(datap, delay, dt, parallel=False)\n\n assert np.allclose(data1, data2)\n assert np.allclose(data3, data2)\n\n\ndef test_dmresample_singlemulti2(st, data):\n dm = 100\n dt = 2\n datap = rfpipe.source.data_prep(st, 0, data)\n delay = rfpipe.util.calc_delay(st.freq, st.freq.max(), dm,\n st.inttime)\n\n data1 = rfpipe.search.dedisperseresample(datap, delay, dt, parallel=False)\n data2 = rfpipe.search.dedisperseresample(datap, delay, dt, parallel=True)\n data3 = rfpipe.search.dedisperseresample(datap, delay, dt, parallel=False)\n\n assert np.allclose(data1, data2)\n assert np.allclose(data3, data2)\n"
] |
[
[
"numpy.allclose"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
leddartech/pioneer.das.api
|
[
"35f2c541ea8d1768d5f4612ea8d29cb2ba8345b7",
"35f2c541ea8d1768d5f4612ea8d29cb2ba8345b7",
"35f2c541ea8d1768d5f4612ea8d29cb2ba8345b7"
] |
[
"pioneer/das/api/samples/annotations/box_3d.py",
"pioneer/das/api/interpolators.py",
"pioneer/das/api/samples/rpm.py"
] |
[
"from pioneer.common import platform, linalg, IoU3d\nfrom pioneer.common.logging_manager import LoggingManager\nfrom pioneer.common import platform as platform_utils\nfrom pioneer.das.api import categories\nfrom pioneer.das.api.samples.sample import Sample\n\nfrom transforms3d import euler\nimport numpy as np\n\n\nclass Box3d(Sample):\n\n def __init__(self, index, datasource, virtual_raw = None, virtual_ts = None):\n super(Box3d, self).__init__(index, datasource, virtual_raw, virtual_ts)\n\n def label_names(self):\n '''Converts the category numbers in their corresponding names (e.g. 0 -> 'pedestrian') and returns the list of names for all boxes in the sample'''\n label_source_name = categories.get_source(platform_utils.parse_datasource_name(self.datasource.label)[2])\n try:\n return [categories.CATEGORIES[label_source_name][str(category_number)]['name'] for category_number in self.raw['data']['classes']]\n except:\n LoggingManager.instance().warning(f\"Can not find the CATEGORIES and NAMES of {label_source_name}.\")\n\n def _mapto(self, tf=None):\n \"\"\"Maps the box3d to the new referential, given a 4x4 matrix transformation\"\"\"\n\n bbox = np.copy(self.raw['data'])\n if tf is None:\n return bbox\n \n for i in range(len(bbox)):\n tf_Localds_from_Box = np.eye(4)\n tf_Localds_from_Box[:3, :3] = euler.euler2mat(bbox['r'][i,0], bbox['r'][i,1], bbox['r'][i,2])\n tf_Localds_from_Box[:3, 3] = bbox['c'][i,:]\n tf_Referential_from_Box = tf @ tf_Localds_from_Box\n bbox['c'][i,:] = tf_Referential_from_Box[:3, 3]\n bbox['r'][i,:] = euler.mat2euler(tf_Referential_from_Box)\n\n return bbox\n \n def mapto(self, referential_or_ds:str=None, ignore_orientation:bool=False, reference_ts:int=-1, dtype=np.float64):\n \"\"\" Will map each box in another referential. \"\"\"\n\n referential = platform.referential_name(referential_or_ds)\n if self.datasource.sensor.name == referential:\n tf_Referential_from_Localds = None\n else:\n tf_Referential_from_Localds = self.compute_transform(referential_or_ds, ignore_orientation, reference_ts, dtype)\n\n return self._mapto(tf_Referential_from_Localds)\n\n def attributes(self):\n if 'attributes' in self.raw:\n return self.raw['attributes']\n LoggingManager.instance().warning(f\"There are no 'attributes' for that sample {self.datasource.label}.\")\n return None\n \n def confidences(self):\n if 'confidence' in self.raw:\n return self.raw['confidence']\n LoggingManager.instance().warning(f\"There are no 'confidences' for that sample {self.datasource.label}.\")\n return None\n\n def num_pts_in(self, pt_cloud, margin=0):\n \"\"\" Returns, for each box, the mask of those points from pt_cloud that are inside the box.\n Args:\n pt_cloud - (M,3)\n margin (optional) - positive float- increases the size of box\n\n Returns:\n mask - boolean (n_boxe,M)\n \"\"\"\n bbox = self.raw['data']\n nbpts = np.zeros((len(bbox), len(pt_cloud)), dtype=bool)\n for i in range(len(bbox)):\n tf_Localds_from_Box = np.eye(4)\n tf_Localds_from_Box[:3, :3] = euler.euler2mat(bbox['r'][i,0], bbox['r'][i,1], bbox['r'][i,2])\n tf_Localds_from_Box[:3, 3] = bbox['c'][i,:]\n aabb = np.vstack([-(bbox['d'][i,:]+margin) / 2.0,(bbox['d'][i,:]+margin) / 2.0])\n nbpts[i,:] = linalg.points_inside_box_mask(pt_cloud, aabb, linalg.tf_inv(tf_Localds_from_Box))\n return nbpts\n\n def set_angle_to_domain(self, domain=[0,2*np.pi]):\n \"\"\"Will set the angles to a given domain\"\"\"\n\n bbox = np.copy(self.raw['data'])\n for i in range(len(bbox)):\n bbox['r'][i,:] = [linalg.map_angle_to_domain(bbox['r'][i,j], domain=domain) for j in range(3)]\n\n return bbox\n \n def compute_iou(self, box, return_max=False, map2yaw=None):\n \"\"\"Compute the iou score between all the elements of self and of box.\n \n Return a matrix len(self), len(box) when row,col are indexed in the same order as self, box.\n\n If return_max=True: return only a single number for each element of self (the max value).\n\n Important note: By default the computation is performed in the sbg ref where only one angle (yaw) is not zero, unless\n map2yaw is provided (a callable) which brings all the boxes in a referential where only one rotation (yaw).\n\n \"\"\"\n if map2yaw is not None:\n box0 = map2yaw(self)\n box1 = map2yaw(box)\n else:\n try: #must find either sbg or ENU.\n referential = platform.referential_name('sbgekinox_bcc')\n tf_TargetRef_from_Local = np.copy(self.datasource.sensor.map_to(referential))\n tf_TargetRef_from_Local[:3, :3] = tf_TargetRef_from_Local[:3, :3] @ self.orientation\n\n except:\n LoggingManager.instance().warning('IoU computation, falling back to ENU system transformation.')\n tf_TargetRef_from_Local = np.eye(4)\n tf_TargetRef_from_Local[:3, :3] = np.array([[0, 0, 1],\n\t\t\t\t\t\t [-1, 0, 0],\n\t\t\t\t\t\t [0, -1, 0]],\n\t\t\t\t\t\t dtype=np.float).T\n box0 = self._mapto(tf=tf_TargetRef_from_Local)\n box1 = box._mapto(tf=tf_TargetRef_from_Local)\n \n Z0 = [box0['c'], box0['d'], 'z', box0['r'][:,2]]\n Z1 = [box1['c'], box1['d'], 'z', box1['r'][:,2]]\n matiou = IoU3d.matrixIoU(Z0=Z0, Z1=Z1)\n if return_max:\n return np.max(matiou, axis=1)\n else:\n return matiou",
"import numbers\nimport numpy as np\n\ndef from_float_index(float_index):\n i = int(np.floor(float_index))\n t = float_index - i\n return i, t\n\ndef _linear_interpolate_helper(t, from_val, to_val):\n return t * to_val + (1 - t) * from_val\n\ndef _angles_linear_interpolate_helper(t, from_val, to_val):\n if from_val-to_val>np.pi:\n return t * (to_val+2.0*np.pi) + (1 - t) * from_val\n elif from_val-to_val<-np.pi:\n return t * to_val + (1 - t) * (from_val+2.0*np.pi)\n else:\n return t * to_val + (1 - t) * from_val\n\n\ndef linear_ndarray_interpolator(datasource, float_index):\n i, t = from_float_index(float_index)\n if i+1 != len(datasource):\n raw_from, raw_to = datasource[i].raw, datasource[i+1].raw\n else:\n raw_from, raw_to = datasource[i].raw, datasource[i].raw\n if raw_from.dtype.names is None:\n return _linear_interpolate_helper(t, raw_from, raw_to)\n \n result = np.zeros_like(raw_from)\n for name in raw_from.dtype.names:\n result[name] = _linear_interpolate_helper(t, raw_from[name], raw_to[name])\n return result\n\n\ndef euler_imu_linear_ndarray_interpolator(datasource, float_index):\n i, t = from_float_index(float_index)\n if i+1 != len(datasource):\n raw_from, raw_to = datasource[i].raw, datasource[i+1].raw\n else:\n raw_from, raw_to = datasource[i].raw, datasource[i].raw\n\n if raw_from.dtype.names is None:\n return _linear_interpolate_helper(t, raw_from, raw_to)\n \n result = np.zeros_like(raw_from)\n for name in raw_from.dtype.names:\n if name in ['roll', 'pitch', 'yaw']:\n result[name] = _angles_linear_interpolate_helper(t, raw_from[name], raw_to[name])\n else:\n result[name] = _linear_interpolate_helper(t, raw_from[name], raw_to[name])\n return result\n\n\ndef linear_dict_of_float_interpolator(datasource, float_index):\n i, t = from_float_index(float_index)\n raw_from, raw_to = datasource[i].raw, datasource[i+1].raw\n interp_dict = raw_from\n\n for k,value_from in raw_from.items():\n value_to = raw_to[k]\n if isinstance(value_from, list):\n interp_dict[k] = _linear_interpolate_helper(t, np.array(value_from), np.array(value_to)).tolist()\n elif isinstance(value_from, numbers.Real):\n interp_dict[k] = type(value_from)(_linear_interpolate_helper(t, value_from, value_to))\n return interp_dict\n\ndef floor_interpolator(datasource, float_index):\n i, _ = from_float_index(float_index)\n return datasource[i].raw\n\ndef ceil_interpolator(datasource, float_index):\n i, _ = from_float_index(float_index)\n return datasource[i+1].raw\n\ndef nearest_interpolator(datasource, float_index):\n return datasource[round(float_index)].raw\n",
"from pioneer.das.api.samples.sample import Sample\n\nimport numpy as np\n\nclass RPM(Sample):\n \"\"\"Rotations per minute measured by wheel encoders (left and right channels)\"\"\"\n\n def __init__(self, index, datasource, virtual_raw = None, virtual_ts = None):\n super(RPM, self).__init__(index, datasource, virtual_raw, virtual_ts)\n\n def meters_per_second(self):\n rpm = self.raw['data']\n rps = np.array([rpm['left']/60, rpm['right']/60])*2.0\n try:\n return rps*self.datasource.sensor.yml['wheel_diameter']*np.pi\n except:\n raise ValueError(\"wheel_diameter has to be in the encoder's yml in order to convert rpm data\") \n \n"
] |
[
[
"numpy.eye",
"numpy.max",
"numpy.copy",
"numpy.array",
"numpy.vstack"
],
[
"numpy.array",
"numpy.zeros_like",
"numpy.floor"
],
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
shaolei-wang/mindspore
|
[
"2d50a43be9d17269f6adb41e51b8f7a540ebc9f1",
"2d50a43be9d17269f6adb41e51b8f7a540ebc9f1",
"2d50a43be9d17269f6adb41e51b8f7a540ebc9f1"
] |
[
"tests/ut/python/dataset/test_random_horizontal_flip_bbox.py",
"tests/ut/python/ir/test_tensor.py",
"model_zoo/resnet101/train.py"
] |
[
"# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"\nTesting the random horizontal flip with bounding boxes op in DE\n\"\"\"\nfrom enum import Enum\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport numpy as np\nimport mindspore.log as logger\nimport mindspore.dataset as ds\nimport mindspore.dataset.transforms.vision.c_transforms as c_vision\n\nGENERATE_GOLDEN = False\n\nDATA_DIR = \"../data/dataset/testVOC2012_2\"\n\n\nclass BoxType(Enum):\n \"\"\"\n Defines box types for test cases\n \"\"\"\n WidthOverflow = 1\n HeightOverflow = 2\n NegativeXY = 3\n OnEdge = 4\n WrongShape = 5\n\ndef add_bad_annotation(img, bboxes, box_type):\n \"\"\"\n Used to generate erroneous bounding box examples on given img.\n :param img: image where the bounding boxes are.\n :param bboxes: in [x_min, y_min, w, h, label, truncate, difficult] format\n :param box_type: type of bad box\n :return: bboxes with bad examples added\n \"\"\"\n height = img.shape[0]\n width = img.shape[1]\n if box_type == BoxType.WidthOverflow:\n # use box that overflows on width\n return img, np.array([[0, 0, width + 1, height, 0, 0, 0]]).astype(np.uint32)\n\n if box_type == BoxType.HeightOverflow:\n # use box that overflows on height\n return img, np.array([[0, 0, width, height + 1, 0, 0, 0]]).astype(np.uint32)\n\n if box_type == BoxType.NegativeXY:\n # use box with negative xy\n return img, np.array([[-10, -10, width, height, 0, 0, 0]]).astype(np.uint32)\n\n if box_type == BoxType.OnEdge:\n # use box that covers the whole image\n return img, np.array([[0, 0, width, height, 0, 0, 0]]).astype(np.uint32)\n\n if box_type == BoxType.WrongShape:\n # use box that covers the whole image\n return img, np.array([[0, 0, width - 1]]).astype(np.uint32)\n return img, bboxes\n\n\ndef h_flip(image):\n \"\"\"\n Apply the random_horizontal\n \"\"\"\n # that's why we flip here too\n image = image[:, ::-1, :]\n return image\n\n\ndef check_bad_box(data, box_type, expected_error):\n \"\"\"\n :param data: de object detection pipeline\n :param box_type: type of bad box\n :param expected_error: error expected to get due to bad box\n :return: None\n \"\"\"\n # DEFINE TEST OP HERE -- (PROB 1 IN CASE OF RANDOM)\n try:\n test_op = c_vision.RandomHorizontalFlipWithBBox(1)\n data = data.map(input_columns=[\"annotation\"],\n output_columns=[\"annotation\"],\n operations=fix_annotate)\n # map to use width overflow\n data = data.map(input_columns=[\"image\", \"annotation\"],\n output_columns=[\"image\", \"annotation\"],\n columns_order=[\"image\", \"annotation\"],\n operations=lambda img, bboxes: add_bad_annotation(img, bboxes, box_type))\n # map to apply ops\n data = data.map(input_columns=[\"image\", \"annotation\"],\n output_columns=[\"image\", \"annotation\"],\n columns_order=[\"image\", \"annotation\"],\n operations=[test_op]) # Add column for \"annotation\"\n for _, _ in enumerate(data.create_dict_iterator()):\n break\n except RuntimeError as error:\n logger.info(\"Got an exception in DE: {}\".format(str(error)))\n assert expected_error in str(error)\n\n\ndef fix_annotate(bboxes):\n \"\"\"\n Fix annotations to format followed by mindspore.\n :param bboxes: in [label, x_min, y_min, w, h, truncate, difficult] format\n :return: annotation in [x_min, y_min, w, h, label, truncate, difficult] format\n \"\"\"\n for bbox in bboxes:\n tmp = bbox[0]\n bbox[0] = bbox[1]\n bbox[1] = bbox[2]\n bbox[2] = bbox[3]\n bbox[3] = bbox[4]\n bbox[4] = tmp\n return bboxes\n\n\ndef add_bounding_boxes(axis, bboxes):\n \"\"\"\n :param axis: axis to modify\n :param bboxes: bounding boxes to draw on the axis\n :return: None\n \"\"\"\n for bbox in bboxes:\n rect = patches.Rectangle((bbox[0], bbox[1]),\n bbox[2], bbox[3],\n linewidth=1, edgecolor='r', facecolor='none')\n # Add the patch to the Axes\n axis.add_patch(rect)\n\n\ndef visualize(unaugmented_data, augment_data):\n \"\"\"\n :param unaugmented_data: original data\n :param augment_data: data after augmentations\n :return: None\n \"\"\"\n for idx, (un_aug_item, aug_item) in \\\n enumerate(zip(unaugmented_data.create_dict_iterator(),\n augment_data.create_dict_iterator())):\n axis = plt.subplot(141)\n plt.imshow(un_aug_item[\"image\"])\n add_bounding_boxes(axis, un_aug_item[\"annotation\"]) # add Orig BBoxes\n plt.title(\"Original\" + str(idx + 1))\n logger.info(\"Original \", str(idx + 1), \" :\", un_aug_item[\"annotation\"])\n\n axis = plt.subplot(142)\n plt.imshow(aug_item[\"image\"])\n add_bounding_boxes(axis, aug_item[\"annotation\"]) # add AugBBoxes\n plt.title(\"Augmented\" + str(idx + 1))\n logger.info(\"Augmented \", str(idx + 1), \" \", aug_item[\"annotation\"], \"\\n\")\n plt.show()\n\n\ndef test_random_horizontal_bbox_op(plot=False):\n \"\"\"\n Test RandomHorizontalFlipWithBBox op\n Prints images side by side with and without Aug applied + bboxes to compare and test\n \"\"\"\n logger.info(\"test_random_horizontal_bbox_c\")\n\n data_voc1 = ds.VOCDataset(DATA_DIR, task=\"Detection\", mode=\"train\", decode=True, shuffle=False)\n data_voc2 = ds.VOCDataset(DATA_DIR, task=\"Detection\", mode=\"train\", decode=True, shuffle=False)\n\n # DEFINE TEST OP HERE -- (PROB 1 IN CASE OF RANDOM)\n test_op = c_vision.RandomHorizontalFlipWithBBox(1)\n\n # maps to fix annotations to minddata standard\n data_voc1 = data_voc1.map(input_columns=[\"annotation\"],\n output_columns=[\"annotation\"],\n operations=fix_annotate)\n data_voc2 = data_voc2.map(input_columns=[\"annotation\"],\n output_columns=[\"annotation\"],\n operations=fix_annotate)\n # map to apply ops\n data_voc2 = data_voc2.map(input_columns=[\"image\", \"annotation\"],\n output_columns=[\"image\", \"annotation\"],\n columns_order=[\"image\", \"annotation\"],\n operations=[test_op]) # Add column for \"annotation\"\n if plot:\n visualize(data_voc1, data_voc2)\n\n\ndef test_random_horizontal_bbox_valid_prob_c(plot=False):\n \"\"\"\n Test RandomHorizontalFlipWithBBox op\n Prints images side by side with and without Aug applied + bboxes to compare and test\n \"\"\"\n logger.info(\"test_random_horizontal_bbox_valid_prob_c\")\n\n data_voc1 = ds.VOCDataset(DATA_DIR, task=\"Detection\", mode=\"train\", decode=True, shuffle=False)\n data_voc2 = ds.VOCDataset(DATA_DIR, task=\"Detection\", mode=\"train\", decode=True, shuffle=False)\n # DEFINE TEST OP HERE -- (PROB 1 IN CASE OF RANDOM)\n test_op = c_vision.RandomHorizontalFlipWithBBox(0.3)\n\n # maps to fix annotations to minddata standard\n data_voc1 = data_voc1.map(input_columns=[\"annotation\"],\n output_columns=[\"annotation\"],\n operations=fix_annotate)\n data_voc2 = data_voc2.map(input_columns=[\"annotation\"],\n output_columns=[\"annotation\"],\n operations=fix_annotate)\n # map to apply ops\n data_voc2 = data_voc2.map(input_columns=[\"image\", \"annotation\"],\n output_columns=[\"image\", \"annotation\"],\n columns_order=[\"image\", \"annotation\"],\n operations=[test_op]) # Add column for \"annotation\"\n if plot:\n visualize(data_voc1, data_voc2)\n\n\ndef test_random_horizontal_bbox_invalid_prob_c():\n \"\"\"\n Test RandomHorizontalFlipWithBBox op with invalid input probability\n \"\"\"\n logger.info(\"test_random_horizontal_bbox_invalid_prob_c\")\n\n data_voc2 = ds.VOCDataset(DATA_DIR, task=\"Detection\", mode=\"train\", decode=True, shuffle=False)\n\n try:\n # Note: Valid range of prob should be [0.0, 1.0]\n test_op = c_vision.RandomHorizontalFlipWithBBox(1.5)\n data_voc2 = data_voc2.map(input_columns=[\"annotation\"],\n output_columns=[\"annotation\"],\n operations=fix_annotate)\n # map to apply ops\n data_voc2 = data_voc2.map(input_columns=[\"image\", \"annotation\"],\n output_columns=[\"image\", \"annotation\"],\n columns_order=[\"image\", \"annotation\"],\n operations=[test_op]) # Add column for \"annotation\"\n except ValueError as error:\n logger.info(\"Got an exception in DE: {}\".format(str(error)))\n assert \"Input is not\" in str(error)\n\n\ndef test_random_horizontal_bbox_invalid_bounds_c():\n \"\"\"\n Test RandomHorizontalFlipWithBBox op with invalid bounding boxes\n \"\"\"\n logger.info(\"test_random_horizontal_bbox_invalid_bounds_c\")\n\n data_voc2 = ds.VOCDataset(DATA_DIR, task=\"Detection\", mode=\"train\", decode=True, shuffle=False)\n check_bad_box(data_voc2, BoxType.WidthOverflow, \"bounding boxes is out of bounds of the image\")\n data_voc2 = ds.VOCDataset(DATA_DIR, task=\"Detection\", mode=\"train\", decode=True, shuffle=False)\n check_bad_box(data_voc2, BoxType.HeightOverflow, \"bounding boxes is out of bounds of the image\")\n data_voc2 = ds.VOCDataset(DATA_DIR, task=\"Detection\", mode=\"train\", decode=True, shuffle=False)\n check_bad_box(data_voc2, BoxType.NegativeXY, \"min_x\")\n data_voc2 = ds.VOCDataset(DATA_DIR, task=\"Detection\", mode=\"train\", decode=True, shuffle=False)\n check_bad_box(data_voc2, BoxType.WrongShape, \"4 features\")\n\nif __name__ == \"__main__\":\n # set to false to not show plots\n test_random_horizontal_bbox_op(False)\n test_random_horizontal_bbox_valid_prob_c(False)\n test_random_horizontal_bbox_invalid_prob_c()\n test_random_horizontal_bbox_invalid_bounds_c()\n",
"# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"\n@File : test_tensor.py\n@Author:\n@Date : 2019-03-14\n@Desc : test mindspore tensor's operation\n\"\"\"\nimport numpy as np\nimport pytest\n\nimport mindspore as ms\nimport mindspore.common.api as me\nimport mindspore.nn as nn\nfrom mindspore import Tensor\nfrom mindspore.common.initializer import initializer\nfrom mindspore.common.parameter import Parameter\nfrom ..ut_filter import non_graph_engine\n\nndarr = np.ones((2, 3))\n\n\ndef test_tensor_flatten():\n with pytest.raises(AttributeError):\n lst = [1, 2, 3, 4,]\n tensor_list = ms.Tensor(lst, ms.float32)\n tensor_list = tensor_list.Flatten()\n print(tensor_list)\n\n\ndef test_tensor_list():\n lst = [[1.0, 2.0, 1.0], [1.0, 10.0, 9.0]]\n tensor_list = ms.Tensor(lst, ms.float32)\n print(tensor_list)\n\n\ndef test_tensor():\n \"\"\"test_tensor\"\"\"\n t1 = ms.Tensor(ndarr)\n assert isinstance(t1, ms.Tensor)\n assert t1.dtype == ms.float64\n\n t2 = ms.Tensor(np.zeros([1, 2, 3]), ms.float32)\n assert isinstance(t2, ms.Tensor)\n assert t2.shape == (1, 2, 3)\n assert t2.dtype == ms.float32\n\n t3 = ms.Tensor(0.1)\n assert isinstance(t3, ms.Tensor)\n assert t3.dtype == ms.float64\n\n t4 = ms.Tensor(1)\n assert isinstance(t4, ms.Tensor)\n assert t4.dtype == ms.int64\n\n\ndef test_tensor_type_float16():\n t_float16 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float16))\n assert isinstance(t_float16, ms.Tensor)\n assert t_float16.shape == (2, 3)\n assert t_float16.dtype == ms.float16\n\n\ndef test_tensor_type_float32():\n t_float32 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32))\n assert isinstance(t_float32, ms.Tensor)\n assert t_float32.shape == (2, 3)\n assert t_float32.dtype == ms.float32\n\n\ndef test_tensor_type_float32_user_define():\n t = ms.Tensor(np.zeros([1, 2, 3]), ms.float32)\n assert isinstance(t, ms.Tensor)\n assert t.shape == (1, 2, 3)\n assert t.dtype == ms.float32\n\n\ndef test_tensor_type_float64():\n t = ms.Tensor([[1.0, 2, 3], [4, 5, 6]])\n assert isinstance(t, ms.Tensor)\n assert t.shape == (2, 3)\n assert t.dtype == ms.float64\n\n t_zero = ms.Tensor(np.zeros([1, 2, 3]))\n assert isinstance(t_zero, ms.Tensor)\n assert t_zero.shape == (1, 2, 3)\n assert t_zero.dtype == ms.float64\n\n\ndef test_tensor_type_float64_user_define():\n t = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=float))\n assert isinstance(t, ms.Tensor)\n assert t.shape == (2, 3)\n assert t.dtype == ms.float64\n\n t_float64 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]]), ms.float64)\n assert isinstance(t_float64, ms.Tensor)\n assert t_float64.shape == (2, 3)\n assert t_float64.dtype == ms.float64\n\n\ndef test_tensor_type_bool():\n # init a tensor with bool type\n ts_bool_array = ms.Tensor(np.zeros([2, 3], np.bool), ms.bool_)\n assert isinstance(ts_bool_array, ms.Tensor)\n assert ts_bool_array.dtype == ms.bool_\n\n t_bool = ms.Tensor(True)\n assert isinstance(t_bool, ms.Tensor)\n assert t_bool.dtype == ms.bool_\n\n t_bool_array = ms.Tensor(np.array([[True, False, True], [False, False, False]]))\n assert isinstance(t_bool_array, ms.Tensor)\n assert t_bool_array.shape == (2, 3)\n assert t_bool_array.dtype == ms.bool_\n\n\ndef test_tensor_type_int8():\n t_int8_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int8))\n assert isinstance(t_int8_array, ms.Tensor)\n assert t_int8_array.shape == (2, 3)\n assert t_int8_array.dtype == ms.int8\n\n\ndef test_tensor_type_int16():\n t_int16_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16))\n assert isinstance(t_int16_array, ms.Tensor)\n assert t_int16_array.shape == (2, 3)\n assert t_int16_array.dtype == ms.int16\n\n\ndef test_tensor_type_int32():\n t_int = ms.Tensor([[1, 2, 3], [4, 5, 6]])\n assert isinstance(t_int, ms.Tensor)\n assert t_int.shape == (2, 3)\n assert t_int.dtype == ms.int64\n\n t_int_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32))\n assert isinstance(t_int_array, ms.Tensor)\n assert t_int_array.shape == (2, 3)\n assert t_int_array.dtype == ms.int32\n\n\ndef test_tensor_type_int64():\n t_int64 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int64))\n assert isinstance(t_int64, ms.Tensor)\n assert t_int64.shape == (2, 3)\n assert t_int64.dtype == ms.int64\n\n\ndef test_tensor_type_uint8():\n t_uint8_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8))\n assert isinstance(t_uint8_array, ms.Tensor)\n assert t_uint8_array.shape == (2, 3)\n assert t_uint8_array.dtype == ms.uint8\n\n\ndef test_tensor_type_uint16():\n t_uint16_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint16))\n assert isinstance(t_uint16_array, ms.Tensor)\n assert t_uint16_array.shape == (2, 3)\n assert t_uint16_array.dtype == ms.uint16\n\n\ndef test_tensor_type_uint32():\n t_uint32_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint32))\n assert isinstance(t_uint32_array, ms.Tensor)\n assert t_uint32_array.shape == (2, 3)\n assert t_uint32_array.dtype == ms.uint32\n\n\ndef test_tensor_type_uint64():\n t_uint64 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint64))\n assert isinstance(t_uint64, ms.Tensor)\n assert t_uint64.shape == (2, 3)\n assert t_uint64.dtype == ms.uint64\n\n\ndef test_set_type():\n t = ms.Tensor(ndarr)\n t.set_dtype(ms.float32)\n assert t.dtype == ms.float32\n\n\n@non_graph_engine\ndef test_add():\n x = ms.Tensor(ndarr)\n y = ms.Tensor(ndarr)\n z = x + y\n assert isinstance(z, ms.Tensor)\n\n\n@non_graph_engine\ndef test_sub():\n x = ms.Tensor(ndarr)\n y = ms.Tensor(ndarr)\n z = x - y\n assert isinstance(z, ms.Tensor)\n\n\n@non_graph_engine\ndef test_div():\n x = ms.Tensor(np.array([[2, 6, 10], [12, 4, 8]]).astype(np.float32))\n y = ms.Tensor(np.array([[2, 2, 5], [6, 1, 2]]).astype(np.float32))\n z = x / y\n z2 = x / 2\n assert isinstance(z, ms.Tensor)\n assert isinstance(z2, ms.Tensor)\n\n\n@non_graph_engine\ndef test_parameter():\n x = Parameter(initializer(1, [1], ms.float32), name=\"beta1_power\")\n x.init_data()\n z = x / 2\n print(z)\n\n\nclass Net(nn.Cell):\n \"\"\"Net definition\"\"\"\n\n def __init__(self, dim):\n super(Net, self).__init__()\n self.dim = dim\n\n def construct(self, input_x):\n return input_x\n\n\n@non_graph_engine\ndef test_return_tensor():\n \"\"\"test_return_tensor\"\"\"\n net = Net(0)\n input_data = ms.Tensor(np.array([[1.2, 2.1], [2.2, 3.2]]).astype('float32'))\n input_data.set_dtype(ms.float32)\n exe = me._executor\n exe.compile(net, input_data)\n tensor_ = exe(net, input_data)\n\n # get shape\n shape_ = tensor_.shape\n print(\"shape = \", shape_)\n\n # get type\n type_ = tensor_.dtype\n print(\"type = \", type_)\n\n # get value\n value_ = tensor_.asnumpy()\n print(\"numpy value = \", value_)\n\n\ndef test_tensor_contiguous():\n \"\"\"test_tensor_contiguous\"\"\"\n input_c = np.arange(6).reshape(2, 3)\n input_f = input_c.T\n np.ascontiguousarray(input_c, dtype=np.float32)\n assert True, input_c.flags['C_CONTIGUOUS']\n\n print(\"input_f flags = \", input_f.flags)\n assert True, input_f.flags['F_CONTIGUOUS']\n\n tensor_f_float32 = ms.Tensor(input_f)\n rt_f = tensor_f_float32.asnumpy()\n assert True, rt_f.flags['C_CONTIGUOUS']\n print(\"rt_f flags = \", rt_f.flags)\n\n\ndef test_tensor_contiguous2():\n input_data = np.random.randn(32, 112, 112, 3).astype(np.float32)\n input_me = input_data.transpose(0, 3, 1, 2)\n print(\"input_me flags = \", input_me.flags)\n tensor_f_float32 = ms.Tensor(input_me)\n out_f = tensor_f_float32.asnumpy()\n print(\"out_f flags = \", out_f.flags)\n\n\ndef test_tensor_input_string():\n with pytest.raises(TypeError):\n input_data = 'ccc'\n ms.Tensor(input_data)\n\n\ndef test_tensor_input_tuple_string():\n with pytest.raises(TypeError):\n input_data = (2, 3, '4', 5)\n ms.Tensor(input_data)\n\n\ndef test_tensor_input_list_string():\n with pytest.raises(TypeError):\n input_data = [[2, 3, '4', 5], [1, 2, 3, 4]]\n ms.Tensor(input_data)\n\n\ndef test_tensor_input_none():\n with pytest.raises(TypeError):\n input_data = None\n ms.Tensor(input_data, np.int64)\n\n\n# pylint: disable=no-value-for-parameter\ndef test_tensor_input_empty():\n with pytest.raises(TypeError):\n ms.Tensor()\n\n\ndef test_tensor_input_ndarray_str():\n with pytest.raises(TypeError):\n inp = np.array([\"88\", 2, 4])\n ms.Tensor(inp)\n\n\ndef test_tensor_input_ndarray_bool():\n inp = np.array([True, 2, 4])\n ms.Tensor(inp)\n\n inp = np.array([False, 2, 4])\n ms.Tensor(inp)\n\n\ndef test_tensor_input_ndarray_complex():\n with pytest.raises(TypeError):\n inp = np.array([20j, 2, 4])\n ms.Tensor(inp)\n\n\ndef test_tensor_input_ndarray_none():\n with pytest.raises(TypeError):\n inp = np.array([None, 2, 4])\n ms.Tensor(inp)\n\n\ndef test_tensor_input_ndarray_dict():\n with pytest.raises(TypeError):\n inp = {'a': 6, 'b': 7}\n ms.Tensor(inp)\n\n\ndef test_tensor_input_np_nan():\n with pytest.raises(TypeError):\n input_data = (1, 2, 3, np.nan)\n ms.Tensor(input_data, np.int64)\n\n\ndef test_tensor_input_tuple_inf():\n with pytest.raises(TypeError):\n input_data = (1, 2, 3, float(\"inf\"))\n ms.Tensor(input_data, np.int64)\n\n\ndef test_tensor_input_dict():\n with pytest.raises(TypeError):\n input_data = {'a': 6, 'b': 7}\n ms.Tensor(input_data, np.int64)\n\n\ndef test_tensor_input_complex():\n with pytest.raises(TypeError):\n input_data = (1, 2j, 3)\n ms.Tensor(input_data, np.int64)\n\n\ndef test_tensor_dtype_np_float():\n with pytest.raises(TypeError):\n input_data = np.random.randn(32, 112, 112, 3).astype(np.float)\n ms.Tensor(input_data, np.float)\n\n\ndef test_tensor_dtype_np_float16():\n with pytest.raises(TypeError):\n input_data = np.random.randn(32, 112, 112, 3).astype(np.float16)\n ms.Tensor(input_data, np.float16)\n\n\ndef test_tensor_dtype_np_float32():\n with pytest.raises(TypeError):\n input_data = np.random.randn(32, 112, 112, 3).astype(np.float32)\n ms.Tensor(input_data, np.float32)\n\n\ndef test_tensor_dtype_np_float64():\n with pytest.raises(TypeError):\n input_data = np.random.randn(32, 112, 112, 3).astype(np.float64)\n ms.Tensor(input_data, np.float64)\n\n\ndef test_tensor_dtype_np_int():\n with pytest.raises(TypeError):\n input_data = np.random.randn(32, 112, 112, 3).astype(np.int)\n ms.Tensor(input_data, np.int)\n\n\ndef test_tensor_dtype_np_int8():\n with pytest.raises(TypeError):\n input_data = np.random.randn(32, 112, 112, 3).astype(np.int8)\n ms.Tensor(input_data, np.int8)\n\n\ndef test_tensor_dtype_np_int16():\n with pytest.raises(TypeError):\n input_data = np.random.randn(32, 112, 112, 3).astype(np.int16)\n ms.Tensor(input_data, np.int16)\n\n\ndef test_tensor_dtype_np_int32():\n with pytest.raises(TypeError):\n input_data = np.random.randn(32, 112, 112, 3).astype(np.int32)\n ms.Tensor(input_data, np.int32)\n\n\ndef test_tensor_dtype_np_int64():\n with pytest.raises(TypeError):\n input_data = np.random.randn(32, 112, 112, 3).astype(np.int64)\n ms.Tensor(input_data, np.int64)\n\n\ndef test_tensor_dtype_fp32_to_bool():\n with pytest.raises(RuntimeError):\n input_ = np.random.randn(2, 3, 4, 5).astype(np.float32)\n input_ = ms.Tensor(input_)\n _ = ms.Tensor(input_, dtype=ms.bool_)\n\n\ndef test_tensor_operation():\n x = Tensor(np.ones((3, 3)) * 4)\n res = x + 1\n assert np.all(res.asnumpy() == np.ones((3, 3)) * 5)\n res = 1 + x\n assert np.all(res.asnumpy() == np.ones((3, 3)) * 5)\n res = x - 2\n assert np.all(res.asnumpy() == np.ones((3, 3)) * 2)\n res = 6 - x\n assert np.all(res.asnumpy() == np.ones((3, 3)) * 2)\n res = x * 3\n assert np.all(res.asnumpy() == np.ones((3, 3)) * 12)\n res = 3 * x\n assert np.all(res.asnumpy() == np.ones((3, 3)) * 12)\n res = x / 2\n assert np.all(res.asnumpy() == np.ones((3, 3)) * 2)\n res = 8 / x\n assert np.all(res.asnumpy() == np.ones((3, 3)) * 2)\n with pytest.raises(ValueError):\n res = x * (2, 3)\n",
"# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"train_imagenet.\"\"\"\nimport os\nimport argparse\nimport random\nimport numpy as np\nfrom mindspore import context\nfrom mindspore import Tensor\nfrom mindspore.parallel._auto_parallel_context import auto_parallel_context\nfrom mindspore.nn.optim.momentum import Momentum\nfrom mindspore.train.model import Model, ParallelMode\nfrom mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor\nfrom mindspore.train.loss_scale_manager import FixedLossScaleManager\nfrom mindspore.train.serialization import load_checkpoint, load_param_into_net\nimport mindspore.dataset.engine as de\nfrom mindspore.communication.management import init\nimport mindspore.nn as nn\nimport mindspore.common.initializer as weight_init\nfrom src.resnet101 import resnet101\nfrom src.dataset import create_dataset\nfrom src.lr_generator import warmup_cosine_annealing_lr\nfrom src.config import config\nfrom src.crossentropy import CrossEntropy\n\nrandom.seed(1)\nnp.random.seed(1)\nde.config.set_seed(1)\n\nparser = argparse.ArgumentParser(description='Image classification')\nparser.add_argument('--run_distribute', type=bool, default=False, help='Run distribute')\nparser.add_argument('--device_num', type=int, default=1, help='Device num.')\nparser.add_argument('--do_train', type=bool, default=True, help='Do train or not.')\nparser.add_argument('--do_eval', type=bool, default=False, help='Do eval or not.')\nparser.add_argument('--dataset_path', type=str, default=None, help='Dataset path')\nparser.add_argument('--pre_trained', type=str, default=None, help='Pretrained checkpoint path')\nargs_opt = parser.parse_args()\n\ndevice_id = int(os.getenv('DEVICE_ID'))\n\ncontext.set_context(mode=context.GRAPH_MODE, device_target=\"Ascend\", save_graphs=False, device_id=device_id,\n enable_auto_mixed_precision=True)\n\nif __name__ == '__main__':\n if not args_opt.do_eval and args_opt.run_distribute:\n context.set_auto_parallel_context(device_num=args_opt.device_num, parallel_mode=ParallelMode.DATA_PARALLEL,\n mirror_mean=True, parameter_broadcast=True)\n auto_parallel_context().set_all_reduce_fusion_split_indices([180, 313])\n init()\n\n epoch_size = config.epoch_size\n net = resnet101(class_num=config.class_num)\n # weight init\n for _, cell in net.cells_and_names():\n if isinstance(cell, nn.Conv2d):\n cell.weight.default_input = weight_init.initializer(weight_init.XavierUniform(),\n cell.weight.default_input.shape,\n cell.weight.default_input.dtype).to_tensor()\n if isinstance(cell, nn.Dense):\n cell.weight.default_input = weight_init.initializer(weight_init.TruncatedNormal(),\n cell.weight.default_input.shape,\n cell.weight.default_input.dtype).to_tensor()\n if not config.label_smooth:\n config.label_smooth_factor = 0.0\n loss = CrossEntropy(smooth_factor=config.label_smooth_factor, num_classes=config.class_num)\n if args_opt.do_train:\n dataset = create_dataset(dataset_path=args_opt.dataset_path, do_train=True,\n repeat_num=epoch_size, batch_size=config.batch_size)\n step_size = dataset.get_dataset_size()\n loss_scale = FixedLossScaleManager(config.loss_scale, drop_overflow_update=False)\n if args_opt.pre_trained:\n param_dict = load_checkpoint(args_opt.pre_trained)\n load_param_into_net(net, param_dict)\n\n # learning rate strategy with cosine\n lr = Tensor(warmup_cosine_annealing_lr(config.lr, step_size, config.warmup_epochs, 120,\n config.pretrain_epoch_size*step_size))\n opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), lr, config.momentum,\n config.weight_decay, config.loss_scale)\n model = Model(net, loss_fn=loss, optimizer=opt, amp_level='O2', keep_batchnorm_fp32=False,\n loss_scale_manager=loss_scale, metrics={'acc'})\n time_cb = TimeMonitor(data_size=step_size)\n loss_cb = LossMonitor()\n cb = [time_cb, loss_cb]\n if config.save_checkpoint:\n config_ck = CheckpointConfig(save_checkpoint_steps=config.save_checkpoint_epochs*step_size,\n keep_checkpoint_max=config.keep_checkpoint_max)\n ckpt_cb = ModelCheckpoint(prefix=\"resnet\", directory=config.save_checkpoint_path, config=config_ck)\n cb += [ckpt_cb]\n model.train(epoch_size, dataset, callbacks=cb)\n"
] |
[
[
"matplotlib.pyplot.imshow",
"matplotlib.patches.Rectangle",
"matplotlib.pyplot.subplot",
"numpy.array",
"matplotlib.pyplot.show"
],
[
"numpy.ascontiguousarray",
"numpy.arange",
"numpy.ones",
"numpy.random.randn",
"numpy.array",
"numpy.zeros"
],
[
"numpy.random.seed"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tody411/PaletteSelection
|
[
"8e8f4192557dad7075f1539b0cfe816541bf9874"
] |
[
"palette/core/palette_selection.py"
] |
[
"# -*- coding: utf-8 -*-\n## @package palette.core.palette_selection\n#\n# Implementation of automatic color palette selection.\n# @author tody\n# @date 2015/08/20\n\nimport os\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom palette.np.norm import normVectors\n\n\n## Implementation of automatic palette selection.\nclass PaletteSelection:\n ## Constructor\n # @param color_coordinates input color coordinates.\n # @param color_densities color densities (normalized frequencies).\n # @param rgb_colors rgb colors.\n # @param num_colors target number of palette selection.\n # @param sigma weight decay term for updating weight.\n def __init__(self, color_coordinates, color_densities, rgb_colors,\n num_colors=7, sigma=70.0):\n self._color_coordinates = color_coordinates\n self._color_densities = color_densities\n self._rgb_colors = rgb_colors\n self._num_colors = num_colors\n self._sigma = sigma\n\n self._palette_coordinates = []\n self._palette_colors = []\n\n self._computeDarkBrightColors()\n self._computeInitialWeight()\n\n self._compute()\n\n self._plotter = PaletteSelectionPlot(self)\n\n def plot(self, plt):\n self._plotter.plot(plt)\n\n def paletteCoordinates(self):\n return self._palette_coordinates\n\n def paletteColors(self):\n return self._palette_colors\n\n def _compute(self):\n for i in xrange(self._num_colors):\n palette_coordinate = self._updatePalette()\n self._updateWeight(palette_coordinate)\n\n def _computeDarkBrightColors(self):\n rgb_colors = self._rgb_colors\n\n intensities = normVectors(rgb_colors)\n c_dark = self._color_coordinates[np.argmin(intensities)]\n c_bright = self._color_coordinates[np.argmax(intensities)]\n self._dark_bright = [c_dark, c_bright]\n\n def _computeInitialWeight(self):\n self._color_weights = np.array(self._color_densities)\n self._updateWeight(self._dark_bright[0])\n self._updateWeight(self._dark_bright[1])\n\n def _updatePalette(self):\n color_id = np.argmax(self._color_weights)\n palette_coordinate = self._color_coordinates[color_id]\n self._palette_coordinates.append(palette_coordinate)\n\n palette_color = self._rgb_colors[color_id]\n self._palette_colors.append(palette_color)\n return palette_coordinate\n\n def _updateWeight(self, palette_coordinate):\n dists = normVectors(self._color_coordinates - palette_coordinate)\n factors = 1.0 - np.exp(- dists ** 2 / (self._sigma ** 2))\n self._color_weights = factors * self._color_weights\n\n\n## Palette selection plotter.\nclass PaletteSelectionPlot:\n ## Constructor\n # @param palette_selection PaletteSelection instance for plotting.\n def __init__(self, palette_selection):\n self._palette_selection = palette_selection\n\n def paletteImage(self, size=16, spacing=4):\n palette_colors = self._palette_selection.paletteColors()\n num_colors = len(palette_colors)\n\n w = num_colors * size + (num_colors - 1) * spacing\n h = size\n\n palette_image = np.zeros((h, w, 4), dtype=np.float)\n\n for i, palette_color in enumerate(palette_colors):\n x_min = i * size + i * spacing\n x_max = x_min + size\n\n palette_image[:, x_min:x_max, 0:3] = palette_color\n palette_image[:, x_min:x_max, 3] = 1.0\n return palette_image\n\n def plot(self, plt):\n palette_image = self.paletteImage()\n plt.imshow(palette_image)"
] |
[
[
"numpy.argmax",
"numpy.argmin",
"numpy.array",
"numpy.exp",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
radovankavicky/pymaclab
|
[
"21da758f64ed0b62969c9289576f677e977cfd98",
"21da758f64ed0b62969c9289576f677e977cfd98",
"21da758f64ed0b62969c9289576f677e977cfd98"
] |
[
"pymaclab/filters/cffilter.py",
"pymaclab/tests/stats_tests/var_sw_jep.py",
"pymaclab/filters/setup.py"
] |
[
"from pymaclab.filters._cffilter import cffilter as cff\nimport numpy as np\n\ndef cffilter(data=None,low=6,high=32,drift=True):\n if type(data) == type(np.matlib.matrix([1,2,3])) and len(data.shape) == 2:\n if data.shape[0] < data.shape[1]: data = data.__array__().T\n else: data = data.__array__()\n elif type(data) != type(np.array([1,2,3])):\n data = np.array([x for x in data])\n elif type(data) == type(np.array([1,2,3])):\n if len(data.shape) == 2 and data.shape[0] < data.shape[1]:\n data = data.reshape(data.shape[1])\n elif len(data.shape) == 2 and data.shape[0] > data.shape[1]:\n data = data.reshape(data.shape[0])\n return cff(data,low=low,high=high,drift=drift) \n",
"import pandas\nimport numpy\nimport matplotlib\nfrom matplotlib import pyplot as plt\nfrom pymaclab import newVAR\nimport os\n\nmodconfig = {}\n# This model's name or title, used for pickling results\nmodname = 'STOCKWATSON_jep_model'\nmodconfig['modname'] = modname\n# Get the data from the directory\ndatafile = 'stwat_jpe_2001.csv'\nmodconfig['datafile'] = datafile\ndatapath = '../data/'\nmodconfig['datapath'] = datapath\ndata = pandas.read_csv(os.path.join(datapath,datafile),delimiter=';')\ndata = data[52:-1] # Select data range\ndata = data[:164] # Further restriction on data, because commodity index is longer\n# Define frequency of data\nfreq = 'Q'\nmodconfig['freq'] = freq\n# Should the data be standardized?\ntrans_data = False\nmodconfig['trans_data'] = trans_data\n# Define the number of lags in the VAR\nnlags = 4\nmodconfig['nlags'] = nlags\n# How many periods for IRFs ?\nirfp = 25\nmodconfig['irfp'] = irfp\n# Calculate variance decomposition?\ndo_vdc = True\nmodconfig['do_vdc'] = do_vdc\n# How many periods forecast for variance decomposition ?\nvdcp = 20\nmodconfig['vdcp'] = vdcp\n# Use the svname matrix for alternative shocks?\nuse_svnames = False\nmodconfig['use_svnames'] = use_svnames\n# Transform log variables in IRFs into percentages ?\ntranslog = False\nmodconfig['translog'] = translog\n# Transform the percentage responses back into absolutes from the mean ?\ntransperc = False\nmodconfig['transperc'] = transperc\n# Add impact matrix to Cholesky responses ?\ncholimp = False\nmodconfig['cholimp'] = cholimp\n# How many matrices for MA Representation\nmaxphi = irfp+2\nmodconfig['maxphi'] = maxphi\n# Boostrap IRF confidence intervals ?\nbootstrap = True\nmodconfig['bootstrap'] = bootstrap\n####################### This is experimental stuff, need to clarify the difference between the two #####################\nkillian_bsinbs = True\nmodconfig['killian_bsinbs'] = killian_bsinbs\n########################################################################################################################\n########################################## Graphing options for IRFs and other graphs ##################################\ngraph_options = {}\ngraph_options['labels'] = {}\ngraph_options['labels']['title'] = True\ngraph_options['labels']['xlabel'] = False\ngraph_options['labels']['ylabel'] = True\ngraph_options['labels']['text_fs'] = 10\ngraph_options['labels']['ylabel_fs'] = 10\ngraph_options['labels']['xlabel_fs'] = 10\ngraph_options['labels']['title_fs'] = 12\ngraph_options['labels']['label_fs'] = 8\ngraph_options['labels']['xticks_fs'] = 8\ngraph_options['labels']['yticks_fs'] = 8\ngraph_options['labels']['legend_fs'] = 8\ngraph_options['labels']['use_tex'] = False\ngraph_options['lines'] = {}\ngraph_options['lines']['width'] = 2.0\ngraph_options['grid'] = True\ngraph_options['irfs'] = {}\ngraph_options['irfs']['outer_colour'] = '#D3B0B0'\ngraph_options['irfs']['inner_colour'] = '#EED6D6'\ngraph_options['irfs']['line_colour'] = 'black'\ngraph_options['irfs']['biased_line'] = True # This allows you to also show the biased IRF when Killian's b-i-b option is on\ngraph_options['irfs']['biased_line_type'] = 'g--'\ngraph_options['save'] = {}\ngraph_options['save']['format'] = {}\ngraph_options['save']['format']['eps'] = True\ngraph_options['save']['format']['pdf'] = True\nmodconfig['graph_options'] = graph_options\n#########################################################################################################################\n# Draw a horizontal zero line into each IRF Plot\nhzline = True\nmodconfig['hzline'] = hzline\n# How thick should the hline be?\nhzline_width = 1.0\nmodconfig['hzline_width'] = hzline_width\n# How many draws for bootstrap ?\nbdraw = 1000\nmodconfig['bdraw'] = bdraw\n# Use multicore processors to speed up bootstrap?\nmulticpu = True\nmodconfig['multicpu'] = multicpu\n# Specify number of cpu cores or set to 'auto'\nncpus = 'auto'\nmodconfig['ncpus'] = ncpus\n# Level of significance for bootstrap confidence intervals\nsignif = [0.66,0.95] # implies 1-alpha = 0.66, use 'mix' to graph a variety of CI\nmodconfig['signif'] = signif\n# What kind of intercept/time trend?\nconst_term = 'ct' # Can be 'None', 'cc' or 'tt'\nmodconfig['const_term'] = const_term\n# Pickle the model run results and settings\npickle_switch = False\n# Define the names of the vars used\nvnames = []\nvnames.append('INF')\nvnames.append('LHUR')\nvnames.append('FYFF')\nmodconfig['vnames'] = vnames\n# Define the names for the vnames used in plotting\npnames = {}\npnames['INF'] = 'Inflation'\npnames['LHUR'] = 'Unemployment'\npnames['FYFF'] = 'Federal Funds Rate'\n\n# Create the data modification dictionary\ntcode_dic = {}\nclist = [1,1,1]\nfor i1,vname in enumerate(vnames):\n tcode_dic[vname] = clist[i1]\nmodconfig['tcode'] = tcode_dic\n\n# Define a matrix for scaling the orthogonalized shock\nsvnames = {}\nfor name in vnames:\n svnames[name] = 1.0\nmodconfig['svnames'] = svnames\n\n# Set the transperc_dic\ntransperc_dic = {}\nfor name in vnames:\n transperc_dic[name] = False\ntransperc_dic['employment'] = True\nmodconfig['transperc_dic'] = transperc_dic\n\n# Get the individual series of interest\nloglist = []\nmodconfig['loglist'] = loglist\ntlist = []\nfor name in vnames:\n if name in loglist:\n tlist.append(data[name].values)\n else:\n tlist.append(data[name].values)\nmatd = numpy.array(tlist)\n# Transpose and get the dims\nmatd = matd.T\ncols = matd.shape[1]\nrows = matd.shape[0]\nmodconfig['cols'] = cols\nmodconfig['rows'] = rows\n\nswvar = newVAR(data=matd,vnames=vnames,pnames=pnames,svnames=svnames,irfs=True,boot=True,plot=True,conf=modconfig,mesg=True)\n'''\ntsvar = var_model.VAR(matd,['INF','LHUR','FYFF'])\ntsvar_res = tsvar.fit(4,trend='ct')\n'''\n\n",
"# File setup.py\ndef configuration(parent_package='',top_path=None):\n from numpy.distutils.misc_util import Configuration\n config = Configuration('filters',parent_package,top_path)\n\n config.add_extension('_hpfilter',\n sources = ['src/hpfilter.f'])\n config.add_extension('_bkfilter',\n sources = ['src/bkfilter.f90'])\n return config\n\nif __name__ == \"__main__\":\n from numpy.distutils.core import setup\n setup(**configuration(top_path='').todict())\n"
] |
[
[
"numpy.array",
"numpy.matlib.matrix"
],
[
"numpy.array"
],
[
"numpy.distutils.misc_util.Configuration"
]
] |
[
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [
"1.11",
"1.19",
"1.24",
"1.16",
"1.23",
"1.20",
"1.7",
"1.12",
"1.21",
"1.22",
"1.14",
"1.6",
"1.13",
"1.9",
"1.17",
"1.10",
"1.18",
"1.15",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dongkwonjin/Semantic-Line-DRM
|
[
"0f20ca85ca80bc9e7c9157932343dfad6f7fdbd5",
"0f20ca85ca80bc9e7c9157932343dfad6f7fdbd5"
] |
[
"Reflection_symmetry_axes_detection/DNet/code/libs/load_model.py",
"Reflection_symmetry_axes_detection/DNet/code/dataset.py"
] |
[
"import torch\nfrom networks.detector import DNet\nfrom networks.loss import *\n\ndef load_DNet_for_test(cfg, dict_DB):\n\n if cfg.run_mode == 'test_paper':\n checkpoint = torch.load(cfg.paper_weight_dir + 'checkpoint_DNet_paper')\n else:\n # select ckpt from output_dir\n checkpoint = torch.load(cfg.weight_dir + '')\n\n\n model = DNet(cfg=cfg)\n model.load_state_dict(checkpoint['model'], strict=False)\n model.cuda()\n dict_DB['DNet'] = model\n\n return dict_DB\n\ndef load_DNet_for_train(cfg, dict_DB):\n model = DNet(cfg=cfg)\n model.cuda()\n optimizer = torch.optim.Adam(params=model.parameters(),\n lr=cfg.lr,\n weight_decay=cfg.weight_decay)\n\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer=optimizer,\n milestones=cfg.milestones,\n gamma=cfg.gamma)\n\n if cfg.resume == False:\n checkpoint = torch.load(cfg.weight_dir + 'checkpoint_DNet_final')\n model.load_state_dict(checkpoint['model'], strict=False)\n optimizer.load_state_dict(checkpoint['optimizer'])\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer=optimizer,\n milestones=cfg.milestones,\n gamma=cfg.gamma,\n last_epoch=checkpoint['epoch'])\n dict_DB['epoch'] = checkpoint['epoch']\n dict_DB['val_result'] = checkpoint['val_result']\n\n loss_fn = Loss_Function()\n\n dict_DB['DNet'] = model\n dict_DB['optimizer'] = optimizer\n dict_DB['scheduler'] = scheduler\n dict_DB['loss_fn'] = loss_fn\n\n return dict_DB\n",
"import os\nimport torch\nimport random\nimport pickle\n\nimport numpy as np\nimport torchvision.transforms as transforms\nimport torch.nn.functional as F\n\nfrom PIL import Image\nfrom torch.utils.data.dataset import Dataset\n\nfrom libs.utils import *\nfrom libs.modules import *\nfrom libs.line_generator import *\n\nclass Train_Dataset_DNet(Dataset):\n def __init__(self, cfg):\n self.cfg = cfg\n self.train_gt = load_pickle(cfg.train_dataset_dir + 'data/train_s')\n self.datalist = self.train_gt['img_path']\n\n self.transform = transforms.Compose([transforms.Resize((cfg.height, cfg.width), 2),\n transforms.ToTensor()])\n self.normalize = transforms.Normalize(mean=cfg.mean, std=cfg.std)\n\n self.pos_num = int(cfg.batch_size['train_line'] * cfg.ratio_pos)\n self.neg_num = int(cfg.batch_size['train_line'] * (1 - cfg.ratio_pos))\n\n self.height = cfg.height\n self.width = cfg.width\n self.size = np.float32(cfg.size)[0:2]\n\n self.line_generator = Training_Line_Generator(cfg)\n _ = self.line_generator.candidate_line()\n\n def get_image(self, idx):\n img_name = os.path.join(self.cfg.train_img_dir, self.datalist[idx])\n img = Image.open(img_name).convert('RGB')\n width, height = img.size\n return img, torch.FloatTensor([height, width]), self.datalist[idx]\n\n def get_flipped_data(self, img, label, flip):\n if flip == 1:\n img = img.transpose(Image.FLIP_LEFT_RIGHT)\n label[:, 0] = self.width - 1 - label[:, 0]\n label[:, 2] = self.width - 1 - label[:, 2]\n\n return img, label\n\n def process_data(self, pos_data, neg_data):\n\n # random sampling\n pos_data = np.concatenate((pos_data['pos']['endpts'],\n pos_data['pos']['cls'],\n pos_data['pos']['offset']), axis=1)\n neg_data = np.concatenate((neg_data['neg']['endpts'],\n neg_data['neg']['cls'],\n neg_data['neg']['offset']), axis=1)\n\n pos_idx = torch.randperm(pos_data.shape[0])[:self.pos_num]\n neg_idx = torch.randperm(neg_data.shape[0])[:self.neg_num]\n\n pos_data = pos_data[pos_idx]\n neg_data = neg_data[neg_idx]\n\n return pos_data, neg_data\n\n def normalize_point_coord(self, data):\n data[:, 6] = data[:, 6] / self.cfg.width\n data[:, 7] = data[:, 7] / self.cfg.height\n data[:, 8] = data[:, 8] / self.cfg.width\n data[:, 9] = data[:, 9] / self.cfg.height\n return data\n\n def __getitem__(self, idx):\n flip = random.randint(0, 1)\n\n # get pre-processed images\n img, img_size, img_name = self.get_image(idx)\n label = self.train_gt['label'][idx]\n img, label = self.get_flipped_data(img, label, flip)\n img = self.transform(img)\n\n # Augmentation by rotation\n theta_aff, theta, scale = random_rotation(self.height)\n aff_grid = F.affine_grid(theta_aff, torch.Size((1, 2, self.height, self.width)), align_corners=True)\n rotated_img = F.grid_sample(img.unsqueeze(0), aff_grid, align_corners=True)[0]\n\n rotated_gt = np.zeros((4), dtype=np.float32)\n rotated_gt[:2] = (np.matmul(np.linalg.inv(theta_aff[0, :, :2].cpu().numpy()), label[0, :2] / (self.size - 1) - 0.5) + 0.5) * (self.size - 1)\n rotated_gt[2:] = (np.matmul(np.linalg.inv(theta_aff[0, :, :2].cpu().numpy()), label[0, 2:] / (self.size - 1) - 0.5) + 0.5) * (self.size - 1)\n gtline = np.expand_dims(find_endpoints(rotated_gt, self.size - 1), 0)\n\n\n # get candidate lines\n self.line_generator.update(gtline=gtline)\n pos_data = self.line_generator.positive_line()\n neg_data = self.line_generator.negative_line()\n pos_data, neg_data = self.process_data(pos_data, neg_data)\n pos_data = self.normalize_point_coord(pos_data)\n\n train_data = np.concatenate((pos_data, neg_data), axis=0)\n\n return {'img_rgb': rotated_img,\n 'img': self.normalize(rotated_img),\n 'img_size': img_size,\n 'img_name': img_name,\n 'flip': flip,\n 'train_data': train_data}\n\n def __len__(self):\n return len(self.datalist)\n\n\n\nclass ICCV_Test_Dataset(Dataset):\n def __init__(self, cfg):\n\n self.cfg = cfg\n\n # load datalist\n self.datalist = load_pickle(cfg.test_dataset_dir + 'data/test_s')\n self.transform = transforms.Compose([transforms.Resize((cfg.height, cfg.width), 2),\n transforms.ToTensor()])\n self.normalize = transforms.Normalize(mean=cfg.mean, std=cfg.std)\n\n self.height = cfg.height\n self.width = cfg.width\n\n def get_image(self, idx):\n img_name = os.path.join(self.cfg.test_img_dir,\n self.datalist['img_path'][idx])\n img = Image.open(img_name).convert('RGB')\n\n width, height = img.size\n return img, torch.FloatTensor([height, width]), self.datalist['img_path'][idx]\n\n def get_gtlines(self, idx):\n\n gt = self.datalist['label'][idx]\n return gt\n\n\n def __getitem__(self, idx):\n\n # get pre-processed images\n img, img_size, img_name = self.get_image(idx)\n img = self.transform(img)\n\n gt = self.get_gtlines(idx)\n\n return {'img_rgb': img,\n 'img': self.normalize(img),\n 'img_size': img_size,\n 'img_name': img_name,\n 'gt': gt}\n\n def __len__(self):\n return len(self.datalist['img_path'])\n\nclass NYU_Test_Dataset(Dataset):\n def __init__(self, cfg):\n\n self.cfg = cfg\n\n # load datalist\n self.datalist = load_pickle(cfg.test_dataset_dir + 'data/test_s')\n self.transform = transforms.Compose([transforms.Resize((cfg.height, cfg.width), 2),\n transforms.ToTensor()])\n self.normalize = transforms.Normalize(mean=cfg.mean, std=cfg.std)\n\n self.height = cfg.height\n self.width = cfg.width\n\n def get_image(self, idx):\n img_name = os.path.join(self.cfg.test_img_dir,\n self.datalist['img_path'][idx])\n img = Image.open(img_name).convert('RGB')\n\n width, height = img.size\n return img, torch.FloatTensor([height, width]), self.datalist['img_path'][idx]\n\n def get_gtlines(self, idx):\n\n gt = self.datalist['label'][idx]\n return gt\n\n\n def __getitem__(self, idx):\n\n # get pre-processed images\n img, img_size, img_name = self.get_image(idx)\n img = self.transform(img)\n\n gt = self.get_gtlines(idx)\n\n return {'img_rgb': img,\n 'img': self.normalize(img),\n 'img_size': img_size,\n 'img_name': img_name,\n 'gt': gt}\n\n def __len__(self):\n return len(self.datalist['img_path'])\n\nclass SYM_Hard_Test_Dataset(Dataset):\n def __init__(self, cfg):\n\n self.cfg = cfg\n\n # load datalist\n self.datalist = load_pickle(cfg.test_dataset_dir + 'data/test_hard')\n self.transform = transforms.Compose([transforms.Resize((cfg.height, cfg.width), 2),\n transforms.ToTensor()])\n self.normalize = transforms.Normalize(mean=cfg.mean, std=cfg.std)\n\n self.height = cfg.height\n self.width = cfg.width\n\n def get_image(self, idx):\n img_name = os.path.join(self.cfg.test_img_dir,\n self.datalist['img_path'][idx])\n img = Image.open(img_name).convert('RGB')\n\n width, height = img.size\n return img, torch.FloatTensor([height, width]), self.datalist['img_path'][idx]\n\n def get_gtlines(self, idx):\n\n gt = self.datalist['label'][idx]\n return gt\n\n\n def __getitem__(self, idx):\n\n # get pre-processed images\n img, img_size, img_name = self.get_image(idx)\n img = self.transform(img)\n\n gt = self.get_gtlines(idx)\n\n return {'img_rgb': img,\n 'img': self.normalize(img),\n 'img_size': img_size,\n 'img_name': img_name,\n 'gt': gt}\n\n def __len__(self):\n return len(self.datalist['img_path'])\n\n\ndef random_rotation(size):\n # theta < 0 -> clock-wise\n theta = np.float32(random.randrange(-90, 90))\n alpha = theta / 180 * np.pi\n\n if theta >= 0:\n alpha_2 = (theta + 45) / 180 * np.pi\n else:\n alpha_2 = (theta * -1 + 45) / 180 * np.pi\n\n theta_aff = np.zeros((2, 3), dtype=np.float32)\n theta_aff[0, 2] = 0\n theta_aff[1, 2] = 0\n theta_aff[0, 0] = np.cos(alpha)\n theta_aff[0, 1] = (-np.sin(alpha))\n theta_aff[1, 0] = np.sin(alpha)\n theta_aff[1, 1] = np.cos(alpha)\n\n x = 0.5 * size * (np.sqrt(2) * np.sin(alpha_2) - 1) / np.sin(alpha_2)\n y = size * (np.sin(alpha_2 - np.pi / 4) * np.cos(alpha_2 - np.pi / 4)) / np.sin(alpha_2)\n t = 0.5 * size / np.sin(alpha_2)\n\n scale = (x + t) / (y + t)\n\n theta_aff = torch.from_numpy(theta_aff * scale).unsqueeze(0)\n\n return theta_aff, theta, np.cos(alpha_2)\n"
] |
[
[
"torch.optim.lr_scheduler.MultiStepLR",
"torch.load"
],
[
"torch.Size",
"numpy.sqrt",
"torch.randperm",
"numpy.cos",
"torch.from_numpy",
"numpy.sin",
"numpy.concatenate",
"torch.FloatTensor",
"numpy.float32",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Czaki/numcodecs
|
[
"673b7b4f2ae5b15a624404e65fbed9704ebf6fc5"
] |
[
"numcodecs/compat.py"
] |
[
"# flake8: noqa\nimport sys\nimport codecs\nimport array\nfrom functools import reduce\n\nimport numpy as np\n\n\ndef ensure_ndarray(buf):\n \"\"\"Convenience function to coerce `buf` to a numpy array, if it is not already a\n numpy array.\n\n Parameters\n ----------\n buf : array-like or bytes-like\n A numpy array or any object exporting a buffer interface.\n\n Returns\n -------\n arr : ndarray\n A numpy array, sharing memory with `buf`.\n\n Notes\n -----\n This function will not create a copy under any circumstances, it is guaranteed to\n return a view on memory exported by `buf`.\n\n \"\"\"\n\n if isinstance(buf, np.ndarray):\n # already a numpy array\n arr = buf\n\n elif isinstance(buf, array.array) and buf.typecode in 'cu':\n # Guard condition, do not support array.array with unicode type, this is\n # problematic because numpy does not support it on all platforms. Also do not\n # support char as it was removed in Python 3.\n raise TypeError('array.array with char or unicode type is not supported')\n\n else:\n\n # N.B., first take a memoryview to make sure that we subsequently create a\n # numpy array from a memory buffer with no copy\n mem = memoryview(buf)\n\n # instantiate array from memoryview, ensures no copy\n arr = np.array(mem, copy=False)\n\n return arr\n\n\ndef ensure_contiguous_ndarray(buf, max_buffer_size=None):\n \"\"\"Convenience function to coerce `buf` to a numpy array, if it is not already a\n numpy array. Also ensures that the returned value exports fully contiguous memory,\n and supports the new-style buffer interface. If the optional max_buffer_size is\n provided, raise a ValueError if the number of bytes consumed by the returned\n array exceeds this value.\n\n Parameters\n ----------\n buf : array-like or bytes-like\n A numpy array or any object exporting a buffer interface.\n max_buffer_size : int\n If specified, the largest allowable value of arr.nbytes, where arr\n is the retured array.\n\n Returns\n -------\n arr : ndarray\n A numpy array, sharing memory with `buf`.\n\n Notes\n -----\n This function will not create a copy under any circumstances, it is guaranteed to\n return a view on memory exported by `buf`.\n\n \"\"\"\n\n # ensure input is a numpy array\n arr = ensure_ndarray(buf)\n\n # check for object arrays, these are just memory pointers, actual memory holding\n # item data is scattered elsewhere\n if arr.dtype == object:\n raise TypeError('object arrays are not supported')\n\n # check for datetime or timedelta ndarray, the buffer interface doesn't support those\n if arr.dtype.kind in 'Mm':\n arr = arr.view(np.int64)\n\n # check memory is contiguous, if so flatten\n if arr.flags.c_contiguous or arr.flags.f_contiguous:\n # can flatten without copy\n arr = arr.reshape(-1, order='A')\n\n else:\n raise ValueError('an array with contiguous memory is required')\n\n if max_buffer_size is not None and arr.nbytes > max_buffer_size:\n msg = \"Codec does not support buffers of > {} bytes\".format(max_buffer_size)\n raise ValueError(msg)\n\n return arr\n\n\ndef ensure_bytes(buf):\n \"\"\"Obtain a bytes object from memory exposed by `buf`.\"\"\"\n\n if not isinstance(buf, bytes):\n\n # go via numpy, for convenience\n arr = ensure_ndarray(buf)\n\n # check for object arrays, these are just memory pointers,\n # actual memory holding item data is scattered elsewhere\n if arr.dtype == object:\n raise TypeError('object arrays are not supported')\n\n # create bytes\n buf = arr.tobytes(order='A')\n\n return buf\n\n\ndef ensure_text(s, encoding='utf-8'):\n if not isinstance(s, str):\n s = ensure_contiguous_ndarray(s)\n s = codecs.decode(s, encoding)\n return s\n\n\ndef ndarray_copy(src, dst):\n \"\"\"Copy the contents of the array from `src` to `dst`.\"\"\"\n\n if dst is None:\n # no-op\n return src\n\n # ensure ndarrays\n src = ensure_ndarray(src)\n dst = ensure_ndarray(dst)\n\n # flatten source array\n src = src.reshape(-1, order='A')\n\n # ensure same data type\n if dst.dtype != object:\n src = src.view(dst.dtype)\n\n # reshape source to match destination\n if src.shape != dst.shape:\n if dst.flags.f_contiguous:\n order = 'F'\n else:\n order = 'C'\n src = src.reshape(dst.shape, order=order)\n\n # copy via numpy\n np.copyto(dst, src)\n\n return dst\n"
] |
[
[
"numpy.copyto",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dimang777/CalorieEstimator
|
[
"f4be77e789790785ba9394e4e66e5a18a678b0be"
] |
[
"scripts/model/rf.py"
] |
[
"import time\nimport pickle\nfrom sklearn.metrics import accuracy_score\nimport numpy as np\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\n\n###############################################################################\n# Set up folders and variables\n###############################################################################\nfilename = 'rf.py'\n\nsave_folder = '../../data/data_for_model/'\nload_folder = '../../data/data_for_model/'\nmodel_folder = '../../data/model/'\n\n###############################################################################\n# Load\n###############################################################################\n\nwith open(save_folder + 'train_test_sel_features.pkl', 'rb') as f:\n [features,\n excluded_features,\n x_train_sel_df,\n x_test_sel_df,\n y_train_sel_df,\n y_test_sel_df,\n train_idx,\n test_idx,\n train_flag,\n test_flag] = pickle.load(f)\n\n###############################################################################\n# Set up hyperparameters\n###############################################################################\n\n# Number of trees in random forest\nn_estimators = [int(x) for x in np.linspace(start=200, stop=2000, num=10)]\n# Number of features to consider at every split\nmax_features = ['auto', 'sqrt']\n# Maximum number of levels in tree\nmax_depth = [int(x) for x in np.linspace(10, 110, num=11)]\nmax_depth.append(None)\n# Minimum number of samples required to split a node\nmin_samples_split = [2, 5, 10]\n# Minimum number of samples required at each leaf node\nmin_samples_leaf = [1, 2, 4]\n# Method of selecting samples for training each tree\nbootstrap = [True, False] # Create the random grid\nrandom_grid = {'n_estimators': n_estimators,\n 'max_features': max_features,\n 'max_depth': max_depth,\n 'min_samples_split': min_samples_split,\n 'min_samples_leaf': min_samples_leaf,\n 'bootstrap': bootstrap}\nprint(random_grid)\n\n###############################################################################\n# Set up functions\n###############################################################################\n\n\ndef evaluate(model, test_features, test_labels):\n y_pred = model.predict(test_features)\n accuracy = accuracy_score(test_labels, y_pred)\n print('Model Performance')\n print(\"Accuracy test: %.2f%%\" % (accuracy * 100.0))\n\n return accuracy*100\n\n\n###############################################################################\n# Set up CV random search\n###############################################################################\n\n\n# Use the random grid to search for best hyperparameters\n# Use the random grid to search for best hyperparameters\n# First create the base model to tune\nmodel = RandomForestClassifier()\n\nstart = time.time()\n# Random search of parameters, using 3 fold cross validation,\n# search across 100 different combinations, and use all available cores\nrf_random = RandomizedSearchCV(estimator=model,\n param_distributions=random_grid,\n n_iter=100,\n cv=3,\n verbose=2,\n random_state=42,\n n_jobs=-1)\n# Fit the random search model\nrf_random.fit(x_train_sel_df.values, y_train_sel_df.values)\n\nprint(rf_random.best_params_)\nend = time.time()\nprint(end - start)\n\n# _ tasks\n# Using multicore - _s\n# Using single core - _s\n\nmodel = rf_random.best_estimator_\nrandom_accuracy_train = evaluate(model,\n x_train_sel_df.values,\n y_train_sel_df.values)\nrandom_accuracy_test = evaluate(model,\n x_test_sel_df.values,\n y_test_sel_df.values)\n\n###############################################################################\n# Grid search around the best parameters\n###############################################################################\n\n# Number of trees in random forest\nn_estimators = [1580, 1590, 1600, 1610, 1620]\n# Number of features to consider at every split\nmax_features = ['sqrt']\n# Maximum number of levels in tree\nmax_depth = [68, 69, 70, 71, 72]\nmax_depth.append(None)\n# Minimum number of samples required to split a node\nmin_samples_split = [4, 5, 6]\n# Minimum number of samples required at each leaf node\nmin_samples_leaf = [1, 2, 3]\n# Method of selecting samples for training each tree\nbootstrap = [False] # Create the random grid\n\nparam_grid = {\n 'bootstrap': bootstrap,\n 'max_depth': max_depth,\n 'max_features': max_features,\n 'min_samples_leaf': min_samples_leaf,\n 'min_samples_split': min_samples_split,\n 'n_estimators': n_estimators\n}\n\nmodel = RandomForestClassifier()\n\nstart = time.time()\n# Instantiate the grid search model\ngrid_search = GridSearchCV(estimator=model,\n param_grid=param_grid,\n cv=3,\n n_jobs=-1,\n verbose=2)\n\n# Fit the grid search to the data\ngrid_search.fit(x_train_sel_df.values, y_train_sel_df.values)\nprint(grid_search.best_params_)\n\nend = time.time()\nprint(end - start)\n# _ tasks\n# Using multicore - _ hours\n# Using single core - _s\n\n###############################################################################\n# Final model\n###############################################################################\n\nmodel = grid_search.best_estimator_\ngrid_accuracy_train = evaluate(model,\n x_train_sel_df.values,\n y_train_sel_df.values)\ngrid_accuracy_test = evaluate(model,\n x_test_sel_df.values,\n y_test_sel_df.values)\n\n# =============================================================================\n# Accuracy Test: 100.00%\n# Accuracy Test: 93.05%\n# =============================================================================\n\n###############################################################################\n# Save model\n###############################################################################\n\nwith open(model_folder+'rf_hyper_tune_bestmodel_sel_fea.pickle', 'wb') \\\n as handle:\n pickle.dump([model], handle)\n\nwith open(model_folder+'rf_hyper_tune_bestmodel_sel_fea.pickle', 'rb') \\\n as handle:\n [model] = pickle.load(handle)\n"
] |
[
[
"sklearn.model_selection.GridSearchCV",
"sklearn.model_selection.RandomizedSearchCV",
"numpy.linspace",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.metrics.accuracy_score"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
joy-rosie/ibis
|
[
"d5b19398f4fdbcf33e1da88d8fcf9e34c64680b7"
] |
[
"ibis/impala/tests/test_udf.py"
] |
[
"import unittest\nfrom decimal import Decimal\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom posixpath import join as pjoin\n\nimport ibis\nimport ibis.common.exceptions as com\nimport ibis.expr.datatypes as dt\nimport ibis.expr.rules as rules\nimport ibis.expr.types as ir\nimport ibis.impala as api # noqa: E402\nimport ibis.util as util\nfrom ibis.common.exceptions import IbisTypeError\nfrom ibis.tests.expr.mocks import MockConnection\nfrom ibis.impala import ddl # noqa: E402\n\npytest.importorskip('hdfs')\npytest.importorskip('sqlalchemy')\npytest.importorskip('impala.dbapi')\n\npytestmark = [pytest.mark.impala, pytest.mark.udf]\n\n\nclass TestWrapping(unittest.TestCase):\n def setUp(self):\n self.con = MockConnection()\n self.table = self.con.table('functional_alltypes')\n\n self.i8 = self.table.tinyint_col\n self.i16 = self.table.smallint_col\n self.i32 = self.table.int_col\n self.i64 = self.table.bigint_col\n self.d = self.table.double_col\n self.f = self.table.float_col\n self.s = self.table.string_col\n self.b = self.table.bool_col\n self.t = self.table.timestamp_col\n self.dec = self.con.table('tpch_customer').c_acctbal\n self.all_cols = [\n self.i8,\n self.i16,\n self.i32,\n self.i64,\n self.d,\n self.f,\n self.dec,\n self.s,\n self.b,\n self.t,\n ]\n\n def test_sql_generation(self):\n func = api.scalar_function(['string'], 'string', name='Tester')\n func.register('identity', 'udf_testing')\n\n result = func('hello world')\n assert (\n ibis.impala.compile(result)\n == \"SELECT udf_testing.identity('hello world') AS `tmp`\"\n )\n\n def test_sql_generation_from_infoclass(self):\n func = api.wrap_udf('test.so', ['string'], 'string', 'info_test')\n repr(func)\n\n func.register('info_test', 'udf_testing')\n result = func('hello world')\n assert (\n ibis.impala.compile(result)\n == \"SELECT udf_testing.info_test('hello world') AS `tmp`\"\n )\n\n def test_udf_primitive_output_types(self):\n types = [\n ('boolean', True, self.b),\n ('int8', 1, self.i8),\n ('int16', 1, self.i16),\n ('int32', 1, self.i32),\n ('int64', 1, self.i64),\n ('float', 1.0, self.f),\n ('double', 1.0, self.d),\n ('string', '1', self.s),\n ('timestamp', ibis.timestamp('1961-04-10'), self.t),\n ]\n for t, sv, av in types:\n func = self._register_udf([t], t, 'test')\n\n ibis_type = dt.validate_type(t)\n\n expr = func(sv)\n assert type(expr) == type( # noqa: E501, E721\n ibis_type.scalar_type()(expr.op())\n )\n expr = func(av)\n assert type(expr) == type( # noqa: E501, E721\n ibis_type.column_type()(expr.op())\n )\n\n def test_uda_primitive_output_types(self):\n types = [\n ('boolean', True, self.b),\n ('int8', 1, self.i8),\n ('int16', 1, self.i16),\n ('int32', 1, self.i32),\n ('int64', 1, self.i64),\n ('float', 1.0, self.f),\n ('double', 1.0, self.d),\n ('string', '1', self.s),\n ('timestamp', ibis.timestamp('1961-04-10'), self.t),\n ]\n for t, sv, av in types:\n func = self._register_uda([t], t, 'test')\n\n ibis_type = dt.validate_type(t)\n\n expr1 = func(sv)\n expr2 = func(sv)\n expected_type1 = type(ibis_type.scalar_type()(expr1.op()))\n expected_type2 = type(ibis_type.scalar_type()(expr2.op()))\n assert isinstance(expr1, expected_type1)\n assert isinstance(expr2, expected_type2)\n\n def test_decimal(self):\n func = self._register_udf(['decimal(9,0)'], 'decimal(9,0)', 'test')\n expr = func(1.0)\n assert type(expr) == ir.DecimalScalar\n expr = func(self.dec)\n assert type(expr) == ir.DecimalColumn\n\n def test_udf_invalid_typecasting(self):\n cases = [\n ('int8', self.all_cols[:1], self.all_cols[1:]),\n ('int16', self.all_cols[:2], self.all_cols[2:]),\n ('int32', self.all_cols[:3], self.all_cols[3:]),\n ('int64', self.all_cols[:4], self.all_cols[4:]),\n ('boolean', [], self.all_cols[:8] + self.all_cols[9:]),\n # allowing double here for now\n ('float', self.all_cols[:6], [self.s, self.b, self.t]),\n ('double', self.all_cols[:6], [self.s, self.b, self.t]),\n ('string', [], self.all_cols[:7] + self.all_cols[8:]),\n ('timestamp', [], self.all_cols[:-1]),\n ('decimal', self.all_cols[:7], self.all_cols[7:]),\n ]\n\n for t, valid_casts, invalid_casts in cases:\n func = self._register_udf([t], 'int32', 'typecast')\n\n for expr in valid_casts:\n func(expr)\n\n for expr in invalid_casts:\n self.assertRaises(IbisTypeError, func, expr)\n\n def test_mult_args(self):\n func = self._register_udf(\n ['int32', 'double', 'string', 'boolean', 'timestamp'],\n 'int64',\n 'mult_types',\n )\n\n expr = func(self.i32, self.d, self.s, self.b, self.t)\n assert issubclass(type(expr), ir.ColumnExpr)\n\n expr = func(1, 1.0, 'a', True, ibis.timestamp('1961-04-10'))\n assert issubclass(type(expr), ir.ScalarExpr)\n\n def _register_udf(self, inputs, output, name):\n func = api.scalar_function(inputs, output, name=name)\n func.register(name, 'ibis_testing')\n return func\n\n def _register_uda(self, inputs, output, name):\n func = api.aggregate_function(inputs, output, name=name)\n func.register(name, 'ibis_testing')\n return func\n\n\[email protected](scope='session')\ndef udfcon(con):\n con.disable_codegen(False)\n try:\n yield con\n finally:\n con.disable_codegen(True)\n\n\[email protected](scope='session')\ndef alltypes(udfcon):\n return udfcon.table('functional_alltypes')\n\n\[email protected](scope='session')\ndef udf_ll(udfcon, test_data_dir):\n return pjoin(test_data_dir, 'udf/udf-sample.ll')\n\n\[email protected](scope='session')\ndef uda_ll(udfcon, test_data_dir):\n return pjoin(test_data_dir, 'udf/uda-sample.ll')\n\n\[email protected](scope='session')\ndef uda_so(udfcon, test_data_dir):\n return pjoin(test_data_dir, 'udf/libudasample.so')\n\n\[email protected](\n ('typ', 'lit_val', 'col_name'),\n [\n ('boolean', True, 'bool_col'),\n ('int8', ibis.literal(5), 'tinyint_col'),\n ('int16', ibis.literal(2 ** 10), 'smallint_col'),\n ('int32', ibis.literal(2 ** 17), 'int_col'),\n ('int64', ibis.literal(2 ** 33), 'bigint_col'),\n ('float', ibis.literal(3.14), 'float_col'),\n ('double', ibis.literal(3.14), 'double_col'),\n ('string', ibis.literal('ibis'), 'string_col'),\n ('timestamp', ibis.timestamp('1961-04-10'), 'timestamp_col'),\n ],\n)\[email protected](\n reason='Unknown reason. xfailing to restore the CI for udf tests. #2358'\n)\ndef test_identity_primitive_types(\n udfcon, alltypes, test_data_db, udf_ll, typ, lit_val, col_name\n):\n col_val = alltypes[col_name]\n identity_func_testing(udf_ll, udfcon, test_data_db, typ, lit_val, col_val)\n\n\[email protected](\n reason='Unknown reason. xfailing to restore the CI for udf tests. #2358'\n)\ndef test_decimal(udfcon, test_data_db, udf_ll):\n col = udfcon.table('tpch_customer').c_acctbal\n literal = ibis.literal(1).cast('decimal(12,2)')\n name = '__tmp_udf_' + util.guid()\n\n func = udf_creation_to_op(\n udf_ll,\n udfcon,\n test_data_db,\n name,\n 'Identity',\n ['decimal(12,2)'],\n 'decimal(12,2)',\n )\n\n expr = func(literal)\n assert issubclass(type(expr), ir.ScalarExpr)\n result = udfcon.execute(expr)\n assert result == Decimal(1)\n\n expr = func(col)\n assert issubclass(type(expr), ir.ColumnExpr)\n udfcon.execute(expr)\n\n\[email protected](\n reason='Unknown reason. xfailing to restore the CI for udf tests. #2358'\n)\ndef test_mixed_inputs(udfcon, alltypes, test_data_db, udf_ll):\n name = 'two_args'\n symbol = 'TwoArgs'\n inputs = ['int32', 'int32']\n output = 'int32'\n func = udf_creation_to_op(\n udf_ll, udfcon, test_data_db, name, symbol, inputs, output\n )\n\n expr = func(alltypes.int_col, 1)\n assert issubclass(type(expr), ir.ColumnExpr)\n udfcon.execute(expr)\n\n expr = func(1, alltypes.int_col)\n assert issubclass(type(expr), ir.ColumnExpr)\n udfcon.execute(expr)\n\n expr = func(alltypes.int_col, alltypes.tinyint_col)\n udfcon.execute(expr)\n\n\[email protected](\n reason='Unknown reason. xfailing to restore the CI for udf tests. #2358'\n)\ndef test_implicit_typecasting(udfcon, alltypes, test_data_db, udf_ll):\n col = alltypes.tinyint_col\n literal = ibis.literal(1000)\n identity_func_testing(udf_ll, udfcon, test_data_db, 'int32', literal, col)\n\n\ndef identity_func_testing(\n udf_ll, udfcon, test_data_db, datatype, literal, column\n):\n inputs = [datatype]\n name = '__tmp_udf_' + util.guid()\n func = udf_creation_to_op(\n udf_ll, udfcon, test_data_db, name, 'Identity', inputs, datatype\n )\n\n expr = func(literal)\n assert issubclass(type(expr), ir.ScalarExpr)\n result = udfcon.execute(expr)\n # Hacky\n if datatype == 'timestamp':\n assert type(result) == pd.Timestamp\n else:\n lop = literal.op()\n if isinstance(lop, ir.Literal):\n np.testing.assert_allclose(lop.value, 5)\n else:\n np.testing.assert_allclose(result, udfcon.execute(literal), 5)\n\n expr = func(column)\n assert issubclass(type(expr), ir.ColumnExpr)\n udfcon.execute(expr)\n\n\[email protected](\n reason='Unknown reason. xfailing to restore the CI for udf tests. #2358'\n)\ndef test_mult_type_args(udfcon, alltypes, test_data_db, udf_ll):\n symbol = 'AlmostAllTypes'\n name = 'most_types'\n inputs = [\n 'string',\n 'boolean',\n 'int8',\n 'int16',\n 'int32',\n 'int64',\n 'float',\n 'double',\n ]\n output = 'int32'\n\n func = udf_creation_to_op(\n udf_ll, udfcon, test_data_db, name, symbol, inputs, output\n )\n\n expr = func('a', True, 1, 1, 1, 1, 1.0, 1.0)\n result = udfcon.execute(expr)\n assert result == 8\n\n table = alltypes\n expr = func(\n table.string_col,\n table.bool_col,\n table.tinyint_col,\n table.tinyint_col,\n table.smallint_col,\n table.smallint_col,\n 1.0,\n 1.0,\n )\n udfcon.execute(expr)\n\n\ndef test_all_type_args(udfcon, test_data_db, udf_ll):\n pytest.skip('failing test, to be fixed later')\n\n symbol = 'AllTypes'\n name = 'all_types'\n inputs = [\n 'string',\n 'boolean',\n 'int8',\n 'int16',\n 'int32',\n 'int64',\n 'float',\n 'double',\n 'decimal',\n ]\n output = 'int32'\n\n func = udf_creation_to_op(\n udf_ll, udfcon, test_data_db, name, symbol, inputs, output\n )\n expr = func('a', True, 1, 1, 1, 1, 1.0, 1.0, 1.0)\n result = udfcon.execute(expr)\n assert result == 9\n\n\[email protected](\n reason='Unknown reason. xfailing to restore the CI for udf tests. #2358'\n)\ndef test_udf_varargs(udfcon, alltypes, udf_ll, test_data_db):\n t = alltypes\n\n name = 'add_numbers_{0}'.format(util.guid()[:4])\n\n input_sig = rules.varargs(rules.double)\n func = api.wrap_udf(udf_ll, input_sig, 'double', 'AddNumbers', name=name)\n func.register(name, test_data_db)\n udfcon.create_function(func, database=test_data_db)\n\n expr = func(t.double_col, t.double_col)\n expr.execute()\n\n\ndef test_drop_udf_not_exists(udfcon):\n random_name = util.guid()\n with pytest.raises(Exception):\n udfcon.drop_udf(random_name)\n\n\ndef test_drop_uda_not_exists(udfcon):\n random_name = util.guid()\n with pytest.raises(Exception):\n udfcon.drop_uda(random_name)\n\n\ndef udf_creation_to_op(\n udf_ll, udfcon, test_data_db, name, symbol, inputs, output\n):\n func = api.wrap_udf(udf_ll, inputs, output, symbol, name)\n\n # self.temp_udfs.append((name, inputs))\n\n udfcon.create_function(func, database=test_data_db)\n\n func.register(name, test_data_db)\n\n assert udfcon.exists_udf(name, test_data_db)\n return func\n\n\ndef test_ll_uda_not_supported(uda_ll):\n # LLVM IR UDAs are not supported as of Impala 2.2\n with pytest.raises(com.IbisError):\n conforming_wrapper(uda_ll, ['double'], 'double', 'Variance')\n\n\ndef conforming_wrapper(\n where, inputs, output, prefix, serialize=True, name=None\n):\n kwds = {'name': name}\n if serialize:\n kwds['serialize_fn'] = '{0}Serialize'.format(prefix)\n return api.wrap_uda(\n where,\n inputs,\n output,\n '{0}Update'.format(prefix),\n init_fn='{0}Init'.format(prefix),\n merge_fn='{0}Merge'.format(prefix),\n finalize_fn='{0}Finalize'.format(prefix),\n **kwds,\n )\n\n\[email protected]\ndef wrapped_count_uda(uda_so):\n name = 'user_count_{0}'.format(util.guid())\n return api.wrap_uda(uda_so, ['int32'], 'int64', 'CountUpdate', name=name)\n\n\ndef test_count_uda(udfcon, alltypes, test_data_db, wrapped_count_uda):\n func = wrapped_count_uda\n func.register(func.name, test_data_db)\n udfcon.create_function(func, database=test_data_db)\n\n # it works!\n func(alltypes.int_col).execute()\n # self.temp_udas.append((func.name, ['int32']))\n\n\ndef test_list_udas(udfcon, temp_database, wrapped_count_uda):\n func = wrapped_count_uda\n db = temp_database\n udfcon.create_function(func, database=db)\n\n funcs = udfcon.list_udas(database=db)\n\n f = funcs[0]\n assert f.name == func.name\n assert f.inputs == func.inputs\n assert f.output == func.output\n\n\[email protected](\n reason='Unknown reason. xfailing to restore the CI for udf tests. #2358'\n)\ndef test_drop_database_with_udfs_and_udas(\n udfcon, temp_database, wrapped_count_uda\n):\n uda1 = wrapped_count_uda\n\n udf1 = api.wrap_udf(\n udf_ll,\n ['boolean'],\n 'boolean',\n 'Identity',\n 'udf_{0}'.format(util.guid()),\n )\n\n db = temp_database\n\n udfcon.create_database(db)\n\n udfcon.create_function(uda1, database=db)\n udfcon.create_function(udf1, database=db)\n # drop happens in test tear down\n\n\nclass TestUDFDDL(unittest.TestCase):\n def setUp(self):\n self.con = MockConnection()\n self.name = 'test_name'\n self.inputs = ['string', 'string']\n self.output = 'int64'\n\n def test_create_udf(self):\n func = api.wrap_udf(\n '/foo/bar.so',\n self.inputs,\n self.output,\n so_symbol='testFunc',\n name=self.name,\n )\n stmt = ddl.CreateUDF(func)\n result = stmt.compile()\n expected = (\n \"CREATE FUNCTION `test_name`(string, string) \"\n \"returns bigint \"\n \"location '/foo/bar.so' symbol='testFunc'\"\n )\n assert result == expected\n\n def test_create_udf_type_conversions(self):\n inputs = ['string', 'int8', 'int16', 'int32']\n func = api.wrap_udf(\n '/foo/bar.so',\n inputs,\n self.output,\n so_symbol='testFunc',\n name=self.name,\n )\n stmt = ddl.CreateUDF(func)\n\n # stmt = ddl.CreateFunction('/foo/bar.so', 'testFunc',\n # ,\n # self.output, self.name)\n result = stmt.compile()\n expected = (\n \"CREATE FUNCTION `test_name`(string, tinyint, \"\n \"smallint, int) returns bigint \"\n \"location '/foo/bar.so' symbol='testFunc'\"\n )\n assert result == expected\n\n def test_delete_udf_simple(self):\n stmt = ddl.DropFunction(self.name, self.inputs)\n result = stmt.compile()\n expected = \"DROP FUNCTION `test_name`(string, string)\"\n assert result == expected\n\n def test_delete_udf_if_exists(self):\n stmt = ddl.DropFunction(self.name, self.inputs, must_exist=False)\n result = stmt.compile()\n expected = \"DROP FUNCTION IF EXISTS `test_name`(string, string)\"\n assert result == expected\n\n def test_delete_udf_aggregate(self):\n stmt = ddl.DropFunction(self.name, self.inputs, aggregate=True)\n result = stmt.compile()\n expected = \"DROP AGGREGATE FUNCTION `test_name`(string, string)\"\n assert result == expected\n\n def test_delete_udf_db(self):\n stmt = ddl.DropFunction(self.name, self.inputs, database='test')\n result = stmt.compile()\n expected = \"DROP FUNCTION test.`test_name`(string, string)\"\n assert result == expected\n\n def test_create_uda(self):\n def make_ex(serialize=False):\n if serialize:\n serialize = \"\\nserialize_fn='Serialize'\"\n else:\n serialize = \"\"\n return (\n (\n \"CREATE AGGREGATE FUNCTION \"\n \"bar.`test_name`(string, string)\"\n \" returns bigint location '/foo/bar.so'\"\n \"\\ninit_fn='Init'\"\n \"\\nupdate_fn='Update'\"\n \"\\nmerge_fn='Merge'\"\n )\n + serialize\n + \"\\nfinalize_fn='Finalize'\"\n )\n\n for ser in [True, False]:\n func = api.wrap_uda(\n '/foo/bar.so',\n self.inputs,\n self.output,\n update_fn='Update',\n init_fn='Init',\n merge_fn='Merge',\n finalize_fn='Finalize',\n serialize_fn='Serialize' if ser else None,\n )\n stmt = ddl.CreateUDA(func, name=self.name, database='bar')\n result = stmt.compile()\n expected = make_ex(ser)\n assert result == expected\n\n def test_list_udf(self):\n stmt = ddl.ListFunction('test')\n result = stmt.compile()\n expected = 'SHOW FUNCTIONS IN test'\n assert result == expected\n\n def test_list_udfs_like(self):\n stmt = ddl.ListFunction('test', like='identity')\n result = stmt.compile()\n expected = \"SHOW FUNCTIONS IN test LIKE 'identity'\"\n assert result == expected\n\n def test_list_udafs(self):\n stmt = ddl.ListFunction('test', aggregate=True)\n result = stmt.compile()\n expected = 'SHOW AGGREGATE FUNCTIONS IN test'\n assert result == expected\n\n def test_list_udafs_like(self):\n stmt = ddl.ListFunction('test', like='identity', aggregate=True)\n result = stmt.compile()\n expected = \"SHOW AGGREGATE FUNCTIONS IN test LIKE 'identity'\"\n assert result == expected\n"
] |
[
[
"numpy.testing.assert_allclose"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LiborKudela/pipe_physics
|
[
"73774d3d9a2fea3f253bdc9842dd899a74c03c34"
] |
[
"csv_to_modelica.py"
] |
[
"import pandas as pd\nimport numpy as np\n\ndef write_lookup_function(name, x_key, y_key):\n code = f\"\"\"\nfunction {name}\n input Real x;\n output Real y;\nalgorithm\n for i in 1:size({x_key}, 1) loop\n if {x_key}[i+1] > x then\n y := {y_key}[i] + (x - {x_key}[i]) * ({y_key}[i] - {y_key}[i + 1]) / ({x_key}[i] - {x_key}[i + 1]);\n break;\n end if;\n end for;\nend {name};\n\"\"\"\n return code\n\ndef write_direct_lookup_function(name, x_key, y_key):\n code = f\"\"\"\nfunction {name}\n input Real x;\n output Real y;\nprotected\n Integer idx;\n Real delta_x;\nalgorithm\n idx := integer(x/dx);\n delta_x := x - idx*dx;\n y := {y_key}[idx+1] + delta_x*({y_key}[idx+2]-{y_key}[idx+1])/dx;\nend {name};\n\"\"\"\n return code\n\ndef write_output_connector():\n code = \"\"\"\nconnector Output = output Real annotation(Icon(graphics = {Polygon(lineColor = {52, 101, 164},\n fillColor = {144, 222, 236},\n fillPattern = FillPattern.Solid,\n lineThickness = 1,\n points = {{-100, 100},\n {100, 0},\n {-100, -100},\n {-100, 100}})}));\n\"\"\"\n return code\n\ndef write_source_base():\n code = \"\"\"\nmodel source_base\n Output y annotation(Placement(visible = true,\n transformation(origin = {90, 0},\n extent = {{-10, -10}, {10, 10}}),\n iconTransformation(origin = {90, 0},\n extent = {{-10, -10}, {10, 10}})));\nequation\n annotation(Icon(graphics = {Rectangle(fillColor = {238, 238, 236},\n fillPattern = FillPattern.Solid,\n lineThickness = 1,\n extent = {{-80, 80}, {80, -80}}),\n Text(origin = {-2, -1},\n extent = {{-74, 13}, {74, -13}},\n textString = \"%name\")}));\nend source_base;\n\"\"\"\n return code\n\ndef write_source(name, function):\n code = f\"\"\"\nmodel {name}\n extends source_base;\nequation\n y=Functions.{name}(time);\nend {name};\n\"\"\"\n return code\n\ndef convert_to_modelica_package(path, dx=None, make_callable=True, output=None):\n code = \"package data\\n\"\n code += f\"constant Real dx = {dx};\\n\" \n # insert data\n df = pd.read_csv(path)\n keys = df.keys()\n x_key = keys[0]\n y_keys = keys[1:]\n x_min = df[x_key].iloc[0]\n x_max = df[x_key].iloc[-1]\n x_vals = np.arange(x_min, x_max, dx)\n if x_vals[-1] != x_max:\n np.append(x_vals,[x_max])\n for key in keys:\n vals = np.interp(x_vals, df[x_key], df[key]).astype(str)\n code += f\"constant Real {key}_data[:] = \" + \"{\" + \",\".join(vals) + \"};\\n\" \n\n #insert 1D interpolations functions\n code += \"package Functions\\n\"\n for y_key in y_keys:\n code += write_direct_lookup_function(y_key, f\"{x_key}_data\", f\"{y_key}_data\") \n code += \"end Functions;\\n\"\n\n # insert data sources blocks\n code += write_output_connector()\n code += write_source_base()\n for y_key in y_keys:\n code += write_source(y_key, f\"Functions.{y_key}\")\n\n code += \"end data;\"\n\n # save modelica file to disk\n if output is None:\n output = f\"{path[:-4]}.mo\" \n f = open(output, \"w\")\n f.write(code)\n f.close()\n"
] |
[
[
"numpy.arange",
"numpy.append",
"pandas.read_csv",
"numpy.interp"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
MrtnMndt/OCDVAEContinualLearning
|
[
"2c5f778dc7f94ff696b923a84246a56c391a8eff"
] |
[
"main.py"
] |
[
"########################\n# Importing libraries\n########################\n# System libraries\nimport os\nimport random\nfrom time import gmtime, strftime\nimport numpy as np\nimport pickle\n\n# Tensorboard for PyTorch logging and visualization\nfrom torch.utils.tensorboard import SummaryWriter\n\n# Torch libraries\nimport torch\nimport torch.backends.cudnn as cudnn\n\n# Custom library\nimport lib.Models.architectures as architectures\nfrom lib.Models.pixelcnn import PixelCNN\nimport lib.Datasets.datasets as datasets\nfrom lib.Models.initialization import WeightInit\nfrom lib.Models.architectures import grow_classifier\nfrom lib.cmdparser import parser\nfrom lib.Training.train import train\nfrom lib.Training.validate import validate\nfrom lib.Training.loss_functions import unified_loss_function as criterion\nfrom lib.Utility.utils import save_checkpoint, save_task_checkpoint\nfrom lib.Training.evaluate import get_latent_embedding\nfrom lib.Utility.visualization import args_to_tensorboard\nfrom lib.Utility.visualization import visualize_dataset_in_2d_embedding\n\n\n# Comment this if CUDNN benchmarking is not desired\ncudnn.benchmark = True\n\n\ndef main():\n # Command line options\n args = parser.parse_args()\n print(\"Command line options:\")\n for arg in vars(args):\n print(arg, getattr(args, arg))\n\n if args.cross_dataset and not args.incremental_data:\n raise ValueError('cross-dataset training possible only if incremental-data flag set')\n\n # Check whether GPU is available and can be used\n # if CUDA is found then device is set accordingly\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # Launch a writer for the tensorboard summary writer instance\n save_path = 'runs/' + strftime(\"%Y-%m-%d_%H-%M-%S\", gmtime()) + '_' + args.dataset + '_' + args.architecture +\\\n '_variational_samples_' + str(args.var_samples) + '_latent_dim_' + str(args.var_latent_dim)\n\n # add option specific naming to separate tensorboard log files later\n if args.autoregression:\n save_path += '_pixelcnn'\n\n if args.incremental_data:\n save_path += '_incremental'\n if args.train_incremental_upper_bound:\n save_path += '_upper_bound'\n if args.generative_replay:\n save_path += '_genreplay'\n if args.openset_generative_replay:\n save_path += '_opensetreplay'\n if args.cross_dataset:\n save_path += '_cross_dataset_' + args.dataset_order\n\n # if we are resuming a previous training, note it in the name\n if args.resume:\n save_path = save_path + '_resumed'\n writer = SummaryWriter(save_path)\n\n # saving the parsed args to file\n log_file = os.path.join(save_path, \"stdout\")\n log = open(log_file, \"a\")\n for arg in vars(args):\n log.write(arg + ':' + str(getattr(args, arg)) + '\\n')\n\n # Dataset loading\n data_init_method = getattr(datasets, args.dataset)\n dataset = data_init_method(torch.cuda.is_available(), args)\n # get the number of classes from the class dictionary\n num_classes = dataset.num_classes\n\n # we set an epoch multiplier to 1 for isolated training and increase it proportional to amount of tasks in CL\n epoch_multiplier = 1\n if args.incremental_data:\n from lib.Datasets.incremental_dataset import get_incremental_dataset\n\n # get the method to create the incremental dataste (inherits from the chosen data loader)\n inc_dataset_init_method = get_incremental_dataset(data_init_method, args)\n\n # different options for class incremental vs. cross-dataset experiments\n if args.cross_dataset:\n # if a task order file is specified, load the task order from it\n if args.load_task_order:\n # check if file exists and if file ends with extension '.txt'\n if os.path.isfile(args.load_task_order) and len(args.load_task_order) >= 4\\\n and args.load_task_order[-4:] == '.txt':\n print(\"=> loading task order from '{}'\".format(args.load_task_order))\n with open(args.load_task_order, 'rb') as fp:\n task_order = pickle.load(fp)\n # if no file is found default to cmd line task order\n else:\n # parse and split string at commas\n task_order = args.dataset_order.split(',')\n for i in range(len(task_order)):\n # remove blank spaces in dataset names\n task_order[i] = task_order[i].replace(\" \", \"\")\n # use task order as specified in command line\n else:\n # parse and split string at commas\n task_order = args.dataset_order.split(',')\n for i in range(len(task_order)):\n # remove blank spaces in dataset names\n task_order[i] = task_order[i].replace(\" \", \"\")\n\n # just for getting the number of classes in the first dataset\n num_classes = 0\n for i in range(args.num_base_tasks):\n temp_dataset_init_method = getattr(datasets, task_order[i])\n temp_dataset = temp_dataset_init_method(torch.cuda.is_available(), args)\n num_classes += temp_dataset.num_classes\n del temp_dataset\n\n # multiply epochs by number of tasks\n if args.num_increment_tasks:\n epoch_multiplier = ((len(task_order) - args.num_base_tasks) / args.num_increment_tasks) + 1\n else:\n # this branch will get active if num_increment_tasks is set to zero. This is useful when training\n # any isolated upper bound with all datasets present from the start.\n epoch_multiplier = 1.0\n else:\n # class incremental\n # if specified load task order from file\n if args.load_task_order:\n if os.path.isfile(args.load_task_order):\n print(\"=> loading task order from '{}'\".format(args.load_task_order))\n task_order = np.load(args.load_task_order).tolist()\n else:\n # if no file is found a random task order is created\n print(\"=> no task order found. Creating randomized task order\")\n task_order = np.random.permutation(num_classes).tolist()\n else:\n # if randomize task order is specified create a random task order, else task order is sequential\n task_order = []\n for i in range(dataset.num_classes):\n task_order.append(i)\n\n if args.randomize_task_order:\n task_order = np.random.permutation(num_classes).tolist()\n\n # save the task order\n np.save(os.path.join(save_path, 'task_order.npy'), task_order)\n # set the number of classes to base tasks + 1 because base tasks is always one less.\n # E.g. if you have 2 classes it's one task. This is a little inconsistent from the naming point of view\n # but we wanted a single variable to work for both class incremental as well as cross-dataset experiments\n num_classes = args.num_base_tasks + 1\n # multiply epochs by number of tasks\n epoch_multiplier = ((len(task_order) - (args.num_base_tasks + 1)) / args.num_increment_tasks) + 1\n\n print(\"Task order: \", task_order)\n # log the task order into the text file\n log.write('task_order:' + str(task_order) + '\\n')\n args.task_order = task_order\n\n # this is a little weird, but it needs to be here because the below method pops items from task_order\n args_to_tensorboard(writer, args)\n\n assert epoch_multiplier.is_integer(), print(\"uneven task division, make sure number of tasks are integers.\")\n\n # Get the incremental dataset\n dataset = inc_dataset_init_method(torch.cuda.is_available(), device, task_order, args)\n else:\n # add command line options to TensorBoard\n args_to_tensorboard(writer, args)\n\n log.close()\n\n # Get a sample input from the data loader to infer color channels/size\n net_input, _ = next(iter(dataset.train_loader))\n # get the amount of color channels in the input images\n num_colors = net_input.size(1)\n\n # import model from architectures class\n net_init_method = getattr(architectures, args.architecture)\n\n # if we are not building an autoregressive model the number of output channels of the model is equivalent to\n # the amount of input channels. For an autoregressive models we set the number of output channels of the\n # non-autoregressive decoder portion according to the command line option below\n if not args.autoregression:\n args.out_channels = num_colors\n\n # build the model\n model = net_init_method(device, num_classes, num_colors, args)\n\n # optionally add the autoregressive decoder\n if args.autoregression:\n model.pixelcnn = PixelCNN(device, num_colors, args.out_channels, args.pixel_cnn_channels,\n num_layers=args.pixel_cnn_layers, k=args.pixel_cnn_kernel_size,\n padding=args.pixel_cnn_kernel_size//2)\n\n # Parallel container for multi GPU use and cast to available device\n model = torch.nn.DataParallel(model).to(device)\n print(model)\n\n # Initialize the weights of the model, by default according to He et al.\n print(\"Initializing network with: \" + args.weight_init)\n WeightInitializer = WeightInit(args.weight_init)\n WeightInitializer.init_model(model)\n\n # Define optimizer and loss function (criterion)\n optimizer = torch.optim.Adam(model.parameters(), args.learning_rate)\n\n epoch = 0\n best_prec = 0\n best_loss = random.getrandbits(128)\n\n # optionally resume from a checkpoint\n if args.resume:\n if os.path.isfile(args.resume):\n print(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n epoch = checkpoint['epoch']\n best_prec = checkpoint['best_prec']\n best_loss = checkpoint['best_loss']\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n print(\"=> loaded checkpoint '{}' (epoch {})\"\n .format(args.resume, checkpoint['epoch']))\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n\n # optimize until final amount of epochs is reached. Final amount of epochs is determined through the\n while epoch < (args.epochs * epoch_multiplier):\n # visualize the latent space before each task increment and at the end of training if it is 2-D\n if epoch % args.epochs == 0 and epoch > 0 or (epoch + 1) % (args.epochs * epoch_multiplier) == 0:\n if model.module.latent_dim == 2:\n print(\"Calculating and visualizing dataset embedding\")\n # infer the number of current tasks to plot the different classes in the embedding\n if args.incremental_data:\n if args.cross_dataset:\n num_tasks = sum(dataset.num_classes_per_task[:len(dataset.seen_tasks)])\n else:\n num_tasks = len(dataset.seen_tasks)\n else:\n num_tasks = num_classes\n\n zs = get_latent_embedding(model, dataset.train_loader, num_tasks, device)\n visualize_dataset_in_2d_embedding(writer, zs, args.dataset, save_path, task=num_tasks)\n\n # continual learning specific part\n if args.incremental_data:\n # at the end of each task increment\n if epoch % args.epochs == 0 and epoch > 0:\n print('Saving the last checkpoint from the previous task ...')\n save_task_checkpoint(save_path, epoch // args.epochs)\n\n print(\"Incrementing dataset ...\")\n dataset.increment_tasks(model, args.batch_size, args.workers, writer, save_path,\n is_gpu=torch.cuda.is_available(),\n upper_bound_baseline=args.train_incremental_upper_bound,\n generative_replay=args.generative_replay,\n openset_generative_replay=args.openset_generative_replay,\n openset_threshold=args.openset_generative_replay_threshold,\n openset_tailsize=args.openset_weibull_tailsize,\n autoregression=args.autoregression)\n\n # grow the classifier and increment the variable for number of overall classes so we can use it later\n if args.cross_dataset:\n grow_classifier(device, model.module.classifier,\n sum(dataset.num_classes_per_task[:len(dataset.seen_tasks)])\n - model.module.num_classes, WeightInitializer)\n model.module.num_classes = sum(dataset.num_classes_per_task[:len(dataset.seen_tasks)])\n else:\n model.module.num_classes += args.num_increment_tasks\n grow_classifier(device, model.module.classifier, args.num_increment_tasks, WeightInitializer)\n\n # reset moving averages etc. of the optimizer\n optimizer = torch.optim.Adam(model.parameters(), args.learning_rate)\n\n # change the number of seen classes\n if epoch % args.epochs == 0:\n model.module.seen_tasks = dataset.seen_tasks\n\n # train\n train(dataset, model, criterion, epoch, optimizer, writer, device, args)\n\n # evaluate on validation set\n prec, loss = validate(dataset, model, criterion, epoch, writer, device, save_path, args)\n\n # remember best prec@1 and save checkpoint\n is_best = loss < best_loss\n best_loss = min(loss, best_loss)\n best_prec = max(prec, best_prec)\n save_checkpoint({'epoch': epoch,\n 'arch': args.architecture,\n 'state_dict': model.state_dict(),\n 'best_prec': best_prec,\n 'best_loss': best_loss,\n 'optimizer': optimizer.state_dict()},\n is_best, save_path)\n\n # increment epoch counters\n epoch += 1\n\n # if a new task begins reset the best prec so that new best model can be stored.\n if args.incremental_data and epoch % args.epochs == 0:\n best_prec = 0\n best_loss = random.getrandbits(128)\n\n writer.close()\n\n\nif __name__ == '__main__': \n main()\n"
] |
[
[
"torch.load",
"numpy.random.permutation",
"torch.utils.tensorboard.SummaryWriter",
"torch.cuda.is_available",
"numpy.load",
"torch.nn.DataParallel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nikgetas/brain_parcellation_project
|
[
"59fa6b976b23250d111f0e2a8683152639be5051",
"59fa6b976b23250d111f0e2a8683152639be5051",
"59fa6b976b23250d111f0e2a8683152639be5051"
] |
[
"HMM clustering/em.py",
"cnmf clustering/cnmf_test.py",
"Spectral clustering/SC_cortex.py"
] |
[
"import copy\nimport distributions\nimport kmeans\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nfrom matplotlib.mlab import bivariate_normal\nfrom numpy import newaxis as nax\nfrom numpy.linalg import det, inv\n\nfrom IPython.core.debugger import Tracer\n\ndef log_likelihood(X, obs_distr, pi):\n N = X.shape[0]\n K = len(obs_distr)\n pdfs = np.zeros((N,K))\n for j in range(K):\n pdfs[:,j] = obs_distr[j].pdf(X)\n\n # ll = sum_i log(sum_j pi_j p(x_i|theta_j))\n ll = sum(np.log(np.dot(pi, pdfs[i,:])) for i in range(N))\n return ll\n\ndef em(X, init_obs_distr, assignments=None, n_iter=10, Xtest=None):\n N = X.shape[0]\n K = len(init_obs_distr)\n\n if assignments is not None:\n pi = np.array([np.sum(assignments == j) for j in range(K)], dtype=np.float)\n pi = pi / np.sum(pi)\n else:\n pi = np.ones(K) / K\n obs_distr = copy.deepcopy(init_obs_distr)\n tau = np.zeros((N, K)) # tau[i,j] = p(z_i = j | x_i)\n\n ll_train = []\n ll_test = []\n\n for i in range(n_iter):\n # E-step\n for j in range(K):\n tau[:,j] = pi[j] * obs_distr[j].pdf(X)\n\n # normalize each line\n tau = tau / np.sum(tau, axis=1)[:,nax]\n print(np.bincount(np.argmax(tau,1)))\n\n # M-step\n pi = np.sum(tau, axis=0) / N\n\n for j in range(K):\n obs_distr[j].max_likelihood(X, tau[:,j])\n # Tracer()()\n\n ll_train.append(log_likelihood(X, obs_distr, pi))\n if Xtest is not None:\n ll_test.append(log_likelihood(Xtest, obs_distr, pi))\n\n return tau, obs_distr, pi, ll_train, ll_test\n\ndef plot_em(X, tau, obs_distr, contours=False):\n means = np.vstack(d.mean for d in obs_distr)\n K = means.shape[0]\n plt.figure()\n plt.scatter(X[:,0], X[:,1], c=np.argmax(tau, axis=1))\n plt.scatter(means[:,0], means[:,1], color='green', s=100)\n \n if contours:\n sigmas = [d.cov for d in obs_distr]\n for j in range(K):\n x, y = np.arange(-10., 10., 0.04), np.arange(-15., 15., 0.04)\n xx, yy = np.meshgrid(x, y)\n sx = np.sqrt(sigmas[j][0,0])\n sy = np.sqrt(sigmas[j][1,1])\n sxy = sigmas[j][1,0]\n z = bivariate_normal(xx, yy, sx, sy, means[j,0], means[j,1], sxy)\n cs = plt.contour(xx, yy, z, [0.01])\n\nif __name__ == '__main__':\n X = np.loadtxt('EMGaussian.data')\n Xtest = np.loadtxt('EMGaussian.test')\n K = 4\n iterations = 40\n\n assignments, centers, _ = kmeans.kmeans_best_of_n(X, K, n_trials=5)\n for k in range(K):\n centers[k].sigma2 = 1.\n\n # Isotropic\n tau, obs_distr, pi, ll_train_iso, ll_test_iso = \\\n em(X, centers, assignments, n_iter=iterations, Xtest=Xtest)\n plot_em(X, tau, obs_distr, contours=True)\n plt.title('EM with covariance matrices proportional to identity')\n\n # General\n new_centers = [distributions.Gaussian(c.mean, c.sigma2*np.eye(2)) \\\n for c in centers]\n tau, obs_distr, pi, ll_train_gen, ll_test_gen = \\\n em(X, new_centers, assignments, n_iter=iterations, Xtest=Xtest)\n plot_em(X, tau, obs_distr, contours=True)\n plt.title('EM with general covariance matrices')\n\n # log-likelihood plot\n plt.figure()\n plt.plot(ll_train_iso, label='isotropic, training')\n plt.plot(ll_test_iso, label='isotropic, test')\n plt.plot(ll_train_gen, label='general, training')\n plt.plot(ll_test_gen, label='general, test')\n plt.xlabel('iterations')\n plt.ylabel('log-likelihood')\n plt.title('Comparison of learning curves')\n plt.legend()\n",
"\"\"\" The Convex Semi Non-negative Matrix Factorization (non-GPU accelerate) \"\"\"\nfrom numpy.testing import *\nimport numpy as np\nimport logging\nimport logging.config\nimport scipy.sparse\nimport scipy.io as spio\nimport matplotlib.pyplot as plt\nimport random\nimport dist\n\n__all__ = [\"PyMFBase\"]\n_EPS = np.finfo(float).eps # In real case, this eps should be larger.\n\n\nclass PyMFBase:\n \"\"\" PyMF base class used in (almost) all matrix factorization methods\n PyMF Base Class. Does nothing useful apart from providing some basic methods. \"\"\"\n # some small value\n _EPS = _EPS\n\n def __init__(self, data, num_bases=4, **kwargs):\n \"\"\"\n \"\"\"\n\n def setup_logging():\n # create logger\n self._logger = logging.getLogger(\"pymf\")\n\n # add ch to logger\n if len(self._logger.handlers) < 1:\n # create console handler and set level to debug\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n # create formatter\n formatter = logging.Formatter(\"%(asctime)s [%(levelname)s] %(message)s\")\n\n # add formatter to ch\n ch.setFormatter(formatter)\n\n self._logger.addHandler(ch)\n\n setup_logging()\n\n # set variables\n self.data = data\n self._num_bases = num_bases\n\n # initialize H and W to random values\n self._data_dimension, self._num_samples = self.data.shape\n\n def residual(self):\n \"\"\" Returns the residual in % of the total amount of data\n Returns: residual (float)\n \"\"\"\n res = np.sum(np.abs(self.data - np.dot(self.W, self.H)))\n total = 100.0 * res / np.sum(np.abs(self.data))\n return total\n\n def frobenius_norm(self):\n \"\"\" Frobenius norm (||data - WH||) of a data matrix and a low rank approximation given by WH.\n Minimizing the Fnorm ist the most common optimization criterion for matrix factorization methods.\n Returns: frobenius norm: F = ||data - WH||\n \"\"\"\n # check if W and H exist\n if hasattr(self, 'H') and hasattr(self, 'W'):\n if scipy.sparse.issparse(self.data):\n tmp = self.data[:, :] - (self.W * self.H)\n tmp = tmp.multiply(tmp).sum()\n err = np.sqrt(tmp)\n else:\n err = np.sqrt(np.sum((self.data[:, :] - np.dot(self.W, self.H)) ** 2))\n else:\n err = None\n\n return err\n\n def _init_w(self):\n \"\"\" Initalize W to random values [0,1].\n \"\"\"\n # add a small value, otherwise nmf and related methods get into trouble as\n # they have difficulties recovering from zero.\n self.W = np.random.random((self._data_dimension, self._num_bases)) + 10 ** -4\n\n def _init_h(self):\n \"\"\" Initalize H to random values [0,1].\n \"\"\"\n self.H = np.random.random((self._num_bases, self._num_samples)) + 0.2\n\n def _update_h(self):\n \"\"\" Overwrite for updating H.\n \"\"\"\n pass\n\n def _update_w(self):\n \"\"\" Overwrite for updating W.\n \"\"\"\n pass\n\n def _converged(self, i):\n \"\"\"\n If the optimization of the approximation is below the machine precision,\n return True.\n\n Parameters\n ----------\n i : index of the update step\n\n Returns\n -------\n converged : boolean\n \"\"\"\n derr = np.abs(self.ferr[i] - self.ferr[i - 1]) / self._num_samples\n if derr < self._EPS:\n return True\n else:\n return False\n\n def factorize(self, niter=100, show_progress=False,\n compute_w=True, compute_h=True, compute_err=True):\n \"\"\" Factorize s.t. WH = data\n\n Parameters\n ----------\n niter : int\n number of iterations.\n show_progress : bool\n print some extra information to stdout.\n compute_h : bool\n iteratively update values for H.\n compute_w : bool\n iteratively update values for W.\n compute_err : bool\n compute Frobenius norm |data-WH| after each update and store\n it to .ferr[k].\n\n Updated Values\n --------------\n .W : updated values for W.\n .H : updated values for H.\n .ferr : Frobenius norm |data-WH| for each iteration.\n \"\"\"\n\n if show_progress:\n self._logger.setLevel(logging.INFO)\n else:\n self._logger.setLevel(logging.ERROR)\n\n # create W and H if they don't already exist\n # -> any custom initialization to W,H should be done before\n if not hasattr(self, 'W') and compute_w:\n self._init_w()\n\n if not hasattr(self, 'H') and compute_h:\n self._init_h()\n\n # Computation of the error can take quite long for large matrices,\n # thus we make it optional.\n if compute_err:\n self.ferr = np.zeros(niter)\n\n for i in range(niter):\n if compute_w:\n self._update_w()\n\n if compute_h:\n self._update_h()\n\n if compute_err:\n self.ferr[i] = self.frobenius_norm()\n self._logger.info('FN: %s (%s/%s)' % (self.ferr[i], i + 1, niter))\n else:\n self._logger.info('Iteration: (%s/%s)' % (i + 1, niter))\n\n # check if the err is not changing anymore\n if i > 1 and compute_err:\n if self._converged(i):\n # adjust the error measure\n self.ferr = self.ferr[:i]\n break\n\n\nclass Kmeans(PyMFBase):\n \"\"\"\n Kmeans(data, num_bases=4)\n\n K-means clustering. Factorize a data matrix into two matrices s.t.\n F = | data - W*H | is minimal. H is restricted to unary vectors, W\n is simply the mean over the corresponding samples in \"data\".\n\n Parameters\n ----------\n data : array_like, shape (_data_dimension, _num_samples)\n the input data\n num_bases: int, optional\n Number of bases to compute (column rank of W and row rank of H).\n 4 (default)\n\n Attributes\n ----------\n W : \"data_dimension x num_bases\" matrix of basis vectors\n H : \"num bases x num_samples\" matrix of coefficients\n ferr : frobenius norm (after calling .factorize())\n \"\"\"\n\n def _init_h(self):\n # W has to be present for H to be initialized\n self.H = np.zeros((self._num_bases, self._num_samples))\n self._update_h()\n\n def _init_w(self):\n # set W to some random data samples\n sel = random.sample(range(self._num_samples), self._num_bases)\n\n # sort indices, otherwise h5py won't work\n self.W = self.data[:, np.sort(sel)]\n\n def _update_h(self):\n # and assign samples to the best matching centers\n self.assigned = dist.vq(self.W, self.data)\n self.H = np.zeros(self.H.shape)\n self.H[self.assigned, range(self._num_samples)] = 1.0\n\n def _update_w(self):\n for i in range(self._num_bases):\n # cast to bool to use H as an index for data\n idx = np.array(self.H[i, :], dtype=np.bool)\n n = np.sum(idx)\n if n > 0:\n self.W[:, i] = np.sum(self.data[:, idx], axis=1) / n\n\n\nclass CNMF(PyMFBase):\n \"\"\"\n CNMF(data, num_bases=4)\n\n\n Convex NMF. Factorize a data matrix into two matrices s.t.\n F = | data - W*H | = | data - data*beta*H| is minimal. H and beta\n are restricted to convexity (beta >=0, sum(beta, axis=1) = [1 .. 1]).\n\n Parameters\n ----------\n data : array_like, shape (_data_dimension, _num_samples)\n the input data\n num_bases: int, optional\n Number of bases to compute (column rank of W and row rank of H).\n 4 (default)\n\n Attributes\n ----------\n W : \"data_dimension x num_bases\" matrix of basis vectors\n H : \"num bases x num_samples\" matrix of coefficients\n ferr : frobenius norm (after calling .factorize())\n\n\n The result is a set of coefficients acnmf_mdl.H, s.t. data = W * cnmf_mdl.H.\n \"\"\"\n\n # see .factorize() for the update of W and H\n # -> proper decoupling of W/H not possible ...\n\n def _init_h(self):\n if not hasattr(self, 'H'):\n # init basic matrices\n self.H = np.zeros((self._num_bases, self._num_samples))\n\n # initialize using k-means\n km = Kmeans(self.data[:, :], num_bases=self._num_bases)\n km.factorize(niter=10)\n assign = km.assigned\n\n num_i = np.zeros(self._num_bases)\n for i in range(self._num_bases):\n num_i[i] = len(np.where(assign == i)[0])\n\n self.H.T[range(len(assign)), assign] = 1.0\n self.H += 0.2 * np.ones((self._num_bases, self._num_samples))\n\n if not hasattr(self, 'G'):\n self.G = np.zeros((self._num_samples, self._num_bases))\n\n self.G[range(len(assign)), assign] = 1.0\n self.G += 0.01\n self.G /= np.tile(np.reshape(num_i[assign], (-1, 1)), self.G.shape[1])\n\n if not hasattr(self, 'W'):\n self.W = np.dot(self.data[:, :], self.G)\n\n def _init_w(self):\n pass\n\n def factorize(self, niter=10, compute_w=True, compute_h=True,\n compute_err=True, show_progress=False):\n \"\"\" Factorize s.t. WH = data.\n\n Parameters\n ----------\n niter : int\n number of iterations.\n show_progress : bool\n print some extra information to stdout.\n compute_h : bool\n iteratively update values for H.\n compute_w : bool\n iteratively update values for W.\n compute_err : bool\n compute Frobenius norm |data-WH| after each update and store\n it to .ferr[k].\n\n Updated Values\n --------------\n .W : updated values for W.\n .H : updated values for H.\n .ferr : Frobenius norm |data-WH| for each iteration.\n \"\"\"\n\n if not hasattr(self, 'W'):\n self._init_w()\n\n if not hasattr(self, 'H'):\n self._init_h()\n\n def separate_positive(m):\n return (np.abs(m) + m) / 2.0\n\n def separate_negative(m):\n return (np.abs(m) - m) / 2.0\n\n if show_progress:\n self._logger.setLevel(logging.INFO)\n else:\n self._logger.setLevel(logging.ERROR)\n\n XtX = np.dot(self.data[:, :].T, self.data[:, :])\n XtX_pos = separate_positive(XtX)\n XtX_neg = separate_negative(XtX)\n\n self.ferr = np.zeros(niter)\n # iterate over W and H\n\n for i in range(niter):\n # update H\n XtX_neg_x_W = np.dot(XtX_neg, self.G)\n XtX_pos_x_W = np.dot(XtX_pos, self.G)\n\n if compute_h:\n H_x_WT = np.dot(self.H.T, self.G.T)\n ha = XtX_pos_x_W + np.dot(H_x_WT, XtX_neg_x_W)\n hb = XtX_neg_x_W + np.dot(H_x_WT, XtX_pos_x_W) + 10 ** -9\n self.H = (self.H.T * np.sqrt(ha / hb)).T\n\n # update W\n if compute_w:\n HT_x_H = np.dot(self.H, self.H.T)\n wa = np.dot(XtX_pos, self.H.T) + np.dot(XtX_neg_x_W, HT_x_H)\n wb = np.dot(XtX_neg, self.H.T) + np.dot(XtX_pos_x_W, HT_x_H) + 10 ** -9\n\n self.G *= np.sqrt(wa / wb)\n self.W = np.dot(self.data[:, :], self.G)\n\n if compute_err:\n self.ferr[i] = self.frobenius_norm()\n self._logger.info('FN: %s (%s/%s)' % (self.ferr[i], i + 1, niter))\n else:\n self._logger.info('Iteration: (%s/%s)' % (i + 1, niter))\n\n if i > 1 and compute_err:\n if self._converged(i):\n self.ferr = self.ferr[:i]\n break\n\n\nclass TestCNMF:\n\n # mat = spio.loadmat('cereb_avrgDataStruct.mat')\n # betaValueStructure = mat['T']\n # betaValueMatrix = betaValueStructure[0, 0]\n # print(betaValueMatrix['data'].shape)\n\n #data = np.random.rand(13, 25)\n #data = betaValueMatrix['data']\n\n data = np.array([[0, 1.0, 0.5],\n [1.0, 0, 0.5]])\n\n def test_cnmf(self):\n\n mdl = CNMF(self.data, num_bases=10)\n # nmf forms a cone in the input space, but it is unlikely to hit the\n # cone exactly.\n mdl.factorize(niter=100)\n residual_y = mdl.ferr\n plot_x = len(residual_y)\n print(\"ferr: \", residual_y, \"\\n\")\n print(plot_x)\n plt.plot(residual_y)\n\n plt.ylabel('residual value by iteration')\n plt.show()\n\n plt.imshow(mdl.H, aspect='auto')\n plt.show()\n\n # the reconstruction quality should be close to perfect\n rec = mdl.frobenius_norm()\n #assert_array_almost_equal(0.0, rec, decimal=1)\n\n # and H is not allowed to have <0 values\n l = np.where(mdl.H < 0)[0]\n assert(len(l) == 0)\n\n print(\"Basis Vector F: \", mdl.W, \"\\n\")\n print(\"Coefficients Matrix G: \", mdl.H, \"\\n\")\n print(\"Residual Value: \", rec)\n\n\ndef main():\n\n A = TestCNMF()\n A.test_cnmf()\n\n\nif __name__ == '__main__':\n main()",
"from sklearn import datasets\nimport matplotlib\nfrom sklearn.cluster import SpectralClustering, AgglomerativeClustering, KMeans\nimport matplotlib.pyplot as plt\nimport scipy.io as spio\nimport numpy as np\nfrom scipy.spatial.distance import pdist\nfrom sklearn.metrics.pairwise import cosine_distances, cosine_similarity\nimport nibabel as nb\nfrom nibabel.gifti import giftiio\n\nwb_dir = \"D:/data/sc1/surfaceWB/group32k/\"\nidv_dir = \"D:/python_workspace/brain_parcellation_project/data/\"\nsubj_name = ['s01', 's02', 's03', 's04', 's05', 's06', 's07', 's08', 's09', 's10', 's11',\n 's12', 's13', 's14', 's15', 's16', 's17', 's18', 's19', 's20', 's21', 's22', 's23', 's24',\n 's25', 's26', 's27', 's28', 's29', 's30', 's31']\ngoodsubj = [2, 3, 4, 6, 8, 9, 10, 12, 14, 15, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31]\nresolution = 2562\nhem = ['L', 'R']\nD = ['A', 'B']\nexp = [1, 2]\n\n# # --------------------------- Parcellation for each subject ------------------------------ #\n# Find the index of medial wall\n# gifti_image = nb.load(wb_dir + \"Icosahedron-%d.32k.L.label.gii\" % resolution)\n# img_data = [x.data for x in gifti_image.darrays]\n# labels = np.reshape(img_data, (len(img_data[0]), 1))\n# nanIndex_L = np.where(labels == 0)[0]\n#\n# gifti_image = nb.load(wb_dir + \"Icosahedron-%d.32k.R.label.gii\" % resolution)\n# img_data = [x.data for x in gifti_image.darrays]\n# labels = np.reshape(img_data, (len(img_data[0]), 1))\n# nanIndex_R = np.where(labels == 0)[0]\n#\n# # Making medial wall mask 32k\n# MAP_L = np.empty((32492, 1))\n# MAP_L[:] = np.nan\n# MAP_L[nanIndex_L, :] = 0\n#\n# MAP_R = np.empty((32492, 1))\n# MAP_R[:] = np.nan\n# MAP_R[nanIndex_R, :] = 0\n# MAP = np.concatenate((MAP_L, MAP_R), axis=0)\n#\n# # Main loop\n# for sub in range(len(goodsubj)):\n# for ts in exp:\n# Data_L = []\n# Data_R = []\n# rawData_L = []\n# rawData_R = []\n# for h in range(len(hem)):\n# # Loading data\n# mat = spio.loadmat(idv_dir + subj_name[goodsubj[sub]-1] + \"/%s.%s.swcon.exp%d.32k.mat\" % (subj_name[goodsubj[sub]-1], hem[h], ts))\n# groupData = mat['data']\n# # gifti_data = nb.load(idv_dir + subj_name[goodsubj[sub]-1] + \"/%s.%s.swcon.32k.func.gii\" % (subj_name[goodsubj[sub]-1], hem[h]))\n# # img_data = [x.data for x in gifti_data.darrays]\n# # data = np.reshape(img_data, (len(img_data), len(img_data[0])))\n# # groupData = data.transpose()\n#\n# verticesIdx = np.reshape(np.arange(len(groupData)), (len(groupData), 1))\n# groupData_labels = np.concatenate((groupData, labels, verticesIdx), axis=1)\n# # groupData_noNaN = np.delete(groupData_labels, nanIndex, 0)\n#\n# groupData_reduced = np.empty((1, groupData.shape[1]))\n# groupData_reduced[:] = np.nan\n# for ico in np.unique(labels[:, 0]):\n# if ico != 0:\n# curr_tessellation = groupData_labels[groupData_labels[:, groupData.shape[1]] == ico]\n# if curr_tessellation.shape[0] != 0:\n# curr_avrg = np.reshape(curr_tessellation[:, 0:groupData.shape[1]].mean(0), (1, groupData.shape[1]))\n# groupData_reduced = np.append(groupData_reduced, curr_avrg, axis=0)\n#\n# groupData_reduced = np.delete(groupData_reduced, 0, 0)\n#\n# if h == 0:\n# Data_L = np.copy(groupData_reduced)\n# rawData_L = np.copy(groupData)\n# elif h == 1:\n# Data_R = np.copy(groupData_reduced)\n# rawData_R = np.copy(groupData)\n#\n# groupData = np.concatenate((Data_L, Data_R), axis=0)\n# raw_groupData = np.concatenate((rawData_L, rawData_R), axis=0)\n# affinity_matrix = cosine_similarity(groupData) + 1\n# print(affinity_matrix.shape)\n#\n# for k in range(7, 31):\n# print('Running cluster %d ...' % k + 'for subject %d ' % goodsubj[sub] + 'of experiment %d.' % ts)\n# curr_map = np.copy(MAP)\n# clustering = SpectralClustering(n_clusters=k, eigen_solver='arpack', n_init=50, affinity=\"precomputed\", n_jobs=-1).fit(affinity_matrix)\n# # Make the clustering result bestG type\n# clustering_result = clustering.labels_ + 1\n#\n# raw_groupData[np.isnan(raw_groupData)] = 0\n# lookupTable = cosine_similarity(raw_groupData, groupData) + 1\n#\n# for idx in range(len(raw_groupData)):\n# this_label = clustering_result[np.argmax(lookupTable[idx])]\n# if np.isnan(curr_map[idx][0]):\n# curr_map[idx][0] = this_label\n#\n# parcels = np.split(curr_map, 2)\n# parcels_L = parcels[0]\n# parcels_R = parcels[1]\n#\n# outfilename = \"../Spectral clustering/subject_clustering_results/sc%d/%s/spec_cosine_sc%d_all_%d.mat\" % (ts, subj_name[goodsubj[sub]-1], ts, k)\n# spio.savemat(outfilename, {\"parcels_L\": parcels_L, \"parcels_R\": parcels_R})\n\n# # --------------------------- Parcellation for group average ------------------------------ #\nmat = spio.loadmat(\"../data/betas_cortex/vertices/group_swcon.mat\")\nraw_groupData = np.concatenate((mat['A'], mat['B']), axis=0)\nraw_groupData = raw_groupData[:, 29:62]\n\nMAP_L = np.empty((32492, 1))\nMAP_L[:] = np.nan\n\nMAP_R = np.empty((32492, 1))\nMAP_R[:] = np.nan\ngroupData_L = []\ngroupData_R = []\n\nfor h in range(len(hem)):\n # Find the index of medial wall\n gifti_image = nb.load(wb_dir + \"Icosahedron-%d.32k.%s.label.gii\" % (resolution, hem[h]))\n img_data = [x.data for x in gifti_image.darrays]\n labels = np.reshape(img_data, (len(img_data[0]), 1))\n nanIndex = np.where(labels == 0)[0]\n\n # Loading data\n groupData = np.copy(mat[D[h]][:, 29:62])\n # groupData = mat['avrgBeta_sc12_%s' % hem[h]]\n # nanIdx = mat['nanIndex_%s' % hem[h]] - 1\n # nanIdx = np.reshape(nanIdx, (nanIdx.shape[0], ))\n # nanIndex = np.concatenate((nanIndex, nanIdx[~np.isin(nanIdx, nanIndex)]))\n\n verticesIdx = np.reshape(np.arange(len(groupData)), (len(groupData), 1))\n groupData_labels = np.concatenate((groupData, labels, verticesIdx), axis=1)\n groupData_noNaN = np.delete(groupData_labels, nanIndex, 0)\n\n if h == 0:\n MAP_L[nanIndex, :] = 0\n elif h == 1:\n MAP_R[nanIndex, :] = 0\n\n groupData_reduced = np.empty((1, groupData.shape[1]))\n groupData_reduced[:] = np.nan\n for ico in np.unique(labels[:, 0]):\n if ico != 0:\n curr_tessellation = groupData_noNaN[groupData_noNaN[:, groupData.shape[1]] == ico]\n if curr_tessellation.shape[0] != 0:\n curr_avrg = np.reshape(curr_tessellation[:, 0:groupData.shape[1]].mean(0), (1, groupData.shape[1]))\n groupData_reduced = np.append(groupData_reduced, curr_avrg, axis=0)\n\n groupData_reduced = np.delete(groupData_reduced, 0, 0)\n\n if h == 0:\n groupData_L = np.copy(groupData_reduced)\n elif h == 1:\n groupData_R = np.copy(groupData_reduced)\n\ngroupData = np.concatenate((groupData_L, groupData_R), axis=0)\n\naffinity_matrix = cosine_similarity(groupData) + 1\nprint(affinity_matrix.shape)\n\nfor k in range(7, 31):\n print('Running cluster %d ...' % k)\n curr_map_L = np.copy(MAP_L)\n curr_map_R = np.copy(MAP_R)\n curr_map = np.concatenate((curr_map_L, curr_map_R), axis=0)\n clustering = SpectralClustering(n_clusters=k, eigen_solver='arpack', n_init=100, affinity=\"precomputed\", n_jobs=-1).fit(affinity_matrix)\n # Make the clustering result bestG type\n clustering_result = clustering.labels_ + 1\n\n raw_groupData[np.isnan(raw_groupData)] = 0\n lookupTable = cosine_similarity(raw_groupData, groupData) + 1\n\n for idx in range(len(raw_groupData)):\n this_label = clustering_result[np.argmax(lookupTable[idx])]\n if np.isnan(curr_map[idx][0]):\n curr_map[idx][0] = this_label\n\n parcels = np.split(curr_map, 2)\n parcels_L = parcels[0]\n parcels_R = parcels[1]\n\n outfilename = \"../Spectral clustering/cortex_clustering_results/group/sc2/spec_cosine_sc2_%d.mat\" % k\n spio.savemat(outfilename, {\"parcels_L\": parcels_L, \"parcels_R\": parcels_R})\n\n\n# # Test different eigen_solver\n# clustering = SpectralClustering(n_clusters=10,\n# eigen_solver='lobpcg',\n# affinity=\"precomputed\",\n# n_jobs=-1).fit(affinity.affinity_matrix_ * 2)\n#\n# # Make the clustering result bestG type\n# clustering_result = np.zeros((25275, 10))\n# for i in range(clustering_result.shape[0]):\n# clustering_result[i, clustering.labels_[i]] = 0.4\n#\n# spio.savemat('spec_sc1_bestG.mat', {\"bestG\": clustering_result})\n# plt.imshow(clustering.affinity_matrix_, aspect='auto')\n# plt.show()\n# np.savetxt(\"spec_sc1_bestG_affinity_rbf_lobpcg.csv\", clustering.affinity_matrix_, delimiter=',', newline=',')\n# # spio.savemat('spec_sc1_bestG_affinity.mat', {\"affinityMatrix\": clustering.affinity_matrix_})\n#\n# # print(clustering, clustering.affinity_matrix_.shape, clustering.affinity_matrix_)\n# # print(X[:, 0], y.shape)\n# print(clustering)\n\n# # ---------------------------- SC 2 ----------------------------- #\n# mat = spio.loadmat('../groupData_sc2.mat')\n# groupData = mat['X_C']\n#\n# affinity_matrix = cosine_similarity(groupData.transpose())\n# print(affinity_matrix.shape, affinity_matrix.min(), affinity_matrix.max())\n#\n# # clustering = SpectralClustering(n_clusters=10,\n# # eigen_solver='arpack',\n# # affinity=\"nearest_neighbors\",\n# # n_neighbors=10,\n# # n_jobs=-1).fit(groupData.transpose() * 2)\n# # # print(affinity.labels_.shape, affinity.labels_)\n# # # # spio.savemat('clusters.mat', {\"Y\": clustering.labels_})\n#\n# clustering = SpectralClustering(n_clusters=10,\n# eigen_solver='arpack',\n# affinity=\"precomputed\",\n# n_jobs=-1).fit(affinity_matrix + 1)\n#\n# print(clustering.labels_.shape, clustering.labels_)\n#\n# # # clustering = AgglomerativeClustering(n_clusters=10,\n# # # affinity='euclidean',\n# # # memory=None,\n# # # connectivity=None,\n# # # compute_full_tree='auto',\n# # # linkage='ward',\n# # # pooling_func='deprecated').fit(groupData.transpose())\n# #\n# # print(clustering.labels_.shape, clustering.labels_)\n# #\n# # Make the clustering result bestG type\n# clustering_result = np.zeros((25275, 10))\n# for i in range(clustering_result.shape[0]):\n# clustering_result[i, clustering.labels_[i]] = 0.6\n#\n# spio.savemat('spec_sc2_bestG.mat', {\"bestG\": clustering_result})\n# print(clustering)\n# # spio.savemat('spec_sc2_bestG_affinity_10nn.mat', {\"affinityMatrix\": clustering.affinity_matrix_})\n#\n# # plt.imshow(clustering.affinity_matrix_, aspect='auto')\n# # plt.show()\n# # Plotting the clustering result\n# # colors = ['red', 'blue']\n# # plt.figure()\n# # # plt.scatter(X[0, 0], y[0, 1])\n# # plt.scatter(X[:, 0], X[:, 1], c=clustering.labels_, marker='.', cmap=matplotlib.colors.ListedColormap(colors))\n# # plt.title('K = 2')\n# # plt.show()\n"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.dot",
"numpy.sqrt",
"matplotlib.pyplot.plot",
"numpy.arange",
"numpy.eye",
"numpy.argmax",
"numpy.zeros",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"numpy.loadtxt",
"numpy.meshgrid",
"numpy.sum",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.scatter",
"numpy.ones",
"matplotlib.pyplot.contour",
"matplotlib.pyplot.xlabel",
"matplotlib.mlab.bivariate_normal",
"numpy.vstack"
],
[
"numpy.dot",
"matplotlib.pyplot.imshow",
"numpy.random.random",
"numpy.abs",
"numpy.sqrt",
"numpy.reshape",
"numpy.sort",
"numpy.finfo",
"matplotlib.pyplot.plot",
"numpy.ones",
"numpy.where",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
],
[
"numpy.split",
"numpy.unique",
"numpy.isnan",
"scipy.io.loadmat",
"sklearn.metrics.pairwise.cosine_similarity",
"sklearn.cluster.SpectralClustering",
"numpy.concatenate",
"numpy.copy",
"numpy.delete",
"numpy.append",
"numpy.argmax",
"scipy.io.savemat",
"numpy.where",
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
pozhijisi/Feature-Extraction-for-Speech-Recognition
|
[
"8c6fa2859e2ef6f91eb39c5b563dd25ffd02089b",
"8c6fa2859e2ef6f91eb39c5b563dd25ffd02089b"
] |
[
"feature_extraction_template.py",
"utils/deltas_np.py"
] |
[
"import tensorflow as tf\nimport wavefile\nimport numpy as np\n\nimport sys\nsys.path.append(\"./utils\")\n\nimport fft2melmx\nimport deltas\nimport extract_window\n\n\n# BLOCK: input and output files/folders\n\n\n# feature extraction arguments\nepsilon = 1e-40\n\nnum_bins = 80\n\nsamp_freq = 16000\nlow_freq = 20\nhigh_freq = None\n\nwindow_opts_dict = {}\n\nwindow_opts_dict['frame_shift_ms'] = 10.0\nwindow_opts_dict['frame_length_ms'] = 25.0\nwindow_opts_dict['dither'] = 1.0\nwindow_opts_dict['preemph_coeff'] = 0.97\nwindow_opts_dict['remove_dc_offset'] = True\nwindow_opts_dict['window_type'] = \"povey\"\nwindow_opts_dict['round_to_power_of_two'] = True\nwindow_opts_dict['blackman_coeff'] = 0.42\nwindow_opts_dict['snip_edges'] = True\n\nwindow_opts_dict['window_shift'] = int(samp_freq * 0.001 * window_opts_dict['frame_shift_ms'])\nwindow_opts_dict['window_size'] = int(samp_freq * 0.001 * window_opts_dict['frame_length_ms'])\nwindow_opts_dict['padded_window_size'] = extract_window.shift_bit_length(window_opts_dict['window_size'])\n\n# generate mel weights\nmel_wts = np.array(fft2melmx.fft2melmx(window_opts_dict['padded_window_size'], samp_freq, num_bins, 1.0, low_freq, high_freq, True, 'const')[0], np.float32)\nmel_wts = mel_wts.T\n\n\n# define TensorFlow graph\nx = tf.placeholder(tf.float32, shape=[None, 80])\n\nlog_mel = tf.log(x + epsilon) # log(mel) features\n\nfeature_delta = deltas.deltas(log_mel, 2, 80)\nfeature_delta_delta = deltas.deltas(feature_delta, 2, 80)\n\nfeature_deltas = tf.concat([log_mel, feature_delta, feature_delta_delta], axis=1)\n\nfeature_out = feature_deltas - tf.reduce_mean(feature_deltas, axis=0, keep_dims=True) # a mean normalization on the deltas features is typically used to normalize the magnitudes of input features\n\n\n# extract features\nwith tf.Session() as sess:\n\t\n\t# BLOCK: get wav_file, the name of the wave file to be processed\n\t\n\twith wavefile.WaveReader(wav_file) as wav_reader:\n\n\t\t# sanity checks\n\t\tchannels = wav_reader.channels\n\t\tassert channels == 1\n\t\tassert wav_reader.samplerate == 16000\n\n\t\tsamples = wav_reader.frames\n\t\twav_data = np.empty((channels, samples), dtype=np.float32, order='F')\n\t\twav_reader.read(wav_data)\n\t\twav_data = np.squeeze(wav_data)\t\t\n\n\twav_data = wav_data * np.iinfo(np.int16).max\n\n\twindowed_utterance = extract_window.extract_window(0, wav_data, window_opts_dict)\n\n\tffted_utterance = np.fft.fft(windowed_utterance) \n\n\tpower_spectrum = np.square(np.absolute(ffted_utterance).astype(np.float32)) # note here we use the power spectrum\n\tpower_spectrum_nodup = power_spectrum[:, 0:window_opts_dict['padded_window_size']//2+1] # remove redundant dimensions\n\n\tmel_spectrum = np.matmul(power_spectrum_nodup, mel_wts)\n\n\tfeature_to_store = sess.run(feature_out, feed_dict={x: mel_spectrum}).astype(np.float32) # the output is the mean normalized deltas features\n\n\t# BLOCK: save feature_to_store\n",
"import numpy as np\r\n\r\n\r\ndef deltas(feat, N):\r\n\tif N < 1:\r\n\t\traise ValueError('N must be an integer >= 1')\r\n\r\n\tdenominator = 2 * sum([i**2 for i in range(1, N+1)])\r\n\r\n\tNUMFRAMES = len(feat)\r\n\r\n\tdelta_feat = np.empty_like(feat)\r\n\r\n\tpadded = np.concatenate((np.tile(feat[0,:],(N,1)), feat, np.tile(feat[-1,:],(N,1))), axis=0)\r\n\tfor t in range(NUMFRAMES):\r\n\t\tdelta_feat[t] = np.dot(np.arange(-N, N+1), padded[t : t+2*N+1])\r\n\tdelta_feat /= denominator\r\n\r\n\treturn delta_feat\r\n"
] |
[
[
"numpy.absolute",
"tensorflow.concat",
"numpy.fft.fft",
"tensorflow.reduce_mean",
"numpy.squeeze",
"numpy.matmul",
"tensorflow.placeholder",
"tensorflow.log",
"tensorflow.Session",
"numpy.iinfo",
"numpy.empty"
],
[
"numpy.empty_like",
"numpy.arange",
"numpy.tile"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Wilder-Wonka/Coloring-greyscale-images
|
[
"84e6ac0482fab00201055d5580e64c36c02fc876"
] |
[
"GAN-version/lib/data_utils.py"
] |
[
"import numpy as np\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\nfrom keras.preprocessing import image\nimport tensorflow as tf\nfrom keras.callbacks import TensorBoard\nfrom keras.layers import Input, Dense\nfrom keras.models import Model\nimport os\nfrom skimage.transform import resize, rotate, rescale\nfrom skimage.color import rgb2lab, lab2rgb, rgb2gray, gray2rgb\nfrom skimage.io import imsave\nimport random\n\n\ndef turn_filename_into_image(filenames, batch_size, width, height, img_dir):\n \n empty_x = []\n rot_value = random.randint(-20,20)\n flip_lr = bool(random.getrandbits(1))\n flip_ud = bool(random.getrandbits(1))\n \n for name in filenames:\n image_x = img_to_array(load_img(img_dir + name, target_size=(width, height)))\n image_x = np.array(image_x, dtype='float32')\n image_x = (1.0/(255./2))*image_x - 1\n \n image_x = rotate(image_x, rot_value, mode='reflect')\n\n if flip_lr:\n image_x = np.fliplr(image_x)\n \n empty_x.append(image_x)\n \n empty_x = np.array(empty_x, dtype='float32')\n lab_batch = rgb2lab(empty_x)\n X_batch = lab_batch[:,:,:,0] / 100\n X_batch = X_batch.reshape(X_batch.shape+(1,))\n Y_batch = lab_batch[:,:,:,1:] / 128\n \n return np.array(X_batch, dtype='float32'), np.array(Y_batch, dtype='float32')\n\n\ndef random_image_index(dataset_len, batchsize):\n start = random.randint(0,(dataset_len - (batchsize + 1)))\n end = start + batchsize\n return start, end\n\ndef generate_training_images(filenames, batch_size, dataset_len, width, height, img_dir):\n \n start, end = random_image_index(dataset_len, batch_size)\n names = filenames[start:end]\n x, y = turn_filename_into_image(names, batch_size, width, height, img_dir)\n x_and_y = np.concatenate([x, y], axis=-1)\n \n return x, y, x_and_y\n\ndef generator(X, img_dir, batch_size, dataset_len, width, height):\n while True:\n x, y, x_and_y = generate_training_images(X, batch_size, dataset_len, width, height, img_dir)\n yield x, y, x_and_y\n\ndef generate_label_data(batch_size, output_size_pred, output_size_features):\n\n fake_labels = np.zeros((batch_size, output_size_pred, 1))\n true_labels = np.ones((batch_size, output_size_pred, 1))\n placeholder_input = np.zeros((batch_size, output_size_features, 1))\n \n return fake_labels, true_labels, placeholder_input\n\n\ndef save_each_image(colored_layers, BW_layer, cycle, nr, path, ending):\n \n cur = np.zeros((128, 128, 3))\n cur[:,:,0] = BW_layer[:,:,0] * 100\n cur[:,:,1:] = colored_layers * 128\n imsave(os.path.join(path, cycle + nr + ending), lab2rgb(cur))\n\ndef save_sample_images(colored_layers, BW_layer, cycle, path):\n for i in range(len(colored_layers)):\n save_each_image(colored_layers[i], BW_layer[i], cycle, str(i), path, '-gen.png')\n\n \ndef write_log(callback, names, logs, batch_no):\n for name, value in zip(names, logs):\n summary = tf.Summary()\n summary_value = summary.value.add()\n summary_value.simple_value = value\n summary_value.tag = name\n callback.writer.add_summary(summary, batch_no)\n callback.writer.flush()\n"
] |
[
[
"numpy.fliplr",
"numpy.ones",
"numpy.concatenate",
"tensorflow.Summary",
"numpy.array",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
chienerh/OverlapNet
|
[
"5e40476444cb0a950ff21f3343017426c6e6415e"
] |
[
"src/two_heads/ImagePairOverlapFunctionAngleOrientationSequence.py"
] |
[
"#!/usr/bin/env python3\n# Developed by Xieyuanli Chen and Thomas Läbe\n# This file is covered by the LICENSE file in the root of this project.\n# Brief: A generator which generates batches for keras training: Special version\nimport os\nimport random\nimport numpy as np\n\nfrom keras.utils import Sequence\n\n\nclass ImagePairOverlapFunctionAngleOrientationSequence(Sequence):\n \"\"\" This class is responsible for loading training/validation data. It\n can be used as keras generator object in e.g. model.fit_generator.\n \"\"\"\n \n def __init__(self, image_path, imgfilenames1, imgfilenames2, dir1, dir2, overlap, function_angle, orientation,\n network_output_size, batch_size, height, width, no_channels=4,\n use_depth=True, use_normals=True, use_class_probabilities=False, use_class_probabilities_pca=False,\n use_intensity=False, rotate_data=0):\n \"\"\" Initialize the dataset.\n Args:\n image_patch: Path where to find all the images. This is the folder which\n includes the subfolders 'depth_data', 'normal_data', 'semantic_data', ...\n imgfilenames1, imgfilenames2: a list of filenames of the images. If\n imgfilenames2 is empty, only one leg is\n assumed and will be generated by __getitem__()\n imgfilename1[i] and imgfilename2[i] build a pair.\n dir1, dir2: sequence directory names for imgfilenames1, imgfilenames2.\n Two lists of the same size as imgfilenames1 and imgfilenames2\n which contain the name of the dataset directory. e.g.\n dir1[0]/depth_data/imgfilenames1[0].png\n overlap: true ouput: a nx1 numpy array with the overlap (0..1). Same length as\n imgfilename1 and imgfilename2\n function_angle: true ouput2: a nx1 numpy array with the function angle (0..1). Same length as\n imgfilename1 and imgfilename2\n orientation: true output position of the peak in the network output which shows the relative rotation of\n the pair (around vertical axis). nx1, same length as overlap\n network_output_size: The network puts out a 1xM vector with ideally one peak, M is given here \n height and width: size of the input images of the network\n no_channels: number of channels of the input of the network, default 4\n use_depth, use_normals, use_class_probabilities: Booleans which define\n whether to use depth, normals, class probabilies. Defaults: True, True, False\n rotate_data:\n 0: no rotation\n 1: rotate every \"right\" image of a pair randomly between 0 and 360\n (That actually means shift the image). The sequence of random rotations\n is the same for every epoch, thus every pair is shifted always with the\n same amount.\n 2: rotate every \"right\" image of a pair randomly between 0 and 360\n (That actually means shift the image). Use a different shift for different\n epochs even for the same pair. The sequence of random numbers is mainly the\n same every time this class is initialized. (Due to threading, it may\n change for some pairs)\n Default:0\n \"\"\"\n self.image_path = image_path\n self.batch_size = batch_size\n self.imgfilenames1 = imgfilenames1\n self.imgfilenames2 = imgfilenames2\n self.dir1 = dir1\n self.dir2 = dir2\n self.overlap = overlap\n self.function_angle = function_angle\n self.orientation = orientation\n self.network_output_size = network_output_size\n # number of pairs\n self.n = overlap.size\n self.height = height\n self.width = width\n self.no_channels = no_channels\n self.use_depth = use_depth\n self.use_normals = use_normals\n self.use_class_probabilities = use_class_probabilities\n self.use_class_probabilities_pca = use_class_probabilities_pca\n self.use_intensity = use_intensity\n self.rotate_data = rotate_data\n self.do_rotation = False\n if self.rotate_data > 0:\n random.seed(1234)\n self.do_rotation = True\n self.random_rotate = np.array([\n random.randint(0, self.width) for i in range(0, self.n)])\n \n def __len__(self):\n \"\"\" Returns number of batches in the sequence. (overwritten method)\n \"\"\"\n return int(np.ceil(self.n / float(self.batch_size)))\n \n def __getitem__(self, idx):\n \"\"\" Get a batch. (overwritten method)\n \"\"\"\n if idx == 0 and self.rotate_data == 2:\n # new random values\n self.random_rotate = np.array([\n random.randint(0, self.width) for i in range(0, self.n)])\n \n maxidx = (idx + 1) * self.batch_size\n size = self.batch_size\n if maxidx > self.n:\n maxidx = self.n\n size = maxidx - idx * self.batch_size\n batch_f1 = self.imgfilenames1[idx * self.batch_size: maxidx]\n dir_f1 = self.dir1[idx * self.batch_size: maxidx]\n x1 = np.zeros((size, self.height, self.width, self.no_channels))\n \n if self.imgfilenames2:\n batch_f2 = self.imgfilenames2[idx * self.batch_size: maxidx]\n dir_f2 = self.dir2[idx * self.batch_size: maxidx]\n x2 = np.zeros((size, self.height, self.width, self.no_channels))\n \n for i in range(0, size):\n self.prepareOneInput(x1, i, batch_f1, dir_f1)\n if self.imgfilenames2:\n self.prepareOneInput(x2, i, batch_f2, dir_f2, idx * size + i, self.do_rotation)\n \n y_overlap = self.overlap[idx * self.batch_size: maxidx]\n y_function_angle = self.function_angle[idx * self.batch_size: maxidx]\n y_orientation = self.orientation[idx * self.batch_size: maxidx]\n y = []\n \n for idx in range(len(y_overlap)):\n y_item = np.zeros(self.network_output_size)\n y_item[int(y_orientation[idx])] = y_function_angle[idx] # y_overlap[idx]\n y.append(y_item)\n \n y = np.asarray(y)\n \n if self.imgfilenames2:\n return ([x1, x2], [np.hstack((y_overlap, y_function_angle)), y])\n else:\n return ([x1], y)\n \n def prepareOneInput(self, x1, i, batch_f1, dir_f1, totalidx=0, rotate_data=False):\n \"\"\" Internal function to generate input for one set of images\n Args:\n x1: n x w x h x chan array: The complete input. (input and ouput)\n i: The index (first dimension of x1) where to put the current image set\n batch_f1: filename prefixes of the current batch. batch_f1[i] is used.\n dir_f1 : dataset directory names for batch_f1\n totalidx: the current index in the whole set of pairs, Used only for\n rotate_data.\n rotate_data: If True, the output is shifted along width axis arbitrarly\n Returns: nothing, output is in x1\n \"\"\"\n channelidx = 0\n if self.use_depth:\n # Depth map == first channel\n f = os.path.join(self.image_path, dir_f1[i], 'depth', batch_f1[i] + '.npy')\n try:\n img1 = np.load(f)\n except IOError: \n raise Exception('Could not read depth image %s' % f)\n \n x1[i, :, :, channelidx] = img1\n channelidx += 1\n \n if self.use_normals:\n # normal map == channel 1..3\n f = os.path.join(self.image_path, dir_f1[i], 'normal', batch_f1[i] + '.npy')\n try:\n img1 = np.load(f)\n except IOError: \n raise Exception('Could not read normal image %s' % f)\n \n x1[i, :, :, channelidx:channelidx+3] = img1\n channelidx += 3\n \n if self.use_class_probabilities:\n if self.use_class_probabilities_pca:\n f = os.path.join(self.image_path, dir_f1[i], 'probability_pca', batch_f1[i] + '.npy')\n else:\n f = os.path.join(self.image_path, dir_f1[i], 'probability', batch_f1[i] + '.npy')\n \n try:\n img1 = np.load(f)\n\n if self.use_class_probabilities_pca:\n x1[i, :, :, channelidx:channelidx + 3] = img1\n channelidx += 3\n else:\n x1[i, :, :, channelidx:channelidx + 20] = img1\n channelidx += 20\n \n except IOError:\n # Try to read format .npz\n if self.use_class_probabilities_pca:\n f = os.path.join(self.image_path, dir_f1[i], 'probability_pca', batch_f1[i] + '.npz')\n else:\n f = os.path.join(self.image_path, dir_f1[i], 'probability', batch_f1[i] + '.npz')\n \n img1 = np.load(f)\n\n if self.use_class_probabilities_pca:\n x1[i, :, :, channelidx:channelidx + 3] = img1\n channelidx += 3\n else:\n x1[i, :, :, channelidx:channelidx + 20] = img1\n channelidx += 20\n\n if self.use_intensity:\n f = os.path.join(self.image_path, dir_f1[i], 'intensity', batch_f1[i] + '.npy')\n try:\n img1 = np.load(f)\n except IOError:\n # Try to read format .npz\n f = os.path.join(self.image_path, dir_f1[i], 'intensity', batch_f1[i] + '.npz')\n img1 = np.load(f)\n\n x1[i, :, :, channelidx] = img1\n channelidx += 1\n \n if rotate_data:\n shift = self.random_rotate[totalidx]\n # print(\"totalidx: %3d shift %3d\" % (totalidx, shift))\n x1[i, :, :, :] = np.roll(x1[i, :, :, :], shift, axis=1)\n"
] |
[
[
"numpy.hstack",
"numpy.asarray",
"numpy.load",
"numpy.zeros",
"numpy.roll"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
eahogue/pandas
|
[
"201ef537dd5003f28c0f56863da9fc817b70392a"
] |
[
"pandas/core/frame.py"
] |
[
"# pylint: disable=E1101\n# pylint: disable=W0212,W0703,W0622\n\"\"\"\nDataFrame\n---------\nAn efficient 2D container for potentially mixed-type time series or other\nlabeled data series.\n\nSimilar to its R counterpart, data.frame, except providing automatic data\nalignment and a host of useful data manipulation methods having to do with the\nlabeling information\n\"\"\"\nfrom __future__ import division\n\nimport collections\nimport functools\nimport itertools\nimport sys\nimport warnings\nfrom textwrap import dedent\n\nimport numpy as np\nimport numpy.ma as ma\n\nfrom pandas._libs import lib, algos as libalgos\n\nfrom pandas.util._decorators import (Appender, Substitution,\n rewrite_axis_style_signature,\n deprecate_kwarg)\nfrom pandas.util._validators import (validate_bool_kwarg,\n validate_axis_style_args)\n\nfrom pandas import compat\nfrom pandas.compat import (range, map, zip, lmap, lzip, StringIO, u,\n OrderedDict, PY36, raise_with_traceback,\n string_and_binary_types)\nfrom pandas.compat.numpy import function as nv\n\nfrom pandas.core.dtypes.cast import (\n maybe_upcast,\n cast_scalar_to_array,\n infer_dtype_from_scalar,\n maybe_cast_to_datetime,\n maybe_infer_to_datetimelike,\n maybe_convert_platform,\n maybe_downcast_to_dtype,\n invalidate_string_dtypes,\n coerce_to_dtypes,\n maybe_upcast_putmask,\n find_common_type)\nfrom pandas.core.dtypes.common import (\n is_object_dtype,\n is_extension_type,\n is_extension_array_dtype,\n is_datetime64_any_dtype,\n is_bool_dtype,\n is_integer_dtype,\n is_float_dtype,\n is_integer,\n is_scalar,\n is_dtype_equal,\n needs_i8_conversion,\n _get_dtype_from_object,\n ensure_float64,\n ensure_int64,\n ensure_platform_int,\n is_list_like,\n is_nested_list_like,\n is_iterator,\n is_sequence,\n is_named_tuple)\nfrom pandas.core.dtypes.generic import ABCSeries, ABCIndexClass, ABCMultiIndex\nfrom pandas.core.dtypes.missing import isna, notna\n\nfrom pandas.core import algorithms\nfrom pandas.core import common as com\nfrom pandas.core import nanops\nfrom pandas.core import ops\nfrom pandas.core.accessor import CachedAccessor\nfrom pandas.core.arrays import Categorical, ExtensionArray\nfrom pandas.core.config import get_option\nfrom pandas.core.generic import NDFrame, _shared_docs\nfrom pandas.core.index import (Index, MultiIndex, ensure_index,\n ensure_index_from_sequences)\nfrom pandas.core.indexes import base as ibase\nfrom pandas.core.indexes.datetimes import DatetimeIndex\nfrom pandas.core.indexes.period import PeriodIndex\nfrom pandas.core.indexing import (maybe_droplevels, convert_to_index_sliceable,\n check_bool_indexer)\nfrom pandas.core.internals import BlockManager\nfrom pandas.core.internals.construction import (\n masked_rec_array_to_mgr, get_names_from_index, to_arrays,\n reorder_arrays, init_ndarray, init_dict,\n arrays_to_mgr, sanitize_index)\nfrom pandas.core.series import Series\n\nfrom pandas.io.formats import console\nfrom pandas.io.formats import format as fmt\nfrom pandas.io.formats.printing import pprint_thing\n\nimport pandas.plotting._core as gfx\n\n# ---------------------------------------------------------------------\n# Docstring templates\n\n_shared_doc_kwargs = dict(\n axes='index, columns', klass='DataFrame',\n axes_single_arg=\"{0 or 'index', 1 or 'columns'}\",\n axis=\"\"\"axis : {0 or 'index', 1 or 'columns'}, default 0\n If 0 or 'index': apply function to each column.\n If 1 or 'columns': apply function to each row.\"\"\",\n optional_by=\"\"\"\n by : str or list of str\n Name or list of names to sort by.\n\n - if `axis` is 0 or `'index'` then `by` may contain index\n levels and/or column labels\n - if `axis` is 1 or `'columns'` then `by` may contain column\n levels and/or index labels\n\n .. versionchanged:: 0.23.0\n Allow specifying index or column level names.\"\"\",\n versionadded_to_excel='',\n optional_labels=\"\"\"labels : array-like, optional\n New labels / index to conform the axis specified by 'axis' to.\"\"\",\n optional_axis=\"\"\"axis : int or str, optional\n Axis to target. Can be either the axis name ('index', 'columns')\n or number (0, 1).\"\"\",\n)\n\n_numeric_only_doc = \"\"\"numeric_only : boolean, default None\n Include only float, int, boolean data. If None, will attempt to use\n everything, then use only numeric data\n\"\"\"\n\n_merge_doc = \"\"\"\nMerge DataFrame or named Series objects with a database-style join.\n\nThe join is done on columns or indexes. If joining columns on\ncolumns, the DataFrame indexes *will be ignored*. Otherwise if joining indexes\non indexes or indexes on a column or columns, the index will be passed on.\n\nParameters\n----------%s\nright : DataFrame or named Series\n Object to merge with.\nhow : {'left', 'right', 'outer', 'inner'}, default 'inner'\n Type of merge to be performed.\n\n * left: use only keys from left frame, similar to a SQL left outer join;\n preserve key order.\n * right: use only keys from right frame, similar to a SQL right outer join;\n preserve key order.\n * outer: use union of keys from both frames, similar to a SQL full outer\n join; sort keys lexicographically.\n * inner: use intersection of keys from both frames, similar to a SQL inner\n join; preserve the order of the left keys.\non : label or list\n Column or index level names to join on. These must be found in both\n DataFrames. If `on` is None and not merging on indexes then this defaults\n to the intersection of the columns in both DataFrames.\nleft_on : label or list, or array-like\n Column or index level names to join on in the left DataFrame. Can also\n be an array or list of arrays of the length of the left DataFrame.\n These arrays are treated as if they are columns.\nright_on : label or list, or array-like\n Column or index level names to join on in the right DataFrame. Can also\n be an array or list of arrays of the length of the right DataFrame.\n These arrays are treated as if they are columns.\nleft_index : bool, default False\n Use the index from the left DataFrame as the join key(s). If it is a\n MultiIndex, the number of keys in the other DataFrame (either the index\n or a number of columns) must match the number of levels.\nright_index : bool, default False\n Use the index from the right DataFrame as the join key. Same caveats as\n left_index.\nsort : bool, default False\n Sort the join keys lexicographically in the result DataFrame. If False,\n the order of the join keys depends on the join type (how keyword).\nsuffixes : tuple of (str, str), default ('_x', '_y')\n Suffix to apply to overlapping column names in the left and right\n side, respectively. To raise an exception on overlapping columns use\n (False, False).\ncopy : bool, default True\n If False, avoid copy if possible.\nindicator : bool or str, default False\n If True, adds a column to output DataFrame called \"_merge\" with\n information on the source of each row.\n If string, column with information on source of each row will be added to\n output DataFrame, and column will be named value of string.\n Information column is Categorical-type and takes on a value of \"left_only\"\n for observations whose merge key only appears in 'left' DataFrame,\n \"right_only\" for observations whose merge key only appears in 'right'\n DataFrame, and \"both\" if the observation's merge key is found in both.\n\nvalidate : str, optional\n If specified, checks if merge is of specified type.\n\n * \"one_to_one\" or \"1:1\": check if merge keys are unique in both\n left and right datasets.\n * \"one_to_many\" or \"1:m\": check if merge keys are unique in left\n dataset.\n * \"many_to_one\" or \"m:1\": check if merge keys are unique in right\n dataset.\n * \"many_to_many\" or \"m:m\": allowed, but does not result in checks.\n\n .. versionadded:: 0.21.0\n\nReturns\n-------\nDataFrame\n A DataFrame of the two merged objects.\n\nSee Also\n--------\nmerge_ordered : Merge with optional filling/interpolation.\nmerge_asof : Merge on nearest keys.\nDataFrame.join : Similar method using indices.\n\nNotes\n-----\nSupport for specifying index levels as the `on`, `left_on`, and\n`right_on` parameters was added in version 0.23.0\nSupport for merging named Series objects was added in version 0.24.0\n\nExamples\n--------\n\n>>> df1 = pd.DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'],\n... 'value': [1, 2, 3, 5]})\n>>> df2 = pd.DataFrame({'rkey': ['foo', 'bar', 'baz', 'foo'],\n... 'value': [5, 6, 7, 8]})\n>>> df1\n lkey value\n0 foo 1\n1 bar 2\n2 baz 3\n3 foo 5\n>>> df2\n rkey value\n0 foo 5\n1 bar 6\n2 baz 7\n3 foo 8\n\nMerge df1 and df2 on the lkey and rkey columns. The value columns have\nthe default suffixes, _x and _y, appended.\n\n>>> df1.merge(df2, left_on='lkey', right_on='rkey')\n lkey value_x rkey value_y\n0 foo 1 foo 5\n1 foo 1 foo 8\n2 foo 5 foo 5\n3 foo 5 foo 8\n4 bar 2 bar 6\n5 baz 3 baz 7\n\nMerge DataFrames df1 and df2 with specified left and right suffixes\nappended to any overlapping columns.\n\n>>> df1.merge(df2, left_on='lkey', right_on='rkey',\n... suffixes=('_left', '_right'))\n lkey value_left rkey value_right\n0 foo 1 foo 5\n1 foo 1 foo 8\n2 foo 5 foo 5\n3 foo 5 foo 8\n4 bar 2 bar 6\n5 baz 3 baz 7\n\nMerge DataFrames df1 and df2, but raise an exception if the DataFrames have\nany overlapping columns.\n\n>>> df1.merge(df2, left_on='lkey', right_on='rkey', suffixes=(False, False))\nTraceback (most recent call last):\n...\nValueError: columns overlap but no suffix specified:\n Index(['value'], dtype='object')\n\"\"\"\n\n# -----------------------------------------------------------------------\n# DataFrame class\n\n\nclass DataFrame(NDFrame):\n \"\"\"\n Two-dimensional size-mutable, potentially heterogeneous tabular data\n structure with labeled axes (rows and columns). Arithmetic operations\n align on both row and column labels. Can be thought of as a dict-like\n container for Series objects. The primary pandas data structure.\n\n Parameters\n ----------\n data : ndarray (structured or homogeneous), Iterable, dict, or DataFrame\n Dict can contain Series, arrays, constants, or list-like objects\n\n .. versionchanged :: 0.23.0\n If data is a dict, argument order is maintained for Python 3.6\n and later.\n\n index : Index or array-like\n Index to use for resulting frame. Will default to RangeIndex if\n no indexing information part of input data and no index provided\n columns : Index or array-like\n Column labels to use for resulting frame. Will default to\n RangeIndex (0, 1, 2, ..., n) if no column labels are provided\n dtype : dtype, default None\n Data type to force. Only a single dtype is allowed. If None, infer\n copy : boolean, default False\n Copy data from inputs. Only affects DataFrame / 2d ndarray input\n\n See Also\n --------\n DataFrame.from_records : Constructor from tuples, also record arrays.\n DataFrame.from_dict : From dicts of Series, arrays, or dicts.\n DataFrame.from_items : From sequence of (key, value) pairs\n pandas.read_csv, pandas.read_table, pandas.read_clipboard.\n\n Examples\n --------\n Constructing DataFrame from a dictionary.\n\n >>> d = {'col1': [1, 2], 'col2': [3, 4]}\n >>> df = pd.DataFrame(data=d)\n >>> df\n col1 col2\n 0 1 3\n 1 2 4\n\n Notice that the inferred dtype is int64.\n\n >>> df.dtypes\n col1 int64\n col2 int64\n dtype: object\n\n To enforce a single dtype:\n\n >>> df = pd.DataFrame(data=d, dtype=np.int8)\n >>> df.dtypes\n col1 int8\n col2 int8\n dtype: object\n\n Constructing DataFrame from numpy ndarray:\n\n >>> df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),\n ... columns=['a', 'b', 'c'])\n >>> df2\n a b c\n 0 1 2 3\n 1 4 5 6\n 2 7 8 9\n \"\"\"\n\n @property\n def _constructor(self):\n return DataFrame\n\n _constructor_sliced = Series\n _deprecations = NDFrame._deprecations | frozenset(\n ['get_value', 'set_value', 'from_csv', 'from_items'])\n _accessors = set()\n\n @property\n def _constructor_expanddim(self):\n from pandas.core.panel import Panel\n return Panel\n\n # ----------------------------------------------------------------------\n # Constructors\n\n def __init__(self, data=None, index=None, columns=None, dtype=None,\n copy=False):\n if data is None:\n data = {}\n if dtype is not None:\n dtype = self._validate_dtype(dtype)\n\n if isinstance(data, DataFrame):\n data = data._data\n\n if isinstance(data, BlockManager):\n mgr = self._init_mgr(data, axes=dict(index=index, columns=columns),\n dtype=dtype, copy=copy)\n elif isinstance(data, dict):\n mgr = init_dict(data, index, columns, dtype=dtype)\n elif isinstance(data, ma.MaskedArray):\n import numpy.ma.mrecords as mrecords\n # masked recarray\n if isinstance(data, mrecords.MaskedRecords):\n mgr = masked_rec_array_to_mgr(data, index, columns, dtype,\n copy)\n\n # a masked array\n else:\n mask = ma.getmaskarray(data)\n if mask.any():\n data, fill_value = maybe_upcast(data, copy=True)\n data[mask] = fill_value\n else:\n data = data.copy()\n mgr = init_ndarray(data, index, columns, dtype=dtype,\n copy=copy)\n\n elif isinstance(data, (np.ndarray, Series, Index)):\n if data.dtype.names:\n data_columns = list(data.dtype.names)\n data = {k: data[k] for k in data_columns}\n if columns is None:\n columns = data_columns\n mgr = init_dict(data, index, columns, dtype=dtype)\n elif getattr(data, 'name', None) is not None:\n mgr = init_dict({data.name: data}, index, columns,\n dtype=dtype)\n else:\n mgr = init_ndarray(data, index, columns, dtype=dtype,\n copy=copy)\n\n # For data is list-like, or Iterable (will consume into list)\n elif (isinstance(data, compat.Iterable)\n and not isinstance(data, string_and_binary_types)):\n if not isinstance(data, compat.Sequence):\n data = list(data)\n if len(data) > 0:\n if is_list_like(data[0]) and getattr(data[0], 'ndim', 1) == 1:\n if is_named_tuple(data[0]) and columns is None:\n columns = data[0]._fields\n arrays, columns = to_arrays(data, columns, dtype=dtype)\n columns = ensure_index(columns)\n\n # set the index\n if index is None:\n if isinstance(data[0], Series):\n index = get_names_from_index(data)\n elif isinstance(data[0], Categorical):\n index = ibase.default_index(len(data[0]))\n else:\n index = ibase.default_index(len(data))\n\n mgr = arrays_to_mgr(arrays, columns, index, columns,\n dtype=dtype)\n else:\n mgr = init_ndarray(data, index, columns, dtype=dtype,\n copy=copy)\n else:\n mgr = init_dict({}, index, columns, dtype=dtype)\n else:\n try:\n arr = np.array(data, dtype=dtype, copy=copy)\n except (ValueError, TypeError) as e:\n exc = TypeError('DataFrame constructor called with '\n 'incompatible data and dtype: {e}'.format(e=e))\n raise_with_traceback(exc)\n\n if arr.ndim == 0 and index is not None and columns is not None:\n values = cast_scalar_to_array((len(index), len(columns)),\n data, dtype=dtype)\n mgr = init_ndarray(values, index, columns,\n dtype=values.dtype, copy=False)\n else:\n raise ValueError('DataFrame constructor not properly called!')\n\n NDFrame.__init__(self, mgr, fastpath=True)\n\n # ----------------------------------------------------------------------\n\n @property\n def axes(self):\n \"\"\"\n Return a list representing the axes of the DataFrame.\n\n It has the row axis labels and column axis labels as the only members.\n They are returned in that order.\n\n Examples\n --------\n >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})\n >>> df.axes\n [RangeIndex(start=0, stop=2, step=1), Index(['coll', 'col2'],\n dtype='object')]\n \"\"\"\n return [self.index, self.columns]\n\n @property\n def shape(self):\n \"\"\"\n Return a tuple representing the dimensionality of the DataFrame.\n\n See Also\n --------\n ndarray.shape\n\n Examples\n --------\n >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})\n >>> df.shape\n (2, 2)\n\n >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4],\n ... 'col3': [5, 6]})\n >>> df.shape\n (2, 3)\n \"\"\"\n return len(self.index), len(self.columns)\n\n @property\n def _is_homogeneous_type(self):\n \"\"\"\n Whether all the columns in a DataFrame have the same type.\n\n Returns\n -------\n bool\n\n Examples\n --------\n >>> DataFrame({\"A\": [1, 2], \"B\": [3, 4]})._is_homogeneous_type\n True\n >>> DataFrame({\"A\": [1, 2], \"B\": [3.0, 4.0]})._is_homogeneous_type\n False\n\n Items with the same type but different sizes are considered\n different types.\n\n >>> DataFrame({\n ... \"A\": np.array([1, 2], dtype=np.int32),\n ... \"B\": np.array([1, 2], dtype=np.int64)})._is_homogeneous_type\n False\n \"\"\"\n if self._data.any_extension_types:\n return len({block.dtype for block in self._data.blocks}) == 1\n else:\n return not self._data.is_mixed_type\n\n # ----------------------------------------------------------------------\n # Rendering Methods\n\n def _repr_fits_vertical_(self):\n \"\"\"\n Check length against max_rows.\n \"\"\"\n max_rows = get_option(\"display.max_rows\")\n return len(self) <= max_rows\n\n def _repr_fits_horizontal_(self, ignore_width=False):\n \"\"\"\n Check if full repr fits in horizontal boundaries imposed by the display\n options width and max_columns.\n\n In case off non-interactive session, no boundaries apply.\n\n `ignore_width` is here so ipnb+HTML output can behave the way\n users expect. display.max_columns remains in effect.\n GH3541, GH3573\n \"\"\"\n\n width, height = console.get_console_size()\n max_columns = get_option(\"display.max_columns\")\n nb_columns = len(self.columns)\n\n # exceed max columns\n if ((max_columns and nb_columns > max_columns) or\n ((not ignore_width) and width and nb_columns > (width // 2))):\n return False\n\n # used by repr_html under IPython notebook or scripts ignore terminal\n # dims\n if ignore_width or not console.in_interactive_session():\n return True\n\n if (get_option('display.width') is not None or\n console.in_ipython_frontend()):\n # check at least the column row for excessive width\n max_rows = 1\n else:\n max_rows = get_option(\"display.max_rows\")\n\n # when auto-detecting, so width=None and not in ipython front end\n # check whether repr fits horizontal by actually checking\n # the width of the rendered repr\n buf = StringIO()\n\n # only care about the stuff we'll actually print out\n # and to_string on entire frame may be expensive\n d = self\n\n if not (max_rows is None): # unlimited rows\n # min of two, where one may be None\n d = d.iloc[:min(max_rows, len(d))]\n else:\n return True\n\n d.to_string(buf=buf)\n value = buf.getvalue()\n repr_width = max(len(l) for l in value.split('\\n'))\n\n return repr_width < width\n\n def _info_repr(self):\n \"\"\"\n True if the repr should show the info view.\n \"\"\"\n info_repr_option = (get_option(\"display.large_repr\") == \"info\")\n return info_repr_option and not (self._repr_fits_horizontal_() and\n self._repr_fits_vertical_())\n\n def __unicode__(self):\n \"\"\"\n Return a string representation for a particular DataFrame.\n\n Invoked by unicode(df) in py2 only. Yields a Unicode String in both\n py2/py3.\n \"\"\"\n buf = StringIO(u(\"\"))\n if self._info_repr():\n self.info(buf=buf)\n return buf.getvalue()\n\n max_rows = get_option(\"display.max_rows\")\n max_cols = get_option(\"display.max_columns\")\n show_dimensions = get_option(\"display.show_dimensions\")\n if get_option(\"display.expand_frame_repr\"):\n width, _ = console.get_console_size()\n else:\n width = None\n self.to_string(buf=buf, max_rows=max_rows, max_cols=max_cols,\n line_width=width, show_dimensions=show_dimensions)\n\n return buf.getvalue()\n\n def _repr_html_(self):\n \"\"\"\n Return a html representation for a particular DataFrame.\n\n Mainly for IPython notebook.\n \"\"\"\n # qtconsole doesn't report its line width, and also\n # behaves badly when outputting an HTML table\n # that doesn't fit the window, so disable it.\n # XXX: In IPython 3.x and above, the Qt console will not attempt to\n # display HTML, so this check can be removed when support for\n # IPython 2.x is no longer needed.\n if console.in_qtconsole():\n # 'HTML output is disabled in QtConsole'\n return None\n\n if self._info_repr():\n buf = StringIO(u(\"\"))\n self.info(buf=buf)\n # need to escape the <class>, should be the first line.\n val = buf.getvalue().replace('<', r'<', 1)\n val = val.replace('>', r'>', 1)\n return '<pre>' + val + '</pre>'\n\n if get_option(\"display.notebook_repr_html\"):\n max_rows = get_option(\"display.max_rows\")\n max_cols = get_option(\"display.max_columns\")\n show_dimensions = get_option(\"display.show_dimensions\")\n\n return self.to_html(max_rows=max_rows, max_cols=max_cols,\n show_dimensions=show_dimensions, notebook=True)\n else:\n return None\n\n @Substitution(header='Write out the column names. If a list of strings '\n 'is given, it is assumed to be aliases for the '\n 'column names')\n @Substitution(shared_params=fmt.common_docstring,\n returns=fmt.return_docstring)\n def to_string(self, buf=None, columns=None, col_space=None, header=True,\n index=True, na_rep='NaN', formatters=None, float_format=None,\n sparsify=None, index_names=True, justify=None,\n max_rows=None, max_cols=None, show_dimensions=False,\n decimal='.', line_width=None):\n \"\"\"\n Render a DataFrame to a console-friendly tabular output.\n %(shared_params)s\n line_width : int, optional\n Width to wrap a line in characters.\n %(returns)s\n See Also\n --------\n to_html : Convert DataFrame to HTML.\n\n Examples\n --------\n >>> d = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}\n >>> df = pd.DataFrame(d)\n >>> print(df.to_string())\n col1 col2\n 0 1 4\n 1 2 5\n 2 3 6\n \"\"\"\n\n formatter = fmt.DataFrameFormatter(self, buf=buf, columns=columns,\n col_space=col_space, na_rep=na_rep,\n formatters=formatters,\n float_format=float_format,\n sparsify=sparsify, justify=justify,\n index_names=index_names,\n header=header, index=index,\n max_rows=max_rows,\n max_cols=max_cols,\n show_dimensions=show_dimensions,\n decimal=decimal,\n line_width=line_width)\n formatter.to_string()\n\n if buf is None:\n result = formatter.buf.getvalue()\n return result\n\n # ----------------------------------------------------------------------\n\n @property\n def style(self):\n \"\"\"\n Property returning a Styler object containing methods for\n building a styled HTML representation fo the DataFrame.\n\n See Also\n --------\n pandas.io.formats.style.Styler\n \"\"\"\n from pandas.io.formats.style import Styler\n return Styler(self)\n\n def iteritems(self):\n r\"\"\"\n Iterator over (column name, Series) pairs.\n\n Iterates over the DataFrame columns, returning a tuple with\n the column name and the content as a Series.\n\n Yields\n ------\n label : object\n The column names for the DataFrame being iterated over.\n content : Series\n The column entries belonging to each label, as a Series.\n\n See Also\n --------\n DataFrame.iterrows : Iterate over DataFrame rows as\n (index, Series) pairs.\n DataFrame.itertuples : Iterate over DataFrame rows as namedtuples\n of the values.\n\n Examples\n --------\n >>> df = pd.DataFrame({'species': ['bear', 'bear', 'marsupial'],\n ... 'population': [1864, 22000, 80000]},\n ... index=['panda', 'polar', 'koala'])\n >>> df\n species population\n panda \tbear \t 1864\n polar \tbear \t 22000\n koala \tmarsupial 80000\n >>> for label, content in df.iteritems():\n ... print('label:', label)\n ... print('content:', content, sep='\\n')\n ...\n label: species\n content:\n panda bear\n polar bear\n koala marsupial\n Name: species, dtype: object\n label: population\n content:\n panda 1864\n polar 22000\n koala 80000\n Name: population, dtype: int64\n \"\"\"\n if self.columns.is_unique and hasattr(self, '_item_cache'):\n for k in self.columns:\n yield k, self._get_item_cache(k)\n else:\n for i, k in enumerate(self.columns):\n yield k, self._ixs(i, axis=1)\n\n def iterrows(self):\n \"\"\"\n Iterate over DataFrame rows as (index, Series) pairs.\n\n Yields\n ------\n index : label or tuple of label\n The index of the row. A tuple for a `MultiIndex`.\n data : Series\n The data of the row as a Series.\n\n it : generator\n A generator that iterates over the rows of the frame.\n\n See Also\n --------\n itertuples : Iterate over DataFrame rows as namedtuples of the values.\n iteritems : Iterate over (column name, Series) pairs.\n\n Notes\n -----\n\n 1. Because ``iterrows`` returns a Series for each row,\n it does **not** preserve dtypes across the rows (dtypes are\n preserved across columns for DataFrames). For example,\n\n >>> df = pd.DataFrame([[1, 1.5]], columns=['int', 'float'])\n >>> row = next(df.iterrows())[1]\n >>> row\n int 1.0\n float 1.5\n Name: 0, dtype: float64\n >>> print(row['int'].dtype)\n float64\n >>> print(df['int'].dtype)\n int64\n\n To preserve dtypes while iterating over the rows, it is better\n to use :meth:`itertuples` which returns namedtuples of the values\n and which is generally faster than ``iterrows``.\n\n 2. You should **never modify** something you are iterating over.\n This is not guaranteed to work in all cases. Depending on the\n data types, the iterator returns a copy and not a view, and writing\n to it will have no effect.\n \"\"\"\n columns = self.columns\n klass = self._constructor_sliced\n for k, v in zip(self.index, self.values):\n s = klass(v, index=columns, name=k)\n yield k, s\n\n def itertuples(self, index=True, name=\"Pandas\"):\n \"\"\"\n Iterate over DataFrame rows as namedtuples.\n\n Parameters\n ----------\n index : bool, default True\n If True, return the index as the first element of the tuple.\n name : str, default \"Pandas\"\n The name of the returned namedtuples or None to return regular\n tuples.\n\n Yields\n -------\n collections.namedtuple\n Yields a namedtuple for each row in the DataFrame with the first\n field possibly being the index and following fields being the\n column values.\n\n See Also\n --------\n DataFrame.iterrows : Iterate over DataFrame rows as (index, Series)\n pairs.\n DataFrame.iteritems : Iterate over (column name, Series) pairs.\n\n Notes\n -----\n The column names will be renamed to positional names if they are\n invalid Python identifiers, repeated, or start with an underscore.\n With a large number of columns (>255), regular tuples are returned.\n\n Examples\n --------\n >>> df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},\n ... index=['dog', 'hawk'])\n >>> df\n num_legs num_wings\n dog 4 0\n hawk 2 2\n >>> for row in df.itertuples():\n ... print(row)\n ...\n Pandas(Index='dog', num_legs=4, num_wings=0)\n Pandas(Index='hawk', num_legs=2, num_wings=2)\n\n By setting the `index` parameter to False we can remove the index\n as the first element of the tuple:\n\n >>> for row in df.itertuples(index=False):\n ... print(row)\n ...\n Pandas(num_legs=4, num_wings=0)\n Pandas(num_legs=2, num_wings=2)\n\n With the `name` parameter set we set a custom name for the yielded\n namedtuples:\n\n >>> for row in df.itertuples(name='Animal'):\n ... print(row)\n ...\n Animal(Index='dog', num_legs=4, num_wings=0)\n Animal(Index='hawk', num_legs=2, num_wings=2)\n \"\"\"\n arrays = []\n fields = []\n if index:\n arrays.append(self.index)\n fields.append(\"Index\")\n\n # use integer indexing because of possible duplicate column names\n arrays.extend(self.iloc[:, k] for k in range(len(self.columns)))\n\n # Python 3 supports at most 255 arguments to constructor, and\n # things get slow with this many fields in Python 2\n if name is not None and len(self.columns) + index < 256:\n # `rename` is unsupported in Python 2.6\n try:\n itertuple = collections.namedtuple(name,\n fields + list(self.columns),\n rename=True)\n return map(itertuple._make, zip(*arrays))\n except Exception:\n pass\n\n # fallback to regular tuples\n return zip(*arrays)\n\n items = iteritems\n\n def __len__(self):\n \"\"\"\n Returns length of info axis, but here we use the index.\n \"\"\"\n return len(self.index)\n\n def dot(self, other):\n \"\"\"\n Matrix multiplication with DataFrame or Series objects. Can also be\n called using `self @ other` in Python >= 3.5.\n\n Parameters\n ----------\n other : DataFrame or Series\n\n Returns\n -------\n dot_product : DataFrame or Series\n \"\"\"\n if isinstance(other, (Series, DataFrame)):\n common = self.columns.union(other.index)\n if (len(common) > len(self.columns) or\n len(common) > len(other.index)):\n raise ValueError('matrices are not aligned')\n\n left = self.reindex(columns=common, copy=False)\n right = other.reindex(index=common, copy=False)\n lvals = left.values\n rvals = right.values\n else:\n left = self\n lvals = self.values\n rvals = np.asarray(other)\n if lvals.shape[1] != rvals.shape[0]:\n raise ValueError('Dot product shape mismatch, '\n '{s} vs {r}'.format(s=lvals.shape,\n r=rvals.shape))\n\n if isinstance(other, DataFrame):\n return self._constructor(np.dot(lvals, rvals), index=left.index,\n columns=other.columns)\n elif isinstance(other, Series):\n return Series(np.dot(lvals, rvals), index=left.index)\n elif isinstance(rvals, (np.ndarray, Index)):\n result = np.dot(lvals, rvals)\n if result.ndim == 2:\n return self._constructor(result, index=left.index)\n else:\n return Series(result, index=left.index)\n else: # pragma: no cover\n raise TypeError('unsupported type: {oth}'.format(oth=type(other)))\n\n def __matmul__(self, other):\n \"\"\"\n Matrix multiplication using binary `@` operator in Python>=3.5.\n \"\"\"\n return self.dot(other)\n\n def __rmatmul__(self, other):\n \"\"\"\n Matrix multiplication using binary `@` operator in Python>=3.5.\n \"\"\"\n return self.T.dot(np.transpose(other)).T\n\n # ----------------------------------------------------------------------\n # IO methods (to / from other formats)\n\n @classmethod\n def from_dict(cls, data, orient='columns', dtype=None, columns=None):\n \"\"\"\n Construct DataFrame from dict of array-like or dicts.\n\n Creates DataFrame object from dictionary by columns or by index\n allowing dtype specification.\n\n Parameters\n ----------\n data : dict\n Of the form {field : array-like} or {field : dict}.\n orient : {'columns', 'index'}, default 'columns'\n The \"orientation\" of the data. If the keys of the passed dict\n should be the columns of the resulting DataFrame, pass 'columns'\n (default). Otherwise if the keys should be rows, pass 'index'.\n dtype : dtype, default None\n Data type to force, otherwise infer.\n columns : list, default None\n Column labels to use when ``orient='index'``. Raises a ValueError\n if used with ``orient='columns'``.\n\n .. versionadded:: 0.23.0\n\n Returns\n -------\n pandas.DataFrame\n\n See Also\n --------\n DataFrame.from_records : DataFrame from ndarray (structured\n dtype), list of tuples, dict, or DataFrame.\n DataFrame : DataFrame object creation using constructor.\n\n Examples\n --------\n By default the keys of the dict become the DataFrame columns:\n\n >>> data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}\n >>> pd.DataFrame.from_dict(data)\n col_1 col_2\n 0 3 a\n 1 2 b\n 2 1 c\n 3 0 d\n\n Specify ``orient='index'`` to create the DataFrame using dictionary\n keys as rows:\n\n >>> data = {'row_1': [3, 2, 1, 0], 'row_2': ['a', 'b', 'c', 'd']}\n >>> pd.DataFrame.from_dict(data, orient='index')\n 0 1 2 3\n row_1 3 2 1 0\n row_2 a b c d\n\n When using the 'index' orientation, the column names can be\n specified manually:\n\n >>> pd.DataFrame.from_dict(data, orient='index',\n ... columns=['A', 'B', 'C', 'D'])\n A B C D\n row_1 3 2 1 0\n row_2 a b c d\n \"\"\"\n index = None\n orient = orient.lower()\n if orient == 'index':\n if len(data) > 0:\n # TODO speed up Series case\n if isinstance(list(data.values())[0], (Series, dict)):\n data = _from_nested_dict(data)\n else:\n data, index = list(data.values()), list(data.keys())\n elif orient == 'columns':\n if columns is not None:\n raise ValueError(\"cannot use columns parameter with \"\n \"orient='columns'\")\n else: # pragma: no cover\n raise ValueError('only recognize index or columns for orient')\n\n return cls(data, index=index, columns=columns, dtype=dtype)\n\n def to_numpy(self):\n \"\"\"\n Convert the DataFrame to a NumPy array.\n\n .. versionadded:: 0.24.0\n\n The dtype of the returned array will be the common NumPy\n dtype of all types in the DataFrame. For example,\n if the dtypes are ``float16`` and ``float32``, the results\n dtype will be ``float32``. This may require copying data and\n coercing values, which may be expensive.\n\n Returns\n -------\n array : numpy.ndarray\n\n See Also\n --------\n Series.to_numpy : Similar method for Series.\n\n Examples\n --------\n >>> pd.DataFrame({\"A\": [1, 2], \"B\": [3, 4]}).to_numpy()\n array([[1, 3],\n [2, 4]])\n\n With heterogenous data, the lowest common type will have to\n be used.\n\n >>> df = pd.DataFrame({\"A\": [1, 2], \"B\": [3.0, 4.5]})\n >>> df.to_numpy()\n array([[1. , 3. ],\n [2. , 4.5]])\n\n For a mix of numeric and non-numeric types, the output array will\n have object dtype.\n\n >>> df['C'] = pd.date_range('2000', periods=2)\n >>> df.to_numpy()\n array([[1, 3.0, Timestamp('2000-01-01 00:00:00')],\n [2, 4.5, Timestamp('2000-01-02 00:00:00')]], dtype=object)\n \"\"\"\n return self.values\n\n def to_dict(self, orient='dict', into=dict):\n \"\"\"\n Convert the DataFrame to a dictionary.\n\n The type of the key-value pairs can be customized with the parameters\n (see below).\n\n Parameters\n ----------\n orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}\n Determines the type of the values of the dictionary.\n\n - 'dict' (default) : dict like {column -> {index -> value}}\n - 'list' : dict like {column -> [values]}\n - 'series' : dict like {column -> Series(values)}\n - 'split' : dict like\n {'index' -> [index], 'columns' -> [columns], 'data' -> [values]}\n - 'records' : list like\n [{column -> value}, ... , {column -> value}]\n - 'index' : dict like {index -> {column -> value}}\n\n Abbreviations are allowed. `s` indicates `series` and `sp`\n indicates `split`.\n\n into : class, default dict\n The collections.Mapping subclass used for all Mappings\n in the return value. Can be the actual class or an empty\n instance of the mapping type you want. If you want a\n collections.defaultdict, you must pass it initialized.\n\n .. versionadded:: 0.21.0\n\n Returns\n -------\n dict, list or collections.Mapping\n Return a collections.Mapping object representing the DataFrame.\n The resulting transformation depends on the `orient` parameter.\n\n See Also\n --------\n DataFrame.from_dict: Create a DataFrame from a dictionary.\n DataFrame.to_json: Convert a DataFrame to JSON format.\n\n Examples\n --------\n >>> df = pd.DataFrame({'col1': [1, 2],\n ... 'col2': [0.5, 0.75]},\n ... index=['row1', 'row2'])\n >>> df\n col1 col2\n row1 1 0.50\n row2 2 0.75\n >>> df.to_dict()\n {'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 0.5, 'row2': 0.75}}\n\n You can specify the return orientation.\n\n >>> df.to_dict('series')\n {'col1': row1 1\n row2 2\n Name: col1, dtype: int64,\n 'col2': row1 0.50\n row2 0.75\n Name: col2, dtype: float64}\n\n >>> df.to_dict('split')\n {'index': ['row1', 'row2'], 'columns': ['col1', 'col2'],\n 'data': [[1, 0.5], [2, 0.75]]}\n\n >>> df.to_dict('records')\n [{'col1': 1, 'col2': 0.5}, {'col1': 2, 'col2': 0.75}]\n\n >>> df.to_dict('index')\n {'row1': {'col1': 1, 'col2': 0.5}, 'row2': {'col1': 2, 'col2': 0.75}}\n\n You can also specify the mapping type.\n\n >>> from collections import OrderedDict, defaultdict\n >>> df.to_dict(into=OrderedDict)\n OrderedDict([('col1', OrderedDict([('row1', 1), ('row2', 2)])),\n ('col2', OrderedDict([('row1', 0.5), ('row2', 0.75)]))])\n\n If you want a `defaultdict`, you need to initialize it:\n\n >>> dd = defaultdict(list)\n >>> df.to_dict('records', into=dd)\n [defaultdict(<class 'list'>, {'col1': 1, 'col2': 0.5}),\n defaultdict(<class 'list'>, {'col1': 2, 'col2': 0.75})]\n \"\"\"\n if not self.columns.is_unique:\n warnings.warn(\"DataFrame columns are not unique, some \"\n \"columns will be omitted.\", UserWarning,\n stacklevel=2)\n # GH16122\n into_c = com.standardize_mapping(into)\n if orient.lower().startswith('d'):\n return into_c(\n (k, v.to_dict(into)) for k, v in compat.iteritems(self))\n elif orient.lower().startswith('l'):\n return into_c((k, v.tolist()) for k, v in compat.iteritems(self))\n elif orient.lower().startswith('sp'):\n return into_c((('index', self.index.tolist()),\n ('columns', self.columns.tolist()),\n ('data', [\n list(map(com.maybe_box_datetimelike, t))\n for t in self.itertuples(index=False)]\n )))\n elif orient.lower().startswith('s'):\n return into_c((k, com.maybe_box_datetimelike(v))\n for k, v in compat.iteritems(self))\n elif orient.lower().startswith('r'):\n return [\n into_c((k, com.maybe_box_datetimelike(v))\n for k, v in compat.iteritems(row._asdict()))\n for row in self.itertuples(index=False)]\n elif orient.lower().startswith('i'):\n if not self.index.is_unique:\n raise ValueError(\n \"DataFrame index must be unique for orient='index'.\"\n )\n return into_c((t[0], dict(zip(self.columns, t[1:])))\n for t in self.itertuples())\n else:\n raise ValueError(\"orient '{o}' not understood\".format(o=orient))\n\n def to_gbq(self, destination_table, project_id=None, chunksize=None,\n reauth=False, if_exists='fail', auth_local_webserver=False,\n table_schema=None, location=None, progress_bar=True,\n credentials=None, verbose=None, private_key=None):\n \"\"\"\n Write a DataFrame to a Google BigQuery table.\n\n This function requires the `pandas-gbq package\n <https://pandas-gbq.readthedocs.io>`__.\n\n See the `How to authenticate with Google BigQuery\n <https://pandas-gbq.readthedocs.io/en/latest/howto/authentication.html>`__\n guide for authentication instructions.\n\n Parameters\n ----------\n destination_table : str\n Name of table to be written, in the form ``dataset.tablename``.\n project_id : str, optional\n Google BigQuery Account project ID. Optional when available from\n the environment.\n chunksize : int, optional\n Number of rows to be inserted in each chunk from the dataframe.\n Set to ``None`` to load the whole dataframe at once.\n reauth : bool, default False\n Force Google BigQuery to re-authenticate the user. This is useful\n if multiple accounts are used.\n if_exists : str, default 'fail'\n Behavior when the destination table exists. Value can be one of:\n\n ``'fail'``\n If table exists, do nothing.\n ``'replace'``\n If table exists, drop it, recreate it, and insert data.\n ``'append'``\n If table exists, insert data. Create if does not exist.\n auth_local_webserver : bool, default False\n Use the `local webserver flow`_ instead of the `console flow`_\n when getting user credentials.\n\n .. _local webserver flow:\n http://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_local_server\n .. _console flow:\n http://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_console\n\n *New in version 0.2.0 of pandas-gbq*.\n table_schema : list of dicts, optional\n List of BigQuery table fields to which according DataFrame\n columns conform to, e.g. ``[{'name': 'col1', 'type':\n 'STRING'},...]``. If schema is not provided, it will be\n generated according to dtypes of DataFrame columns. See\n BigQuery API documentation on available names of a field.\n\n *New in version 0.3.1 of pandas-gbq*.\n location : str, optional\n Location where the load job should run. See the `BigQuery locations\n documentation\n <https://cloud.google.com/bigquery/docs/dataset-locations>`__ for a\n list of available locations. The location must match that of the\n target dataset.\n\n *New in version 0.5.0 of pandas-gbq*.\n progress_bar : bool, default True\n Use the library `tqdm` to show the progress bar for the upload,\n chunk by chunk.\n\n *New in version 0.5.0 of pandas-gbq*.\n credentials : google.auth.credentials.Credentials, optional\n Credentials for accessing Google APIs. Use this parameter to\n override default credentials, such as to use Compute Engine\n :class:`google.auth.compute_engine.Credentials` or Service\n Account :class:`google.oauth2.service_account.Credentials`\n directly.\n\n *New in version 0.8.0 of pandas-gbq*.\n\n .. versionadded:: 0.24.0\n verbose : bool, deprecated\n Deprecated in pandas-gbq version 0.4.0. Use the `logging module\n to adjust verbosity instead\n <https://pandas-gbq.readthedocs.io/en/latest/intro.html#logging>`__.\n private_key : str, deprecated\n Deprecated in pandas-gbq version 0.8.0. Use the ``credentials``\n parameter and\n :func:`google.oauth2.service_account.Credentials.from_service_account_info`\n or\n :func:`google.oauth2.service_account.Credentials.from_service_account_file`\n instead.\n\n Service account private key in JSON format. Can be file path\n or string contents. This is useful for remote server\n authentication (eg. Jupyter/IPython notebook on remote host).\n\n See Also\n --------\n pandas_gbq.to_gbq : This function in the pandas-gbq library.\n pandas.read_gbq : Read a DataFrame from Google BigQuery.\n \"\"\"\n from pandas.io import gbq\n return gbq.to_gbq(\n self, destination_table, project_id=project_id,\n chunksize=chunksize, reauth=reauth, if_exists=if_exists,\n auth_local_webserver=auth_local_webserver,\n table_schema=table_schema, location=location,\n progress_bar=progress_bar, credentials=credentials,\n verbose=verbose, private_key=private_key)\n\n @classmethod\n def from_records(cls, data, index=None, exclude=None, columns=None,\n coerce_float=False, nrows=None):\n \"\"\"\n Convert structured or record ndarray to DataFrame.\n\n Parameters\n ----------\n data : ndarray (structured dtype), list of tuples, dict, or DataFrame\n index : string, list of fields, array-like\n Field of array to use as the index, alternately a specific set of\n input labels to use\n exclude : sequence, default None\n Columns or fields to exclude\n columns : sequence, default None\n Column names to use. If the passed data do not have names\n associated with them, this argument provides names for the\n columns. Otherwise this argument indicates the order of the columns\n in the result (any names not found in the data will become all-NA\n columns)\n coerce_float : boolean, default False\n Attempt to convert values of non-string, non-numeric objects (like\n decimal.Decimal) to floating point, useful for SQL result sets\n nrows : int, default None\n Number of rows to read if data is an iterator\n\n Returns\n -------\n df : DataFrame\n \"\"\"\n\n # Make a copy of the input columns so we can modify it\n if columns is not None:\n columns = ensure_index(columns)\n\n if is_iterator(data):\n if nrows == 0:\n return cls()\n\n try:\n first_row = next(data)\n except StopIteration:\n return cls(index=index, columns=columns)\n\n dtype = None\n if hasattr(first_row, 'dtype') and first_row.dtype.names:\n dtype = first_row.dtype\n\n values = [first_row]\n\n if nrows is None:\n values += data\n else:\n values.extend(itertools.islice(data, nrows - 1))\n\n if dtype is not None:\n data = np.array(values, dtype=dtype)\n else:\n data = values\n\n if isinstance(data, dict):\n if columns is None:\n columns = arr_columns = ensure_index(sorted(data))\n arrays = [data[k] for k in columns]\n else:\n arrays = []\n arr_columns = []\n for k, v in compat.iteritems(data):\n if k in columns:\n arr_columns.append(k)\n arrays.append(v)\n\n arrays, arr_columns = reorder_arrays(arrays, arr_columns,\n columns)\n\n elif isinstance(data, (np.ndarray, DataFrame)):\n arrays, columns = to_arrays(data, columns)\n if columns is not None:\n columns = ensure_index(columns)\n arr_columns = columns\n else:\n arrays, arr_columns = to_arrays(data, columns,\n coerce_float=coerce_float)\n\n arr_columns = ensure_index(arr_columns)\n if columns is not None:\n columns = ensure_index(columns)\n else:\n columns = arr_columns\n\n if exclude is None:\n exclude = set()\n else:\n exclude = set(exclude)\n\n result_index = None\n if index is not None:\n if (isinstance(index, compat.string_types) or\n not hasattr(index, \"__iter__\")):\n i = columns.get_loc(index)\n exclude.add(index)\n if len(arrays) > 0:\n result_index = Index(arrays[i], name=index)\n else:\n result_index = Index([], name=index)\n else:\n try:\n to_remove = [arr_columns.get_loc(field) for field in index]\n index_data = [arrays[i] for i in to_remove]\n result_index = ensure_index_from_sequences(index_data,\n names=index)\n\n exclude.update(index)\n except Exception:\n result_index = index\n\n if any(exclude):\n arr_exclude = [x for x in exclude if x in arr_columns]\n to_remove = [arr_columns.get_loc(col) for col in arr_exclude]\n arrays = [v for i, v in enumerate(arrays) if i not in to_remove]\n\n arr_columns = arr_columns.drop(arr_exclude)\n columns = columns.drop(exclude)\n\n mgr = arrays_to_mgr(arrays, arr_columns, result_index, columns)\n\n return cls(mgr)\n\n def to_records(self, index=True, convert_datetime64=None):\n \"\"\"\n Convert DataFrame to a NumPy record array.\n\n Index will be included as the first field of the record array if\n requested.\n\n Parameters\n ----------\n index : bool, default True\n Include index in resulting record array, stored in 'index'\n field or using the index label, if set.\n convert_datetime64 : bool, default None\n .. deprecated:: 0.23.0\n\n Whether to convert the index to datetime.datetime if it is a\n DatetimeIndex.\n\n Returns\n -------\n numpy.recarray\n NumPy ndarray with the DataFrame labels as fields and each row\n of the DataFrame as entries.\n\n See Also\n --------\n DataFrame.from_records: Convert structured or record ndarray\n to DataFrame.\n numpy.recarray: An ndarray that allows field access using\n attributes, analogous to typed columns in a\n spreadsheet.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': [1, 2], 'B': [0.5, 0.75]},\n ... index=['a', 'b'])\n >>> df\n A B\n a 1 0.50\n b 2 0.75\n >>> df.to_records()\n rec.array([('a', 1, 0.5 ), ('b', 2, 0.75)],\n dtype=[('index', 'O'), ('A', '<i8'), ('B', '<f8')])\n\n If the DataFrame index has no label then the recarray field name\n is set to 'index'. If the index has a label then this is used as the\n field name:\n\n >>> df.index = df.index.rename(\"I\")\n >>> df.to_records()\n rec.array([('a', 1, 0.5 ), ('b', 2, 0.75)],\n dtype=[('I', 'O'), ('A', '<i8'), ('B', '<f8')])\n\n The index can be excluded from the record array:\n\n >>> df.to_records(index=False)\n rec.array([(1, 0.5 ), (2, 0.75)],\n dtype=[('A', '<i8'), ('B', '<f8')])\n \"\"\"\n\n if convert_datetime64 is not None:\n warnings.warn(\"The 'convert_datetime64' parameter is \"\n \"deprecated and will be removed in a future \"\n \"version\",\n FutureWarning, stacklevel=2)\n\n if index:\n if is_datetime64_any_dtype(self.index) and convert_datetime64:\n ix_vals = [self.index.to_pydatetime()]\n else:\n if isinstance(self.index, MultiIndex):\n # array of tuples to numpy cols. copy copy copy\n ix_vals = lmap(np.array, zip(*self.index.values))\n else:\n ix_vals = [self.index.values]\n\n arrays = ix_vals + [self[c].get_values() for c in self.columns]\n\n count = 0\n index_names = list(self.index.names)\n if isinstance(self.index, MultiIndex):\n for i, n in enumerate(index_names):\n if n is None:\n index_names[i] = 'level_%d' % count\n count += 1\n elif index_names[0] is None:\n index_names = ['index']\n names = (lmap(compat.text_type, index_names) +\n lmap(compat.text_type, self.columns))\n else:\n arrays = [self[c].get_values() for c in self.columns]\n names = lmap(compat.text_type, self.columns)\n\n formats = [v.dtype for v in arrays]\n return np.rec.fromarrays(\n arrays,\n dtype={'names': names, 'formats': formats}\n )\n\n @classmethod\n def from_items(cls, items, columns=None, orient='columns'):\n \"\"\"\n Construct a DataFrame from a list of tuples.\n\n .. deprecated:: 0.23.0\n `from_items` is deprecated and will be removed in a future version.\n Use :meth:`DataFrame.from_dict(dict(items)) <DataFrame.from_dict>`\n instead.\n :meth:`DataFrame.from_dict(OrderedDict(items)) <DataFrame.from_dict>`\n may be used to preserve the key order.\n\n Convert (key, value) pairs to DataFrame. The keys will be the axis\n index (usually the columns, but depends on the specified\n orientation). The values should be arrays or Series.\n\n Parameters\n ----------\n items : sequence of (key, value) pairs\n Values should be arrays or Series.\n columns : sequence of column labels, optional\n Must be passed if orient='index'.\n orient : {'columns', 'index'}, default 'columns'\n The \"orientation\" of the data. If the keys of the\n input correspond to column labels, pass 'columns'\n (default). Otherwise if the keys correspond to the index,\n pass 'index'.\n\n Returns\n -------\n frame : DataFrame\n \"\"\"\n\n warnings.warn(\"from_items is deprecated. Please use \"\n \"DataFrame.from_dict(dict(items), ...) instead. \"\n \"DataFrame.from_dict(OrderedDict(items)) may be used to \"\n \"preserve the key order.\",\n FutureWarning, stacklevel=2)\n\n keys, values = lzip(*items)\n\n if orient == 'columns':\n if columns is not None:\n columns = ensure_index(columns)\n\n idict = dict(items)\n if len(idict) < len(items):\n if not columns.equals(ensure_index(keys)):\n raise ValueError('With non-unique item names, passed '\n 'columns must be identical')\n arrays = values\n else:\n arrays = [idict[k] for k in columns if k in idict]\n else:\n columns = ensure_index(keys)\n arrays = values\n\n # GH 17312\n # Provide more informative error msg when scalar values passed\n try:\n return cls._from_arrays(arrays, columns, None)\n\n except ValueError:\n if not is_nested_list_like(values):\n raise ValueError('The value in each (key, value) pair '\n 'must be an array, Series, or dict')\n\n elif orient == 'index':\n if columns is None:\n raise TypeError(\"Must pass columns with orient='index'\")\n\n keys = ensure_index(keys)\n\n # GH 17312\n # Provide more informative error msg when scalar values passed\n try:\n arr = np.array(values, dtype=object).T\n data = [lib.maybe_convert_objects(v) for v in arr]\n return cls._from_arrays(data, columns, keys)\n\n except TypeError:\n if not is_nested_list_like(values):\n raise ValueError('The value in each (key, value) pair '\n 'must be an array, Series, or dict')\n\n else: # pragma: no cover\n raise ValueError(\"'orient' must be either 'columns' or 'index'\")\n\n @classmethod\n def _from_arrays(cls, arrays, columns, index, dtype=None):\n mgr = arrays_to_mgr(arrays, columns, index, columns, dtype=dtype)\n return cls(mgr)\n\n @classmethod\n def from_csv(cls, path, header=0, sep=',', index_col=0, parse_dates=True,\n encoding=None, tupleize_cols=None,\n infer_datetime_format=False):\n \"\"\"\n Read CSV file.\n\n .. deprecated:: 0.21.0\n Use :func:`pandas.read_csv` instead.\n\n It is preferable to use the more powerful :func:`pandas.read_csv`\n for most general purposes, but ``from_csv`` makes for an easy\n roundtrip to and from a file (the exact counterpart of\n ``to_csv``), especially with a DataFrame of time series data.\n\n This method only differs from the preferred :func:`pandas.read_csv`\n in some defaults:\n\n - `index_col` is ``0`` instead of ``None`` (take first column as index\n by default)\n - `parse_dates` is ``True`` instead of ``False`` (try parsing the index\n as datetime by default)\n\n So a ``pd.DataFrame.from_csv(path)`` can be replaced by\n ``pd.read_csv(path, index_col=0, parse_dates=True)``.\n\n Parameters\n ----------\n path : string file path or file handle / StringIO\n header : int, default 0\n Row to use as header (skip prior rows)\n sep : string, default ','\n Field delimiter\n index_col : int or sequence, default 0\n Column to use for index. If a sequence is given, a MultiIndex\n is used. Different default from read_table\n parse_dates : boolean, default True\n Parse dates. Different default from read_table\n tupleize_cols : boolean, default False\n write multi_index columns as a list of tuples (if True)\n or new (expanded format) if False)\n infer_datetime_format : boolean, default False\n If True and `parse_dates` is True for a column, try to infer the\n datetime format based on the first datetime string. If the format\n can be inferred, there often will be a large parsing speed-up.\n\n Returns\n -------\n y : DataFrame\n\n See Also\n --------\n pandas.read_csv\n \"\"\"\n\n warnings.warn(\"from_csv is deprecated. Please use read_csv(...) \"\n \"instead. Note that some of the default arguments are \"\n \"different, so please refer to the documentation \"\n \"for from_csv when changing your function calls\",\n FutureWarning, stacklevel=2)\n\n from pandas.io.parsers import read_csv\n return read_csv(path, header=header, sep=sep,\n parse_dates=parse_dates, index_col=index_col,\n encoding=encoding, tupleize_cols=tupleize_cols,\n infer_datetime_format=infer_datetime_format)\n\n def to_sparse(self, fill_value=None, kind='block'):\n \"\"\"\n Convert to SparseDataFrame.\n\n Implement the sparse version of the DataFrame meaning that any data\n matching a specific value it's omitted in the representation.\n The sparse DataFrame allows for a more efficient storage.\n\n Parameters\n ----------\n fill_value : float, default None\n The specific value that should be omitted in the representation.\n kind : {'block', 'integer'}, default 'block'\n The kind of the SparseIndex tracking where data is not equal to\n the fill value:\n\n - 'block' tracks only the locations and sizes of blocks of data.\n - 'integer' keeps an array with all the locations of the data.\n\n In most cases 'block' is recommended, since it's more memory\n efficient.\n\n Returns\n -------\n SparseDataFrame\n The sparse representation of the DataFrame.\n\n See Also\n --------\n DataFrame.to_dense :\n Converts the DataFrame back to the its dense form.\n\n Examples\n --------\n >>> df = pd.DataFrame([(np.nan, np.nan),\n ... (1., np.nan),\n ... (np.nan, 1.)])\n >>> df\n 0 1\n 0 NaN NaN\n 1 1.0 NaN\n 2 NaN 1.0\n >>> type(df)\n <class 'pandas.core.frame.DataFrame'>\n\n >>> sdf = df.to_sparse()\n >>> sdf\n 0 1\n 0 NaN NaN\n 1 1.0 NaN\n 2 NaN 1.0\n >>> type(sdf)\n <class 'pandas.core.sparse.frame.SparseDataFrame'>\n \"\"\"\n from pandas.core.sparse.api import SparseDataFrame\n return SparseDataFrame(self._series, index=self.index,\n columns=self.columns, default_kind=kind,\n default_fill_value=fill_value)\n\n def to_panel(self):\n \"\"\"\n Transform long (stacked) format (DataFrame) into wide (3D, Panel)\n format.\n\n .. deprecated:: 0.20.0\n\n Currently the index of the DataFrame must be a 2-level MultiIndex. This\n may be generalized later\n\n Returns\n -------\n panel : Panel\n \"\"\"\n # only support this kind for now\n if (not isinstance(self.index, MultiIndex) or # pragma: no cover\n len(self.index.levels) != 2):\n raise NotImplementedError('Only 2-level MultiIndex are supported.')\n\n if not self.index.is_unique:\n raise ValueError(\"Can't convert non-uniquely indexed \"\n \"DataFrame to Panel\")\n\n self._consolidate_inplace()\n\n # minor axis must be sorted\n if self.index.lexsort_depth < 2:\n selfsorted = self.sort_index(level=0)\n else:\n selfsorted = self\n\n major_axis, minor_axis = selfsorted.index.levels\n major_codes, minor_codes = selfsorted.index.codes\n shape = len(major_axis), len(minor_axis)\n\n # preserve names, if any\n major_axis = major_axis.copy()\n major_axis.name = self.index.names[0]\n\n minor_axis = minor_axis.copy()\n minor_axis.name = self.index.names[1]\n\n # create new axes\n new_axes = [selfsorted.columns, major_axis, minor_axis]\n\n # create new manager\n new_mgr = selfsorted._data.reshape_nd(axes=new_axes,\n labels=[major_codes,\n minor_codes],\n shape=shape,\n ref_items=selfsorted.columns)\n\n return self._constructor_expanddim(new_mgr)\n\n @deprecate_kwarg(old_arg_name='encoding', new_arg_name=None)\n def to_stata(self, fname, convert_dates=None, write_index=True,\n encoding=\"latin-1\", byteorder=None, time_stamp=None,\n data_label=None, variable_labels=None, version=114,\n convert_strl=None):\n \"\"\"\n Export DataFrame object to Stata dta format.\n\n Writes the DataFrame to a Stata dataset file.\n \"dta\" files contain a Stata dataset.\n\n Parameters\n ----------\n fname : str, buffer or path object\n String, path object (pathlib.Path or py._path.local.LocalPath) or\n object implementing a binary write() function. If using a buffer\n then the buffer will not be automatically closed after the file\n data has been written.\n convert_dates : dict\n Dictionary mapping columns containing datetime types to stata\n internal format to use when writing the dates. Options are 'tc',\n 'td', 'tm', 'tw', 'th', 'tq', 'ty'. Column can be either an integer\n or a name. Datetime columns that do not have a conversion type\n specified will be converted to 'tc'. Raises NotImplementedError if\n a datetime column has timezone information.\n write_index : bool\n Write the index to Stata dataset.\n encoding : str\n Default is latin-1. Unicode is not supported.\n byteorder : str\n Can be \">\", \"<\", \"little\", or \"big\". default is `sys.byteorder`.\n time_stamp : datetime\n A datetime to use as file creation date. Default is the current\n time.\n data_label : str, optional\n A label for the data set. Must be 80 characters or smaller.\n variable_labels : dict\n Dictionary containing columns as keys and variable labels as\n values. Each label must be 80 characters or smaller.\n\n .. versionadded:: 0.19.0\n\n version : {114, 117}, default 114\n Version to use in the output dta file. Version 114 can be used\n read by Stata 10 and later. Version 117 can be read by Stata 13\n or later. Version 114 limits string variables to 244 characters or\n fewer while 117 allows strings with lengths up to 2,000,000\n characters.\n\n .. versionadded:: 0.23.0\n\n convert_strl : list, optional\n List of column names to convert to string columns to Stata StrL\n format. Only available if version is 117. Storing strings in the\n StrL format can produce smaller dta files if strings have more than\n 8 characters and values are repeated.\n\n .. versionadded:: 0.23.0\n\n Raises\n ------\n NotImplementedError\n * If datetimes contain timezone information\n * Column dtype is not representable in Stata\n ValueError\n * Columns listed in convert_dates are neither datetime64[ns]\n or datetime.datetime\n * Column listed in convert_dates is not in DataFrame\n * Categorical label contains more than 32,000 characters\n\n .. versionadded:: 0.19.0\n\n See Also\n --------\n read_stata : Import Stata data files.\n io.stata.StataWriter : Low-level writer for Stata data files.\n io.stata.StataWriter117 : Low-level writer for version 117 files.\n\n Examples\n --------\n >>> df = pd.DataFrame({'animal': ['falcon', 'parrot', 'falcon',\n ... 'parrot'],\n ... 'speed': [350, 18, 361, 15]})\n >>> df.to_stata('animals.dta') # doctest: +SKIP\n \"\"\"\n kwargs = {}\n if version not in (114, 117):\n raise ValueError('Only formats 114 and 117 supported.')\n if version == 114:\n if convert_strl is not None:\n raise ValueError('strl support is only available when using '\n 'format 117')\n from pandas.io.stata import StataWriter as statawriter\n else:\n from pandas.io.stata import StataWriter117 as statawriter\n kwargs['convert_strl'] = convert_strl\n\n writer = statawriter(fname, self, convert_dates=convert_dates,\n byteorder=byteorder, time_stamp=time_stamp,\n data_label=data_label, write_index=write_index,\n variable_labels=variable_labels, **kwargs)\n writer.write_file()\n\n def to_feather(self, fname):\n \"\"\"\n Write out the binary feather-format for DataFrames.\n\n .. versionadded:: 0.20.0\n\n Parameters\n ----------\n fname : str\n string file path\n \"\"\"\n from pandas.io.feather_format import to_feather\n to_feather(self, fname)\n\n def to_parquet(self, fname, engine='auto', compression='snappy',\n index=None, partition_cols=None, **kwargs):\n \"\"\"\n Write a DataFrame to the binary parquet format.\n\n .. versionadded:: 0.21.0\n\n This function writes the dataframe as a `parquet file\n <https://parquet.apache.org/>`_. You can choose different parquet\n backends, and have the option of compression. See\n :ref:`the user guide <io.parquet>` for more details.\n\n Parameters\n ----------\n fname : str\n File path or Root Directory path. Will be used as Root Directory\n path while writing a partitioned dataset.\n\n .. versionchanged:: 0.24.0\n\n engine : {'auto', 'pyarrow', 'fastparquet'}, default 'auto'\n Parquet library to use. If 'auto', then the option\n ``io.parquet.engine`` is used. The default ``io.parquet.engine``\n behavior is to try 'pyarrow', falling back to 'fastparquet' if\n 'pyarrow' is unavailable.\n compression : {'snappy', 'gzip', 'brotli', None}, default 'snappy'\n Name of the compression to use. Use ``None`` for no compression.\n index : bool, default None\n If ``True``, include the dataframe's index(es) in the file output.\n If ``False``, they will not be written to the file. If ``None``,\n the behavior depends on the chosen engine.\n\n .. versionadded:: 0.24.0\n\n partition_cols : list, optional, default None\n Column names by which to partition the dataset\n Columns are partitioned in the order they are given\n\n .. versionadded:: 0.24.0\n\n **kwargs\n Additional arguments passed to the parquet library. See\n :ref:`pandas io <io.parquet>` for more details.\n\n See Also\n --------\n read_parquet : Read a parquet file.\n DataFrame.to_csv : Write a csv file.\n DataFrame.to_sql : Write to a sql table.\n DataFrame.to_hdf : Write to hdf.\n\n Notes\n -----\n This function requires either the `fastparquet\n <https://pypi.org/project/fastparquet>`_ or `pyarrow\n <https://arrow.apache.org/docs/python/>`_ library.\n\n Examples\n --------\n >>> df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]})\n >>> df.to_parquet('df.parquet.gzip',\n ... compression='gzip') # doctest: +SKIP\n >>> pd.read_parquet('df.parquet.gzip') # doctest: +SKIP\n col1 col2\n 0 1 3\n 1 2 4\n \"\"\"\n from pandas.io.parquet import to_parquet\n to_parquet(self, fname, engine,\n compression=compression, index=index,\n partition_cols=partition_cols, **kwargs)\n\n @Substitution(header='Whether to print column labels, default True')\n @Substitution(shared_params=fmt.common_docstring,\n returns=fmt.return_docstring)\n def to_html(self, buf=None, columns=None, col_space=None, header=True,\n index=True, na_rep='NaN', formatters=None, float_format=None,\n sparsify=None, index_names=True, justify=None, max_rows=None,\n max_cols=None, show_dimensions=False, decimal='.',\n bold_rows=True, classes=None, escape=True,\n notebook=False, border=None, table_id=None):\n \"\"\"\n Render a DataFrame as an HTML table.\n %(shared_params)s\n bold_rows : bool, default True\n Make the row labels bold in the output.\n classes : str or list or tuple, default None\n CSS class(es) to apply to the resulting html table.\n escape : bool, default True\n Convert the characters <, >, and & to HTML-safe sequences.\n notebook : {True, False}, default False\n Whether the generated HTML is for IPython Notebook.\n border : int\n A ``border=border`` attribute is included in the opening\n `<table>` tag. Default ``pd.options.html.border``.\n\n .. versionadded:: 0.19.0\n\n table_id : str, optional\n A css id is included in the opening `<table>` tag if specified.\n\n .. versionadded:: 0.23.0\n %(returns)s\n See Also\n --------\n to_string : Convert DataFrame to a string.\n \"\"\"\n\n if (justify is not None and\n justify not in fmt._VALID_JUSTIFY_PARAMETERS):\n raise ValueError(\"Invalid value for justify parameter\")\n\n formatter = fmt.DataFrameFormatter(self, buf=buf, columns=columns,\n col_space=col_space, na_rep=na_rep,\n formatters=formatters,\n float_format=float_format,\n sparsify=sparsify, justify=justify,\n index_names=index_names,\n header=header, index=index,\n bold_rows=bold_rows, escape=escape,\n max_rows=max_rows,\n max_cols=max_cols,\n show_dimensions=show_dimensions,\n decimal=decimal, table_id=table_id)\n # TODO: a generic formatter wld b in DataFrameFormatter\n formatter.to_html(classes=classes, notebook=notebook, border=border)\n\n if buf is None:\n return formatter.buf.getvalue()\n\n # ----------------------------------------------------------------------\n\n def info(self, verbose=None, buf=None, max_cols=None, memory_usage=None,\n null_counts=None):\n \"\"\"\n Print a concise summary of a DataFrame.\n\n This method prints information about a DataFrame including\n the index dtype and column dtypes, non-null values and memory usage.\n\n Parameters\n ----------\n verbose : bool, optional\n Whether to print the full summary. By default, the setting in\n ``pandas.options.display.max_info_columns`` is followed.\n buf : writable buffer, defaults to sys.stdout\n Where to send the output. By default, the output is printed to\n sys.stdout. Pass a writable buffer if you need to further process\n the output.\n max_cols : int, optional\n When to switch from the verbose to the truncated output. If the\n DataFrame has more than `max_cols` columns, the truncated output\n is used. By default, the setting in\n ``pandas.options.display.max_info_columns`` is used.\n memory_usage : bool, str, optional\n Specifies whether total memory usage of the DataFrame\n elements (including the index) should be displayed. By default,\n this follows the ``pandas.options.display.memory_usage`` setting.\n\n True always show memory usage. False never shows memory usage.\n A value of 'deep' is equivalent to \"True with deep introspection\".\n Memory usage is shown in human-readable units (base-2\n representation). Without deep introspection a memory estimation is\n made based in column dtype and number of rows assuming values\n consume the same memory amount for corresponding dtypes. With deep\n memory introspection, a real memory usage calculation is performed\n at the cost of computational resources.\n null_counts : bool, optional\n Whether to show the non-null counts. By default, this is shown\n only if the frame is smaller than\n ``pandas.options.display.max_info_rows`` and\n ``pandas.options.display.max_info_columns``. A value of True always\n shows the counts, and False never shows the counts.\n\n Returns\n -------\n None\n This method prints a summary of a DataFrame and returns None.\n\n See Also\n --------\n DataFrame.describe: Generate descriptive statistics of DataFrame\n columns.\n DataFrame.memory_usage: Memory usage of DataFrame columns.\n\n Examples\n --------\n >>> int_values = [1, 2, 3, 4, 5]\n >>> text_values = ['alpha', 'beta', 'gamma', 'delta', 'epsilon']\n >>> float_values = [0.0, 0.25, 0.5, 0.75, 1.0]\n >>> df = pd.DataFrame({\"int_col\": int_values, \"text_col\": text_values,\n ... \"float_col\": float_values})\n >>> df\n int_col text_col float_col\n 0 1 alpha 0.00\n 1 2 beta 0.25\n 2 3 gamma 0.50\n 3 4 delta 0.75\n 4 5 epsilon 1.00\n\n Prints information of all columns:\n\n >>> df.info(verbose=True)\n <class 'pandas.core.frame.DataFrame'>\n RangeIndex: 5 entries, 0 to 4\n Data columns (total 3 columns):\n int_col 5 non-null int64\n text_col 5 non-null object\n float_col 5 non-null float64\n dtypes: float64(1), int64(1), object(1)\n memory usage: 200.0+ bytes\n\n Prints a summary of columns count and its dtypes but not per column\n information:\n\n >>> df.info(verbose=False)\n <class 'pandas.core.frame.DataFrame'>\n RangeIndex: 5 entries, 0 to 4\n Columns: 3 entries, int_col to float_col\n dtypes: float64(1), int64(1), object(1)\n memory usage: 200.0+ bytes\n\n Pipe output of DataFrame.info to buffer instead of sys.stdout, get\n buffer content and writes to a text file:\n\n >>> import io\n >>> buffer = io.StringIO()\n >>> df.info(buf=buffer)\n >>> s = buffer.getvalue()\n >>> with open(\"df_info.txt\", \"w\",\n ... encoding=\"utf-8\") as f: # doctest: +SKIP\n ... f.write(s)\n 260\n\n The `memory_usage` parameter allows deep introspection mode, specially\n useful for big DataFrames and fine-tune memory optimization:\n\n >>> random_strings_array = np.random.choice(['a', 'b', 'c'], 10 ** 6)\n >>> df = pd.DataFrame({\n ... 'column_1': np.random.choice(['a', 'b', 'c'], 10 ** 6),\n ... 'column_2': np.random.choice(['a', 'b', 'c'], 10 ** 6),\n ... 'column_3': np.random.choice(['a', 'b', 'c'], 10 ** 6)\n ... })\n >>> df.info()\n <class 'pandas.core.frame.DataFrame'>\n RangeIndex: 1000000 entries, 0 to 999999\n Data columns (total 3 columns):\n column_1 1000000 non-null object\n column_2 1000000 non-null object\n column_3 1000000 non-null object\n dtypes: object(3)\n memory usage: 22.9+ MB\n\n >>> df.info(memory_usage='deep')\n <class 'pandas.core.frame.DataFrame'>\n RangeIndex: 1000000 entries, 0 to 999999\n Data columns (total 3 columns):\n column_1 1000000 non-null object\n column_2 1000000 non-null object\n column_3 1000000 non-null object\n dtypes: object(3)\n memory usage: 188.8 MB\n \"\"\"\n\n if buf is None: # pragma: no cover\n buf = sys.stdout\n\n lines = []\n\n lines.append(str(type(self)))\n lines.append(self.index._summary())\n\n if len(self.columns) == 0:\n lines.append('Empty {name}'.format(name=type(self).__name__))\n fmt.buffer_put_lines(buf, lines)\n return\n\n cols = self.columns\n\n # hack\n if max_cols is None:\n max_cols = get_option('display.max_info_columns',\n len(self.columns) + 1)\n\n max_rows = get_option('display.max_info_rows', len(self) + 1)\n\n if null_counts is None:\n show_counts = ((len(self.columns) <= max_cols) and\n (len(self) < max_rows))\n else:\n show_counts = null_counts\n exceeds_info_cols = len(self.columns) > max_cols\n\n def _verbose_repr():\n lines.append('Data columns (total %d columns):' %\n len(self.columns))\n space = max(len(pprint_thing(k)) for k in self.columns) + 4\n counts = None\n\n tmpl = \"{count}{dtype}\"\n if show_counts:\n counts = self.count()\n if len(cols) != len(counts): # pragma: no cover\n raise AssertionError(\n 'Columns must equal counts '\n '({cols:d} != {counts:d})'.format(\n cols=len(cols), counts=len(counts)))\n tmpl = \"{count} non-null {dtype}\"\n\n dtypes = self.dtypes\n for i, col in enumerate(self.columns):\n dtype = dtypes.iloc[i]\n col = pprint_thing(col)\n\n count = \"\"\n if show_counts:\n count = counts.iloc[i]\n\n lines.append(_put_str(col, space) + tmpl.format(count=count,\n dtype=dtype))\n\n def _non_verbose_repr():\n lines.append(self.columns._summary(name='Columns'))\n\n def _sizeof_fmt(num, size_qualifier):\n # returns size in human readable format\n for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:\n if num < 1024.0:\n return (\"{num:3.1f}{size_q} \"\n \"{x}\".format(num=num, size_q=size_qualifier, x=x))\n num /= 1024.0\n return \"{num:3.1f}{size_q} {pb}\".format(num=num,\n size_q=size_qualifier,\n pb='PB')\n\n if verbose:\n _verbose_repr()\n elif verbose is False: # specifically set to False, not nesc None\n _non_verbose_repr()\n else:\n if exceeds_info_cols:\n _non_verbose_repr()\n else:\n _verbose_repr()\n\n counts = self.get_dtype_counts()\n dtypes = ['{k}({kk:d})'.format(k=k[0], kk=k[1]) for k\n in sorted(compat.iteritems(counts))]\n lines.append('dtypes: {types}'.format(types=', '.join(dtypes)))\n\n if memory_usage is None:\n memory_usage = get_option('display.memory_usage')\n if memory_usage:\n # append memory usage of df to display\n size_qualifier = ''\n if memory_usage == 'deep':\n deep = True\n else:\n # size_qualifier is just a best effort; not guaranteed to catch\n # all cases (e.g., it misses categorical data even with object\n # categories)\n deep = False\n if ('object' in counts or\n self.index._is_memory_usage_qualified()):\n size_qualifier = '+'\n mem_usage = self.memory_usage(index=True, deep=deep).sum()\n lines.append(\"memory usage: {mem}\\n\".format(\n mem=_sizeof_fmt(mem_usage, size_qualifier)))\n\n fmt.buffer_put_lines(buf, lines)\n\n def memory_usage(self, index=True, deep=False):\n \"\"\"\n Return the memory usage of each column in bytes.\n\n The memory usage can optionally include the contribution of\n the index and elements of `object` dtype.\n\n This value is displayed in `DataFrame.info` by default. This can be\n suppressed by setting ``pandas.options.display.memory_usage`` to False.\n\n Parameters\n ----------\n index : bool, default True\n Specifies whether to include the memory usage of the DataFrame's\n index in returned Series. If ``index=True`` the memory usage of the\n index the first item in the output.\n deep : bool, default False\n If True, introspect the data deeply by interrogating\n `object` dtypes for system-level memory consumption, and include\n it in the returned values.\n\n Returns\n -------\n sizes : Series\n A Series whose index is the original column names and whose values\n is the memory usage of each column in bytes.\n\n See Also\n --------\n numpy.ndarray.nbytes : Total bytes consumed by the elements of an\n ndarray.\n Series.memory_usage : Bytes consumed by a Series.\n pandas.Categorical : Memory-efficient array for string values with\n many repeated values.\n DataFrame.info : Concise summary of a DataFrame.\n\n Examples\n --------\n >>> dtypes = ['int64', 'float64', 'complex128', 'object', 'bool']\n >>> data = dict([(t, np.ones(shape=5000).astype(t))\n ... for t in dtypes])\n >>> df = pd.DataFrame(data)\n >>> df.head()\n int64 float64 complex128 object bool\n 0 1 1.0 (1+0j) 1 True\n 1 1 1.0 (1+0j) 1 True\n 2 1 1.0 (1+0j) 1 True\n 3 1 1.0 (1+0j) 1 True\n 4 1 1.0 (1+0j) 1 True\n\n >>> df.memory_usage()\n Index 80\n int64 40000\n float64 40000\n complex128 80000\n object 40000\n bool 5000\n dtype: int64\n\n >>> df.memory_usage(index=False)\n int64 40000\n float64 40000\n complex128 80000\n object 40000\n bool 5000\n dtype: int64\n\n The memory footprint of `object` dtype columns is ignored by default:\n\n >>> df.memory_usage(deep=True)\n Index 80\n int64 40000\n float64 40000\n complex128 80000\n object 160000\n bool 5000\n dtype: int64\n\n Use a Categorical for efficient storage of an object-dtype column with\n many repeated values.\n\n >>> df['object'].astype('category').memory_usage(deep=True)\n 5168\n \"\"\"\n result = Series([c.memory_usage(index=False, deep=deep)\n for col, c in self.iteritems()], index=self.columns)\n if index:\n result = Series(self.index.memory_usage(deep=deep),\n index=['Index']).append(result)\n return result\n\n def transpose(self, *args, **kwargs):\n \"\"\"\n Transpose index and columns.\n\n Reflect the DataFrame over its main diagonal by writing rows as columns\n and vice-versa. The property :attr:`.T` is an accessor to the method\n :meth:`transpose`.\n\n Parameters\n ----------\n copy : bool, default False\n If True, the underlying data is copied. Otherwise (default), no\n copy is made if possible.\n *args, **kwargs\n Additional keywords have no effect but might be accepted for\n compatibility with numpy.\n\n Returns\n -------\n DataFrame\n The transposed DataFrame.\n\n See Also\n --------\n numpy.transpose : Permute the dimensions of a given array.\n\n Notes\n -----\n Transposing a DataFrame with mixed dtypes will result in a homogeneous\n DataFrame with the `object` dtype. In such a case, a copy of the data\n is always made.\n\n Examples\n --------\n **Square DataFrame with homogeneous dtype**\n\n >>> d1 = {'col1': [1, 2], 'col2': [3, 4]}\n >>> df1 = pd.DataFrame(data=d1)\n >>> df1\n col1 col2\n 0 1 3\n 1 2 4\n\n >>> df1_transposed = df1.T # or df1.transpose()\n >>> df1_transposed\n 0 1\n col1 1 2\n col2 3 4\n\n When the dtype is homogeneous in the original DataFrame, we get a\n transposed DataFrame with the same dtype:\n\n >>> df1.dtypes\n col1 int64\n col2 int64\n dtype: object\n >>> df1_transposed.dtypes\n 0 int64\n 1 int64\n dtype: object\n\n **Non-square DataFrame with mixed dtypes**\n\n >>> d2 = {'name': ['Alice', 'Bob'],\n ... 'score': [9.5, 8],\n ... 'employed': [False, True],\n ... 'kids': [0, 0]}\n >>> df2 = pd.DataFrame(data=d2)\n >>> df2\n name score employed kids\n 0 Alice 9.5 False 0\n 1 Bob 8.0 True 0\n\n >>> df2_transposed = df2.T # or df2.transpose()\n >>> df2_transposed\n 0 1\n name Alice Bob\n score 9.5 8\n employed False True\n kids 0 0\n\n When the DataFrame has mixed dtypes, we get a transposed DataFrame with\n the `object` dtype:\n\n >>> df2.dtypes\n name object\n score float64\n employed bool\n kids int64\n dtype: object\n >>> df2_transposed.dtypes\n 0 object\n 1 object\n dtype: object\n \"\"\"\n nv.validate_transpose(args, dict())\n return super(DataFrame, self).transpose(1, 0, **kwargs)\n\n T = property(transpose)\n\n # ----------------------------------------------------------------------\n # Picklability\n\n # legacy pickle formats\n def _unpickle_frame_compat(self, state): # pragma: no cover\n if len(state) == 2: # pragma: no cover\n series, idx = state\n columns = sorted(series)\n else:\n series, cols, idx = state\n columns = com._unpickle_array(cols)\n\n index = com._unpickle_array(idx)\n self._data = self._init_dict(series, index, columns, None)\n\n def _unpickle_matrix_compat(self, state): # pragma: no cover\n # old unpickling\n (vals, idx, cols), object_state = state\n\n index = com._unpickle_array(idx)\n dm = DataFrame(vals, index=index, columns=com._unpickle_array(cols),\n copy=False)\n\n if object_state is not None:\n ovals, _, ocols = object_state\n objects = DataFrame(ovals, index=index,\n columns=com._unpickle_array(ocols), copy=False)\n\n dm = dm.join(objects)\n\n self._data = dm._data\n\n # ----------------------------------------------------------------------\n # Getting and setting elements\n\n def get_value(self, index, col, takeable=False):\n \"\"\"\n Quickly retrieve single value at passed column and index.\n\n .. deprecated:: 0.21.0\n Use .at[] or .iat[] accessors instead.\n\n Parameters\n ----------\n index : row label\n col : column label\n takeable : interpret the index/col as indexers, default False\n\n Returns\n -------\n value : scalar value\n \"\"\"\n\n warnings.warn(\"get_value is deprecated and will be removed \"\n \"in a future release. Please use \"\n \".at[] or .iat[] accessors instead\", FutureWarning,\n stacklevel=2)\n return self._get_value(index, col, takeable=takeable)\n\n def _get_value(self, index, col, takeable=False):\n\n if takeable:\n series = self._iget_item_cache(col)\n return com.maybe_box_datetimelike(series._values[index])\n\n series = self._get_item_cache(col)\n engine = self.index._engine\n\n try:\n return engine.get_value(series._values, index)\n except (TypeError, ValueError):\n\n # we cannot handle direct indexing\n # use positional\n col = self.columns.get_loc(col)\n index = self.index.get_loc(index)\n return self._get_value(index, col, takeable=True)\n _get_value.__doc__ = get_value.__doc__\n\n def set_value(self, index, col, value, takeable=False):\n \"\"\"\n Put single value at passed column and index.\n\n .. deprecated:: 0.21.0\n Use .at[] or .iat[] accessors instead.\n\n Parameters\n ----------\n index : row label\n col : column label\n value : scalar value\n takeable : interpret the index/col as indexers, default False\n\n Returns\n -------\n frame : DataFrame\n If label pair is contained, will be reference to calling DataFrame,\n otherwise a new object\n \"\"\"\n warnings.warn(\"set_value is deprecated and will be removed \"\n \"in a future release. Please use \"\n \".at[] or .iat[] accessors instead\", FutureWarning,\n stacklevel=2)\n return self._set_value(index, col, value, takeable=takeable)\n\n def _set_value(self, index, col, value, takeable=False):\n try:\n if takeable is True:\n series = self._iget_item_cache(col)\n return series._set_value(index, value, takeable=True)\n\n series = self._get_item_cache(col)\n engine = self.index._engine\n engine.set_value(series._values, index, value)\n return self\n except (KeyError, TypeError):\n\n # set using a non-recursive method & reset the cache\n self.loc[index, col] = value\n self._item_cache.pop(col, None)\n\n return self\n _set_value.__doc__ = set_value.__doc__\n\n def _ixs(self, i, axis=0):\n \"\"\"\n Parameters\n ----------\n i : int, slice, or sequence of integers\n axis : int\n\n Notes\n -----\n If slice passed, the resulting data will be a view.\n \"\"\"\n # irow\n if axis == 0:\n if isinstance(i, slice):\n return self[i]\n else:\n label = self.index[i]\n if isinstance(label, Index):\n # a location index by definition\n result = self.take(i, axis=axis)\n copy = True\n else:\n new_values = self._data.fast_xs(i)\n if is_scalar(new_values):\n return new_values\n\n # if we are a copy, mark as such\n copy = (isinstance(new_values, np.ndarray) and\n new_values.base is None)\n result = self._constructor_sliced(new_values,\n index=self.columns,\n name=self.index[i],\n dtype=new_values.dtype)\n result._set_is_copy(self, copy=copy)\n return result\n\n # icol\n else:\n label = self.columns[i]\n if isinstance(i, slice):\n # need to return view\n lab_slice = slice(label[0], label[-1])\n return self.loc[:, lab_slice]\n else:\n if isinstance(label, Index):\n return self._take(i, axis=1)\n\n index_len = len(self.index)\n\n # if the values returned are not the same length\n # as the index (iow a not found value), iget returns\n # a 0-len ndarray. This is effectively catching\n # a numpy error (as numpy should really raise)\n values = self._data.iget(i)\n\n if index_len and not len(values):\n values = np.array([np.nan] * index_len, dtype=object)\n result = self._box_col_values(values, label)\n\n # this is a cached value, mark it so\n result._set_as_cached(label, self)\n\n return result\n\n def __getitem__(self, key):\n key = com.apply_if_callable(key, self)\n\n # shortcut if the key is in columns\n try:\n if self.columns.is_unique and key in self.columns:\n if self.columns.nlevels > 1:\n return self._getitem_multilevel(key)\n return self._get_item_cache(key)\n except (TypeError, ValueError):\n # The TypeError correctly catches non hashable \"key\" (e.g. list)\n # The ValueError can be removed once GH #21729 is fixed\n pass\n\n # Do we have a slicer (on rows)?\n indexer = convert_to_index_sliceable(self, key)\n if indexer is not None:\n return self._slice(indexer, axis=0)\n\n # Do we have a (boolean) DataFrame?\n if isinstance(key, DataFrame):\n return self._getitem_frame(key)\n\n # Do we have a (boolean) 1d indexer?\n if com.is_bool_indexer(key):\n return self._getitem_bool_array(key)\n\n # We are left with two options: a single key, and a collection of keys,\n # We interpret tuples as collections only for non-MultiIndex\n is_single_key = isinstance(key, tuple) or not is_list_like(key)\n\n if is_single_key:\n if self.columns.nlevels > 1:\n return self._getitem_multilevel(key)\n indexer = self.columns.get_loc(key)\n if is_integer(indexer):\n indexer = [indexer]\n else:\n if is_iterator(key):\n key = list(key)\n indexer = self.loc._convert_to_indexer(key, axis=1,\n raise_missing=True)\n\n # take() does not accept boolean indexers\n if getattr(indexer, \"dtype\", None) == bool:\n indexer = np.where(indexer)[0]\n\n data = self._take(indexer, axis=1)\n\n if is_single_key:\n # What does looking for a single key in a non-unique index return?\n # The behavior is inconsistent. It returns a Series, except when\n # - the key itself is repeated (test on data.shape, #9519), or\n # - we have a MultiIndex on columns (test on self.columns, #21309)\n if data.shape[1] == 1 and not isinstance(self.columns, MultiIndex):\n data = data[key]\n\n return data\n\n def _getitem_bool_array(self, key):\n # also raises Exception if object array with NA values\n # warning here just in case -- previously __setitem__ was\n # reindexing but __getitem__ was not; it seems more reasonable to\n # go with the __setitem__ behavior since that is more consistent\n # with all other indexing behavior\n if isinstance(key, Series) and not key.index.equals(self.index):\n warnings.warn(\"Boolean Series key will be reindexed to match \"\n \"DataFrame index.\", UserWarning, stacklevel=3)\n elif len(key) != len(self.index):\n raise ValueError('Item wrong length %d instead of %d.' %\n (len(key), len(self.index)))\n\n # check_bool_indexer will throw exception if Series key cannot\n # be reindexed to match DataFrame rows\n key = check_bool_indexer(self.index, key)\n indexer = key.nonzero()[0]\n return self._take(indexer, axis=0)\n\n def _getitem_multilevel(self, key):\n loc = self.columns.get_loc(key)\n if isinstance(loc, (slice, Series, np.ndarray, Index)):\n new_columns = self.columns[loc]\n result_columns = maybe_droplevels(new_columns, key)\n if self._is_mixed_type:\n result = self.reindex(columns=new_columns)\n result.columns = result_columns\n else:\n new_values = self.values[:, loc]\n result = self._constructor(new_values, index=self.index,\n columns=result_columns)\n result = result.__finalize__(self)\n\n # If there is only one column being returned, and its name is\n # either an empty string, or a tuple with an empty string as its\n # first element, then treat the empty string as a placeholder\n # and return the column as if the user had provided that empty\n # string in the key. If the result is a Series, exclude the\n # implied empty string from its name.\n if len(result.columns) == 1:\n top = result.columns[0]\n if isinstance(top, tuple):\n top = top[0]\n if top == '':\n result = result['']\n if isinstance(result, Series):\n result = self._constructor_sliced(result,\n index=self.index,\n name=key)\n\n result._set_is_copy(self)\n return result\n else:\n return self._get_item_cache(key)\n\n def _getitem_frame(self, key):\n if key.values.size and not is_bool_dtype(key.values):\n raise ValueError('Must pass DataFrame with boolean values only')\n return self.where(key)\n\n def query(self, expr, inplace=False, **kwargs):\n \"\"\"\n Query the columns of a DataFrame with a boolean expression.\n\n Parameters\n ----------\n expr : string\n The query string to evaluate. You can refer to variables\n in the environment by prefixing them with an '@' character like\n ``@a + b``.\n inplace : bool\n Whether the query should modify the data in place or return\n a modified copy\n\n .. versionadded:: 0.18.0\n\n kwargs : dict\n See the documentation for :func:`pandas.eval` for complete details\n on the keyword arguments accepted by :meth:`DataFrame.query`.\n\n Returns\n -------\n q : DataFrame\n\n See Also\n --------\n pandas.eval\n DataFrame.eval\n\n Notes\n -----\n The result of the evaluation of this expression is first passed to\n :attr:`DataFrame.loc` and if that fails because of a\n multidimensional key (e.g., a DataFrame) then the result will be passed\n to :meth:`DataFrame.__getitem__`.\n\n This method uses the top-level :func:`pandas.eval` function to\n evaluate the passed query.\n\n The :meth:`~pandas.DataFrame.query` method uses a slightly\n modified Python syntax by default. For example, the ``&`` and ``|``\n (bitwise) operators have the precedence of their boolean cousins,\n :keyword:`and` and :keyword:`or`. This *is* syntactically valid Python,\n however the semantics are different.\n\n You can change the semantics of the expression by passing the keyword\n argument ``parser='python'``. This enforces the same semantics as\n evaluation in Python space. Likewise, you can pass ``engine='python'``\n to evaluate an expression using Python itself as a backend. This is not\n recommended as it is inefficient compared to using ``numexpr`` as the\n engine.\n\n The :attr:`DataFrame.index` and\n :attr:`DataFrame.columns` attributes of the\n :class:`~pandas.DataFrame` instance are placed in the query namespace\n by default, which allows you to treat both the index and columns of the\n frame as a column in the frame.\n The identifier ``index`` is used for the frame index; you can also\n use the name of the index to identify it in a query. Please note that\n Python keywords may not be used as identifiers.\n\n For further details and examples see the ``query`` documentation in\n :ref:`indexing <indexing.query>`.\n\n Examples\n --------\n >>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('ab'))\n >>> df.query('a > b')\n >>> df[df.a > df.b] # same result as the previous expression\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n if not isinstance(expr, compat.string_types):\n msg = \"expr must be a string to be evaluated, {0} given\"\n raise ValueError(msg.format(type(expr)))\n kwargs['level'] = kwargs.pop('level', 0) + 1\n kwargs['target'] = None\n res = self.eval(expr, **kwargs)\n\n try:\n new_data = self.loc[res]\n except ValueError:\n # when res is multi-dimensional loc raises, but this is sometimes a\n # valid query\n new_data = self[res]\n\n if inplace:\n self._update_inplace(new_data)\n else:\n return new_data\n\n def eval(self, expr, inplace=False, **kwargs):\n \"\"\"\n Evaluate a string describing operations on DataFrame columns.\n\n Operates on columns only, not specific rows or elements. This allows\n `eval` to run arbitrary code, which can make you vulnerable to code\n injection if you pass user input to this function.\n\n Parameters\n ----------\n expr : str\n The expression string to evaluate.\n inplace : bool, default False\n If the expression contains an assignment, whether to perform the\n operation inplace and mutate the existing DataFrame. Otherwise,\n a new DataFrame is returned.\n\n .. versionadded:: 0.18.0.\n kwargs : dict\n See the documentation for :func:`~pandas.eval` for complete details\n on the keyword arguments accepted by\n :meth:`~pandas.DataFrame.query`.\n\n Returns\n -------\n ndarray, scalar, or pandas object\n The result of the evaluation.\n\n See Also\n --------\n DataFrame.query : Evaluates a boolean expression to query the columns\n of a frame.\n DataFrame.assign : Can evaluate an expression or function to create new\n values for a column.\n pandas.eval : Evaluate a Python expression as a string using various\n backends.\n\n Notes\n -----\n For more details see the API documentation for :func:`~pandas.eval`.\n For detailed examples see :ref:`enhancing performance with eval\n <enhancingperf.eval>`.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': range(1, 6), 'B': range(10, 0, -2)})\n >>> df\n A B\n 0 1 10\n 1 2 8\n 2 3 6\n 3 4 4\n 4 5 2\n >>> df.eval('A + B')\n 0 11\n 1 10\n 2 9\n 3 8\n 4 7\n dtype: int64\n\n Assignment is allowed though by default the original DataFrame is not\n modified.\n\n >>> df.eval('C = A + B')\n A B C\n 0 1 10 11\n 1 2 8 10\n 2 3 6 9\n 3 4 4 8\n 4 5 2 7\n >>> df\n A B\n 0 1 10\n 1 2 8\n 2 3 6\n 3 4 4\n 4 5 2\n\n Use ``inplace=True`` to modify the original DataFrame.\n\n >>> df.eval('C = A + B', inplace=True)\n >>> df\n A B C\n 0 1 10 11\n 1 2 8 10\n 2 3 6 9\n 3 4 4 8\n 4 5 2 7\n \"\"\"\n from pandas.core.computation.eval import eval as _eval\n\n inplace = validate_bool_kwarg(inplace, 'inplace')\n resolvers = kwargs.pop('resolvers', None)\n kwargs['level'] = kwargs.pop('level', 0) + 1\n if resolvers is None:\n index_resolvers = self._get_index_resolvers()\n resolvers = dict(self.iteritems()), index_resolvers\n if 'target' not in kwargs:\n kwargs['target'] = self\n kwargs['resolvers'] = kwargs.get('resolvers', ()) + tuple(resolvers)\n return _eval(expr, inplace=inplace, **kwargs)\n\n def select_dtypes(self, include=None, exclude=None):\n \"\"\"\n Return a subset of the DataFrame's columns based on the column dtypes.\n\n Parameters\n ----------\n include, exclude : scalar or list-like\n A selection of dtypes or strings to be included/excluded. At least\n one of these parameters must be supplied.\n\n Returns\n -------\n subset : DataFrame\n The subset of the frame including the dtypes in ``include`` and\n excluding the dtypes in ``exclude``.\n\n Raises\n ------\n ValueError\n * If both of ``include`` and ``exclude`` are empty\n * If ``include`` and ``exclude`` have overlapping elements\n * If any kind of string dtype is passed in.\n\n Notes\n -----\n * To select all *numeric* types, use ``np.number`` or ``'number'``\n * To select strings you must use the ``object`` dtype, but note that\n this will return *all* object dtype columns\n * See the `numpy dtype hierarchy\n <http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html>`__\n * To select datetimes, use ``np.datetime64``, ``'datetime'`` or\n ``'datetime64'``\n * To select timedeltas, use ``np.timedelta64``, ``'timedelta'`` or\n ``'timedelta64'``\n * To select Pandas categorical dtypes, use ``'category'``\n * To select Pandas datetimetz dtypes, use ``'datetimetz'`` (new in\n 0.20.0) or ``'datetime64[ns, tz]'``\n\n Examples\n --------\n >>> df = pd.DataFrame({'a': [1, 2] * 3,\n ... 'b': [True, False] * 3,\n ... 'c': [1.0, 2.0] * 3})\n >>> df\n a b c\n 0 1 True 1.0\n 1 2 False 2.0\n 2 1 True 1.0\n 3 2 False 2.0\n 4 1 True 1.0\n 5 2 False 2.0\n\n >>> df.select_dtypes(include='bool')\n b\n 0 True\n 1 False\n 2 True\n 3 False\n 4 True\n 5 False\n\n >>> df.select_dtypes(include=['float64'])\n c\n 0 1.0\n 1 2.0\n 2 1.0\n 3 2.0\n 4 1.0\n 5 2.0\n\n >>> df.select_dtypes(exclude=['int'])\n b c\n 0 True 1.0\n 1 False 2.0\n 2 True 1.0\n 3 False 2.0\n 4 True 1.0\n 5 False 2.0\n \"\"\"\n def _get_info_slice(obj, indexer):\n \"\"\"Slice the info axis of `obj` with `indexer`.\"\"\"\n if not hasattr(obj, '_info_axis_number'):\n msg = 'object of type {typ!r} has no info axis'\n raise TypeError(msg.format(typ=type(obj).__name__))\n slices = [slice(None)] * obj.ndim\n slices[obj._info_axis_number] = indexer\n return tuple(slices)\n\n if not is_list_like(include):\n include = (include,) if include is not None else ()\n if not is_list_like(exclude):\n exclude = (exclude,) if exclude is not None else ()\n\n selection = tuple(map(frozenset, (include, exclude)))\n\n if not any(selection):\n raise ValueError('at least one of include or exclude must be '\n 'nonempty')\n\n # convert the myriad valid dtypes object to a single representation\n include, exclude = map(\n lambda x: frozenset(map(_get_dtype_from_object, x)), selection)\n for dtypes in (include, exclude):\n invalidate_string_dtypes(dtypes)\n\n # can't both include AND exclude!\n if not include.isdisjoint(exclude):\n raise ValueError('include and exclude overlap on {inc_ex}'.format(\n inc_ex=(include & exclude)))\n\n # empty include/exclude -> defaults to True\n # three cases (we've already raised if both are empty)\n # case 1: empty include, nonempty exclude\n # we have True, True, ... True for include, same for exclude\n # in the loop below we get the excluded\n # and when we call '&' below we get only the excluded\n # case 2: nonempty include, empty exclude\n # same as case 1, but with include\n # case 3: both nonempty\n # the \"union\" of the logic of case 1 and case 2:\n # we get the included and excluded, and return their logical and\n include_these = Series(not bool(include), index=self.columns)\n exclude_these = Series(not bool(exclude), index=self.columns)\n\n def is_dtype_instance_mapper(idx, dtype):\n return idx, functools.partial(issubclass, dtype.type)\n\n for idx, f in itertools.starmap(is_dtype_instance_mapper,\n enumerate(self.dtypes)):\n if include: # checks for the case of empty include or exclude\n include_these.iloc[idx] = any(map(f, include))\n if exclude:\n exclude_these.iloc[idx] = not any(map(f, exclude))\n\n dtype_indexer = include_these & exclude_these\n return self.loc[_get_info_slice(self, dtype_indexer)]\n\n def _box_item_values(self, key, values):\n items = self.columns[self.columns.get_loc(key)]\n if values.ndim == 2:\n return self._constructor(values.T, columns=items, index=self.index)\n else:\n return self._box_col_values(values, items)\n\n def _box_col_values(self, values, items):\n \"\"\"\n Provide boxed values for a column.\n \"\"\"\n klass = self._constructor_sliced\n return klass(values, index=self.index, name=items, fastpath=True)\n\n def __setitem__(self, key, value):\n key = com.apply_if_callable(key, self)\n\n # see if we can slice the rows\n indexer = convert_to_index_sliceable(self, key)\n if indexer is not None:\n return self._setitem_slice(indexer, value)\n\n if isinstance(key, DataFrame) or getattr(key, 'ndim', None) == 2:\n self._setitem_frame(key, value)\n elif isinstance(key, (Series, np.ndarray, list, Index)):\n self._setitem_array(key, value)\n else:\n # set column\n self._set_item(key, value)\n\n def _setitem_slice(self, key, value):\n self._check_setitem_copy()\n self.loc._setitem_with_indexer(key, value)\n\n def _setitem_array(self, key, value):\n # also raises Exception if object array with NA values\n if com.is_bool_indexer(key):\n if len(key) != len(self.index):\n raise ValueError('Item wrong length %d instead of %d!' %\n (len(key), len(self.index)))\n key = check_bool_indexer(self.index, key)\n indexer = key.nonzero()[0]\n self._check_setitem_copy()\n self.loc._setitem_with_indexer(indexer, value)\n else:\n if isinstance(value, DataFrame):\n if len(value.columns) != len(key):\n raise ValueError('Columns must be same length as key')\n for k1, k2 in zip(key, value.columns):\n self[k1] = value[k2]\n else:\n indexer = self.loc._convert_to_indexer(key, axis=1)\n self._check_setitem_copy()\n self.loc._setitem_with_indexer((slice(None), indexer), value)\n\n def _setitem_frame(self, key, value):\n # support boolean setting with DataFrame input, e.g.\n # df[df > df2] = 0\n if isinstance(key, np.ndarray):\n if key.shape != self.shape:\n raise ValueError(\n 'Array conditional must be same shape as self'\n )\n key = self._constructor(key, **self._construct_axes_dict())\n\n if key.values.size and not is_bool_dtype(key.values):\n raise TypeError(\n 'Must pass DataFrame or 2-d ndarray with boolean values only'\n )\n\n self._check_inplace_setting(value)\n self._check_setitem_copy()\n self._where(-key, value, inplace=True)\n\n def _ensure_valid_index(self, value):\n \"\"\"\n Ensure that if we don't have an index, that we can create one from the\n passed value.\n \"\"\"\n # GH5632, make sure that we are a Series convertible\n if not len(self.index) and is_list_like(value):\n try:\n value = Series(value)\n except (ValueError, NotImplementedError, TypeError):\n raise ValueError('Cannot set a frame with no defined index '\n 'and a value that cannot be converted to a '\n 'Series')\n\n self._data = self._data.reindex_axis(value.index.copy(), axis=1,\n fill_value=np.nan)\n\n def _set_item(self, key, value):\n \"\"\"\n Add series to DataFrame in specified column.\n\n If series is a numpy-array (not a Series/TimeSeries), it must be the\n same length as the DataFrames index or an error will be thrown.\n\n Series/TimeSeries will be conformed to the DataFrames index to\n ensure homogeneity.\n \"\"\"\n\n self._ensure_valid_index(value)\n value = self._sanitize_column(key, value)\n NDFrame._set_item(self, key, value)\n\n # check if we are modifying a copy\n # try to set first as we want an invalid\n # value exception to occur first\n if len(self):\n self._check_setitem_copy()\n\n def insert(self, loc, column, value, allow_duplicates=False):\n \"\"\"\n Insert column into DataFrame at specified location.\n\n Raises a ValueError if `column` is already contained in the DataFrame,\n unless `allow_duplicates` is set to True.\n\n Parameters\n ----------\n loc : int\n Insertion index. Must verify 0 <= loc <= len(columns)\n column : string, number, or hashable object\n label of the inserted column\n value : int, Series, or array-like\n allow_duplicates : bool, optional\n \"\"\"\n self._ensure_valid_index(value)\n value = self._sanitize_column(column, value, broadcast=False)\n self._data.insert(loc, column, value,\n allow_duplicates=allow_duplicates)\n\n def assign(self, **kwargs):\n r\"\"\"\n Assign new columns to a DataFrame.\n\n Returns a new object with all original columns in addition to new ones.\n Existing columns that are re-assigned will be overwritten.\n\n Parameters\n ----------\n **kwargs : dict of {str: callable or Series}\n The column names are keywords. If the values are\n callable, they are computed on the DataFrame and\n assigned to the new columns. The callable must not\n change input DataFrame (though pandas doesn't check it).\n If the values are not callable, (e.g. a Series, scalar, or array),\n they are simply assigned.\n\n Returns\n -------\n DataFrame\n A new DataFrame with the new columns in addition to\n all the existing columns.\n\n Notes\n -----\n Assigning multiple columns within the same ``assign`` is possible.\n For Python 3.6 and above, later items in '\\*\\*kwargs' may refer to\n newly created or modified columns in 'df'; items are computed and\n assigned into 'df' in order. For Python 3.5 and below, the order of\n keyword arguments is not specified, you cannot refer to newly created\n or modified columns. All items are computed first, and then assigned\n in alphabetical order.\n\n .. versionchanged :: 0.23.0\n\n Keyword argument order is maintained for Python 3.6 and later.\n\n Examples\n --------\n >>> df = pd.DataFrame({'temp_c': [17.0, 25.0]},\n ... index=['Portland', 'Berkeley'])\n >>> df\n temp_c\n Portland 17.0\n Berkeley 25.0\n\n Where the value is a callable, evaluated on `df`:\n\n >>> df.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32)\n temp_c temp_f\n Portland 17.0 62.6\n Berkeley 25.0 77.0\n\n Alternatively, the same behavior can be achieved by directly\n referencing an existing Series or sequence:\n\n >>> df.assign(temp_f=df['temp_c'] * 9 / 5 + 32)\n temp_c temp_f\n Portland 17.0 62.6\n Berkeley 25.0 77.0\n\n In Python 3.6+, you can create multiple columns within the same assign\n where one of the columns depends on another one defined within the same\n assign:\n\n >>> df.assign(temp_f=lambda x: x['temp_c'] * 9 / 5 + 32,\n ... temp_k=lambda x: (x['temp_f'] + 459.67) * 5 / 9)\n temp_c temp_f temp_k\n Portland 17.0 62.6 290.15\n Berkeley 25.0 77.0 298.15\n \"\"\"\n data = self.copy()\n\n # >= 3.6 preserve order of kwargs\n if PY36:\n for k, v in kwargs.items():\n data[k] = com.apply_if_callable(v, data)\n else:\n # <= 3.5: do all calculations first...\n results = OrderedDict()\n for k, v in kwargs.items():\n results[k] = com.apply_if_callable(v, data)\n\n # <= 3.5 and earlier\n results = sorted(results.items())\n # ... and then assign\n for k, v in results:\n data[k] = v\n return data\n\n def _sanitize_column(self, key, value, broadcast=True):\n \"\"\"\n Ensures new columns (which go into the BlockManager as new blocks) are\n always copied and converted into an array.\n\n Parameters\n ----------\n key : object\n value : scalar, Series, or array-like\n broadcast : bool, default True\n If ``key`` matches multiple duplicate column names in the\n DataFrame, this parameter indicates whether ``value`` should be\n tiled so that the returned array contains a (duplicated) column for\n each occurrence of the key. If False, ``value`` will not be tiled.\n\n Returns\n -------\n sanitized_column : numpy-array\n \"\"\"\n\n def reindexer(value):\n # reindex if necessary\n\n if value.index.equals(self.index) or not len(self.index):\n value = value._values.copy()\n else:\n\n # GH 4107\n try:\n value = value.reindex(self.index)._values\n except Exception as e:\n\n # duplicate axis\n if not value.index.is_unique:\n raise e\n\n # other\n raise TypeError('incompatible index of inserted column '\n 'with frame index')\n return value\n\n if isinstance(value, Series):\n value = reindexer(value)\n\n elif isinstance(value, DataFrame):\n # align right-hand-side columns if self.columns\n # is multi-index and self[key] is a sub-frame\n if isinstance(self.columns, MultiIndex) and key in self.columns:\n loc = self.columns.get_loc(key)\n if isinstance(loc, (slice, Series, np.ndarray, Index)):\n cols = maybe_droplevels(self.columns[loc], key)\n if len(cols) and not cols.equals(value.columns):\n value = value.reindex(cols, axis=1)\n # now align rows\n value = reindexer(value).T\n\n elif isinstance(value, ExtensionArray):\n # Explicitly copy here, instead of in sanitize_index,\n # as sanitize_index won't copy an EA, even with copy=True\n value = value.copy()\n value = sanitize_index(value, self.index, copy=False)\n\n elif isinstance(value, Index) or is_sequence(value):\n\n # turn me into an ndarray\n value = sanitize_index(value, self.index, copy=False)\n if not isinstance(value, (np.ndarray, Index)):\n if isinstance(value, list) and len(value) > 0:\n value = maybe_convert_platform(value)\n else:\n value = com.asarray_tuplesafe(value)\n elif value.ndim == 2:\n value = value.copy().T\n elif isinstance(value, Index):\n value = value.copy(deep=True)\n else:\n value = value.copy()\n\n # possibly infer to datetimelike\n if is_object_dtype(value.dtype):\n value = maybe_infer_to_datetimelike(value)\n\n else:\n # cast ignores pandas dtypes. so save the dtype first\n infer_dtype, _ = infer_dtype_from_scalar(\n value, pandas_dtype=True)\n\n # upcast\n value = cast_scalar_to_array(len(self.index), value)\n value = maybe_cast_to_datetime(value, infer_dtype)\n\n # return internal types directly\n if is_extension_type(value) or is_extension_array_dtype(value):\n return value\n\n # broadcast across multiple columns if necessary\n if broadcast and key in self.columns and value.ndim == 1:\n if (not self.columns.is_unique or\n isinstance(self.columns, MultiIndex)):\n existing_piece = self[key]\n if isinstance(existing_piece, DataFrame):\n value = np.tile(value, (len(existing_piece.columns), 1))\n\n return np.atleast_2d(np.asarray(value))\n\n @property\n def _series(self):\n return {item: Series(self._data.iget(idx), index=self.index, name=item)\n for idx, item in enumerate(self.columns)}\n\n def lookup(self, row_labels, col_labels):\n \"\"\"\n Label-based \"fancy indexing\" function for DataFrame.\n\n Given equal-length arrays of row and column labels, return an\n array of the values corresponding to each (row, col) pair.\n\n Parameters\n ----------\n row_labels : sequence\n The row labels to use for lookup\n col_labels : sequence\n The column labels to use for lookup\n\n Notes\n -----\n Akin to::\n\n result = [df.get_value(row, col)\n for row, col in zip(row_labels, col_labels)]\n\n Examples\n --------\n values : ndarray\n The found values\n \"\"\"\n n = len(row_labels)\n if n != len(col_labels):\n raise ValueError('Row labels must have same size as column labels')\n\n thresh = 1000\n if not self._is_mixed_type or n > thresh:\n values = self.values\n ridx = self.index.get_indexer(row_labels)\n cidx = self.columns.get_indexer(col_labels)\n if (ridx == -1).any():\n raise KeyError('One or more row labels was not found')\n if (cidx == -1).any():\n raise KeyError('One or more column labels was not found')\n flat_index = ridx * len(self.columns) + cidx\n result = values.flat[flat_index]\n else:\n result = np.empty(n, dtype='O')\n for i, (r, c) in enumerate(zip(row_labels, col_labels)):\n result[i] = self._get_value(r, c)\n\n if is_object_dtype(result):\n result = lib.maybe_convert_objects(result)\n\n return result\n\n # ----------------------------------------------------------------------\n # Reindexing and alignment\n\n def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value,\n copy):\n frame = self\n\n columns = axes['columns']\n if columns is not None:\n frame = frame._reindex_columns(columns, method, copy, level,\n fill_value, limit, tolerance)\n\n index = axes['index']\n if index is not None:\n frame = frame._reindex_index(index, method, copy, level,\n fill_value, limit, tolerance)\n\n return frame\n\n def _reindex_index(self, new_index, method, copy, level, fill_value=np.nan,\n limit=None, tolerance=None):\n new_index, indexer = self.index.reindex(new_index, method=method,\n level=level, limit=limit,\n tolerance=tolerance)\n return self._reindex_with_indexers({0: [new_index, indexer]},\n copy=copy, fill_value=fill_value,\n allow_dups=False)\n\n def _reindex_columns(self, new_columns, method, copy, level,\n fill_value=None, limit=None, tolerance=None):\n new_columns, indexer = self.columns.reindex(new_columns, method=method,\n level=level, limit=limit,\n tolerance=tolerance)\n return self._reindex_with_indexers({1: [new_columns, indexer]},\n copy=copy, fill_value=fill_value,\n allow_dups=False)\n\n def _reindex_multi(self, axes, copy, fill_value):\n \"\"\"\n We are guaranteed non-Nones in the axes.\n \"\"\"\n\n new_index, row_indexer = self.index.reindex(axes['index'])\n new_columns, col_indexer = self.columns.reindex(axes['columns'])\n\n if row_indexer is not None and col_indexer is not None:\n indexer = row_indexer, col_indexer\n new_values = algorithms.take_2d_multi(self.values, indexer,\n fill_value=fill_value)\n return self._constructor(new_values, index=new_index,\n columns=new_columns)\n else:\n return self._reindex_with_indexers({0: [new_index, row_indexer],\n 1: [new_columns, col_indexer]},\n copy=copy,\n fill_value=fill_value)\n\n @Appender(_shared_docs['align'] % _shared_doc_kwargs)\n def align(self, other, join='outer', axis=None, level=None, copy=True,\n fill_value=None, method=None, limit=None, fill_axis=0,\n broadcast_axis=None):\n return super(DataFrame, self).align(other, join=join, axis=axis,\n level=level, copy=copy,\n fill_value=fill_value,\n method=method, limit=limit,\n fill_axis=fill_axis,\n broadcast_axis=broadcast_axis)\n\n @Substitution(**_shared_doc_kwargs)\n @Appender(NDFrame.reindex.__doc__)\n @rewrite_axis_style_signature('labels', [('method', None),\n ('copy', True),\n ('level', None),\n ('fill_value', np.nan),\n ('limit', None),\n ('tolerance', None)])\n def reindex(self, *args, **kwargs):\n axes = validate_axis_style_args(self, args, kwargs, 'labels',\n 'reindex')\n kwargs.update(axes)\n # Pop these, since the values are in `kwargs` under different names\n kwargs.pop('axis', None)\n kwargs.pop('labels', None)\n return super(DataFrame, self).reindex(**kwargs)\n\n @Appender(_shared_docs['reindex_axis'] % _shared_doc_kwargs)\n def reindex_axis(self, labels, axis=0, method=None, level=None, copy=True,\n limit=None, fill_value=np.nan):\n return super(DataFrame,\n self).reindex_axis(labels=labels, axis=axis,\n method=method, level=level, copy=copy,\n limit=limit, fill_value=fill_value)\n\n def drop(self, labels=None, axis=0, index=None, columns=None,\n level=None, inplace=False, errors='raise'):\n \"\"\"\n Drop specified labels from rows or columns.\n\n Remove rows or columns by specifying label names and corresponding\n axis, or by specifying directly index or column names. When using a\n multi-index, labels on different levels can be removed by specifying\n the level.\n\n Parameters\n ----------\n labels : single label or list-like\n Index or column labels to drop.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Whether to drop labels from the index (0 or 'index') or\n columns (1 or 'columns').\n index, columns : single label or list-like\n Alternative to specifying axis (``labels, axis=1``\n is equivalent to ``columns=labels``).\n\n .. versionadded:: 0.21.0\n level : int or level name, optional\n For MultiIndex, level from which the labels will be removed.\n inplace : bool, default False\n If True, do operation inplace and return None.\n errors : {'ignore', 'raise'}, default 'raise'\n If 'ignore', suppress error and only existing labels are\n dropped.\n\n Returns\n -------\n dropped : pandas.DataFrame\n\n Raises\n ------\n KeyError\n If none of the labels are found in the selected axis\n\n See Also\n --------\n DataFrame.loc : Label-location based indexer for selection by label.\n DataFrame.dropna : Return DataFrame with labels on given axis omitted\n where (all or any) data are missing.\n DataFrame.drop_duplicates : Return DataFrame with duplicate rows\n removed, optionally only considering certain columns.\n Series.drop : Return Series with specified index labels removed.\n\n Examples\n --------\n >>> df = pd.DataFrame(np.arange(12).reshape(3,4),\n ... columns=['A', 'B', 'C', 'D'])\n >>> df\n A B C D\n 0 0 1 2 3\n 1 4 5 6 7\n 2 8 9 10 11\n\n Drop columns\n\n >>> df.drop(['B', 'C'], axis=1)\n A D\n 0 0 3\n 1 4 7\n 2 8 11\n\n >>> df.drop(columns=['B', 'C'])\n A D\n 0 0 3\n 1 4 7\n 2 8 11\n\n Drop a row by index\n\n >>> df.drop([0, 1])\n A B C D\n 2 8 9 10 11\n\n Drop columns and/or rows of MultiIndex DataFrame\n\n >>> midx = pd.MultiIndex(levels=[['lama', 'cow', 'falcon'],\n ... ['speed', 'weight', 'length']],\n ... codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2],\n ... [0, 1, 2, 0, 1, 2, 0, 1, 2]])\n >>> df = pd.DataFrame(index=midx, columns=['big', 'small'],\n ... data=[[45, 30], [200, 100], [1.5, 1], [30, 20],\n ... [250, 150], [1.5, 0.8], [320, 250],\n ... [1, 0.8], [0.3,0.2]])\n >>> df\n big small\n lama speed 45.0 30.0\n weight 200.0 100.0\n length 1.5 1.0\n cow speed 30.0 20.0\n weight 250.0 150.0\n length 1.5 0.8\n falcon speed 320.0 250.0\n weight 1.0 0.8\n length 0.3 0.2\n\n >>> df.drop(index='cow', columns='small')\n big\n lama speed 45.0\n weight 200.0\n length 1.5\n falcon speed 320.0\n weight 1.0\n length 0.3\n\n >>> df.drop(index='length', level=1)\n big small\n lama speed 45.0 30.0\n weight 200.0 100.0\n cow speed 30.0 20.0\n weight 250.0 150.0\n falcon speed 320.0 250.0\n weight 1.0 0.8\n \"\"\"\n return super(DataFrame, self).drop(labels=labels, axis=axis,\n index=index, columns=columns,\n level=level, inplace=inplace,\n errors=errors)\n\n @rewrite_axis_style_signature('mapper', [('copy', True),\n ('inplace', False),\n ('level', None)])\n def rename(self, *args, **kwargs):\n \"\"\"\n Alter axes labels.\n\n Function / dict values must be unique (1-to-1). Labels not contained in\n a dict / Series will be left as-is. Extra labels listed don't throw an\n error.\n\n See the :ref:`user guide <basics.rename>` for more.\n\n Parameters\n ----------\n mapper, index, columns : dict-like or function, optional\n dict-like or functions transformations to apply to\n that axis' values. Use either ``mapper`` and ``axis`` to\n specify the axis to target with ``mapper``, or ``index`` and\n ``columns``.\n axis : int or str, optional\n Axis to target with ``mapper``. Can be either the axis name\n ('index', 'columns') or number (0, 1). The default is 'index'.\n copy : boolean, default True\n Also copy underlying data\n inplace : boolean, default False\n Whether to return a new DataFrame. If True then value of copy is\n ignored.\n level : int or level name, default None\n In case of a MultiIndex, only rename labels in the specified\n level.\n\n Returns\n -------\n renamed : DataFrame\n\n See Also\n --------\n pandas.DataFrame.rename_axis\n\n Examples\n --------\n\n ``DataFrame.rename`` supports two calling conventions\n\n * ``(index=index_mapper, columns=columns_mapper, ...)``\n * ``(mapper, axis={'index', 'columns'}, ...)``\n\n We *highly* recommend using keyword arguments to clarify your\n intent.\n\n >>> df = pd.DataFrame({\"A\": [1, 2, 3], \"B\": [4, 5, 6]})\n >>> df.rename(index=str, columns={\"A\": \"a\", \"B\": \"c\"})\n a c\n 0 1 4\n 1 2 5\n 2 3 6\n\n >>> df.rename(index=str, columns={\"A\": \"a\", \"C\": \"c\"})\n a B\n 0 1 4\n 1 2 5\n 2 3 6\n\n Using axis-style parameters\n\n >>> df.rename(str.lower, axis='columns')\n a b\n 0 1 4\n 1 2 5\n 2 3 6\n\n >>> df.rename({1: 2, 2: 4}, axis='index')\n A B\n 0 1 4\n 2 2 5\n 4 3 6\n \"\"\"\n axes = validate_axis_style_args(self, args, kwargs, 'mapper', 'rename')\n kwargs.update(axes)\n # Pop these, since the values are in `kwargs` under different names\n kwargs.pop('axis', None)\n kwargs.pop('mapper', None)\n return super(DataFrame, self).rename(**kwargs)\n\n @Substitution(**_shared_doc_kwargs)\n @Appender(NDFrame.fillna.__doc__)\n def fillna(self, value=None, method=None, axis=None, inplace=False,\n limit=None, downcast=None, **kwargs):\n return super(DataFrame,\n self).fillna(value=value, method=method, axis=axis,\n inplace=inplace, limit=limit,\n downcast=downcast, **kwargs)\n\n @Appender(_shared_docs['replace'] % _shared_doc_kwargs)\n def replace(self, to_replace=None, value=None, inplace=False, limit=None,\n regex=False, method='pad'):\n return super(DataFrame, self).replace(to_replace=to_replace,\n value=value, inplace=inplace,\n limit=limit, regex=regex,\n method=method)\n\n @Appender(_shared_docs['shift'] % _shared_doc_kwargs)\n def shift(self, periods=1, freq=None, axis=0):\n return super(DataFrame, self).shift(periods=periods, freq=freq,\n axis=axis)\n\n def set_index(self, keys, drop=True, append=False, inplace=False,\n verify_integrity=False):\n \"\"\"\n Set the DataFrame index using existing columns.\n\n Set the DataFrame index (row labels) using one or more existing\n columns. The index can replace the existing index or expand on it.\n\n Parameters\n ----------\n keys : label or list of label\n Name or names of the columns that will be used as the index.\n drop : bool, default True\n Delete columns to be used as the new index.\n append : bool, default False\n Whether to append columns to existing index.\n inplace : bool, default False\n Modify the DataFrame in place (do not create a new object).\n verify_integrity : bool, default False\n Check the new index for duplicates. Otherwise defer the check until\n necessary. Setting to False will improve the performance of this\n method.\n\n Returns\n -------\n DataFrame\n Changed row labels.\n\n See Also\n --------\n DataFrame.reset_index : Opposite of set_index.\n DataFrame.reindex : Change to new indices or expand indices.\n DataFrame.reindex_like : Change to same indices as other DataFrame.\n\n Examples\n --------\n >>> df = pd.DataFrame({'month': [1, 4, 7, 10],\n ... 'year': [2012, 2014, 2013, 2014],\n ... 'sale': [55, 40, 84, 31]})\n >>> df\n month year sale\n 0 1 2012 55\n 1 4 2014 40\n 2 7 2013 84\n 3 10 2014 31\n\n Set the index to become the 'month' column:\n\n >>> df.set_index('month')\n year sale\n month\n 1 2012 55\n 4 2014 40\n 7 2013 84\n 10 2014 31\n\n Create a multi-index using columns 'year' and 'month':\n\n >>> df.set_index(['year', 'month'])\n sale\n year month\n 2012 1 55\n 2014 4 40\n 2013 7 84\n 2014 10 31\n\n Create a multi-index using a set of values and a column:\n\n >>> df.set_index([[1, 2, 3, 4], 'year'])\n month sale\n year\n 1 2012 1 55\n 2 2014 4 40\n 3 2013 7 84\n 4 2014 10 31\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n if not isinstance(keys, list):\n keys = [keys]\n\n missing = []\n for col in keys:\n if (is_scalar(col) or isinstance(col, tuple)) and col in self:\n # tuples can be both column keys or list-likes\n # if they are valid column keys, everything is fine\n continue\n elif is_scalar(col) and col not in self:\n # tuples that are not column keys are considered list-like,\n # not considered missing\n missing.append(col)\n elif (not is_list_like(col, allow_sets=False)\n or getattr(col, 'ndim', 1) > 1):\n raise TypeError('The parameter \"keys\" may only contain a '\n 'combination of valid column keys and '\n 'one-dimensional list-likes')\n\n if missing:\n raise KeyError('{}'.format(missing))\n\n if inplace:\n frame = self\n else:\n frame = self.copy()\n\n arrays = []\n names = []\n if append:\n names = [x for x in self.index.names]\n if isinstance(self.index, ABCMultiIndex):\n for i in range(self.index.nlevels):\n arrays.append(self.index._get_level_values(i))\n else:\n arrays.append(self.index)\n\n to_remove = []\n for col in keys:\n if isinstance(col, ABCMultiIndex):\n for n in range(col.nlevels):\n arrays.append(col._get_level_values(n))\n names.extend(col.names)\n elif isinstance(col, (ABCIndexClass, ABCSeries)):\n # if Index then not MultiIndex (treated above)\n arrays.append(col)\n names.append(col.name)\n elif isinstance(col, (list, np.ndarray)):\n arrays.append(col)\n names.append(None)\n elif (is_list_like(col)\n and not (isinstance(col, tuple) and col in self)):\n # all other list-likes (but avoid valid column keys)\n col = list(col) # ensure iterator do not get read twice etc.\n arrays.append(col)\n names.append(None)\n # from here, col can only be a column label\n else:\n arrays.append(frame[col]._values)\n names.append(col)\n if drop:\n to_remove.append(col)\n\n index = ensure_index_from_sequences(arrays, names)\n\n if verify_integrity and not index.is_unique:\n duplicates = index[index.duplicated()].unique()\n raise ValueError('Index has duplicate keys: {dup}'.format(\n dup=duplicates))\n\n # use set to handle duplicate column names gracefully in case of drop\n for c in set(to_remove):\n del frame[c]\n\n # clear up memory usage\n index._cleanup()\n\n frame.index = index\n\n if not inplace:\n return frame\n\n def reset_index(self, level=None, drop=False, inplace=False, col_level=0,\n col_fill=''):\n \"\"\"\n Reset the index, or a level of it.\n\n Reset the index of the DataFrame, and use the default one instead.\n If the DataFrame has a MultiIndex, this method can remove one or more\n levels.\n\n Parameters\n ----------\n level : int, str, tuple, or list, default None\n Only remove the given levels from the index. Removes all levels by\n default.\n drop : bool, default False\n Do not try to insert index into dataframe columns. This resets\n the index to the default integer index.\n inplace : bool, default False\n Modify the DataFrame in place (do not create a new object).\n col_level : int or str, default 0\n If the columns have multiple levels, determines which level the\n labels are inserted into. By default it is inserted into the first\n level.\n col_fill : object, default ''\n If the columns have multiple levels, determines how the other\n levels are named. If None then the index name is repeated.\n\n Returns\n -------\n DataFrame\n DataFrame with the new index.\n\n See Also\n --------\n DataFrame.set_index : Opposite of reset_index.\n DataFrame.reindex : Change to new indices or expand indices.\n DataFrame.reindex_like : Change to same indices as other DataFrame.\n\n Examples\n --------\n >>> df = pd.DataFrame([('bird', 389.0),\n ... ('bird', 24.0),\n ... ('mammal', 80.5),\n ... ('mammal', np.nan)],\n ... index=['falcon', 'parrot', 'lion', 'monkey'],\n ... columns=('class', 'max_speed'))\n >>> df\n class max_speed\n falcon bird 389.0\n parrot bird 24.0\n lion mammal 80.5\n monkey mammal NaN\n\n When we reset the index, the old index is added as a column, and a\n new sequential index is used:\n\n >>> df.reset_index()\n index class max_speed\n 0 falcon bird 389.0\n 1 parrot bird 24.0\n 2 lion mammal 80.5\n 3 monkey mammal NaN\n\n We can use the `drop` parameter to avoid the old index being added as\n a column:\n\n >>> df.reset_index(drop=True)\n class max_speed\n 0 bird 389.0\n 1 bird 24.0\n 2 mammal 80.5\n 3 mammal NaN\n\n You can also use `reset_index` with `MultiIndex`.\n\n >>> index = pd.MultiIndex.from_tuples([('bird', 'falcon'),\n ... ('bird', 'parrot'),\n ... ('mammal', 'lion'),\n ... ('mammal', 'monkey')],\n ... names=['class', 'name'])\n >>> columns = pd.MultiIndex.from_tuples([('speed', 'max'),\n ... ('species', 'type')])\n >>> df = pd.DataFrame([(389.0, 'fly'),\n ... ( 24.0, 'fly'),\n ... ( 80.5, 'run'),\n ... (np.nan, 'jump')],\n ... index=index,\n ... columns=columns)\n >>> df\n speed species\n max type\n class name\n bird falcon 389.0 fly\n parrot 24.0 fly\n mammal lion 80.5 run\n monkey NaN jump\n\n If the index has multiple levels, we can reset a subset of them:\n\n >>> df.reset_index(level='class')\n class speed species\n max type\n name\n falcon bird 389.0 fly\n parrot bird 24.0 fly\n lion mammal 80.5 run\n monkey mammal NaN jump\n\n If we are not dropping the index, by default, it is placed in the top\n level. We can place it in another level:\n\n >>> df.reset_index(level='class', col_level=1)\n speed species\n class max type\n name\n falcon bird 389.0 fly\n parrot bird 24.0 fly\n lion mammal 80.5 run\n monkey mammal NaN jump\n\n When the index is inserted under another level, we can specify under\n which one with the parameter `col_fill`:\n\n >>> df.reset_index(level='class', col_level=1, col_fill='species')\n species speed species\n class max type\n name\n falcon bird 389.0 fly\n parrot bird 24.0 fly\n lion mammal 80.5 run\n monkey mammal NaN jump\n\n If we specify a nonexistent level for `col_fill`, it is created:\n\n >>> df.reset_index(level='class', col_level=1, col_fill='genus')\n genus speed species\n class max type\n name\n falcon bird 389.0 fly\n parrot bird 24.0 fly\n lion mammal 80.5 run\n monkey mammal NaN jump\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n if inplace:\n new_obj = self\n else:\n new_obj = self.copy()\n\n def _maybe_casted_values(index, labels=None):\n values = index._values\n if not isinstance(index, (PeriodIndex, DatetimeIndex)):\n if values.dtype == np.object_:\n values = lib.maybe_convert_objects(values)\n\n # if we have the labels, extract the values with a mask\n if labels is not None:\n mask = labels == -1\n\n # we can have situations where the whole mask is -1,\n # meaning there is nothing found in labels, so make all nan's\n if mask.all():\n values = np.empty(len(mask))\n values.fill(np.nan)\n else:\n values = values.take(labels)\n if mask.any():\n values, changed = maybe_upcast_putmask(\n values, mask, np.nan)\n return values\n\n new_index = ibase.default_index(len(new_obj))\n if level is not None:\n if not isinstance(level, (tuple, list)):\n level = [level]\n level = [self.index._get_level_number(lev) for lev in level]\n if len(level) < self.index.nlevels:\n new_index = self.index.droplevel(level)\n\n if not drop:\n if isinstance(self.index, MultiIndex):\n names = [n if n is not None else ('level_%d' % i)\n for (i, n) in enumerate(self.index.names)]\n to_insert = lzip(self.index.levels, self.index.codes)\n else:\n default = 'index' if 'index' not in self else 'level_0'\n names = ([default] if self.index.name is None\n else [self.index.name])\n to_insert = ((self.index, None),)\n\n multi_col = isinstance(self.columns, MultiIndex)\n for i, (lev, lab) in reversed(list(enumerate(to_insert))):\n if not (level is None or i in level):\n continue\n name = names[i]\n if multi_col:\n col_name = (list(name) if isinstance(name, tuple)\n else [name])\n if col_fill is None:\n if len(col_name) not in (1, self.columns.nlevels):\n raise ValueError(\"col_fill=None is incompatible \"\n \"with incomplete column name \"\n \"{}\".format(name))\n col_fill = col_name[0]\n\n lev_num = self.columns._get_level_number(col_level)\n name_lst = [col_fill] * lev_num + col_name\n missing = self.columns.nlevels - len(name_lst)\n name_lst += [col_fill] * missing\n name = tuple(name_lst)\n # to ndarray and maybe infer different dtype\n level_values = _maybe_casted_values(lev, lab)\n new_obj.insert(0, name, level_values)\n\n new_obj.index = new_index\n if not inplace:\n return new_obj\n\n # ----------------------------------------------------------------------\n # Reindex-based selection methods\n\n @Appender(_shared_docs['isna'] % _shared_doc_kwargs)\n def isna(self):\n return super(DataFrame, self).isna()\n\n @Appender(_shared_docs['isna'] % _shared_doc_kwargs)\n def isnull(self):\n return super(DataFrame, self).isnull()\n\n @Appender(_shared_docs['notna'] % _shared_doc_kwargs)\n def notna(self):\n return super(DataFrame, self).notna()\n\n @Appender(_shared_docs['notna'] % _shared_doc_kwargs)\n def notnull(self):\n return super(DataFrame, self).notnull()\n\n def dropna(self, axis=0, how='any', thresh=None, subset=None,\n inplace=False):\n \"\"\"\n Remove missing values.\n\n See the :ref:`User Guide <missing_data>` for more on which values are\n considered missing, and how to work with missing data.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Determine if rows or columns which contain missing values are\n removed.\n\n * 0, or 'index' : Drop rows which contain missing values.\n * 1, or 'columns' : Drop columns which contain missing value.\n\n .. deprecated:: 0.23.0\n\n Pass tuple or list to drop on multiple axes.\n Only a single axis is allowed.\n\n how : {'any', 'all'}, default 'any'\n Determine if row or column is removed from DataFrame, when we have\n at least one NA or all NA.\n\n * 'any' : If any NA values are present, drop that row or column.\n * 'all' : If all values are NA, drop that row or column.\n\n thresh : int, optional\n Require that many non-NA values.\n subset : array-like, optional\n Labels along other axis to consider, e.g. if you are dropping rows\n these would be a list of columns to include.\n inplace : bool, default False\n If True, do operation inplace and return None.\n\n Returns\n -------\n DataFrame\n DataFrame with NA entries dropped from it.\n\n See Also\n --------\n DataFrame.isna: Indicate missing values.\n DataFrame.notna : Indicate existing (non-missing) values.\n DataFrame.fillna : Replace missing values.\n Series.dropna : Drop missing values.\n Index.dropna : Drop missing indices.\n\n Examples\n --------\n >>> df = pd.DataFrame({\"name\": ['Alfred', 'Batman', 'Catwoman'],\n ... \"toy\": [np.nan, 'Batmobile', 'Bullwhip'],\n ... \"born\": [pd.NaT, pd.Timestamp(\"1940-04-25\"),\n ... pd.NaT]})\n >>> df\n name toy born\n 0 Alfred NaN NaT\n 1 Batman Batmobile 1940-04-25\n 2 Catwoman Bullwhip NaT\n\n Drop the rows where at least one element is missing.\n\n >>> df.dropna()\n name toy born\n 1 Batman Batmobile 1940-04-25\n\n Drop the columns where at least one element is missing.\n\n >>> df.dropna(axis='columns')\n name\n 0 Alfred\n 1 Batman\n 2 Catwoman\n\n Drop the rows where all elements are missing.\n\n >>> df.dropna(how='all')\n name toy born\n 0 Alfred NaN NaT\n 1 Batman Batmobile 1940-04-25\n 2 Catwoman Bullwhip NaT\n\n Keep only the rows with at least 2 non-NA values.\n\n >>> df.dropna(thresh=2)\n name toy born\n 1 Batman Batmobile 1940-04-25\n 2 Catwoman Bullwhip NaT\n\n Define in which columns to look for missing values.\n\n >>> df.dropna(subset=['name', 'born'])\n name toy born\n 1 Batman Batmobile 1940-04-25\n\n Keep the DataFrame with valid entries in the same variable.\n\n >>> df.dropna(inplace=True)\n >>> df\n name toy born\n 1 Batman Batmobile 1940-04-25\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n if isinstance(axis, (tuple, list)):\n # GH20987\n msg = (\"supplying multiple axes to axis is deprecated and \"\n \"will be removed in a future version.\")\n warnings.warn(msg, FutureWarning, stacklevel=2)\n\n result = self\n for ax in axis:\n result = result.dropna(how=how, thresh=thresh, subset=subset,\n axis=ax)\n else:\n axis = self._get_axis_number(axis)\n agg_axis = 1 - axis\n\n agg_obj = self\n if subset is not None:\n ax = self._get_axis(agg_axis)\n indices = ax.get_indexer_for(subset)\n check = indices == -1\n if check.any():\n raise KeyError(list(np.compress(check, subset)))\n agg_obj = self.take(indices, axis=agg_axis)\n\n count = agg_obj.count(axis=agg_axis)\n\n if thresh is not None:\n mask = count >= thresh\n elif how == 'any':\n mask = count == len(agg_obj._get_axis(agg_axis))\n elif how == 'all':\n mask = count > 0\n else:\n if how is not None:\n raise ValueError('invalid how option: {h}'.format(h=how))\n else:\n raise TypeError('must specify how or thresh')\n\n result = self._take(mask.nonzero()[0], axis=axis)\n\n if inplace:\n self._update_inplace(result)\n else:\n return result\n\n def drop_duplicates(self, subset=None, keep='first', inplace=False):\n \"\"\"\n Return DataFrame with duplicate rows removed, optionally only\n considering certain columns.\n\n Parameters\n ----------\n subset : column label or sequence of labels, optional\n Only consider certain columns for identifying duplicates, by\n default use all of the columns\n keep : {'first', 'last', False}, default 'first'\n - ``first`` : Drop duplicates except for the first occurrence.\n - ``last`` : Drop duplicates except for the last occurrence.\n - False : Drop all duplicates.\n inplace : boolean, default False\n Whether to drop duplicates in place or to return a copy\n\n Returns\n -------\n deduplicated : DataFrame\n \"\"\"\n if self.empty:\n return self.copy()\n\n inplace = validate_bool_kwarg(inplace, 'inplace')\n duplicated = self.duplicated(subset, keep=keep)\n\n if inplace:\n inds, = (-duplicated).nonzero()\n new_data = self._data.take(inds)\n self._update_inplace(new_data)\n else:\n return self[-duplicated]\n\n def duplicated(self, subset=None, keep='first'):\n \"\"\"\n Return boolean Series denoting duplicate rows, optionally only\n considering certain columns.\n\n Parameters\n ----------\n subset : column label or sequence of labels, optional\n Only consider certain columns for identifying duplicates, by\n default use all of the columns\n keep : {'first', 'last', False}, default 'first'\n - ``first`` : Mark duplicates as ``True`` except for the\n first occurrence.\n - ``last`` : Mark duplicates as ``True`` except for the\n last occurrence.\n - False : Mark all duplicates as ``True``.\n\n Returns\n -------\n duplicated : Series\n \"\"\"\n from pandas.core.sorting import get_group_index\n from pandas._libs.hashtable import duplicated_int64, _SIZE_HINT_LIMIT\n\n if self.empty:\n return Series()\n\n def f(vals):\n labels, shape = algorithms.factorize(\n vals, size_hint=min(len(self), _SIZE_HINT_LIMIT))\n return labels.astype('i8', copy=False), len(shape)\n\n if subset is None:\n subset = self.columns\n elif (not np.iterable(subset) or\n isinstance(subset, compat.string_types) or\n isinstance(subset, tuple) and subset in self.columns):\n subset = subset,\n\n # Verify all columns in subset exist in the queried dataframe\n # Otherwise, raise a KeyError, same as if you try to __getitem__ with a\n # key that doesn't exist.\n diff = Index(subset).difference(self.columns)\n if not diff.empty:\n raise KeyError(diff)\n\n vals = (col.values for name, col in self.iteritems()\n if name in subset)\n labels, shape = map(list, zip(*map(f, vals)))\n\n ids = get_group_index(labels, shape, sort=False, xnull=False)\n return Series(duplicated_int64(ids, keep), index=self.index)\n\n # ----------------------------------------------------------------------\n # Sorting\n\n @Substitution(**_shared_doc_kwargs)\n @Appender(NDFrame.sort_values.__doc__)\n def sort_values(self, by, axis=0, ascending=True, inplace=False,\n kind='quicksort', na_position='last'):\n inplace = validate_bool_kwarg(inplace, 'inplace')\n axis = self._get_axis_number(axis)\n\n if not isinstance(by, list):\n by = [by]\n if is_sequence(ascending) and len(by) != len(ascending):\n raise ValueError('Length of ascending (%d) != length of by (%d)' %\n (len(ascending), len(by)))\n if len(by) > 1:\n from pandas.core.sorting import lexsort_indexer\n\n keys = [self._get_label_or_level_values(x, axis=axis)\n for x in by]\n indexer = lexsort_indexer(keys, orders=ascending,\n na_position=na_position)\n indexer = ensure_platform_int(indexer)\n else:\n from pandas.core.sorting import nargsort\n\n by = by[0]\n k = self._get_label_or_level_values(by, axis=axis)\n\n if isinstance(ascending, (tuple, list)):\n ascending = ascending[0]\n\n indexer = nargsort(k, kind=kind, ascending=ascending,\n na_position=na_position)\n\n new_data = self._data.take(indexer,\n axis=self._get_block_manager_axis(axis),\n verify=False)\n\n if inplace:\n return self._update_inplace(new_data)\n else:\n return self._constructor(new_data).__finalize__(self)\n\n @Substitution(**_shared_doc_kwargs)\n @Appender(NDFrame.sort_index.__doc__)\n def sort_index(self, axis=0, level=None, ascending=True, inplace=False,\n kind='quicksort', na_position='last', sort_remaining=True,\n by=None):\n\n # TODO: this can be combined with Series.sort_index impl as\n # almost identical\n\n inplace = validate_bool_kwarg(inplace, 'inplace')\n # 10726\n if by is not None:\n warnings.warn(\"by argument to sort_index is deprecated, \"\n \"please use .sort_values(by=...)\",\n FutureWarning, stacklevel=2)\n if level is not None:\n raise ValueError(\"unable to simultaneously sort by and level\")\n return self.sort_values(by, axis=axis, ascending=ascending,\n inplace=inplace)\n\n axis = self._get_axis_number(axis)\n labels = self._get_axis(axis)\n\n # make sure that the axis is lexsorted to start\n # if not we need to reconstruct to get the correct indexer\n labels = labels._sort_levels_monotonic()\n if level is not None:\n\n new_axis, indexer = labels.sortlevel(level, ascending=ascending,\n sort_remaining=sort_remaining)\n\n elif isinstance(labels, MultiIndex):\n from pandas.core.sorting import lexsort_indexer\n\n indexer = lexsort_indexer(labels._get_codes_for_sorting(),\n orders=ascending,\n na_position=na_position)\n else:\n from pandas.core.sorting import nargsort\n\n # Check monotonic-ness before sort an index\n # GH11080\n if ((ascending and labels.is_monotonic_increasing) or\n (not ascending and labels.is_monotonic_decreasing)):\n if inplace:\n return\n else:\n return self.copy()\n\n indexer = nargsort(labels, kind=kind, ascending=ascending,\n na_position=na_position)\n\n baxis = self._get_block_manager_axis(axis)\n new_data = self._data.take(indexer,\n axis=baxis,\n verify=False)\n\n # reconstruct axis if needed\n new_data.axes[baxis] = new_data.axes[baxis]._sort_levels_monotonic()\n\n if inplace:\n return self._update_inplace(new_data)\n else:\n return self._constructor(new_data).__finalize__(self)\n\n def nlargest(self, n, columns, keep='first'):\n \"\"\"\n Return the first `n` rows ordered by `columns` in descending order.\n\n Return the first `n` rows with the largest values in `columns`, in\n descending order. The columns that are not specified are returned as\n well, but not used for ordering.\n\n This method is equivalent to\n ``df.sort_values(columns, ascending=False).head(n)``, but more\n performant.\n\n Parameters\n ----------\n n : int\n Number of rows to return.\n columns : label or list of labels\n Column label(s) to order by.\n keep : {'first', 'last', 'all'}, default 'first'\n Where there are duplicate values:\n\n - `first` : prioritize the first occurrence(s)\n - `last` : prioritize the last occurrence(s)\n - ``all`` : do not drop any duplicates, even it means\n selecting more than `n` items.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n DataFrame\n The first `n` rows ordered by the given columns in descending\n order.\n\n See Also\n --------\n DataFrame.nsmallest : Return the first `n` rows ordered by `columns` in\n ascending order.\n DataFrame.sort_values : Sort DataFrame by the values.\n DataFrame.head : Return the first `n` rows without re-ordering.\n\n Notes\n -----\n This function cannot be used with all column types. For example, when\n specifying columns with `object` or `category` dtypes, ``TypeError`` is\n raised.\n\n Examples\n --------\n >>> df = pd.DataFrame({'population': [59000000, 65000000, 434000,\n ... 434000, 434000, 337000, 11300,\n ... 11300, 11300],\n ... 'GDP': [1937894, 2583560 , 12011, 4520, 12128,\n ... 17036, 182, 38, 311],\n ... 'alpha-2': [\"IT\", \"FR\", \"MT\", \"MV\", \"BN\",\n ... \"IS\", \"NR\", \"TV\", \"AI\"]},\n ... index=[\"Italy\", \"France\", \"Malta\",\n ... \"Maldives\", \"Brunei\", \"Iceland\",\n ... \"Nauru\", \"Tuvalu\", \"Anguilla\"])\n >>> df\n population GDP alpha-2\n Italy 59000000 1937894 IT\n France 65000000 2583560 FR\n Malta 434000 12011 MT\n Maldives 434000 4520 MV\n Brunei 434000 12128 BN\n Iceland 337000 17036 IS\n Nauru 11300 182 NR\n Tuvalu 11300 38 TV\n Anguilla 11300 311 AI\n\n In the following example, we will use ``nlargest`` to select the three\n rows having the largest values in column \"population\".\n\n >>> df.nlargest(3, 'population')\n population GDP alpha-2\n France 65000000 2583560 FR\n Italy 59000000 1937894 IT\n Malta 434000 12011 MT\n\n When using ``keep='last'``, ties are resolved in reverse order:\n\n >>> df.nlargest(3, 'population', keep='last')\n population GDP alpha-2\n France 65000000 2583560 FR\n Italy 59000000 1937894 IT\n Brunei 434000 12128 BN\n\n When using ``keep='all'``, all duplicate items are maintained:\n\n >>> df.nlargest(3, 'population', keep='all')\n population GDP alpha-2\n France 65000000 2583560 FR\n Italy 59000000 1937894 IT\n Malta 434000 12011 MT\n Maldives 434000 4520 MV\n Brunei 434000 12128 BN\n\n To order by the largest values in column \"population\" and then \"GDP\",\n we can specify multiple columns like in the next example.\n\n >>> df.nlargest(3, ['population', 'GDP'])\n population GDP alpha-2\n France 65000000 2583560 FR\n Italy 59000000 1937894 IT\n Brunei 434000 12128 BN\n \"\"\"\n return algorithms.SelectNFrame(self,\n n=n,\n keep=keep,\n columns=columns).nlargest()\n\n def nsmallest(self, n, columns, keep='first'):\n \"\"\"\n Return the first `n` rows ordered by `columns` in ascending order.\n\n Return the first `n` rows with the smallest values in `columns`, in\n ascending order. The columns that are not specified are returned as\n well, but not used for ordering.\n\n This method is equivalent to\n ``df.sort_values(columns, ascending=True).head(n)``, but more\n performant.\n\n Parameters\n ----------\n n : int\n Number of items to retrieve.\n columns : list or str\n Column name or names to order by.\n keep : {'first', 'last', 'all'}, default 'first'\n Where there are duplicate values:\n\n - ``first`` : take the first occurrence.\n - ``last`` : take the last occurrence.\n - ``all`` : do not drop any duplicates, even it means\n selecting more than `n` items.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n DataFrame\n\n See Also\n --------\n DataFrame.nlargest : Return the first `n` rows ordered by `columns` in\n descending order.\n DataFrame.sort_values : Sort DataFrame by the values.\n DataFrame.head : Return the first `n` rows without re-ordering.\n\n Examples\n --------\n >>> df = pd.DataFrame({'population': [59000000, 65000000, 434000,\n ... 434000, 434000, 337000, 11300,\n ... 11300, 11300],\n ... 'GDP': [1937894, 2583560 , 12011, 4520, 12128,\n ... 17036, 182, 38, 311],\n ... 'alpha-2': [\"IT\", \"FR\", \"MT\", \"MV\", \"BN\",\n ... \"IS\", \"NR\", \"TV\", \"AI\"]},\n ... index=[\"Italy\", \"France\", \"Malta\",\n ... \"Maldives\", \"Brunei\", \"Iceland\",\n ... \"Nauru\", \"Tuvalu\", \"Anguilla\"])\n >>> df\n population GDP alpha-2\n Italy 59000000 1937894 IT\n France 65000000 2583560 FR\n Malta 434000 12011 MT\n Maldives 434000 4520 MV\n Brunei 434000 12128 BN\n Iceland 337000 17036 IS\n Nauru 11300 182 NR\n Tuvalu 11300 38 TV\n Anguilla 11300 311 AI\n\n In the following example, we will use ``nsmallest`` to select the\n three rows having the smallest values in column \"a\".\n\n >>> df.nsmallest(3, 'population')\n population GDP alpha-2\n Nauru 11300 182 NR\n Tuvalu 11300 38 TV\n Anguilla 11300 311 AI\n\n When using ``keep='last'``, ties are resolved in reverse order:\n\n >>> df.nsmallest(3, 'population', keep='last')\n population GDP alpha-2\n Anguilla 11300 311 AI\n Tuvalu 11300 38 TV\n Nauru 11300 182 NR\n\n When using ``keep='all'``, all duplicate items are maintained:\n\n >>> df.nsmallest(3, 'population', keep='all')\n population GDP alpha-2\n Nauru 11300 182 NR\n Tuvalu 11300 38 TV\n Anguilla 11300 311 AI\n\n To order by the largest values in column \"a\" and then \"c\", we can\n specify multiple columns like in the next example.\n\n >>> df.nsmallest(3, ['population', 'GDP'])\n population GDP alpha-2\n Tuvalu 11300 38 TV\n Nauru 11300 182 NR\n Anguilla 11300 311 AI\n \"\"\"\n return algorithms.SelectNFrame(self,\n n=n,\n keep=keep,\n columns=columns).nsmallest()\n\n def swaplevel(self, i=-2, j=-1, axis=0):\n \"\"\"\n Swap levels i and j in a MultiIndex on a particular axis.\n\n Parameters\n ----------\n i, j : int, string (can be mixed)\n Level of index to be swapped. Can pass level name as string.\n\n Returns\n -------\n swapped : same type as caller (new object)\n\n .. versionchanged:: 0.18.1\n\n The indexes ``i`` and ``j`` are now optional, and default to\n the two innermost levels of the index.\n \"\"\"\n result = self.copy()\n\n axis = self._get_axis_number(axis)\n if axis == 0:\n result.index = result.index.swaplevel(i, j)\n else:\n result.columns = result.columns.swaplevel(i, j)\n return result\n\n def reorder_levels(self, order, axis=0):\n \"\"\"\n Rearrange index levels using input order. May not drop or\n duplicate levels.\n\n Parameters\n ----------\n order : list of int or list of str\n List representing new level order. Reference level by number\n (position) or by key (label).\n axis : int\n Where to reorder levels.\n\n Returns\n -------\n type of caller (new object)\n \"\"\"\n axis = self._get_axis_number(axis)\n if not isinstance(self._get_axis(axis),\n MultiIndex): # pragma: no cover\n raise TypeError('Can only reorder levels on a hierarchical axis.')\n\n result = self.copy()\n\n if axis == 0:\n result.index = result.index.reorder_levels(order)\n else:\n result.columns = result.columns.reorder_levels(order)\n return result\n\n # ----------------------------------------------------------------------\n # Arithmetic / combination related\n\n def _combine_frame(self, other, func, fill_value=None, level=None):\n this, other = self.align(other, join='outer', level=level, copy=False)\n new_index, new_columns = this.index, this.columns\n\n def _arith_op(left, right):\n # for the mixed_type case where we iterate over columns,\n # _arith_op(left, right) is equivalent to\n # left._binop(right, func, fill_value=fill_value)\n left, right = ops.fill_binop(left, right, fill_value)\n return func(left, right)\n\n if ops.should_series_dispatch(this, other, func):\n # iterate over columns\n return ops.dispatch_to_series(this, other, _arith_op)\n else:\n result = _arith_op(this.values, other.values)\n return self._constructor(result,\n index=new_index, columns=new_columns,\n copy=False)\n\n def _combine_match_index(self, other, func, level=None):\n left, right = self.align(other, join='outer', axis=0, level=level,\n copy=False)\n assert left.index.equals(right.index)\n\n if left._is_mixed_type or right._is_mixed_type:\n # operate column-wise; avoid costly object-casting in `.values`\n return ops.dispatch_to_series(left, right, func)\n else:\n # fastpath --> operate directly on values\n with np.errstate(all=\"ignore\"):\n new_data = func(left.values.T, right.values).T\n return self._constructor(new_data,\n index=left.index, columns=self.columns,\n copy=False)\n\n def _combine_match_columns(self, other, func, level=None):\n assert isinstance(other, Series)\n left, right = self.align(other, join='outer', axis=1, level=level,\n copy=False)\n assert left.columns.equals(right.index)\n return ops.dispatch_to_series(left, right, func, axis=\"columns\")\n\n def _combine_const(self, other, func):\n assert lib.is_scalar(other) or np.ndim(other) == 0\n return ops.dispatch_to_series(self, other, func)\n\n def combine(self, other, func, fill_value=None, overwrite=True):\n \"\"\"\n Perform column-wise combine with another DataFrame based on a\n passed function.\n\n Combines a DataFrame with `other` DataFrame using `func`\n to element-wise combine columns. The row and column indexes of the\n resulting DataFrame will be the union of the two.\n\n Parameters\n ----------\n other : DataFrame\n The DataFrame to merge column-wise.\n func : function\n Function that takes two series as inputs and return a Series or a\n scalar. Used to merge the two dataframes column by columns.\n fill_value : scalar value, default None\n The value to fill NaNs with prior to passing any column to the\n merge func.\n overwrite : boolean, default True\n If True, columns in `self` that do not exist in `other` will be\n overwritten with NaNs.\n\n Returns\n -------\n result : DataFrame\n\n See Also\n --------\n DataFrame.combine_first : Combine two DataFrame objects and default to\n non-null values in frame calling the method.\n\n Examples\n --------\n Combine using a simple function that chooses the smaller column.\n\n >>> df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})\n >>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})\n >>> take_smaller = lambda s1, s2: s1 if s1.sum() < s2.sum() else s2\n >>> df1.combine(df2, take_smaller)\n A B\n 0 0 3\n 1 0 3\n\n Example using a true element-wise combine function.\n\n >>> df1 = pd.DataFrame({'A': [5, 0], 'B': [2, 4]})\n >>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})\n >>> df1.combine(df2, np.minimum)\n A B\n 0 1 2\n 1 0 3\n\n Using `fill_value` fills Nones prior to passing the column to the\n merge function.\n\n >>> df1 = pd.DataFrame({'A': [0, 0], 'B': [None, 4]})\n >>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})\n >>> df1.combine(df2, take_smaller, fill_value=-5)\n A B\n 0 0 -5.0\n 1 0 4.0\n\n However, if the same element in both dataframes is None, that None\n is preserved\n\n >>> df1 = pd.DataFrame({'A': [0, 0], 'B': [None, 4]})\n >>> df2 = pd.DataFrame({'A': [1, 1], 'B': [None, 3]})\n >>> df1.combine(df2, take_smaller, fill_value=-5)\n A B\n 0 0 NaN\n 1 0 3.0\n\n Example that demonstrates the use of `overwrite` and behavior when\n the axis differ between the dataframes.\n\n >>> df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})\n >>> df2 = pd.DataFrame({'B': [3, 3], 'C': [-10, 1],}, index=[1, 2])\n >>> df1.combine(df2, take_smaller)\n A B C\n 0 NaN NaN NaN\n 1 NaN 3.0 -10.0\n 2 NaN 3.0 1.0\n\n >>> df1.combine(df2, take_smaller, overwrite=False)\n A B C\n 0 0.0 NaN NaN\n 1 0.0 3.0 -10.0\n 2 NaN 3.0 1.0\n\n Demonstrating the preference of the passed in dataframe.\n\n >>> df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1],}, index=[1, 2])\n >>> df2.combine(df1, take_smaller)\n A B C\n 0 0.0 NaN NaN\n 1 0.0 3.0 NaN\n 2 NaN 3.0 NaN\n\n >>> df2.combine(df1, take_smaller, overwrite=False)\n A B C\n 0 0.0 NaN NaN\n 1 0.0 3.0 1.0\n 2 NaN 3.0 1.0\n \"\"\"\n other_idxlen = len(other.index) # save for compare\n\n this, other = self.align(other, copy=False)\n new_index = this.index\n\n if other.empty and len(new_index) == len(self.index):\n return self.copy()\n\n if self.empty and len(other) == other_idxlen:\n return other.copy()\n\n # sorts if possible\n new_columns = this.columns.union(other.columns)\n do_fill = fill_value is not None\n result = {}\n for col in new_columns:\n series = this[col]\n otherSeries = other[col]\n\n this_dtype = series.dtype\n other_dtype = otherSeries.dtype\n\n this_mask = isna(series)\n other_mask = isna(otherSeries)\n\n # don't overwrite columns unecessarily\n # DO propagate if this column is not in the intersection\n if not overwrite and other_mask.all():\n result[col] = this[col].copy()\n continue\n\n if do_fill:\n series = series.copy()\n otherSeries = otherSeries.copy()\n series[this_mask] = fill_value\n otherSeries[other_mask] = fill_value\n\n if col not in self.columns:\n # If self DataFrame does not have col in other DataFrame,\n # try to promote series, which is all NaN, as other_dtype.\n new_dtype = other_dtype\n try:\n series = series.astype(new_dtype, copy=False)\n except ValueError:\n # e.g. new_dtype is integer types\n pass\n else:\n # if we have different dtypes, possibly promote\n new_dtype = find_common_type([this_dtype, other_dtype])\n if not is_dtype_equal(this_dtype, new_dtype):\n series = series.astype(new_dtype)\n if not is_dtype_equal(other_dtype, new_dtype):\n otherSeries = otherSeries.astype(new_dtype)\n\n arr = func(series, otherSeries)\n arr = maybe_downcast_to_dtype(arr, this_dtype)\n\n result[col] = arr\n\n # convert_objects just in case\n return self._constructor(result, index=new_index,\n columns=new_columns)\n\n def combine_first(self, other):\n \"\"\"\n Update null elements with value in the same location in `other`.\n\n Combine two DataFrame objects by filling null values in one DataFrame\n with non-null values from other DataFrame. The row and column indexes\n of the resulting DataFrame will be the union of the two.\n\n Parameters\n ----------\n other : DataFrame\n Provided DataFrame to use to fill null values.\n\n Returns\n -------\n combined : DataFrame\n\n See Also\n --------\n DataFrame.combine : Perform series-wise operation on two DataFrames\n using a given function.\n\n Examples\n --------\n\n >>> df1 = pd.DataFrame({'A': [None, 0], 'B': [None, 4]})\n >>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})\n >>> df1.combine_first(df2)\n A B\n 0 1.0 3.0\n 1 0.0 4.0\n\n Null values still persist if the location of that null value\n does not exist in `other`\n\n >>> df1 = pd.DataFrame({'A': [None, 0], 'B': [4, None]})\n >>> df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1]}, index=[1, 2])\n >>> df1.combine_first(df2)\n A B C\n 0 NaN 4.0 NaN\n 1 0.0 3.0 1.0\n 2 NaN 3.0 1.0\n \"\"\"\n import pandas.core.computation.expressions as expressions\n\n def extract_values(arr):\n # Does two things:\n # 1. maybe gets the values from the Series / Index\n # 2. convert datelike to i8\n if isinstance(arr, (ABCIndexClass, ABCSeries)):\n arr = arr._values\n\n if needs_i8_conversion(arr):\n # TODO(DatetimelikeArray): just use .asi8\n if is_extension_array_dtype(arr.dtype):\n arr = arr.asi8\n else:\n arr = arr.view('i8')\n return arr\n\n def combiner(x, y):\n mask = isna(x)\n if isinstance(mask, (ABCIndexClass, ABCSeries)):\n mask = mask._values\n\n x_values = extract_values(x)\n y_values = extract_values(y)\n\n # If the column y in other DataFrame is not in first DataFrame,\n # just return y_values.\n if y.name not in self.columns:\n return y_values\n\n return expressions.where(mask, y_values, x_values)\n\n return self.combine(other, combiner, overwrite=False)\n\n @deprecate_kwarg(old_arg_name='raise_conflict', new_arg_name='errors',\n mapping={False: 'ignore', True: 'raise'})\n def update(self, other, join='left', overwrite=True, filter_func=None,\n errors='ignore'):\n \"\"\"\n Modify in place using non-NA values from another DataFrame.\n\n Aligns on indices. There is no return value.\n\n Parameters\n ----------\n other : DataFrame, or object coercible into a DataFrame\n Should have at least one matching index/column label\n with the original DataFrame. If a Series is passed,\n its name attribute must be set, and that will be\n used as the column name to align with the original DataFrame.\n join : {'left'}, default 'left'\n Only left join is implemented, keeping the index and columns of the\n original object.\n overwrite : bool, default True\n How to handle non-NA values for overlapping keys:\n\n * True: overwrite original DataFrame's values\n with values from `other`.\n * False: only update values that are NA in\n the original DataFrame.\n\n filter_func : callable(1d-array) -> bool 1d-array, optional\n Can choose to replace values other than NA. Return True for values\n that should be updated.\n errors : {'raise', 'ignore'}, default 'ignore'\n If 'raise', will raise a ValueError if the DataFrame and `other`\n both contain non-NA data in the same place.\n\n .. versionchanged :: 0.24.0\n Changed from `raise_conflict=False|True`\n to `errors='ignore'|'raise'`.\n\n Returns\n -------\n None : method directly changes calling object\n\n Raises\n ------\n ValueError\n * When `errors='raise'` and there's overlapping non-NA data.\n * When `errors` is not either `'ignore'` or `'raise'`\n NotImplementedError\n * If `join != 'left'`\n\n See Also\n --------\n dict.update : Similar method for dictionaries.\n DataFrame.merge : For column(s)-on-columns(s) operations.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': [1, 2, 3],\n ... 'B': [400, 500, 600]})\n >>> new_df = pd.DataFrame({'B': [4, 5, 6],\n ... 'C': [7, 8, 9]})\n >>> df.update(new_df)\n >>> df\n A B\n 0 1 4\n 1 2 5\n 2 3 6\n\n The DataFrame's length does not increase as a result of the update,\n only values at matching index/column labels are updated.\n\n >>> df = pd.DataFrame({'A': ['a', 'b', 'c'],\n ... 'B': ['x', 'y', 'z']})\n >>> new_df = pd.DataFrame({'B': ['d', 'e', 'f', 'g', 'h', 'i']})\n >>> df.update(new_df)\n >>> df\n A B\n 0 a d\n 1 b e\n 2 c f\n\n For Series, it's name attribute must be set.\n\n >>> df = pd.DataFrame({'A': ['a', 'b', 'c'],\n ... 'B': ['x', 'y', 'z']})\n >>> new_column = pd.Series(['d', 'e'], name='B', index=[0, 2])\n >>> df.update(new_column)\n >>> df\n A B\n 0 a d\n 1 b y\n 2 c e\n >>> df = pd.DataFrame({'A': ['a', 'b', 'c'],\n ... 'B': ['x', 'y', 'z']})\n >>> new_df = pd.DataFrame({'B': ['d', 'e']}, index=[1, 2])\n >>> df.update(new_df)\n >>> df\n A B\n 0 a x\n 1 b d\n 2 c e\n\n If `other` contains NaNs the corresponding values are not updated\n in the original dataframe.\n\n >>> df = pd.DataFrame({'A': [1, 2, 3],\n ... 'B': [400, 500, 600]})\n >>> new_df = pd.DataFrame({'B': [4, np.nan, 6]})\n >>> df.update(new_df)\n >>> df\n A B\n 0 1 4.0\n 1 2 500.0\n 2 3 6.0\n \"\"\"\n import pandas.core.computation.expressions as expressions\n # TODO: Support other joins\n if join != 'left': # pragma: no cover\n raise NotImplementedError(\"Only left join is supported\")\n if errors not in ['ignore', 'raise']:\n raise ValueError(\"The parameter errors must be either \"\n \"'ignore' or 'raise'\")\n\n if not isinstance(other, DataFrame):\n other = DataFrame(other)\n\n other = other.reindex_like(self)\n\n for col in self.columns:\n this = self[col].values\n that = other[col].values\n if filter_func is not None:\n with np.errstate(all='ignore'):\n mask = ~filter_func(this) | isna(that)\n else:\n if errors == 'raise':\n mask_this = notna(that)\n mask_that = notna(this)\n if any(mask_this & mask_that):\n raise ValueError(\"Data overlaps.\")\n\n if overwrite:\n mask = isna(that)\n else:\n mask = notna(this)\n\n # don't overwrite columns unecessarily\n if mask.all():\n continue\n\n self[col] = expressions.where(mask, this, that)\n\n # ----------------------------------------------------------------------\n # Data reshaping\n\n _shared_docs['pivot'] = \"\"\"\n Return reshaped DataFrame organized by given index / column values.\n\n Reshape data (produce a \"pivot\" table) based on column values. Uses\n unique values from specified `index` / `columns` to form axes of the\n resulting DataFrame. This function does not support data\n aggregation, multiple values will result in a MultiIndex in the\n columns. See the :ref:`User Guide <reshaping>` for more on reshaping.\n\n Parameters\n ----------%s\n index : string or object, optional\n Column to use to make new frame's index. If None, uses\n existing index.\n columns : string or object\n Column to use to make new frame's columns.\n values : string, object or a list of the previous, optional\n Column(s) to use for populating new frame's values. If not\n specified, all remaining columns will be used and the result will\n have hierarchically indexed columns.\n\n .. versionchanged :: 0.23.0\n Also accept list of column names.\n\n Returns\n -------\n DataFrame\n Returns reshaped DataFrame.\n\n Raises\n ------\n ValueError:\n When there are any `index`, `columns` combinations with multiple\n values. `DataFrame.pivot_table` when you need to aggregate.\n\n See Also\n --------\n DataFrame.pivot_table : Generalization of pivot that can handle\n duplicate values for one index/column pair.\n DataFrame.unstack : Pivot based on the index values instead of a\n column.\n\n Notes\n -----\n For finer-tuned control, see hierarchical indexing documentation along\n with the related stack/unstack methods.\n\n Examples\n --------\n >>> df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two',\n ... 'two'],\n ... 'bar': ['A', 'B', 'C', 'A', 'B', 'C'],\n ... 'baz': [1, 2, 3, 4, 5, 6],\n ... 'zoo': ['x', 'y', 'z', 'q', 'w', 't']})\n >>> df\n foo bar baz zoo\n 0 one A 1 x\n 1 one B 2 y\n 2 one C 3 z\n 3 two A 4 q\n 4 two B 5 w\n 5 two C 6 t\n\n >>> df.pivot(index='foo', columns='bar', values='baz')\n bar A B C\n foo\n one 1 2 3\n two 4 5 6\n\n >>> df.pivot(index='foo', columns='bar')['baz']\n bar A B C\n foo\n one 1 2 3\n two 4 5 6\n\n >>> df.pivot(index='foo', columns='bar', values=['baz', 'zoo'])\n baz zoo\n bar A B C A B C\n foo\n one 1 2 3 x y z\n two 4 5 6 q w t\n\n A ValueError is raised if there are any duplicates.\n\n >>> df = pd.DataFrame({\"foo\": ['one', 'one', 'two', 'two'],\n ... \"bar\": ['A', 'A', 'B', 'C'],\n ... \"baz\": [1, 2, 3, 4]})\n >>> df\n foo bar baz\n 0 one A 1\n 1 one A 2\n 2 two B 3\n 3 two C 4\n\n Notice that the first two rows are the same for our `index`\n and `columns` arguments.\n\n >>> df.pivot(index='foo', columns='bar', values='baz')\n Traceback (most recent call last):\n ...\n ValueError: Index contains duplicate entries, cannot reshape\n \"\"\"\n\n @Substitution('')\n @Appender(_shared_docs['pivot'])\n def pivot(self, index=None, columns=None, values=None):\n from pandas.core.reshape.pivot import pivot\n return pivot(self, index=index, columns=columns, values=values)\n\n _shared_docs['pivot_table'] = \"\"\"\n Create a spreadsheet-style pivot table as a DataFrame. The levels in\n the pivot table will be stored in MultiIndex objects (hierarchical\n indexes) on the index and columns of the result DataFrame.\n\n Parameters\n ----------%s\n values : column to aggregate, optional\n index : column, Grouper, array, or list of the previous\n If an array is passed, it must be the same length as the data. The\n list can contain any of the other types (except list).\n Keys to group by on the pivot table index. If an array is passed,\n it is being used as the same manner as column values.\n columns : column, Grouper, array, or list of the previous\n If an array is passed, it must be the same length as the data. The\n list can contain any of the other types (except list).\n Keys to group by on the pivot table column. If an array is passed,\n it is being used as the same manner as column values.\n aggfunc : function, list of functions, dict, default numpy.mean\n If list of functions passed, the resulting pivot table will have\n hierarchical columns whose top level are the function names\n (inferred from the function objects themselves)\n If dict is passed, the key is column to aggregate and value\n is function or list of functions\n fill_value : scalar, default None\n Value to replace missing values with\n margins : boolean, default False\n Add all row / columns (e.g. for subtotal / grand totals)\n dropna : boolean, default True\n Do not include columns whose entries are all NaN\n margins_name : string, default 'All'\n Name of the row / column that will contain the totals\n when margins is True.\n\n Returns\n -------\n table : DataFrame\n\n See Also\n --------\n DataFrame.pivot : Pivot without aggregation that can handle\n non-numeric data.\n\n Examples\n --------\n >>> df = pd.DataFrame({\"A\": [\"foo\", \"foo\", \"foo\", \"foo\", \"foo\",\n ... \"bar\", \"bar\", \"bar\", \"bar\"],\n ... \"B\": [\"one\", \"one\", \"one\", \"two\", \"two\",\n ... \"one\", \"one\", \"two\", \"two\"],\n ... \"C\": [\"small\", \"large\", \"large\", \"small\",\n ... \"small\", \"large\", \"small\", \"small\",\n ... \"large\"],\n ... \"D\": [1, 2, 2, 3, 3, 4, 5, 6, 7],\n ... \"E\": [2, 4, 5, 5, 6, 6, 8, 9, 9]})\n >>> df\n A B C D E\n 0 foo one small 1 2\n 1 foo one large 2 4\n 2 foo one large 2 5\n 3 foo two small 3 5\n 4 foo two small 3 6\n 5 bar one large 4 6\n 6 bar one small 5 8\n 7 bar two small 6 9\n 8 bar two large 7 9\n\n This first example aggregates values by taking the sum.\n\n >>> table = pivot_table(df, values='D', index=['A', 'B'],\n ... columns=['C'], aggfunc=np.sum)\n >>> table\n C large small\n A B\n bar one 4 5\n two 7 6\n foo one 4 1\n two NaN 6\n\n We can also fill missing values using the `fill_value` parameter.\n\n >>> table = pivot_table(df, values='D', index=['A', 'B'],\n ... columns=['C'], aggfunc=np.sum, fill_value=0)\n >>> table\n C large small\n A B\n bar one 4 5\n two 7 6\n foo one 4 1\n two 0 6\n\n The next example aggregates by taking the mean across multiple columns.\n\n >>> table = pivot_table(df, values=['D', 'E'], index=['A', 'C'],\n ... aggfunc={'D': np.mean,\n ... 'E': np.mean})\n >>> table\n D E\n mean mean\n A C\n bar large 5.500000 7.500000\n small 5.500000 8.500000\n foo large 2.000000 4.500000\n small 2.333333 4.333333\n\n We can also calculate multiple types of aggregations for any given\n value column.\n\n >>> table = pivot_table(df, values=['D', 'E'], index=['A', 'C'],\n ... aggfunc={'D': np.mean,\n ... 'E': [min, max, np.mean]})\n >>> table\n D E\n mean max mean min\n A C\n bar large 5.500000 9 7.500000 6\n small 5.500000 9 8.500000 8\n foo large 2.000000 5 4.500000 4\n small 2.333333 6 4.333333 2\n \"\"\"\n\n @Substitution('')\n @Appender(_shared_docs['pivot_table'])\n def pivot_table(self, values=None, index=None, columns=None,\n aggfunc='mean', fill_value=None, margins=False,\n dropna=True, margins_name='All'):\n from pandas.core.reshape.pivot import pivot_table\n return pivot_table(self, values=values, index=index, columns=columns,\n aggfunc=aggfunc, fill_value=fill_value,\n margins=margins, dropna=dropna,\n margins_name=margins_name)\n\n def stack(self, level=-1, dropna=True):\n \"\"\"\n Stack the prescribed level(s) from columns to index.\n\n Return a reshaped DataFrame or Series having a multi-level\n index with one or more new inner-most levels compared to the current\n DataFrame. The new inner-most levels are created by pivoting the\n columns of the current dataframe:\n\n - if the columns have a single level, the output is a Series;\n - if the columns have multiple levels, the new index\n level(s) is (are) taken from the prescribed level(s) and\n the output is a DataFrame.\n\n The new index levels are sorted.\n\n Parameters\n ----------\n level : int, str, list, default -1\n Level(s) to stack from the column axis onto the index\n axis, defined as one index or label, or a list of indices\n or labels.\n dropna : bool, default True\n Whether to drop rows in the resulting Frame/Series with\n missing values. Stacking a column level onto the index\n axis can create combinations of index and column values\n that are missing from the original dataframe. See Examples\n section.\n\n Returns\n -------\n DataFrame or Series\n Stacked dataframe or series.\n\n See Also\n --------\n DataFrame.unstack : Unstack prescribed level(s) from index axis\n onto column axis.\n DataFrame.pivot : Reshape dataframe from long format to wide\n format.\n DataFrame.pivot_table : Create a spreadsheet-style pivot table\n as a DataFrame.\n\n Notes\n -----\n The function is named by analogy with a collection of books\n being re-organised from being side by side on a horizontal\n position (the columns of the dataframe) to being stacked\n vertically on top of of each other (in the index of the\n dataframe).\n\n Examples\n --------\n **Single level columns**\n\n >>> df_single_level_cols = pd.DataFrame([[0, 1], [2, 3]],\n ... index=['cat', 'dog'],\n ... columns=['weight', 'height'])\n\n Stacking a dataframe with a single level column axis returns a Series:\n\n >>> df_single_level_cols\n weight height\n cat 0 1\n dog 2 3\n >>> df_single_level_cols.stack()\n cat weight 0\n height 1\n dog weight 2\n height 3\n dtype: int64\n\n **Multi level columns: simple case**\n\n >>> multicol1 = pd.MultiIndex.from_tuples([('weight', 'kg'),\n ... ('weight', 'pounds')])\n >>> df_multi_level_cols1 = pd.DataFrame([[1, 2], [2, 4]],\n ... index=['cat', 'dog'],\n ... columns=multicol1)\n\n Stacking a dataframe with a multi-level column axis:\n\n >>> df_multi_level_cols1\n weight\n kg pounds\n cat 1 2\n dog 2 4\n >>> df_multi_level_cols1.stack()\n weight\n cat kg 1\n pounds 2\n dog kg 2\n pounds 4\n\n **Missing values**\n\n >>> multicol2 = pd.MultiIndex.from_tuples([('weight', 'kg'),\n ... ('height', 'm')])\n >>> df_multi_level_cols2 = pd.DataFrame([[1.0, 2.0], [3.0, 4.0]],\n ... index=['cat', 'dog'],\n ... columns=multicol2)\n\n It is common to have missing values when stacking a dataframe\n with multi-level columns, as the stacked dataframe typically\n has more values than the original dataframe. Missing values\n are filled with NaNs:\n\n >>> df_multi_level_cols2\n weight height\n kg m\n cat 1.0 2.0\n dog 3.0 4.0\n >>> df_multi_level_cols2.stack()\n height weight\n cat kg NaN 1.0\n m 2.0 NaN\n dog kg NaN 3.0\n m 4.0 NaN\n\n **Prescribing the level(s) to be stacked**\n\n The first parameter controls which level or levels are stacked:\n\n >>> df_multi_level_cols2.stack(0)\n kg m\n cat height NaN 2.0\n weight 1.0 NaN\n dog height NaN 4.0\n weight 3.0 NaN\n >>> df_multi_level_cols2.stack([0, 1])\n cat height m 2.0\n weight kg 1.0\n dog height m 4.0\n weight kg 3.0\n dtype: float64\n\n **Dropping missing values**\n\n >>> df_multi_level_cols3 = pd.DataFrame([[None, 1.0], [2.0, 3.0]],\n ... index=['cat', 'dog'],\n ... columns=multicol2)\n\n Note that rows where all values are missing are dropped by\n default but this behaviour can be controlled via the dropna\n keyword parameter:\n\n >>> df_multi_level_cols3\n weight height\n kg m\n cat NaN 1.0\n dog 2.0 3.0\n >>> df_multi_level_cols3.stack(dropna=False)\n height weight\n cat kg NaN NaN\n m 1.0 NaN\n dog kg NaN 2.0\n m 3.0 NaN\n >>> df_multi_level_cols3.stack(dropna=True)\n height weight\n cat m 1.0 NaN\n dog kg NaN 2.0\n m 3.0 NaN\n \"\"\"\n from pandas.core.reshape.reshape import stack, stack_multiple\n\n if isinstance(level, (tuple, list)):\n return stack_multiple(self, level, dropna=dropna)\n else:\n return stack(self, level, dropna=dropna)\n\n def unstack(self, level=-1, fill_value=None):\n \"\"\"\n Pivot a level of the (necessarily hierarchical) index labels, returning\n a DataFrame having a new level of column labels whose inner-most level\n consists of the pivoted index labels.\n\n If the index is not a MultiIndex, the output will be a Series\n (the analogue of stack when the columns are not a MultiIndex).\n\n The level involved will automatically get sorted.\n\n Parameters\n ----------\n level : int, string, or list of these, default -1 (last level)\n Level(s) of index to unstack, can pass level name\n fill_value : replace NaN with this value if the unstack produces\n missing values\n\n .. versionadded:: 0.18.0\n\n Returns\n -------\n unstacked : DataFrame or Series\n\n See Also\n --------\n DataFrame.pivot : Pivot a table based on column values.\n DataFrame.stack : Pivot a level of the column labels (inverse operation\n from `unstack`).\n\n Examples\n --------\n >>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),\n ... ('two', 'a'), ('two', 'b')])\n >>> s = pd.Series(np.arange(1.0, 5.0), index=index)\n >>> s\n one a 1.0\n b 2.0\n two a 3.0\n b 4.0\n dtype: float64\n\n >>> s.unstack(level=-1)\n a b\n one 1.0 2.0\n two 3.0 4.0\n\n >>> s.unstack(level=0)\n one two\n a 1.0 3.0\n b 2.0 4.0\n\n >>> df = s.unstack(level=0)\n >>> df.unstack()\n one a 1.0\n b 2.0\n two a 3.0\n b 4.0\n dtype: float64\n \"\"\"\n from pandas.core.reshape.reshape import unstack\n return unstack(self, level, fill_value)\n\n _shared_docs['melt'] = (\"\"\"\n Unpivots a DataFrame from wide format to long format, optionally\n leaving identifier variables set.\n\n This function is useful to massage a DataFrame into a format where one\n or more columns are identifier variables (`id_vars`), while all other\n columns, considered measured variables (`value_vars`), are \"unpivoted\" to\n the row axis, leaving just two non-identifier columns, 'variable' and\n 'value'.\n\n %(versionadded)s\n Parameters\n ----------\n frame : DataFrame\n id_vars : tuple, list, or ndarray, optional\n Column(s) to use as identifier variables.\n value_vars : tuple, list, or ndarray, optional\n Column(s) to unpivot. If not specified, uses all columns that\n are not set as `id_vars`.\n var_name : scalar\n Name to use for the 'variable' column. If None it uses\n ``frame.columns.name`` or 'variable'.\n value_name : scalar, default 'value'\n Name to use for the 'value' column.\n col_level : int or string, optional\n If columns are a MultiIndex then use this level to melt.\n\n See Also\n --------\n %(other)s\n pivot_table\n DataFrame.pivot\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'},\n ... 'B': {0: 1, 1: 3, 2: 5},\n ... 'C': {0: 2, 1: 4, 2: 6}})\n >>> df\n A B C\n 0 a 1 2\n 1 b 3 4\n 2 c 5 6\n\n >>> %(caller)sid_vars=['A'], value_vars=['B'])\n A variable value\n 0 a B 1\n 1 b B 3\n 2 c B 5\n\n >>> %(caller)sid_vars=['A'], value_vars=['B', 'C'])\n A variable value\n 0 a B 1\n 1 b B 3\n 2 c B 5\n 3 a C 2\n 4 b C 4\n 5 c C 6\n\n The names of 'variable' and 'value' columns can be customized:\n\n >>> %(caller)sid_vars=['A'], value_vars=['B'],\n ... var_name='myVarname', value_name='myValname')\n A myVarname myValname\n 0 a B 1\n 1 b B 3\n 2 c B 5\n\n If you have multi-index columns:\n\n >>> df.columns = [list('ABC'), list('DEF')]\n >>> df\n A B C\n D E F\n 0 a 1 2\n 1 b 3 4\n 2 c 5 6\n\n >>> %(caller)scol_level=0, id_vars=['A'], value_vars=['B'])\n A variable value\n 0 a B 1\n 1 b B 3\n 2 c B 5\n\n >>> %(caller)sid_vars=[('A', 'D')], value_vars=[('B', 'E')])\n (A, D) variable_0 variable_1 value\n 0 a B E 1\n 1 b B E 3\n 2 c B E 5\n \"\"\")\n\n @Appender(_shared_docs['melt'] %\n dict(caller='df.melt(',\n versionadded='.. versionadded:: 0.20.0\\n',\n other='melt'))\n def melt(self, id_vars=None, value_vars=None, var_name=None,\n value_name='value', col_level=None):\n from pandas.core.reshape.melt import melt\n return melt(self, id_vars=id_vars, value_vars=value_vars,\n var_name=var_name, value_name=value_name,\n col_level=col_level)\n\n # ----------------------------------------------------------------------\n # Time series-related\n\n def diff(self, periods=1, axis=0):\n \"\"\"\n First discrete difference of element.\n\n Calculates the difference of a DataFrame element compared with another\n element in the DataFrame (default is the element in the same column\n of the previous row).\n\n Parameters\n ----------\n periods : int, default 1\n Periods to shift for calculating difference, accepts negative\n values.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Take difference over rows (0) or columns (1).\n\n .. versionadded:: 0.16.1.\n\n Returns\n -------\n diffed : DataFrame\n\n See Also\n --------\n Series.diff: First discrete difference for a Series.\n DataFrame.pct_change: Percent change over given number of periods.\n DataFrame.shift: Shift index by desired number of periods with an\n optional time freq.\n\n Examples\n --------\n Difference with previous row\n\n >>> df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6],\n ... 'b': [1, 1, 2, 3, 5, 8],\n ... 'c': [1, 4, 9, 16, 25, 36]})\n >>> df\n a b c\n 0 1 1 1\n 1 2 1 4\n 2 3 2 9\n 3 4 3 16\n 4 5 5 25\n 5 6 8 36\n\n >>> df.diff()\n a b c\n 0 NaN NaN NaN\n 1 1.0 0.0 3.0\n 2 1.0 1.0 5.0\n 3 1.0 1.0 7.0\n 4 1.0 2.0 9.0\n 5 1.0 3.0 11.0\n\n Difference with previous column\n\n >>> df.diff(axis=1)\n a b c\n 0 NaN 0.0 0.0\n 1 NaN -1.0 3.0\n 2 NaN -1.0 7.0\n 3 NaN -1.0 13.0\n 4 NaN 0.0 20.0\n 5 NaN 2.0 28.0\n\n Difference with 3rd previous row\n\n >>> df.diff(periods=3)\n a b c\n 0 NaN NaN NaN\n 1 NaN NaN NaN\n 2 NaN NaN NaN\n 3 3.0 2.0 15.0\n 4 3.0 4.0 21.0\n 5 3.0 6.0 27.0\n\n Difference with following row\n\n >>> df.diff(periods=-1)\n a b c\n 0 -1.0 0.0 -3.0\n 1 -1.0 -1.0 -5.0\n 2 -1.0 -1.0 -7.0\n 3 -1.0 -2.0 -9.0\n 4 -1.0 -3.0 -11.0\n 5 NaN NaN NaN\n \"\"\"\n bm_axis = self._get_block_manager_axis(axis)\n new_data = self._data.diff(n=periods, axis=bm_axis)\n return self._constructor(new_data)\n\n # ----------------------------------------------------------------------\n # Function application\n\n def _gotitem(self,\n key, # type: Union[str, List[str]]\n ndim, # type: int\n subset=None # type: Union[Series, DataFrame, None]\n ):\n # type: (...) -> Union[Series, DataFrame]\n \"\"\"\n Sub-classes to define. Return a sliced object.\n\n Parameters\n ----------\n key : string / list of selections\n ndim : 1,2\n requested ndim of result\n subset : object, default None\n subset to act on\n \"\"\"\n if subset is None:\n subset = self\n elif subset.ndim == 1: # is Series\n return subset\n\n # TODO: _shallow_copy(subset)?\n return subset[key]\n\n _agg_doc = dedent(\"\"\"\n The aggregation operations are always performed over an axis, either the\n index (default) or the column axis. This behavior is different from\n `numpy` aggregation functions (`mean`, `median`, `prod`, `sum`, `std`,\n `var`), where the default is to compute the aggregation of the flattened\n array, e.g., ``numpy.mean(arr_2d)`` as opposed to ``numpy.mean(arr_2d,\n axis=0)``.\n\n `agg` is an alias for `aggregate`. Use the alias.\n\n Examples\n --------\n >>> df = pd.DataFrame([[1, 2, 3],\n ... [4, 5, 6],\n ... [7, 8, 9],\n ... [np.nan, np.nan, np.nan]],\n ... columns=['A', 'B', 'C'])\n\n Aggregate these functions over the rows.\n\n >>> df.agg(['sum', 'min'])\n A B C\n sum 12.0 15.0 18.0\n min 1.0 2.0 3.0\n\n Different aggregations per column.\n\n >>> df.agg({'A' : ['sum', 'min'], 'B' : ['min', 'max']})\n A B\n max NaN 8.0\n min 1.0 2.0\n sum 12.0 NaN\n\n Aggregate over the columns.\n\n >>> df.agg(\"mean\", axis=\"columns\")\n 0 2.0\n 1 5.0\n 2 8.0\n 3 NaN\n dtype: float64\n\n See Also\n --------\n DataFrame.apply : Perform any type of operations.\n DataFrame.transform : Perform transformation type operations.\n pandas.core.groupby.GroupBy : Perform operations over groups.\n pandas.core.resample.Resampler : Perform operations over resampled bins.\n pandas.core.window.Rolling : Perform operations over rolling window.\n pandas.core.window.Expanding : Perform operations over expanding window.\n pandas.core.window.EWM : Perform operation over exponential weighted\n window.\n \"\"\")\n\n @Appender(_agg_doc)\n @Appender(_shared_docs['aggregate'] % dict(\n versionadded='.. versionadded:: 0.20.0',\n **_shared_doc_kwargs))\n def aggregate(self, func, axis=0, *args, **kwargs):\n axis = self._get_axis_number(axis)\n\n result = None\n try:\n result, how = self._aggregate(func, axis=axis, *args, **kwargs)\n except TypeError:\n pass\n if result is None:\n return self.apply(func, axis=axis, args=args, **kwargs)\n return result\n\n def _aggregate(self, arg, axis=0, *args, **kwargs):\n if axis == 1:\n # NDFrame.aggregate returns a tuple, and we need to transpose\n # only result\n result, how = (super(DataFrame, self.T)\n ._aggregate(arg, *args, **kwargs))\n result = result.T if result is not None else result\n return result, how\n return super(DataFrame, self)._aggregate(arg, *args, **kwargs)\n\n agg = aggregate\n\n @Appender(_shared_docs['transform'] % _shared_doc_kwargs)\n def transform(self, func, axis=0, *args, **kwargs):\n axis = self._get_axis_number(axis)\n if axis == 1:\n return super(DataFrame, self.T).transform(func, *args, **kwargs).T\n return super(DataFrame, self).transform(func, *args, **kwargs)\n\n def apply(self, func, axis=0, broadcast=None, raw=False, reduce=None,\n result_type=None, args=(), **kwds):\n \"\"\"\n Apply a function along an axis of the DataFrame.\n\n Objects passed to the function are Series objects whose index is\n either the DataFrame's index (``axis=0``) or the DataFrame's columns\n (``axis=1``). By default (``result_type=None``), the final return type\n is inferred from the return type of the applied function. Otherwise,\n it depends on the `result_type` argument.\n\n Parameters\n ----------\n func : function\n Function to apply to each column or row.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Axis along which the function is applied:\n\n * 0 or 'index': apply function to each column.\n * 1 or 'columns': apply function to each row.\n broadcast : bool, optional\n Only relevant for aggregation functions:\n\n * ``False`` or ``None`` : returns a Series whose length is the\n length of the index or the number of columns (based on the\n `axis` parameter)\n * ``True`` : results will be broadcast to the original shape\n of the frame, the original index and columns will be retained.\n\n .. deprecated:: 0.23.0\n This argument will be removed in a future version, replaced\n by result_type='broadcast'.\n\n raw : bool, default False\n * ``False`` : passes each row or column as a Series to the\n function.\n * ``True`` : the passed function will receive ndarray objects\n instead.\n If you are just applying a NumPy reduction function this will\n achieve much better performance.\n reduce : bool or None, default None\n Try to apply reduction procedures. If the DataFrame is empty,\n `apply` will use `reduce` to determine whether the result\n should be a Series or a DataFrame. If ``reduce=None`` (the\n default), `apply`'s return value will be guessed by calling\n `func` on an empty Series\n (note: while guessing, exceptions raised by `func` will be\n ignored).\n If ``reduce=True`` a Series will always be returned, and if\n ``reduce=False`` a DataFrame will always be returned.\n\n .. deprecated:: 0.23.0\n This argument will be removed in a future version, replaced\n by ``result_type='reduce'``.\n\n result_type : {'expand', 'reduce', 'broadcast', None}, default None\n These only act when ``axis=1`` (columns):\n\n * 'expand' : list-like results will be turned into columns.\n * 'reduce' : returns a Series if possible rather than expanding\n list-like results. This is the opposite of 'expand'.\n * 'broadcast' : results will be broadcast to the original shape\n of the DataFrame, the original index and columns will be\n retained.\n\n The default behaviour (None) depends on the return value of the\n applied function: list-like results will be returned as a Series\n of those. However if the apply function returns a Series these\n are expanded to columns.\n\n .. versionadded:: 0.23.0\n\n args : tuple\n Positional arguments to pass to `func` in addition to the\n array/series.\n **kwds\n Additional keyword arguments to pass as keywords arguments to\n `func`.\n\n Returns\n -------\n applied : Series or DataFrame\n\n See Also\n --------\n DataFrame.applymap: For elementwise operations.\n DataFrame.aggregate: Only perform aggregating type operations.\n DataFrame.transform: Only perform transforming type operations.\n\n Notes\n -----\n In the current implementation apply calls `func` twice on the\n first column/row to decide whether it can take a fast or slow\n code path. This can lead to unexpected behavior if `func` has\n side-effects, as they will take effect twice for the first\n column/row.\n\n Examples\n --------\n\n >>> df = pd.DataFrame([[4, 9],] * 3, columns=['A', 'B'])\n >>> df\n A B\n 0 4 9\n 1 4 9\n 2 4 9\n\n Using a numpy universal function (in this case the same as\n ``np.sqrt(df)``):\n\n >>> df.apply(np.sqrt)\n A B\n 0 2.0 3.0\n 1 2.0 3.0\n 2 2.0 3.0\n\n Using a reducing function on either axis\n\n >>> df.apply(np.sum, axis=0)\n A 12\n B 27\n dtype: int64\n\n >>> df.apply(np.sum, axis=1)\n 0 13\n 1 13\n 2 13\n dtype: int64\n\n Retuning a list-like will result in a Series\n\n >>> df.apply(lambda x: [1, 2], axis=1)\n 0 [1, 2]\n 1 [1, 2]\n 2 [1, 2]\n dtype: object\n\n Passing result_type='expand' will expand list-like results\n to columns of a Dataframe\n\n >>> df.apply(lambda x: [1, 2], axis=1, result_type='expand')\n 0 1\n 0 1 2\n 1 1 2\n 2 1 2\n\n Returning a Series inside the function is similar to passing\n ``result_type='expand'``. The resulting column names\n will be the Series index.\n\n >>> df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1)\n foo bar\n 0 1 2\n 1 1 2\n 2 1 2\n\n Passing ``result_type='broadcast'`` will ensure the same shape\n result, whether list-like or scalar is returned by the function,\n and broadcast it along the axis. The resulting column names will\n be the originals.\n\n >>> df.apply(lambda x: [1, 2], axis=1, result_type='broadcast')\n A B\n 0 1 2\n 1 1 2\n 2 1 2\n \"\"\"\n from pandas.core.apply import frame_apply\n op = frame_apply(self,\n func=func,\n axis=axis,\n broadcast=broadcast,\n raw=raw,\n reduce=reduce,\n result_type=result_type,\n args=args,\n kwds=kwds)\n return op.get_result()\n\n def applymap(self, func):\n \"\"\"\n Apply a function to a Dataframe elementwise.\n\n This method applies a function that accepts and returns a scalar\n to every element of a DataFrame.\n\n Parameters\n ----------\n func : callable\n Python function, returns a single value from a single value.\n\n Returns\n -------\n DataFrame\n Transformed DataFrame.\n\n See Also\n --------\n DataFrame.apply : Apply a function along input axis of DataFrame.\n\n Examples\n --------\n >>> df = pd.DataFrame([[1, 2.12], [3.356, 4.567]])\n >>> df\n 0 1\n 0 1.000 2.120\n 1 3.356 4.567\n\n >>> df.applymap(lambda x: len(str(x)))\n 0 1\n 0 3 4\n 1 5 5\n\n Note that a vectorized version of `func` often exists, which will\n be much faster. You could square each number elementwise.\n\n >>> df.applymap(lambda x: x**2)\n 0 1\n 0 1.000000 4.494400\n 1 11.262736 20.857489\n\n But it's better to avoid applymap in that case.\n\n >>> df ** 2\n 0 1\n 0 1.000000 4.494400\n 1 11.262736 20.857489\n \"\"\"\n\n # if we have a dtype == 'M8[ns]', provide boxed values\n def infer(x):\n if x.empty:\n return lib.map_infer(x, func)\n return lib.map_infer(x.astype(object).values, func)\n\n return self.apply(infer)\n\n # ----------------------------------------------------------------------\n # Merging / joining methods\n\n def append(self, other, ignore_index=False,\n verify_integrity=False, sort=None):\n \"\"\"\n Append rows of `other` to the end of caller, returning a new object.\n\n Columns in `other` that are not in the caller are added as new columns.\n\n Parameters\n ----------\n other : DataFrame or Series/dict-like object, or list of these\n The data to append.\n ignore_index : boolean, default False\n If True, do not use the index labels.\n verify_integrity : boolean, default False\n If True, raise ValueError on creating index with duplicates.\n sort : boolean, default None\n Sort columns if the columns of `self` and `other` are not aligned.\n The default sorting is deprecated and will change to not-sorting\n in a future version of pandas. Explicitly pass ``sort=True`` to\n silence the warning and sort. Explicitly pass ``sort=False`` to\n silence the warning and not sort.\n\n .. versionadded:: 0.23.0\n\n Returns\n -------\n appended : DataFrame\n\n See Also\n --------\n pandas.concat : General function to concatenate DataFrame, Series\n or Panel objects.\n\n Notes\n -----\n If a list of dict/series is passed and the keys are all contained in\n the DataFrame's index, the order of the columns in the resulting\n DataFrame will be unchanged.\n\n Iteratively appending rows to a DataFrame can be more computationally\n intensive than a single concatenate. A better solution is to append\n those rows to a list and then concatenate the list with the original\n DataFrame all at once.\n\n Examples\n --------\n\n >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))\n >>> df\n A B\n 0 1 2\n 1 3 4\n >>> df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))\n >>> df.append(df2)\n A B\n 0 1 2\n 1 3 4\n 0 5 6\n 1 7 8\n\n With `ignore_index` set to True:\n\n >>> df.append(df2, ignore_index=True)\n A B\n 0 1 2\n 1 3 4\n 2 5 6\n 3 7 8\n\n The following, while not recommended methods for generating DataFrames,\n show two ways to generate a DataFrame from multiple data sources.\n\n Less efficient:\n\n >>> df = pd.DataFrame(columns=['A'])\n >>> for i in range(5):\n ... df = df.append({'A': i}, ignore_index=True)\n >>> df\n A\n 0 0\n 1 1\n 2 2\n 3 3\n 4 4\n\n More efficient:\n\n >>> pd.concat([pd.DataFrame([i], columns=['A']) for i in range(5)],\n ... ignore_index=True)\n A\n 0 0\n 1 1\n 2 2\n 3 3\n 4 4\n \"\"\"\n if isinstance(other, (Series, dict)):\n if isinstance(other, dict):\n other = Series(other)\n if other.name is None and not ignore_index:\n raise TypeError('Can only append a Series if ignore_index=True'\n ' or if the Series has a name')\n\n if other.name is None:\n index = None\n else:\n # other must have the same index name as self, otherwise\n # index name will be reset\n index = Index([other.name], name=self.index.name)\n\n idx_diff = other.index.difference(self.columns)\n try:\n combined_columns = self.columns.append(idx_diff)\n except TypeError:\n combined_columns = self.columns.astype(object).append(idx_diff)\n other = other.reindex(combined_columns, copy=False)\n other = DataFrame(other.values.reshape((1, len(other))),\n index=index,\n columns=combined_columns)\n other = other._convert(datetime=True, timedelta=True)\n if not self.columns.equals(combined_columns):\n self = self.reindex(columns=combined_columns)\n elif isinstance(other, list) and not isinstance(other[0], DataFrame):\n other = DataFrame(other)\n if (self.columns.get_indexer(other.columns) >= 0).all():\n other = other.loc[:, self.columns]\n\n from pandas.core.reshape.concat import concat\n if isinstance(other, (list, tuple)):\n to_concat = [self] + other\n else:\n to_concat = [self, other]\n return concat(to_concat, ignore_index=ignore_index,\n verify_integrity=verify_integrity,\n sort=sort)\n\n def join(self, other, on=None, how='left', lsuffix='', rsuffix='',\n sort=False):\n \"\"\"\n Join columns of another DataFrame.\n\n Join columns with `other` DataFrame either on index or on a key\n column. Efficiently join multiple DataFrame objects by index at once by\n passing a list.\n\n Parameters\n ----------\n other : DataFrame, Series, or list of DataFrame\n Index should be similar to one of the columns in this one. If a\n Series is passed, its name attribute must be set, and that will be\n used as the column name in the resulting joined DataFrame.\n on : str, list of str, or array-like, optional\n Column or index level name(s) in the caller to join on the index\n in `other`, otherwise joins index-on-index. If multiple\n values given, the `other` DataFrame must have a MultiIndex. Can\n pass an array as the join key if it is not already contained in\n the calling DataFrame. Like an Excel VLOOKUP operation.\n how : {'left', 'right', 'outer', 'inner'}, default 'left'\n How to handle the operation of the two objects.\n\n * left: use calling frame's index (or column if on is specified)\n * right: use `other`'s index.\n * outer: form union of calling frame's index (or column if on is\n specified) with `other`'s index, and sort it.\n lexicographically.\n * inner: form intersection of calling frame's index (or column if\n on is specified) with `other`'s index, preserving the order\n of the calling's one.\n lsuffix : str, default ''\n Suffix to use from left frame's overlapping columns.\n rsuffix : str, default ''\n Suffix to use from right frame's overlapping columns.\n sort : bool, default False\n Order result DataFrame lexicographically by the join key. If False,\n the order of the join key depends on the join type (how keyword).\n\n Returns\n -------\n DataFrame\n A dataframe containing columns from both the caller and `other`.\n\n See Also\n --------\n DataFrame.merge : For column(s)-on-columns(s) operations.\n\n Notes\n -----\n Parameters `on`, `lsuffix`, and `rsuffix` are not supported when\n passing a list of `DataFrame` objects.\n\n Support for specifying index levels as the `on` parameter was added\n in version 0.23.0.\n\n Examples\n --------\n >>> df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'],\n ... 'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})\n\n >>> df\n key A\n 0 K0 A0\n 1 K1 A1\n 2 K2 A2\n 3 K3 A3\n 4 K4 A4\n 5 K5 A5\n\n >>> other = pd.DataFrame({'key': ['K0', 'K1', 'K2'],\n ... 'B': ['B0', 'B1', 'B2']})\n\n >>> other\n key B\n 0 K0 B0\n 1 K1 B1\n 2 K2 B2\n\n Join DataFrames using their indexes.\n\n >>> df.join(other, lsuffix='_caller', rsuffix='_other')\n key_caller A key_other B\n 0 K0 A0 K0 B0\n 1 K1 A1 K1 B1\n 2 K2 A2 K2 B2\n 3 K3 A3 NaN NaN\n 4 K4 A4 NaN NaN\n 5 K5 A5 NaN NaN\n\n If we want to join using the key columns, we need to set key to be\n the index in both `df` and `other`. The joined DataFrame will have\n key as its index.\n\n >>> df.set_index('key').join(other.set_index('key'))\n A B\n key\n K0 A0 B0\n K1 A1 B1\n K2 A2 B2\n K3 A3 NaN\n K4 A4 NaN\n K5 A5 NaN\n\n Another option to join using the key columns is to use the `on`\n parameter. DataFrame.join always uses `other`'s index but we can use\n any column in `df`. This method preserves the original DataFrame's\n index in the result.\n\n >>> df.join(other.set_index('key'), on='key')\n key A B\n 0 K0 A0 B0\n 1 K1 A1 B1\n 2 K2 A2 B2\n 3 K3 A3 NaN\n 4 K4 A4 NaN\n 5 K5 A5 NaN\n \"\"\"\n # For SparseDataFrame's benefit\n return self._join_compat(other, on=on, how=how, lsuffix=lsuffix,\n rsuffix=rsuffix, sort=sort)\n\n def _join_compat(self, other, on=None, how='left', lsuffix='', rsuffix='',\n sort=False):\n from pandas.core.reshape.merge import merge\n from pandas.core.reshape.concat import concat\n\n if isinstance(other, Series):\n if other.name is None:\n raise ValueError('Other Series must have a name')\n other = DataFrame({other.name: other})\n\n if isinstance(other, DataFrame):\n return merge(self, other, left_on=on, how=how,\n left_index=on is None, right_index=True,\n suffixes=(lsuffix, rsuffix), sort=sort)\n else:\n if on is not None:\n raise ValueError('Joining multiple DataFrames only supported'\n ' for joining on index')\n\n frames = [self] + list(other)\n\n can_concat = all(df.index.is_unique for df in frames)\n\n # join indexes only using concat\n if can_concat:\n if how == 'left':\n how = 'outer'\n join_axes = [self.index]\n else:\n join_axes = None\n return concat(frames, axis=1, join=how, join_axes=join_axes,\n verify_integrity=True)\n\n joined = frames[0]\n\n for frame in frames[1:]:\n joined = merge(joined, frame, how=how, left_index=True,\n right_index=True)\n\n return joined\n\n @Substitution('')\n @Appender(_merge_doc, indents=2)\n def merge(self, right, how='inner', on=None, left_on=None, right_on=None,\n left_index=False, right_index=False, sort=False,\n suffixes=('_x', '_y'), copy=True, indicator=False,\n validate=None):\n from pandas.core.reshape.merge import merge\n return merge(self, right, how=how, on=on, left_on=left_on,\n right_on=right_on, left_index=left_index,\n right_index=right_index, sort=sort, suffixes=suffixes,\n copy=copy, indicator=indicator, validate=validate)\n\n def round(self, decimals=0, *args, **kwargs):\n \"\"\"\n Round a DataFrame to a variable number of decimal places.\n\n Parameters\n ----------\n decimals : int, dict, Series\n Number of decimal places to round each column to. If an int is\n given, round each column to the same number of places.\n Otherwise dict and Series round to variable numbers of places.\n Column names should be in the keys if `decimals` is a\n dict-like, or in the index if `decimals` is a Series. Any\n columns not included in `decimals` will be left as is. Elements\n of `decimals` which are not columns of the input will be\n ignored.\n\n Returns\n -------\n DataFrame\n\n See Also\n --------\n numpy.around\n Series.round\n\n Examples\n --------\n >>> df = pd.DataFrame(np.random.random([3, 3]),\n ... columns=['A', 'B', 'C'], index=['first', 'second', 'third'])\n >>> df\n A B C\n first 0.028208 0.992815 0.173891\n second 0.038683 0.645646 0.577595\n third 0.877076 0.149370 0.491027\n >>> df.round(2)\n A B C\n first 0.03 0.99 0.17\n second 0.04 0.65 0.58\n third 0.88 0.15 0.49\n >>> df.round({'A': 1, 'C': 2})\n A B C\n first 0.0 0.992815 0.17\n second 0.0 0.645646 0.58\n third 0.9 0.149370 0.49\n >>> decimals = pd.Series([1, 0, 2], index=['A', 'B', 'C'])\n >>> df.round(decimals)\n A B C\n first 0.0 1 0.17\n second 0.0 1 0.58\n third 0.9 0 0.49\n \"\"\"\n from pandas.core.reshape.concat import concat\n\n def _dict_round(df, decimals):\n for col, vals in df.iteritems():\n try:\n yield _series_round(vals, decimals[col])\n except KeyError:\n yield vals\n\n def _series_round(s, decimals):\n if is_integer_dtype(s) or is_float_dtype(s):\n return s.round(decimals)\n return s\n\n nv.validate_round(args, kwargs)\n\n if isinstance(decimals, (dict, Series)):\n if isinstance(decimals, Series):\n if not decimals.index.is_unique:\n raise ValueError(\"Index of decimals must be unique\")\n new_cols = [col for col in _dict_round(self, decimals)]\n elif is_integer(decimals):\n # Dispatch to Series.round\n new_cols = [_series_round(v, decimals)\n for _, v in self.iteritems()]\n else:\n raise TypeError(\"decimals must be an integer, a dict-like or a \"\n \"Series\")\n\n if len(new_cols) > 0:\n return self._constructor(concat(new_cols, axis=1),\n index=self.index,\n columns=self.columns)\n else:\n return self\n\n # ----------------------------------------------------------------------\n # Statistical methods, etc.\n\n def corr(self, method='pearson', min_periods=1):\n \"\"\"\n Compute pairwise correlation of columns, excluding NA/null values.\n\n Parameters\n ----------\n method : {'pearson', 'kendall', 'spearman'} or callable\n * pearson : standard correlation coefficient\n * kendall : Kendall Tau correlation coefficient\n * spearman : Spearman rank correlation\n * callable: callable with input two 1d ndarrays\n and returning a float\n .. versionadded:: 0.24.0\n\n min_periods : int, optional\n Minimum number of observations required per pair of columns\n to have a valid result. Currently only available for pearson\n and spearman correlation\n\n Returns\n -------\n y : DataFrame\n\n Examples\n --------\n >>> histogram_intersection = lambda a, b: np.minimum(a, b\n ... ).sum().round(decimals=1)\n >>> df = pd.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)],\n ... columns=['dogs', 'cats'])\n >>> df.corr(method=histogram_intersection)\n dogs cats\n dogs 1.0 0.3\n cats 0.3 1.0\n \"\"\"\n numeric_df = self._get_numeric_data()\n cols = numeric_df.columns\n idx = cols.copy()\n mat = numeric_df.values\n\n if method == 'pearson':\n correl = libalgos.nancorr(ensure_float64(mat), minp=min_periods)\n elif method == 'spearman':\n correl = libalgos.nancorr_spearman(ensure_float64(mat),\n minp=min_periods)\n elif method == 'kendall' or callable(method):\n if min_periods is None:\n min_periods = 1\n mat = ensure_float64(mat).T\n corrf = nanops.get_corr_func(method)\n K = len(cols)\n correl = np.empty((K, K), dtype=float)\n mask = np.isfinite(mat)\n for i, ac in enumerate(mat):\n for j, bc in enumerate(mat):\n if i > j:\n continue\n\n valid = mask[i] & mask[j]\n if valid.sum() < min_periods:\n c = np.nan\n elif i == j:\n c = 1.\n elif not valid.all():\n c = corrf(ac[valid], bc[valid])\n else:\n c = corrf(ac, bc)\n correl[i, j] = c\n correl[j, i] = c\n else:\n raise ValueError(\"method must be either 'pearson', \"\n \"'spearman', or 'kendall', '{method}' \"\n \"was supplied\".format(method=method))\n\n return self._constructor(correl, index=idx, columns=cols)\n\n def cov(self, min_periods=None):\n \"\"\"\n Compute pairwise covariance of columns, excluding NA/null values.\n\n Compute the pairwise covariance among the series of a DataFrame.\n The returned data frame is the `covariance matrix\n <https://en.wikipedia.org/wiki/Covariance_matrix>`__ of the columns\n of the DataFrame.\n\n Both NA and null values are automatically excluded from the\n calculation. (See the note below about bias from missing values.)\n A threshold can be set for the minimum number of\n observations for each value created. Comparisons with observations\n below this threshold will be returned as ``NaN``.\n\n This method is generally used for the analysis of time series data to\n understand the relationship between different measures\n across time.\n\n Parameters\n ----------\n min_periods : int, optional\n Minimum number of observations required per pair of columns\n to have a valid result.\n\n Returns\n -------\n DataFrame\n The covariance matrix of the series of the DataFrame.\n\n See Also\n --------\n pandas.Series.cov : Compute covariance with another Series.\n pandas.core.window.EWM.cov: Exponential weighted sample covariance.\n pandas.core.window.Expanding.cov : Expanding sample covariance.\n pandas.core.window.Rolling.cov : Rolling sample covariance.\n\n Notes\n -----\n Returns the covariance matrix of the DataFrame's time series.\n The covariance is normalized by N-1.\n\n For DataFrames that have Series that are missing data (assuming that\n data is `missing at random\n <https://en.wikipedia.org/wiki/Missing_data#Missing_at_random>`__)\n the returned covariance matrix will be an unbiased estimate\n of the variance and covariance between the member Series.\n\n However, for many applications this estimate may not be acceptable\n because the estimate covariance matrix is not guaranteed to be positive\n semi-definite. This could lead to estimate correlations having\n absolute values which are greater than one, and/or a non-invertible\n covariance matrix. See `Estimation of covariance matrices\n <http://en.wikipedia.org/w/index.php?title=Estimation_of_covariance_\n matrices>`__ for more details.\n\n Examples\n --------\n >>> df = pd.DataFrame([(1, 2), (0, 3), (2, 0), (1, 1)],\n ... columns=['dogs', 'cats'])\n >>> df.cov()\n dogs cats\n dogs 0.666667 -1.000000\n cats -1.000000 1.666667\n\n >>> np.random.seed(42)\n >>> df = pd.DataFrame(np.random.randn(1000, 5),\n ... columns=['a', 'b', 'c', 'd', 'e'])\n >>> df.cov()\n a b c d e\n a 0.998438 -0.020161 0.059277 -0.008943 0.014144\n b -0.020161 1.059352 -0.008543 -0.024738 0.009826\n c 0.059277 -0.008543 1.010670 -0.001486 -0.000271\n d -0.008943 -0.024738 -0.001486 0.921297 -0.013692\n e 0.014144 0.009826 -0.000271 -0.013692 0.977795\n\n **Minimum number of periods**\n\n This method also supports an optional ``min_periods`` keyword\n that specifies the required minimum number of non-NA observations for\n each column pair in order to have a valid result:\n\n >>> np.random.seed(42)\n >>> df = pd.DataFrame(np.random.randn(20, 3),\n ... columns=['a', 'b', 'c'])\n >>> df.loc[df.index[:5], 'a'] = np.nan\n >>> df.loc[df.index[5:10], 'b'] = np.nan\n >>> df.cov(min_periods=12)\n a b c\n a 0.316741 NaN -0.150812\n b NaN 1.248003 0.191417\n c -0.150812 0.191417 0.895202\n \"\"\"\n numeric_df = self._get_numeric_data()\n cols = numeric_df.columns\n idx = cols.copy()\n mat = numeric_df.values\n\n if notna(mat).all():\n if min_periods is not None and min_periods > len(mat):\n baseCov = np.empty((mat.shape[1], mat.shape[1]))\n baseCov.fill(np.nan)\n else:\n baseCov = np.cov(mat.T)\n baseCov = baseCov.reshape((len(cols), len(cols)))\n else:\n baseCov = libalgos.nancorr(ensure_float64(mat), cov=True,\n minp=min_periods)\n\n return self._constructor(baseCov, index=idx, columns=cols)\n\n def corrwith(self, other, axis=0, drop=False):\n \"\"\"\n Compute pairwise correlation between rows or columns of two DataFrame\n objects.\n\n Parameters\n ----------\n other : DataFrame, Series\n axis : {0 or 'index', 1 or 'columns'}, default 0\n 0 or 'index' to compute column-wise, 1 or 'columns' for row-wise\n drop : boolean, default False\n Drop missing indices from result, default returns union of all\n\n Returns\n -------\n correls : Series\n \"\"\"\n axis = self._get_axis_number(axis)\n this = self._get_numeric_data()\n\n if isinstance(other, Series):\n return this.apply(other.corr, axis=axis)\n\n other = other._get_numeric_data()\n\n left, right = this.align(other, join='inner', copy=False)\n\n # mask missing values\n left = left + right * 0\n right = right + left * 0\n\n if axis == 1:\n left = left.T\n right = right.T\n\n # demeaned data\n ldem = left - left.mean()\n rdem = right - right.mean()\n\n num = (ldem * rdem).sum()\n dom = (left.count() - 1) * left.std() * right.std()\n\n correl = num / dom\n\n if not drop:\n raxis = 1 if axis == 0 else 0\n result_index = this._get_axis(raxis).union(other._get_axis(raxis))\n correl = correl.reindex(result_index)\n\n return correl\n\n # ----------------------------------------------------------------------\n # ndarray-like stats methods\n\n def count(self, axis=0, level=None, numeric_only=False):\n \"\"\"\n Count non-NA cells for each column or row.\n\n The values `None`, `NaN`, `NaT`, and optionally `numpy.inf` (depending\n on `pandas.options.mode.use_inf_as_na`) are considered NA.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n If 0 or 'index' counts are generated for each column.\n If 1 or 'columns' counts are generated for each **row**.\n level : int or str, optional\n If the axis is a `MultiIndex` (hierarchical), count along a\n particular `level`, collapsing into a `DataFrame`.\n A `str` specifies the level name.\n numeric_only : boolean, default False\n Include only `float`, `int` or `boolean` data.\n\n Returns\n -------\n Series or DataFrame\n For each column/row the number of non-NA/null entries.\n If `level` is specified returns a `DataFrame`.\n\n See Also\n --------\n Series.count: Number of non-NA elements in a Series.\n DataFrame.shape: Number of DataFrame rows and columns (including NA\n elements).\n DataFrame.isna: Boolean same-sized DataFrame showing places of NA\n elements.\n\n Examples\n --------\n Constructing DataFrame from a dictionary:\n\n >>> df = pd.DataFrame({\"Person\":\n ... [\"John\", \"Myla\", \"Lewis\", \"John\", \"Myla\"],\n ... \"Age\": [24., np.nan, 21., 33, 26],\n ... \"Single\": [False, True, True, True, False]})\n >>> df\n Person Age Single\n 0 John 24.0 False\n 1 Myla NaN True\n 2 Lewis 21.0 True\n 3 John 33.0 True\n 4 Myla 26.0 False\n\n Notice the uncounted NA values:\n\n >>> df.count()\n Person 5\n Age 4\n Single 5\n dtype: int64\n\n Counts for each **row**:\n\n >>> df.count(axis='columns')\n 0 3\n 1 2\n 2 3\n 3 3\n 4 3\n dtype: int64\n\n Counts for one level of a `MultiIndex`:\n\n >>> df.set_index([\"Person\", \"Single\"]).count(level=\"Person\")\n Age\n Person\n John 2\n Lewis 1\n Myla 1\n \"\"\"\n axis = self._get_axis_number(axis)\n if level is not None:\n return self._count_level(level, axis=axis,\n numeric_only=numeric_only)\n\n if numeric_only:\n frame = self._get_numeric_data()\n else:\n frame = self\n\n # GH #423\n if len(frame._get_axis(axis)) == 0:\n result = Series(0, index=frame._get_agg_axis(axis))\n else:\n if frame._is_mixed_type or frame._data.any_extension_types:\n # the or any_extension_types is really only hit for single-\n # column frames with an extension array\n result = notna(frame).sum(axis=axis)\n else:\n # GH13407\n series_counts = notna(frame).sum(axis=axis)\n counts = series_counts.values\n result = Series(counts, index=frame._get_agg_axis(axis))\n\n return result.astype('int64')\n\n def _count_level(self, level, axis=0, numeric_only=False):\n if numeric_only:\n frame = self._get_numeric_data()\n else:\n frame = self\n\n count_axis = frame._get_axis(axis)\n agg_axis = frame._get_agg_axis(axis)\n\n if not isinstance(count_axis, MultiIndex):\n raise TypeError(\"Can only count levels on hierarchical \"\n \"{ax}.\".format(ax=self._get_axis_name(axis)))\n\n if frame._is_mixed_type:\n # Since we have mixed types, calling notna(frame.values) might\n # upcast everything to object\n mask = notna(frame).values\n else:\n # But use the speedup when we have homogeneous dtypes\n mask = notna(frame.values)\n\n if axis == 1:\n # We're transposing the mask rather than frame to avoid potential\n # upcasts to object, which induces a ~20x slowdown\n mask = mask.T\n\n if isinstance(level, compat.string_types):\n level = count_axis._get_level_number(level)\n\n level_index = count_axis.levels[level]\n level_codes = ensure_int64(count_axis.codes[level])\n counts = lib.count_level_2d(mask, level_codes, len(level_index),\n axis=0)\n\n result = DataFrame(counts, index=level_index, columns=agg_axis)\n\n if axis == 1:\n # Undo our earlier transpose\n return result.T\n else:\n return result\n\n def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,\n filter_type=None, **kwds):\n if axis is None and filter_type == 'bool':\n labels = None\n constructor = None\n else:\n # TODO: Make other agg func handle axis=None properly\n axis = self._get_axis_number(axis)\n labels = self._get_agg_axis(axis)\n constructor = self._constructor\n\n def f(x):\n return op(x, axis=axis, skipna=skipna, **kwds)\n\n # exclude timedelta/datetime unless we are uniform types\n if axis == 1 and self._is_mixed_type and self._is_datelike_mixed_type:\n numeric_only = True\n\n if numeric_only is None:\n try:\n values = self.values\n result = f(values)\n\n if (filter_type == 'bool' and is_object_dtype(values) and\n axis is None):\n # work around https://github.com/numpy/numpy/issues/10489\n # TODO: combine with hasattr(result, 'dtype') further down\n # hard since we don't have `values` down there.\n result = np.bool_(result)\n except Exception as e:\n\n # try by-column first\n if filter_type is None and axis == 0:\n try:\n\n # this can end up with a non-reduction\n # but not always. if the types are mixed\n # with datelike then need to make sure a series\n\n # we only end up here if we have not specified\n # numeric_only and yet we have tried a\n # column-by-column reduction, where we have mixed type.\n # So let's just do what we can\n from pandas.core.apply import frame_apply\n opa = frame_apply(self,\n func=f,\n result_type='expand',\n ignore_failures=True)\n result = opa.get_result()\n if result.ndim == self.ndim:\n result = result.iloc[0]\n return result\n except Exception:\n pass\n\n if filter_type is None or filter_type == 'numeric':\n data = self._get_numeric_data()\n elif filter_type == 'bool':\n data = self._get_bool_data()\n else: # pragma: no cover\n e = NotImplementedError(\n \"Handling exception with filter_type {f} not\"\n \"implemented.\".format(f=filter_type))\n raise_with_traceback(e)\n with np.errstate(all='ignore'):\n result = f(data.values)\n labels = data._get_agg_axis(axis)\n else:\n if numeric_only:\n if filter_type is None or filter_type == 'numeric':\n data = self._get_numeric_data()\n elif filter_type == 'bool':\n data = self._get_bool_data()\n else: # pragma: no cover\n msg = (\"Generating numeric_only data with filter_type {f}\"\n \"not supported.\".format(f=filter_type))\n raise NotImplementedError(msg)\n values = data.values\n labels = data._get_agg_axis(axis)\n else:\n values = self.values\n result = f(values)\n\n if hasattr(result, 'dtype') and is_object_dtype(result.dtype):\n try:\n if filter_type is None or filter_type == 'numeric':\n result = result.astype(np.float64)\n elif filter_type == 'bool' and notna(result).all():\n result = result.astype(np.bool_)\n except (ValueError, TypeError):\n\n # try to coerce to the original dtypes item by item if we can\n if axis == 0:\n result = coerce_to_dtypes(result, self.dtypes)\n\n if constructor is not None:\n result = Series(result, index=labels)\n return result\n\n def nunique(self, axis=0, dropna=True):\n \"\"\"\n Count distinct observations over requested axis.\n\n Return Series with number of distinct observations. Can ignore NaN\n values.\n\n .. versionadded:: 0.20.0\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for\n column-wise.\n dropna : bool, default True\n Don't include NaN in the counts.\n\n Returns\n -------\n nunique : Series\n\n See Also\n --------\n Series.nunique: Method nunique for Series.\n DataFrame.count: Count non-NA cells for each column or row.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 1, 1]})\n >>> df.nunique()\n A 3\n B 1\n dtype: int64\n\n >>> df.nunique(axis=1)\n 0 1\n 1 2\n 2 2\n dtype: int64\n \"\"\"\n return self.apply(Series.nunique, axis=axis, dropna=dropna)\n\n def idxmin(self, axis=0, skipna=True):\n \"\"\"\n Return index of first occurrence of minimum over requested axis.\n NA/null values are excluded.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n 0 or 'index' for row-wise, 1 or 'columns' for column-wise\n skipna : boolean, default True\n Exclude NA/null values. If an entire row/column is NA, the result\n will be NA.\n\n Returns\n -------\n idxmin : Series\n\n Raises\n ------\n ValueError\n * If the row/column is empty\n\n See Also\n --------\n Series.idxmin\n\n Notes\n -----\n This method is the DataFrame version of ``ndarray.argmin``.\n \"\"\"\n axis = self._get_axis_number(axis)\n indices = nanops.nanargmin(self.values, axis=axis, skipna=skipna)\n index = self._get_axis(axis)\n result = [index[i] if i >= 0 else np.nan for i in indices]\n return Series(result, index=self._get_agg_axis(axis))\n\n def idxmax(self, axis=0, skipna=True):\n \"\"\"\n Return index of first occurrence of maximum over requested axis.\n NA/null values are excluded.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n 0 or 'index' for row-wise, 1 or 'columns' for column-wise\n skipna : boolean, default True\n Exclude NA/null values. If an entire row/column is NA, the result\n will be NA.\n\n Returns\n -------\n idxmax : Series\n\n Raises\n ------\n ValueError\n * If the row/column is empty\n\n See Also\n --------\n Series.idxmax\n\n Notes\n -----\n This method is the DataFrame version of ``ndarray.argmax``.\n \"\"\"\n axis = self._get_axis_number(axis)\n indices = nanops.nanargmax(self.values, axis=axis, skipna=skipna)\n index = self._get_axis(axis)\n result = [index[i] if i >= 0 else np.nan for i in indices]\n return Series(result, index=self._get_agg_axis(axis))\n\n def _get_agg_axis(self, axis_num):\n \"\"\"\n Let's be explicit about this.\n \"\"\"\n if axis_num == 0:\n return self.columns\n elif axis_num == 1:\n return self.index\n else:\n raise ValueError('Axis must be 0 or 1 (got %r)' % axis_num)\n\n def mode(self, axis=0, numeric_only=False, dropna=True):\n \"\"\"\n Get the mode(s) of each element along the selected axis.\n\n The mode of a set of values is the value that appears most often.\n It can be multiple values.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to iterate over while searching for the mode:\n\n * 0 or 'index' : get mode of each column\n * 1 or 'columns' : get mode of each row\n numeric_only : bool, default False\n If True, only apply to numeric columns.\n dropna : bool, default True\n Don't consider counts of NaN/NaT.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n DataFrame\n The modes of each column or row.\n\n See Also\n --------\n Series.mode : Return the highest frequency value in a Series.\n Series.value_counts : Return the counts of values in a Series.\n\n Examples\n --------\n >>> df = pd.DataFrame([('bird', 2, 2),\n ... ('mammal', 4, np.nan),\n ... ('arthropod', 8, 0),\n ... ('bird', 2, np.nan)],\n ... index=('falcon', 'horse', 'spider', 'ostrich'),\n ... columns=('species', 'legs', 'wings'))\n >>> df\n species legs wings\n falcon bird 2 2.0\n horse mammal 4 NaN\n spider arthropod 8 0.0\n ostrich bird 2 NaN\n\n By default, missing values are not considered, and the mode of wings\n are both 0 and 2. The second row of species and legs contains ``NaN``,\n because they have only one mode, but the DataFrame has two rows.\n\n >>> df.mode()\n species legs wings\n 0 bird 2.0 0.0\n 1 NaN NaN 2.0\n\n Setting ``dropna=False`` ``NaN`` values are considered and they can be\n the mode (like for wings).\n\n >>> df.mode(dropna=False)\n species legs wings\n 0 bird 2 NaN\n\n Setting ``numeric_only=True``, only the mode of numeric columns is\n computed, and columns of other types are ignored.\n\n >>> df.mode(numeric_only=True)\n legs wings\n 0 2.0 0.0\n 1 NaN 2.0\n\n To compute the mode over columns and not rows, use the axis parameter:\n\n >>> df.mode(axis='columns', numeric_only=True)\n 0 1\n falcon 2.0 NaN\n horse 4.0 NaN\n spider 0.0 8.0\n ostrich 2.0 NaN\n \"\"\"\n data = self if not numeric_only else self._get_numeric_data()\n\n def f(s):\n return s.mode(dropna=dropna)\n\n return data.apply(f, axis=axis)\n\n def quantile(self, q=0.5, axis=0, numeric_only=True,\n interpolation='linear'):\n \"\"\"\n Return values at the given quantile over requested axis.\n\n Parameters\n ----------\n q : float or array-like, default 0.5 (50% quantile)\n 0 <= q <= 1, the quantile(s) to compute\n axis : {0, 1, 'index', 'columns'} (default 0)\n 0 or 'index' for row-wise, 1 or 'columns' for column-wise\n numeric_only : boolean, default True\n If False, the quantile of datetime and timedelta data will be\n computed as well\n interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}\n .. versionadded:: 0.18.0\n\n This optional parameter specifies the interpolation method to use,\n when the desired quantile lies between two data points `i` and `j`:\n\n * linear: `i + (j - i) * fraction`, where `fraction` is the\n fractional part of the index surrounded by `i` and `j`.\n * lower: `i`.\n * higher: `j`.\n * nearest: `i` or `j` whichever is nearest.\n * midpoint: (`i` + `j`) / 2.\n\n Returns\n -------\n quantiles : Series or DataFrame\n\n - If ``q`` is an array, a DataFrame will be returned where the\n index is ``q``, the columns are the columns of self, and the\n values are the quantiles.\n - If ``q`` is a float, a Series will be returned where the\n index is the columns of self and the values are the quantiles.\n\n See Also\n --------\n pandas.core.window.Rolling.quantile\n numpy.percentile\n\n Examples\n --------\n\n >>> df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]),\n columns=['a', 'b'])\n >>> df.quantile(.1)\n a 1.3\n b 3.7\n dtype: float64\n >>> df.quantile([.1, .5])\n a b\n 0.1 1.3 3.7\n 0.5 2.5 55.0\n\n Specifying `numeric_only=False` will also compute the quantile of\n datetime and timedelta data.\n\n >>> df = pd.DataFrame({'A': [1, 2],\n 'B': [pd.Timestamp('2010'),\n pd.Timestamp('2011')],\n 'C': [pd.Timedelta('1 days'),\n pd.Timedelta('2 days')]})\n >>> df.quantile(0.5, numeric_only=False)\n A 1.5\n B 2010-07-02 12:00:00\n C 1 days 12:00:00\n Name: 0.5, dtype: object\n \"\"\"\n self._check_percentile(q)\n\n data = self._get_numeric_data() if numeric_only else self\n axis = self._get_axis_number(axis)\n is_transposed = axis == 1\n\n if is_transposed:\n data = data.T\n\n result = data._data.quantile(qs=q,\n axis=1,\n interpolation=interpolation,\n transposed=is_transposed)\n\n if result.ndim == 2:\n result = self._constructor(result)\n else:\n result = self._constructor_sliced(result, name=q)\n\n if is_transposed:\n result = result.T\n\n return result\n\n def to_timestamp(self, freq=None, how='start', axis=0, copy=True):\n \"\"\"\n Cast to DatetimeIndex of timestamps, at *beginning* of period.\n\n Parameters\n ----------\n freq : string, default frequency of PeriodIndex\n Desired frequency\n how : {'s', 'e', 'start', 'end'}\n Convention for converting period to timestamp; start of period\n vs. end\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to convert (the index by default)\n copy : boolean, default True\n If false then underlying input data is not copied\n\n Returns\n -------\n df : DataFrame with DatetimeIndex\n \"\"\"\n new_data = self._data\n if copy:\n new_data = new_data.copy()\n\n axis = self._get_axis_number(axis)\n if axis == 0:\n new_data.set_axis(1, self.index.to_timestamp(freq=freq, how=how))\n elif axis == 1:\n new_data.set_axis(0, self.columns.to_timestamp(freq=freq, how=how))\n else: # pragma: no cover\n raise AssertionError('Axis must be 0 or 1. Got {ax!s}'.format(\n ax=axis))\n\n return self._constructor(new_data)\n\n def to_period(self, freq=None, axis=0, copy=True):\n \"\"\"\n Convert DataFrame from DatetimeIndex to PeriodIndex with desired\n frequency (inferred from index if not passed).\n\n Parameters\n ----------\n freq : string, default\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to convert (the index by default)\n copy : boolean, default True\n If False then underlying input data is not copied\n\n Returns\n -------\n ts : TimeSeries with PeriodIndex\n \"\"\"\n new_data = self._data\n if copy:\n new_data = new_data.copy()\n\n axis = self._get_axis_number(axis)\n if axis == 0:\n new_data.set_axis(1, self.index.to_period(freq=freq))\n elif axis == 1:\n new_data.set_axis(0, self.columns.to_period(freq=freq))\n else: # pragma: no cover\n raise AssertionError('Axis must be 0 or 1. Got {ax!s}'.format(\n ax=axis))\n\n return self._constructor(new_data)\n\n def isin(self, values):\n \"\"\"\n Whether each element in the DataFrame is contained in values.\n\n Parameters\n ----------\n values : iterable, Series, DataFrame or dict\n The result will only be true at a location if all the\n labels match. If `values` is a Series, that's the index. If\n `values` is a dict, the keys must be the column names,\n which must match. If `values` is a DataFrame,\n then both the index and column labels must match.\n\n Returns\n -------\n DataFrame\n DataFrame of booleans showing whether each element in the DataFrame\n is contained in values.\n\n See Also\n --------\n DataFrame.eq: Equality test for DataFrame.\n Series.isin: Equivalent method on Series.\n Series.str.contains: Test if pattern or regex is contained within a\n string of a Series or Index.\n\n Examples\n --------\n\n >>> df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]},\n ... index=['falcon', 'dog'])\n >>> df\n num_legs num_wings\n falcon 2 2\n dog 4 0\n\n When ``values`` is a list check whether every value in the DataFrame\n is present in the list (which animals have 0 or 2 legs or wings)\n\n >>> df.isin([0, 2])\n num_legs num_wings\n falcon True True\n dog False True\n\n When ``values`` is a dict, we can pass values to check for each\n column separately:\n\n >>> df.isin({'num_wings': [0, 3]})\n num_legs num_wings\n falcon False False\n dog False True\n\n When ``values`` is a Series or DataFrame the index and column must\n match. Note that 'falcon' does not match based on the number of legs\n in df2.\n\n >>> other = pd.DataFrame({'num_legs': [8, 2],'num_wings': [0, 2]},\n ... index=['spider', 'falcon'])\n >>> df.isin(other)\n num_legs num_wings\n falcon True True\n dog False False\n \"\"\"\n if isinstance(values, dict):\n from pandas.core.reshape.concat import concat\n values = collections.defaultdict(list, values)\n return concat((self.iloc[:, [i]].isin(values[col])\n for i, col in enumerate(self.columns)), axis=1)\n elif isinstance(values, Series):\n if not values.index.is_unique:\n raise ValueError(\"cannot compute isin with \"\n \"a duplicate axis.\")\n return self.eq(values.reindex_like(self), axis='index')\n elif isinstance(values, DataFrame):\n if not (values.columns.is_unique and values.index.is_unique):\n raise ValueError(\"cannot compute isin with \"\n \"a duplicate axis.\")\n return self.eq(values.reindex_like(self))\n else:\n if not is_list_like(values):\n raise TypeError(\"only list-like or dict-like objects are \"\n \"allowed to be passed to DataFrame.isin(), \"\n \"you passed a \"\n \"{0!r}\".format(type(values).__name__))\n return DataFrame(\n algorithms.isin(self.values.ravel(),\n values).reshape(self.shape), self.index,\n self.columns)\n\n # ----------------------------------------------------------------------\n # Add plotting methods to DataFrame\n plot = CachedAccessor(\"plot\", gfx.FramePlotMethods)\n hist = gfx.hist_frame\n boxplot = gfx.boxplot_frame\n\n\nDataFrame._setup_axes(['index', 'columns'], info_axis=1, stat_axis=0,\n axes_are_reversed=True, aliases={'rows': 0},\n docs={\n 'index': 'The index (row labels) of the DataFrame.',\n 'columns': 'The column labels of the DataFrame.'})\nDataFrame._add_numeric_operations()\nDataFrame._add_series_or_dataframe_operations()\n\nops.add_flex_arithmetic_methods(DataFrame)\nops.add_special_arithmetic_methods(DataFrame)\n\n\ndef _from_nested_dict(data):\n # TODO: this should be seriously cythonized\n new_data = OrderedDict()\n for index, s in compat.iteritems(data):\n for col, v in compat.iteritems(s):\n new_data[col] = new_data.get(col, OrderedDict())\n new_data[col][index] = v\n return new_data\n\n\ndef _put_str(s, space):\n return u'{s}'.format(s=s)[:space].ljust(space)\n"
] |
[
[
"pandas.util._validators.validate_bool_kwarg",
"pandas.core.sparse.api.SparseDataFrame",
"pandas.compat.lzip",
"numpy.where",
"pandas.core.dtypes.common.is_named_tuple",
"pandas.compat.OrderedDict",
"pandas.core.common.standardize_mapping",
"pandas.compat.raise_with_traceback",
"pandas.core.dtypes.cast.maybe_convert_platform",
"pandas.core.internals.construction.init_dict",
"pandas._libs.lib.map_infer",
"pandas.core.dtypes.common.is_iterator",
"pandas.core.dtypes.common.is_float_dtype",
"pandas.core.sorting.lexsort_indexer",
"pandas.core.dtypes.cast.coerce_to_dtypes",
"pandas.core.dtypes.common.is_list_like",
"pandas.core.dtypes.common.is_sequence",
"pandas._libs.hashtable.duplicated_int64",
"pandas.core.nanops.nanargmax",
"pandas.core.internals.construction.masked_rec_array_to_mgr",
"numpy.array",
"pandas.io.formats.format.DataFrameFormatter",
"pandas.core.dtypes.cast.maybe_downcast_to_dtype",
"pandas.core.ops.dispatch_to_series",
"pandas.core.reshape.reshape.stack",
"pandas.core.dtypes.common.is_bool_dtype",
"pandas.core.computation.eval.eval",
"pandas.core.ops.fill_binop",
"pandas.core.dtypes.cast.find_common_type",
"pandas.core.dtypes.common.is_extension_type",
"pandas.core.internals.construction.arrays_to_mgr",
"pandas.io.formats.style.Styler",
"pandas.core.dtypes.missing.isna",
"pandas.io.formats.printing.pprint_thing",
"pandas.core.internals.construction.get_names_from_index",
"pandas.compat.range",
"pandas.core.index.ensure_index_from_sequences",
"pandas.core.generic.NDFrame.__init__",
"numpy.asarray",
"pandas.core.dtypes.cast.maybe_cast_to_datetime",
"pandas.compat.numpy.function.validate_round",
"pandas.io.gbq.to_gbq",
"pandas.core.internals.construction.sanitize_index",
"numpy.ma.getmaskarray",
"pandas.core.dtypes.cast.invalidate_string_dtypes",
"pandas.compat.StringIO",
"pandas.core.common.asarray_tuplesafe",
"pandas.io.formats.console.in_interactive_session",
"pandas.core.index.ensure_index",
"pandas.core.internals.construction.to_arrays",
"pandas.compat.u",
"pandas.core.common.maybe_box_datetimelike",
"pandas.core.dtypes.cast.infer_dtype_from_scalar",
"numpy.ndim",
"numpy.errstate",
"pandas.core.dtypes.cast.maybe_infer_to_datetimelike",
"pandas.util._validators.validate_axis_style_args",
"numpy.rec.fromarrays",
"pandas.core.dtypes.common.is_integer",
"pandas.core.dtypes.cast.maybe_upcast",
"pandas.core.nanops.get_corr_func",
"numpy.empty",
"pandas.core.index.Index",
"pandas.core.reshape.pivot.pivot_table",
"pandas.util._decorators.deprecate_kwarg",
"pandas.io.formats.console.get_console_size",
"pandas.core.dtypes.common.is_extension_array_dtype",
"pandas.core.reshape.pivot.pivot",
"pandas.core.dtypes.common.is_dtype_equal",
"pandas._libs.lib.is_scalar",
"pandas.core.common._unpickle_array",
"pandas.core.dtypes.missing.notna",
"pandas.compat.map",
"pandas.compat.iteritems",
"pandas.io.formats.console.in_qtconsole",
"pandas.core.sorting.get_group_index",
"pandas.core.reshape.melt.melt",
"numpy.bool_",
"pandas.util._decorators.Substitution",
"pandas.core.series.Series",
"pandas.core.ops.add_special_arithmetic_methods",
"pandas.core.internals.construction.init_ndarray",
"pandas.core.nanops.nanargmin",
"pandas.core.dtypes.common.ensure_int64",
"pandas.core.dtypes.common.is_integer_dtype",
"pandas.util._decorators.Appender",
"pandas.io.formats.format.buffer_put_lines",
"numpy.cov",
"pandas.core.dtypes.common.is_nested_list_like",
"numpy.transpose",
"numpy.iterable",
"pandas.core.dtypes.common.needs_i8_conversion",
"pandas.util._decorators.rewrite_axis_style_signature",
"pandas.core.ops.add_flex_arithmetic_methods",
"pandas.core.algorithms.SelectNFrame",
"pandas.core.sorting.nargsort",
"pandas.core.common.is_bool_indexer",
"pandas.core.dtypes.common.is_scalar",
"pandas.core.accessor.CachedAccessor",
"pandas.compat.zip",
"pandas.core.ops.should_series_dispatch",
"numpy.dot",
"pandas.core.dtypes.cast.maybe_upcast_putmask",
"pandas.core.computation.expressions.where",
"pandas.core.generic.NDFrame._set_item",
"pandas.core.indexing.check_bool_indexer",
"pandas.core.config.get_option",
"pandas.core.dtypes.common.ensure_float64",
"pandas.io.parquet.to_parquet",
"pandas.compat.lmap",
"pandas.core.reshape.reshape.stack_multiple",
"pandas.core.apply.frame_apply",
"pandas.core.dtypes.common.is_datetime64_any_dtype",
"pandas.core.indexing.convert_to_index_sliceable",
"pandas.io.stata.StataWriter117",
"pandas.core.dtypes.common.ensure_platform_int",
"pandas.core.reshape.concat.concat",
"pandas.io.parsers.read_csv",
"pandas.core.algorithms.take_2d_multi",
"pandas.core.reshape.reshape.unstack",
"numpy.isfinite",
"pandas.io.formats.console.in_ipython_frontend",
"numpy.compress",
"pandas.core.reshape.merge.merge",
"pandas.core.dtypes.common.is_object_dtype",
"pandas.core.common.apply_if_callable",
"pandas._libs.lib.maybe_convert_objects",
"pandas.io.feather_format.to_feather",
"pandas.core.internals.construction.reorder_arrays",
"pandas.core.indexing.maybe_droplevels"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.24",
"0.25"
],
"scipy": [],
"tensorflow": []
}
] |
Rumiachang/keras-examples
|
[
"467ac2e693930980bb21315fb33b298fff852a31"
] |
[
"vgg16/test_vgg16/test_vgg16.py"
] |
[
"from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions\nfrom keras.preprocessing import image\nimport numpy as np\nimport sys\n\n\"\"\"\nImageNetで学習済みのVGG16モデルを使って入力画像のクラスを予測する\n\"\"\"\n\nif len(sys.argv) != 2:\n print(\"usage: python test_vgg16.py [image file]\")\n sys.exit(1)\n\nfilename = sys.argv[1]\n\n# 学習済みのVGG16をロード\n# 構造とともに学習済みの重みも読み込まれる\nmodel = VGG16(weights='imagenet')\n# model.summary()\n\n# 引数で指定した画像ファイルを読み込む\n# サイズはVGG16のデフォルトである224x224にリサイズされる\nimg = image.load_img(filename, target_size=(224, 224))\n\n# 読み込んだPIL形式の画像をarrayに変換\nx = image.img_to_array(img)\n\n# 3次元テンソル(rows, cols, channels) を\n# 4次元テンソル (samples, rows, cols, channels) に変換\n# 入力画像は1枚なのでsamples=1でよい\nx = np.expand_dims(x, axis=0)\n\n# Top-5のクラスを予測する\n# VGG16の1000クラスはdecode_predictions()で文字列に変換される\npreds = model.predict(preprocess_input(x))\nresults = decode_predictions(preds, top=5)[0]\nfor result in results:\n print(result)\n"
] |
[
[
"numpy.expand_dims"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
maxfrei750/fvcore
|
[
"4ede864f410e204ce1b40284852aa238a85f2e64"
] |
[
"tests/test_common.py"
] |
[
"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nimport numpy as np\nimport time\nimport unittest\n\nfrom fvcore.common.config import CfgNode\nfrom fvcore.common.history_buffer import HistoryBuffer\nfrom fvcore.common.registry import Registry\nfrom fvcore.common.timer import Timer\n\n\nclass TestHistoryBuffer(unittest.TestCase):\n def setUp(self) -> None:\n super().setUp()\n np.random.seed(42)\n\n @staticmethod\n def create_buffer_with_init(num_values: int, buffer_len: int = 1000000):\n \"\"\"\n Return a HistoryBuffer of the given length filled with random numbers.\n\n Args:\n buffer_len: length of the created history buffer.\n num_values: number of random numbers added to the history buffer.\n \"\"\"\n\n max_value = 1000\n values = np.random.randint(max_value, size=num_values)\n\n def create_buffer():\n buf = HistoryBuffer(buffer_len)\n for v in values:\n buf.update(v)\n return buf, values\n\n return create_buffer\n\n def test_buffer(self) -> None:\n \"\"\"\n Test creation of HistoryBuffer and the methods provided in the class.\n \"\"\"\n\n num_iters = 100\n for _ in range(num_iters):\n gt_len = 1000\n buffer_len = np.random.randint(1, gt_len)\n create_buffer = TestHistoryBuffer.create_buffer_with_init(\n gt_len, buffer_len\n )\n buf, gt = create_buffer()\n\n values, iterations = zip(*buf.values())\n self.assertEqual(len(values), buffer_len)\n self.assertEqual(len(iterations), buffer_len)\n self.assertTrue((values == gt[-buffer_len:]).all())\n iterations_gt = np.arange(gt_len - buffer_len, gt_len)\n self.assertTrue(\n (iterations == iterations_gt).all(),\n \", \".join(str(x) for x in iterations),\n )\n self.assertAlmostEqual(buf.global_avg(), gt.mean())\n w = 100\n effective_w = min(w, buffer_len)\n self.assertAlmostEqual(\n buf.median(w),\n np.median(gt[-effective_w:]),\n None,\n \" \".join(str(x) for x in gt[-effective_w:]),\n )\n self.assertAlmostEqual(\n buf.avg(w),\n np.mean(gt[-effective_w:]),\n None,\n \" \".join(str(x) for x in gt[-effective_w:]),\n )\n\n\nclass TestTimer(unittest.TestCase):\n def test_timer(self):\n timer = Timer()\n time.sleep(0.5)\n self.assertTrue(0.99 > timer.seconds() >= 0.5)\n\n timer.pause()\n time.sleep(0.5)\n\n self.assertTrue(0.99 > timer.seconds() >= 0.5)\n\n timer.resume()\n time.sleep(0.5)\n self.assertTrue(1.49 > timer.seconds() >= 1.0)\n\n timer.reset()\n self.assertTrue(0.49 > timer.seconds() >= 0)\n\n\nclass TestCfgNode(unittest.TestCase):\n @staticmethod\n def gen_default_cfg():\n cfg = CfgNode()\n cfg.KEY1 = \"default\"\n cfg.KEY2 = \"default\"\n cfg.EXPRESSION = [3.0]\n\n return cfg\n\n def test_merge_from_file(self):\n \"\"\"\n Test merge_from_file function provided in the class.\n \"\"\"\n import pkg_resources\n\n base_yaml = pkg_resources.resource_filename(\n __name__, \"configs/base.yaml\"\n )\n config_yaml = pkg_resources.resource_filename(\n __name__, \"configs/config.yaml\"\n )\n\n cfg = TestCfgNode.gen_default_cfg()\n cfg.merge_from_file(base_yaml)\n self.assertEqual(cfg.KEY1, \"base\")\n self.assertEqual(cfg.KEY2, \"base\")\n\n cfg = TestCfgNode.gen_default_cfg()\n\n with self.assertRaises(Exception):\n # config.yaml contains unsafe yaml tags,\n # test if an exception is thrown\n cfg.merge_from_file(config_yaml)\n\n cfg.merge_from_file(config_yaml, allow_unsafe=True)\n self.assertEqual(cfg.KEY1, \"base\")\n self.assertEqual(cfg.KEY2, \"config\")\n self.assertEqual(cfg.EXPRESSION, [1, 4, 9])\n\n def test_merge_from_list(self):\n \"\"\"\n Test merge_from_list function provided in the class.\n \"\"\"\n cfg = TestCfgNode.gen_default_cfg()\n cfg.merge_from_list([\"KEY1\", \"list1\", \"KEY2\", \"list2\"])\n self.assertEqual(cfg.KEY1, \"list1\")\n self.assertEqual(cfg.KEY2, \"list2\")\n\n def test_setattr(self):\n \"\"\"\n Test __setattr__ function provided in the class.\n \"\"\"\n cfg = TestCfgNode.gen_default_cfg()\n cfg.KEY1 = \"new1\"\n cfg.KEY3 = \"new3\"\n self.assertEqual(cfg.KEY1, \"new1\")\n self.assertEqual(cfg.KEY3, \"new3\")\n\n # Test computed attributes, which can be inserted regardless of whether\n # the CfgNode is frozen or not.\n cfg = TestCfgNode.gen_default_cfg()\n cfg.COMPUTED_1 = \"computed1\"\n self.assertEqual(cfg.COMPUTED_1, \"computed1\")\n cfg.freeze()\n cfg.COMPUTED_2 = \"computed2\"\n self.assertEqual(cfg.COMPUTED_2, \"computed2\")\n\n # Test computed attributes, which should be 'insert only' (could not be\n # updated).\n cfg = TestCfgNode.gen_default_cfg()\n cfg.COMPUTED_1 = \"computed1\"\n with self.assertRaises(KeyError) as err:\n cfg.COMPUTED_1 = \"update_computed1\"\n self.assertTrue(\n \"Computed attributed 'COMPUTED_1' already exists\"\n in str(err.exception)\n )\n\n # Resetting the same value should be safe:\n cfg.COMPUTED_1 = \"computed1\"\n\n\nclass TestRegistry(unittest.TestCase):\n def test_registry(self):\n \"\"\"\n Test registering and accessing objects in the Registry.\n \"\"\"\n OBJECT_REGISTRY = Registry(\"OBJECT\")\n\n @OBJECT_REGISTRY.register()\n class Object1:\n pass\n\n with self.assertRaises(Exception) as err:\n OBJECT_REGISTRY.register(Object1)\n self.assertTrue(\n \"An object named 'Object1' was already registered in 'OBJECT' registry!\"\n in str(err.exception)\n )\n\n self.assertEqual(OBJECT_REGISTRY.get(\"Object1\"), Object1)\n\n with self.assertRaises(KeyError) as err:\n OBJECT_REGISTRY.get(\"Object2\")\n self.assertTrue(\n \"No object named 'Object2' found in 'OBJECT' registry!\"\n in str(err.exception)\n )\n"
] |
[
[
"numpy.random.seed",
"numpy.arange",
"numpy.median",
"numpy.mean",
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ShiNik/marathon_machine_learning
|
[
"9320e161a2e25eb3772f6eeb3ba5a292177ec6e7"
] |
[
"src/my_package/data_cleanup.py"
] |
[
"import pandas as pd\nimport numpy as np\n\ndef distance_calculation (df):\n df['Time'] = pd.to_datetime(df['Time'])\n df['Pace'] = pd.to_datetime(df['Pace'])\n time = pd.to_timedelta(df['Time'].dt.strftime(\"%H:%M:%S\")).dt.total_seconds().astype(int).to_numpy()\n # convert %H:%M to %M:%S by dividing by 60\n pace = pd.to_timedelta(df['Pace'].dt.strftime(\"%H:%M:%S\")).dt.total_seconds().astype(int).to_numpy()/60\n # In marathon distance compute by miles per minuets therefore we need to\n # convert time and pace from second to minutes\n df['distance'] = time/60 *pace/60\n\ndef perform_cleanup(df, threshold):\n # drop columns: Time, Pace\n # drop row if empty cell :.isnull() , Id, Age, Rank,Year\n # Sex or Name isnull(), try to fill it otherwise drop the row\n # If one Id links to 2 names, drop one if one group smaller than another, otherwise drop both\n # If one Name links to 2 Ids, drop one if one group smaller than another, otherwise drop both\n # group by Id, group by year, if a group has count more than one, drop both row\n # group by Id then group by Sex, if more than one group, modify the sex type of small group to the biggest type\n # group by Id, sort by year, sort by age, compare the to list fix the year is less than 505 are not matched\n distance_calculation(df)\n half_marathon = dict()\n full_marathon = dict()\n df_cleaned = df.drop(columns=['Name', 'Time', 'Pace'])\n df_cleaned.loc[df_cleaned['Sex'] == 'F', 'Sex'] = 0\n df_cleaned.loc[df_cleaned['Sex'] == 'M', 'Sex'] = 1\n df_cleaned.loc[df_cleaned['Sex'] == 'U', 'Sex'] = 2\n full_marathon = df_cleaned[df_cleaned['distance'] >= threshold].reset_index(drop=True)\n half_marathon = df_cleaned[df_cleaned['distance'] < threshold].reset_index(drop=True)\n return half_marathon, full_marathon\n\n\n"
] |
[
[
"pandas.to_datetime"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
vijayphugat/Practice
|
[
"7d8560d62a5d6bfa9488526da318973295a25255",
"7d8560d62a5d6bfa9488526da318973295a25255"
] |
[
"healthcareai/common/table_archiver.py",
"healthcareai/tests/test_cardinality_checks.py"
] |
[
"import time\r\nimport datetime\r\nimport pandas as pd\r\n\r\nfrom healthcareai.common.healthcareai_error import HealthcareAIError\r\n\r\n\r\ndef table_archiver(server, database, source_table, destination_table, timestamp_column_name='ArchivedDTS'):\r\n \"\"\"\r\n Takes a table and archives a complete copy of it with the addition of a timestamp of when the archive occurred to a\r\n given destination table on the same database.\r\n\r\n This should build a new table if the table doesn't exist.\r\n\r\n Args:\r\n server (str): Server name \r\n database (str): Database name \r\n source_table (str): Source table name \r\n destination_table (str): Destination table name \r\n timestamp_column_name (str): New timestamp column name \r\n\r\n Returns:\r\n (str): A string with details on records archived.\r\n \r\n Example usage:\r\n\r\n ```\r\n from healthcareai.common.table_archiver import table_archiver\r\n table_archiver('localhost', 'SAM_123', 'RiskScores', 'RiskScoreArchive', 'ArchiveDTS')\r\n ```\r\n \"\"\"\r\n # Basic input validation\r\n if type(server) is not str:\r\n raise HealthcareAIError('Please specify a server address')\r\n if type(database) is not str:\r\n raise HealthcareAIError('Please specify a database name')\r\n if type(source_table) is not str:\r\n raise HealthcareAIError('Please specify a source table name')\r\n if type(destination_table) is not str:\r\n raise HealthcareAIError('Please specify a destination table name')\r\n\r\n start_time = time.time()\r\n\r\n connection_string = 'mssql+pyodbc://{}/{}?driver=SQL+Server+Native+Client+11.0'.format(server, database)\r\n\r\n # Load the table to be archived\r\n df = pd.read_sql_table(source_table, connection_string)\r\n number_records_to_add = len(df)\r\n\r\n # Add timestamp to dataframe\r\n df[timestamp_column_name] = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')\r\n\r\n # Save the new dataframe out to the db without the index, appending values\r\n df.to_sql(destination_table, connection_string, index=False, if_exists='append')\r\n\r\n end_time = time.time()\r\n delta_time = end_time - start_time\r\n result = 'Archived {0} records from {1}/{2}/{3} to {4} in {5} seconds'.format(\r\n number_records_to_add,\r\n server,\r\n database,\r\n source_table,\r\n destination_table,\r\n delta_time)\r\n\r\n return result\r\n",
"\"\"\"Test the cardinality checks module.\"\"\"\r\n\r\nimport unittest\r\n\r\nimport pandas as pd\r\n\r\nfrom healthcareai.common.healthcareai_error import HealthcareAIError\r\nimport healthcareai.common.cardinality_checks as cardinality\r\n\r\n\r\nclass TestCalculateCardinality(unittest.TestCase):\r\n \"\"\"Test `calculate_cardinality()` method.\"\"\"\r\n\r\n def setUp(self):\r\n self.df = pd.DataFrame({\r\n 'id': [1, 2, 3, 4],\r\n 'category': ['a', 'b', 'c', 'a'],\r\n 'gender': ['F', 'M', 'F', 'M'],\r\n 'age': [1, 1, 2, 3],\r\n 'boring': [1, 1, 1, 1]\r\n })\r\n\r\n def test_returns_dataframe(self):\r\n self.assertIsInstance(\r\n cardinality.calculate_cardinality(self.df),\r\n pd.DataFrame)\r\n\r\n def test_calculates_cardinality(self):\r\n expected = pd.DataFrame({\r\n 'Feature Name': ['id', 'age', 'category', 'gender', 'boring'],\r\n 'unique_value_count': [4, 3, 3, 2, 1],\r\n 'unique_ratio': [1, 0.75, 0.75, 0.5, 0.25]\r\n })\r\n\r\n result = cardinality.calculate_cardinality(self.df)\r\n\r\n for column in expected:\r\n self.assertEqual(result[column].all(), expected[column].all())\r\n\r\n\r\nclass TestCardinalityThreshold(unittest.TestCase):\r\n \"\"\"Test `cardinality_threshold_filter()` method.\"\"\"\r\n\r\n def setUp(self):\r\n self.df = pd.DataFrame({\r\n 'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\r\n 'category': ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b'],\r\n 'gender': ['F', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'F', 'M'],\r\n 'age': [1, 2, 3, 1, 2, 3, 1, 2, 3, 1]\r\n })\r\n\r\n self.cardinality = cardinality.calculate_cardinality(self.df)\r\n\r\n def test_returns_dataframe(self):\r\n self.assertIsInstance(\r\n cardinality.cardinality_threshold_filter(self.cardinality,\r\n 'unique_ratio'),\r\n pd.DataFrame)\r\n\r\n def test_returns_with_default_threshold(self):\r\n expected = pd.DataFrame({\r\n 'Feature Name': ['id', 'category', 'age'],\r\n 'unique_value_count': [10, 4, 3],\r\n 'unique_ratio': [1, 4 / 10, 3 / 10]\r\n })\r\n\r\n result = cardinality.cardinality_threshold_filter(\r\n self.cardinality,\r\n 'unique_ratio')\r\n\r\n for column in result:\r\n self.assertEqual(result[column].all(), expected[column].all())\r\n\r\n def test_raise_error_with_threshold_greater_than_one(self):\r\n self.assertRaises(\r\n HealthcareAIError,\r\n cardinality.cardinality_threshold_filter,\r\n self.cardinality,\r\n 'unique_ratio',\r\n warning_threshold=2)\r\n\r\n\r\nclass TestZeroCardinalityFilter(unittest.TestCase):\r\n \"\"\"Test `cardinality_threshold_filter()` method.\"\"\"\r\n\r\n def setUp(self):\r\n self.df = pd.DataFrame({\r\n 'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\r\n 'category': ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b'],\r\n 'gender': ['F', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'F', 'M'],\r\n 'age': [1, 2, 3, 1, 2, 3, 1, 2, 3, 1],\r\n 'boring': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\r\n })\r\n\r\n self.df['bad_string'] = 'yup'\r\n self.df['bad_float'] = 3.33\r\n self.df['bad_int'] = 1\r\n self.df['bad_bool'] = False\r\n\r\n self.cardinality = cardinality.calculate_cardinality(self.df)\r\n\r\n def test_returns_dataframe(self):\r\n self.assertIsInstance(\r\n cardinality.cardinality_low_filter(self.cardinality),\r\n pd.DataFrame)\r\n\r\n def test_raises_error_on_missing_key(self):\r\n # intentionally pass in a dataframe without `unique_value_count`\r\n self.assertRaises(\r\n HealthcareAIError,\r\n cardinality.cardinality_low_filter,\r\n self.df)\r\n\r\n def test_returns_zero_cardinal_features(self):\r\n expected = pd.DataFrame({\r\n 'Feature Name': ['boring', 'bad_string', 'bad_int', 'bad_float', 'bad_bool'],\r\n 'unique_value_count': [1, 1, 1, 1, 1],\r\n 'unique_ratio': [0.1, 0.1, 0.1, 0.1, 0.1]\r\n })\r\n\r\n result = cardinality.cardinality_low_filter(self.cardinality)\r\n\r\n print(expected)\r\n print(result)\r\n\r\n for column in result:\r\n print('checking {}'.format(column))\r\n self.assertEqual(result[column].all(), expected[column].all())\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n"
] |
[
[
"pandas.read_sql_table"
],
[
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
ms802x/CarND-Capstone
|
[
"efd6606090b2395cb49f71b0eb53393f859a5e39"
] |
[
"ros/src/tl_detector/tl_detector.py"
] |
[
"#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import Int32\nfrom geometry_msgs.msg import PoseStamped, Pose\nfrom styx_msgs.msg import TrafficLightArray, TrafficLight\nfrom styx_msgs.msg import Lane\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge\nfrom light_classification.tl_classifier import TLClassifier\nimport tf\nimport cv2\nimport yaml\nfrom scipy.spatial import KDTree\n\n\nSTATE_COUNT_THRESHOLD = 3\n\nclass TLDetector(object):\n def __init__(self):\n rospy.init_node('tl_detector')\n\n self.pose = None\n self.waypoints = None\n self.camera_image = None\n self.lights = []\n\n sub1 = rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb)\n sub2 = rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb)\n sub3 = rospy.Subscriber('/vehicle/traffic_lights', TrafficLightArray, self.traffic_cb)\n \n config_string = rospy.get_param(\"/traffic_light_config\")\n \n self.config = yaml.load(config_string)\n self.upcoming_red_light_pub = rospy.Publisher('/traffic_waypoint', Int32, queue_size=1)\n\n self.bridge = CvBridge()\n self.light_classifier = TLClassifier()\n self.listener = tf.TransformListener()\n\n self.state = TrafficLight.UNKNOWN\n self.last_state = TrafficLight.UNKNOWN\n self.last_wp = -1\n self.state_count = 0\n\n rospy.spin()\n\n def pose_cb(self, msg):\n \n self.pose = msg\n \n light_wp, state = self.process_traffic_lights()\n\n\n if self.state != state:\n self.state_count = 0\n self.state = state\n \n elif self.state_count >= STATE_COUNT_THRESHOLD:\n self.last_state = self.state\n light_wp = light_wp if state == TrafficLight.RED else -1\n self.last_wp = light_wp\n self.upcoming_red_light_pub.publish(Int32(light_wp))\n \n else:\n self.upcoming_red_light_pub.publish(Int32(self.last_wp))\n self.state_count += 1\n\n def waypoints_cb(self, waypoints):\n self.waypoints = waypoints\n self.waypoints_2d = [[waypoint.pose.pose.position.x, waypoint.pose.pose.position.y] for waypoint in waypoints.waypoints]\n self.waypoint_tree = KDTree(self.waypoints_2d)\n\n def traffic_cb(self, msg):\n self.lights = msg.lights\n\n def image_cb(self, msg):\n # the code of this method I have included it in the pose method\n pass\n\n def get_closest_waypoint(self, x,y):\n \n #TODO implement\n closest_idx = self.waypoint_tree.query([x,y],1)[1]\n return closest_idx\n\n def get_light_state(self, light):\n \n return light.state\n\n \n\n def process_traffic_lights(self):\n #TODO find the closest visible traffic light (if one exists)\n\n closest_light = None\n line_wp_id = None\n \n stop_line_positions = self.config['stop_line_positions']\n \n if(self.pose):\n closest_wp = self.get_closest_waypoint(self.pose.pose.position.x,self.pose.pose.position.y)\n \n diff= len(self.waypoints.waypoints)\n \n for i,light in enumerate(self.lights):\n \n line = stop_line_positions[i]\n temp_wp_idx=self.get_closest_waypoint(line[0], line[1])\n d = temp_wp_idx-closest_wp\n \n if (d>=0 and d<diff):\n diff=d\n closest_light=light\n line_wp_id=temp_wp_idx\n \n \n if closest_light:\n state = self.get_light_state(closest_light)\n return line_wp_id, state\n \n return -1, TrafficLight.UNKNOWN\n\nif __name__ == '__main__':\n try:\n TLDetector()\n except rospy.ROSInterruptException:\n rospy.logerr('Could not start traffic node.')"
] |
[
[
"scipy.spatial.KDTree"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
SeanSyue/TensorflowReferences
|
[
"2c93f4c770e2713ef4769f287e022d03e7097188",
"2c93f4c770e2713ef4769f287e022d03e7097188"
] |
[
"MorvanZhou/tf19_saver.py",
"reference/eval_and_run.py"
] |
[
"from __future__ import print_function\r\nimport tensorflow as tf\r\nimport numpy as np\r\n\r\n# # Save to file\r\n# # remember to define the same dtype and shape when restore\r\n# W = tf.Variable([[1,2,3],[3,4,5]], dtype=tf.float32, name='weights')\r\n# b = tf.Variable([[1,2,3]], dtype=tf.float32, name='biases')\r\n#\r\n# # tf.initialize_all_variables() no long valid from\r\n# # 2017-03-02 if using tensorflow >= 0.12\r\n# if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:\r\n# init = tf.initialize_all_variables()\r\n# else:\r\n# init = tf.global_variables_initializer()\r\n#\r\n# saver = tf.train.Saver()\r\n#\r\n# with tf.Session() as sess:\r\n# sess.run(init)\r\n# save_path = saver.save(sess, \"my_net/save_net.ckpt\")\r\n# print(\"Save to path: \", save_path)\r\n\r\n\r\n################################################\r\n# restore variables\r\n# redefine the same shape and same type for your variables\r\nW = tf.Variable(np.arange(6).reshape((2, 3)), dtype=tf.float32, name=\"weights\") # [[ 0. 1. 2.][ 3. 4. 5.]]\r\nb = tf.Variable(np.arange(3).reshape((1, 3)), dtype=tf.float32, name=\"biases\") # [[ 0. 1. 2.]]\r\n\r\n# not need init step\r\n\r\nsaver = tf.train.Saver()\r\nwith tf.Session() as sess:\r\n saver.restore(sess, \"my_net/save_net.ckpt\")\r\n print(\"weights:\", sess.run(W))\r\n print(\"biases:\", sess.run(b))\r\n",
"# Source:\r\n# https://github.com/Kulbear/tensorflow-for-deep-learning-research/issues/2\r\n\r\nimport tensorflow as tf\r\n\r\n# if you have a Tensor a, and a Session sess like me in the code,\r\n# then a.eval() and sess.run(a) are exactly one thing.\r\na = tf.Variable(5, name=\"scalar\")\r\nwith tf.Session() as sess:\r\n sess.run(a.initializer)\r\n assert a.eval() == sess.run(a)\r\n\r\n# the most important difference is that you can use sess.run() to fetch the values of many tensors\r\nb = tf.Variable(4, name=\"scalar\")\r\nwith tf.Session() as sess:\r\n sess.run(tf.global_variables_initializer())\r\n assert a.eval() == sess.run(a)\r\n print(a.eval()) # 5\r\n print(b.eval()) # 4\r\n print(sess.run([a, b])) # [5, 4]\r\n"
] |
[
[
"tensorflow.train.Saver",
"numpy.arange",
"tensorflow.Session"
],
[
"tensorflow.Session",
"tensorflow.global_variables_initializer",
"tensorflow.Variable"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.4",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
loaywael/ObjectDetection
|
[
"9006cfdb2284a83426510a70c894824b27f40566"
] |
[
"2D_ObjectDetectors/yolov1/network/test/test_loss.py"
] |
[
"from network.loss import YoloLoss\nfrom unittest import TestCase\nimport numpy as np\nimport torch\n\nfrom network.dataset import VOCDataset\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport os \n\n\ntorch.manual_seed(13)\nDATA_DIR = \"data/pascal_voc_yolo/\"\nIMG_DIR = DATA_DIR+\"images/\"\nLABEL_DIR = DATA_DIR+\"labels/\"\nBATCH_SIZE = 4\nNUM_WORKERS = 4\nTRANSFORM = False\nS = 7\nB = 2\nC = 20\n\n \ntorch.set_printoptions(linewidth=10000, edgeitems=160)\n\ntorch.manual_seed(13)\nclass TestLoss(TestCase):\n def setUp(self):\n self.model_loss = YoloLoss(7, 2, 20)\n dataset_args = dict(S=S, B=B, C=C)\n self.dataset = VOCDataset(DATA_DIR+\"8examples.csv\", IMG_DIR, LABEL_DIR, **dataset_args)\n\n def test_fake_loss(self):\n output_shape = (2, 7, 7, 30)\n self.y = torch.abs(torch.zeros(output_shape))\n self.y[0, 2, 2, 3] = 1 \n self.y[0, 2, 2, 20] = 1 \n self.y[0, 2, 2, 21:25] = 0.5\n # -------------------------- \n self.y[1, 5, 3, 3] = 1 \n self.y[1, 5, 3, 25] = 1 \n self.y[1, 5, 3, 26:30] = 0.25\n # -------------------------- \n self.yhat = torch.abs(torch.zeros(output_shape))\n self.yhat[0, 2, 2, 3] = 1 \n self.yhat[0, 2, 2, 20] = 1 \n self.yhat[0, 2, 2, 21:25] = 0.75\n # -------------------------- \n self.yhat[1, 5, 3, 3] = 1 \n self.yhat[1, 5, 3, 25] = 1 \n self.yhat[1, 5, 3, 26:30] = 0.2\n\n loss = self.model_loss(self.y.to(\"cuda\"), self.yhat.to(\"cuda\"))\n print(loss)\n\n def test_loss(self):\n \n img1, target = self.dataset.__getitem__(1)\n y = target.unsqueeze(0)\n yhat = y.clone()\n yhat[..., 21:23] += 0.05\n yhat[..., 26:28] += 0.6\n # print(y, \"\\n\\n\\n\")\n # print(yhat, \"\\n\\n\\n\")\n loss = self.model_loss(y.cuda(), yhat.cuda())\n print(loss)\n"
] |
[
[
"torch.set_printoptions",
"torch.manual_seed",
"torch.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AmolShahh/examples
|
[
"9321bae747548a70d9667752a5334e5330b1ce49",
"9321bae747548a70d9667752a5334e5330b1ce49",
"9321bae747548a70d9667752a5334e5330b1ce49"
] |
[
"tensorflow_examples/lite/model_maker/third_party/efficientdet/keras/efficientdet_keras.py",
"lite/examples/pose_estimation/raspberry_pi/visualizer.py",
"lite/examples/pose_estimation/raspberry_pi/utils.py"
] |
[
"# Copyright 2020 Google Research. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Keras implementation of efficientdet.\"\"\"\nimport functools\nfrom absl import logging\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet import dataloader\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet import hparams_config\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet import utils\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.backbone import backbone_factory\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.backbone import efficientnet_builder\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.keras import fpn_configs\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.keras import postprocess\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.keras import tfmot\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.keras import util_keras\n\n\ndef add_n(nodes):\n \"\"\"A customized add_n to add up a list of tensors.\"\"\"\n # tf.add_n is not supported by EdgeTPU, while tf.reduce_sum is not supported\n # by GPU and runs slow on EdgeTPU because of the 5-dimension op.\n with tf.name_scope('add_n'):\n new_node = nodes[0]\n for n in nodes[1:]:\n new_node = new_node + n\n return new_node\n\n\nclass FNode(tf.keras.layers.Layer):\n \"\"\"A Keras Layer implementing BiFPN Node.\"\"\"\n\n def __init__(self,\n feat_level,\n inputs_offsets,\n fpn_num_filters,\n apply_bn_for_resampling,\n is_training_bn,\n conv_after_downsample,\n conv_bn_act_pattern,\n separable_conv,\n act_type,\n strategy,\n weight_method,\n data_format,\n model_optimizations,\n name='fnode'):\n super().__init__(name=name)\n self.feat_level = feat_level\n self.inputs_offsets = inputs_offsets\n self.fpn_num_filters = fpn_num_filters\n self.apply_bn_for_resampling = apply_bn_for_resampling\n self.separable_conv = separable_conv\n self.act_type = act_type\n self.is_training_bn = is_training_bn\n self.conv_after_downsample = conv_after_downsample\n self.strategy = strategy\n self.data_format = data_format\n self.weight_method = weight_method\n self.conv_bn_act_pattern = conv_bn_act_pattern\n self.resample_layers = []\n self.vars = []\n self.model_optimizations = model_optimizations\n\n def fuse_features(self, nodes):\n \"\"\"Fuse features from different resolutions and return a weighted sum.\n\n Args:\n nodes: a list of tensorflow features at different levels\n\n Returns:\n A tensor denoting the fused feature.\n \"\"\"\n dtype = nodes[0].dtype\n\n if self.weight_method == 'attn':\n edge_weights = [tf.cast(var, dtype=dtype) for var in self.vars]\n normalized_weights = tf.nn.softmax(tf.stack(edge_weights))\n nodes = tf.stack(nodes, axis=-1)\n new_node = tf.reduce_sum(nodes * normalized_weights, -1)\n elif self.weight_method == 'fastattn':\n edge_weights = [\n tf.nn.relu(tf.cast(var, dtype=dtype)) for var in self.vars\n ]\n weights_sum = add_n(edge_weights)\n nodes = [\n nodes[i] * edge_weights[i] / (weights_sum + 0.0001)\n for i in range(len(nodes))\n ]\n new_node = add_n(nodes)\n elif self.weight_method == 'channel_attn':\n edge_weights = [tf.cast(var, dtype=dtype) for var in self.vars]\n normalized_weights = tf.nn.softmax(tf.stack(edge_weights, -1), axis=-1)\n nodes = tf.stack(nodes, axis=-1)\n new_node = tf.reduce_sum(nodes * normalized_weights, -1)\n elif self.weight_method == 'channel_fastattn':\n edge_weights = [\n tf.nn.relu(tf.cast(var, dtype=dtype)) for var in self.vars\n ]\n weights_sum = add_n(edge_weights)\n nodes = [\n nodes[i] * edge_weights[i] / (weights_sum + 0.0001)\n for i in range(len(nodes))\n ]\n new_node = add_n(nodes)\n elif self.weight_method == 'sum':\n new_node = add_n(nodes)\n else:\n raise ValueError('unknown weight_method %s' % self.weight_method)\n\n return new_node\n\n def _add_wsm(self, initializer, shape=None):\n for i, _ in enumerate(self.inputs_offsets):\n name = 'WSM' + ('' if i == 0 else '_' + str(i))\n self.vars.append(\n self.add_weight(initializer=initializer, name=name, shape=shape))\n\n def build(self, feats_shape):\n for i, input_offset in enumerate(self.inputs_offsets):\n name = 'resample_{}_{}_{}'.format(i, input_offset, len(feats_shape))\n self.resample_layers.append(\n ResampleFeatureMap(\n self.feat_level,\n self.fpn_num_filters,\n self.apply_bn_for_resampling,\n self.is_training_bn,\n self.conv_after_downsample,\n strategy=self.strategy,\n data_format=self.data_format,\n model_optimizations=self.model_optimizations,\n name=name))\n if self.weight_method == 'attn':\n self._add_wsm('ones')\n elif self.weight_method == 'fastattn':\n self._add_wsm('ones')\n elif self.weight_method == 'channel_attn':\n num_filters = int(self.fpn_num_filters)\n self._add_wsm(tf.ones, num_filters)\n elif self.weight_method == 'channel_fastattn':\n num_filters = int(self.fpn_num_filters)\n self._add_wsm(tf.ones, num_filters)\n self.op_after_combine = OpAfterCombine(\n self.is_training_bn,\n self.conv_bn_act_pattern,\n self.separable_conv,\n self.fpn_num_filters,\n self.act_type,\n self.data_format,\n self.strategy,\n self.model_optimizations,\n name='op_after_combine{}'.format(len(feats_shape)))\n self.built = True\n super().build(feats_shape)\n\n def call(self, feats, training):\n nodes = []\n for i, input_offset in enumerate(self.inputs_offsets):\n input_node = feats[input_offset]\n input_node = self.resample_layers[i](input_node, training, feats)\n nodes.append(input_node)\n new_node = self.fuse_features(nodes)\n new_node = self.op_after_combine(new_node)\n return feats + [new_node]\n\n\nclass OpAfterCombine(tf.keras.layers.Layer):\n \"\"\"Operation after combining input features during feature fusiong.\"\"\"\n\n def __init__(self,\n is_training_bn,\n conv_bn_act_pattern,\n separable_conv,\n fpn_num_filters,\n act_type,\n data_format,\n strategy,\n model_optimizations,\n name='op_after_combine'):\n super().__init__(name=name)\n self.conv_bn_act_pattern = conv_bn_act_pattern\n self.separable_conv = separable_conv\n self.fpn_num_filters = fpn_num_filters\n self.act_type = act_type\n self.data_format = data_format\n self.strategy = strategy\n self.is_training_bn = is_training_bn\n if self.separable_conv:\n conv2d_layer = functools.partial(\n tf.keras.layers.SeparableConv2D, depth_multiplier=1)\n else:\n conv2d_layer = tf.keras.layers.Conv2D\n\n self.conv_op = conv2d_layer(\n filters=fpn_num_filters,\n kernel_size=(3, 3),\n padding='same',\n use_bias=not self.conv_bn_act_pattern,\n data_format=self.data_format,\n name='conv')\n if model_optimizations:\n for method in model_optimizations.keys():\n self.conv_op = (\n tfmot.get_method(method)(self.conv_op))\n self.bn = util_keras.build_batch_norm(\n is_training_bn=self.is_training_bn,\n data_format=self.data_format,\n strategy=self.strategy,\n name='bn')\n\n def call(self, new_node, training):\n if not self.conv_bn_act_pattern:\n new_node = utils.activation_fn(new_node, self.act_type)\n new_node = self.conv_op(new_node)\n new_node = self.bn(new_node, training=training)\n if self.conv_bn_act_pattern:\n new_node = utils.activation_fn(new_node, self.act_type)\n return new_node\n\n\nclass ResampleFeatureMap(tf.keras.layers.Layer):\n \"\"\"Resample feature map for downsampling or upsampling.\"\"\"\n\n def __init__(self,\n feat_level,\n target_num_channels,\n apply_bn=False,\n is_training_bn=None,\n conv_after_downsample=False,\n strategy=None,\n data_format=None,\n pooling_type=None,\n upsampling_type=None,\n model_optimizations=None,\n name='resample_p0'):\n super().__init__(name=name)\n self.apply_bn = apply_bn\n self.is_training_bn = is_training_bn\n self.data_format = data_format\n self.target_num_channels = target_num_channels\n self.feat_level = feat_level\n self.strategy = strategy\n self.conv_after_downsample = conv_after_downsample\n self.pooling_type = pooling_type or 'max'\n self.upsampling_type = upsampling_type or 'nearest'\n\n self.conv2d = tf.keras.layers.Conv2D(\n self.target_num_channels, (1, 1),\n padding='same',\n data_format=self.data_format,\n name='conv2d')\n if model_optimizations:\n for method in model_optimizations.keys():\n self.conv2d = tfmot.get_method(method)(self.conv2d)\n self.bn = util_keras.build_batch_norm(\n is_training_bn=self.is_training_bn,\n data_format=self.data_format,\n strategy=self.strategy,\n name='bn')\n\n def _pool2d(self, inputs, height, width, target_height, target_width):\n \"\"\"Pool the inputs to target height and width.\"\"\"\n height_stride_size = int((height - 1) // target_height + 1)\n width_stride_size = int((width - 1) // target_width + 1)\n if self.pooling_type == 'max':\n return tf.keras.layers.MaxPooling2D(\n pool_size=[height_stride_size + 1, width_stride_size + 1],\n strides=[height_stride_size, width_stride_size],\n padding='SAME',\n data_format=self.data_format)(inputs)\n if self.pooling_type == 'avg':\n return tf.keras.layers.AveragePooling2D(\n pool_size=[height_stride_size + 1, width_stride_size + 1],\n strides=[height_stride_size, width_stride_size],\n padding='SAME',\n data_format=self.data_format)(inputs)\n raise ValueError('Unsupported pooling type {}.'.format(self.pooling_type))\n\n def _upsample2d(self, inputs, target_height, target_width):\n return tf.cast(\n tf.compat.v1.image.resize_nearest_neighbor(\n tf.cast(inputs, tf.float32), [target_height, target_width]),\n inputs.dtype)\n\n def _maybe_apply_1x1(self, feat, training, num_channels):\n \"\"\"Apply 1x1 conv to change layer width if necessary.\"\"\"\n if num_channels != self.target_num_channels:\n feat = self.conv2d(feat)\n if self.apply_bn:\n feat = self.bn(feat, training=training)\n return feat\n\n def call(self, feat, training, all_feats):\n hwc_idx = (2, 3, 1) if self.data_format == 'channels_first' else (1, 2, 3)\n height, width, num_channels = [feat.shape.as_list()[i] for i in hwc_idx]\n if all_feats:\n target_feat_shape = all_feats[self.feat_level].shape.as_list()\n target_height, target_width, _ = [target_feat_shape[i] for i in hwc_idx]\n else:\n # Default to downsampling if all_feats is empty.\n target_height, target_width = (height + 1) // 2, (width + 1) // 2\n\n # If conv_after_downsample is True, when downsampling, apply 1x1 after\n # downsampling for efficiency.\n if height > target_height and width > target_width:\n if not self.conv_after_downsample:\n feat = self._maybe_apply_1x1(feat, training, num_channels)\n feat = self._pool2d(feat, height, width, target_height, target_width)\n if self.conv_after_downsample:\n feat = self._maybe_apply_1x1(feat, training, num_channels)\n elif height <= target_height and width <= target_width:\n feat = self._maybe_apply_1x1(feat, training, num_channels)\n if height < target_height or width < target_width:\n feat = self._upsample2d(feat, target_height, target_width)\n else:\n raise ValueError(\n 'Incompatible Resampling : feat shape {}x{} target_shape: {}x{}'\n .format(height, width, target_height, target_width))\n\n return feat\n\n\nclass ClassNet(tf.keras.layers.Layer):\n \"\"\"Object class prediction network.\"\"\"\n\n def __init__(self,\n num_classes=90,\n num_anchors=9,\n num_filters=32,\n min_level=3,\n max_level=7,\n is_training_bn=False,\n act_type='swish',\n repeats=4,\n separable_conv=True,\n survival_prob=None,\n strategy=None,\n data_format='channels_last',\n grad_checkpoint=False,\n name='class_net',\n feature_only=False,\n **kwargs):\n \"\"\"Initialize the ClassNet.\n\n Args:\n num_classes: number of classes.\n num_anchors: number of anchors.\n num_filters: number of filters for \"intermediate\" layers.\n min_level: minimum level for features.\n max_level: maximum level for features.\n is_training_bn: True if we train the BatchNorm.\n act_type: String of the activation used.\n repeats: number of intermediate layers.\n separable_conv: True to use separable_conv instead of conv2D.\n survival_prob: if a value is set then drop connect will be used.\n strategy: string to specify training strategy for TPU/GPU/CPU.\n data_format: string of 'channel_first' or 'channels_last'.\n grad_checkpoint: bool, If true, apply grad checkpoint for saving memory.\n name: the name of this layerl.\n feature_only: build the base feature network only (excluding final class\n head).\n **kwargs: other parameters.\n \"\"\"\n\n super().__init__(name=name, **kwargs)\n self.num_classes = num_classes\n self.num_anchors = num_anchors\n self.num_filters = num_filters\n self.min_level = min_level\n self.max_level = max_level\n self.repeats = repeats\n self.separable_conv = separable_conv\n self.is_training_bn = is_training_bn\n self.survival_prob = survival_prob\n self.act_type = act_type\n self.strategy = strategy\n self.data_format = data_format\n self.conv_ops = []\n self.bns = []\n self.grad_checkpoint = grad_checkpoint\n self.feature_only = feature_only\n\n conv2d_layer = self.conv2d_layer(separable_conv, data_format)\n for i in range(self.repeats):\n # If using SeparableConv2D\n self.conv_ops.append(\n conv2d_layer(\n self.num_filters,\n kernel_size=3,\n bias_initializer=tf.zeros_initializer(),\n activation=None,\n padding='same',\n name='class-%d' % i))\n\n bn_per_level = []\n for level in range(self.min_level, self.max_level + 1):\n bn_per_level.append(\n util_keras.build_batch_norm(\n is_training_bn=self.is_training_bn,\n strategy=self.strategy,\n data_format=self.data_format,\n name='class-%d-bn-%d' % (i, level),\n ))\n self.bns.append(bn_per_level)\n\n self.classes = self.classes_layer(\n conv2d_layer, num_classes, num_anchors, name='class-predict')\n\n @tf.autograph.experimental.do_not_convert\n def _conv_bn_act(self, image, i, level_id, training):\n conv_op = self.conv_ops[i]\n bn = self.bns[i][level_id]\n act_type = self.act_type\n\n @utils.recompute_grad(self.grad_checkpoint)\n def _call(image):\n original_image = image\n image = conv_op(image)\n image = bn(image, training=training)\n if self.act_type:\n image = utils.activation_fn(image, act_type)\n if i > 0 and self.survival_prob:\n image = utils.drop_connect(image, training, self.survival_prob)\n image = image + original_image\n return image\n\n return _call(image)\n\n def call(self, inputs, training, **kwargs):\n \"\"\"Call ClassNet.\"\"\"\n class_outputs = []\n for level_id in range(0, self.max_level - self.min_level + 1):\n image = inputs[level_id]\n for i in range(self.repeats):\n image = self._conv_bn_act(image, i, level_id, training)\n if self.feature_only:\n class_outputs.append(image)\n else:\n class_outputs.append(self.classes(image))\n\n return class_outputs\n\n @classmethod\n def conv2d_layer(cls, separable_conv, data_format):\n \"\"\"Gets the conv2d layer in ClassNet class.\"\"\"\n if separable_conv:\n conv2d_layer = functools.partial(\n tf.keras.layers.SeparableConv2D,\n depth_multiplier=1,\n data_format=data_format,\n pointwise_initializer=tf.initializers.variance_scaling(),\n depthwise_initializer=tf.initializers.variance_scaling())\n else:\n conv2d_layer = functools.partial(\n tf.keras.layers.Conv2D,\n data_format=data_format,\n kernel_initializer=tf.random_normal_initializer(stddev=0.01))\n return conv2d_layer\n\n @classmethod\n def classes_layer(cls, conv2d_layer, num_classes, num_anchors, name):\n \"\"\"Gets the classes layer in ClassNet class.\"\"\"\n return conv2d_layer(\n num_classes * num_anchors,\n kernel_size=3,\n bias_initializer=tf.constant_initializer(-np.log((1 - 0.01) / 0.01)),\n padding='same',\n name=name)\n\n\nclass BoxNet(tf.keras.layers.Layer):\n \"\"\"Box regression network.\"\"\"\n\n def __init__(self,\n num_anchors=9,\n num_filters=32,\n min_level=3,\n max_level=7,\n is_training_bn=False,\n act_type='swish',\n repeats=4,\n separable_conv=True,\n survival_prob=None,\n strategy=None,\n data_format='channels_last',\n grad_checkpoint=False,\n name='box_net',\n feature_only=False,\n **kwargs):\n \"\"\"Initialize BoxNet.\n\n Args:\n num_anchors: number of anchors used.\n num_filters: number of filters for \"intermediate\" layers.\n min_level: minimum level for features.\n max_level: maximum level for features.\n is_training_bn: True if we train the BatchNorm.\n act_type: String of the activation used.\n repeats: number of \"intermediate\" layers.\n separable_conv: True to use separable_conv instead of conv2D.\n survival_prob: if a value is set then drop connect will be used.\n strategy: string to specify training strategy for TPU/GPU/CPU.\n data_format: string of 'channel_first' or 'channels_last'.\n grad_checkpoint: bool, If true, apply grad checkpoint for saving memory.\n name: Name of the layer.\n feature_only: build the base feature network only (excluding box class\n head).\n **kwargs: other parameters.\n \"\"\"\n\n super().__init__(name=name, **kwargs)\n\n self.num_anchors = num_anchors\n self.num_filters = num_filters\n self.min_level = min_level\n self.max_level = max_level\n self.repeats = repeats\n self.separable_conv = separable_conv\n self.is_training_bn = is_training_bn\n self.survival_prob = survival_prob\n self.act_type = act_type\n self.strategy = strategy\n self.data_format = data_format\n self.grad_checkpoint = grad_checkpoint\n self.feature_only = feature_only\n\n self.conv_ops = []\n self.bns = []\n\n for i in range(self.repeats):\n # If using SeparableConv2D\n if self.separable_conv:\n self.conv_ops.append(\n tf.keras.layers.SeparableConv2D(\n filters=self.num_filters,\n depth_multiplier=1,\n pointwise_initializer=tf.initializers.variance_scaling(),\n depthwise_initializer=tf.initializers.variance_scaling(),\n data_format=self.data_format,\n kernel_size=3,\n activation=None,\n bias_initializer=tf.zeros_initializer(),\n padding='same',\n name='box-%d' % i))\n # If using Conv2d\n else:\n self.conv_ops.append(\n tf.keras.layers.Conv2D(\n filters=self.num_filters,\n kernel_initializer=tf.random_normal_initializer(stddev=0.01),\n data_format=self.data_format,\n kernel_size=3,\n activation=None,\n bias_initializer=tf.zeros_initializer(),\n padding='same',\n name='box-%d' % i))\n\n bn_per_level = []\n for level in range(self.min_level, self.max_level + 1):\n bn_per_level.append(\n util_keras.build_batch_norm(\n is_training_bn=self.is_training_bn,\n strategy=self.strategy,\n data_format=self.data_format,\n name='box-%d-bn-%d' % (i, level)))\n self.bns.append(bn_per_level)\n\n self.boxes = self.boxes_layer(\n separable_conv, num_anchors, data_format, name='box-predict')\n\n @tf.autograph.experimental.do_not_convert\n def _conv_bn_act(self, image, i, level_id, training):\n conv_op = self.conv_ops[i]\n bn = self.bns[i][level_id]\n act_type = self.act_type\n\n @utils.recompute_grad(self.grad_checkpoint)\n def _call(image):\n original_image = image\n image = conv_op(image)\n image = bn(image, training=training)\n if self.act_type:\n image = utils.activation_fn(image, act_type)\n if i > 0 and self.survival_prob:\n image = utils.drop_connect(image, training, self.survival_prob)\n image = image + original_image\n return image\n\n return _call(image)\n\n def call(self, inputs, training):\n \"\"\"Call boxnet.\"\"\"\n box_outputs = []\n for level_id in range(0, self.max_level - self.min_level + 1):\n image = inputs[level_id]\n for i in range(self.repeats):\n image = self._conv_bn_act(image, i, level_id, training)\n\n if self.feature_only:\n box_outputs.append(image)\n else:\n box_outputs.append(self.boxes(image))\n\n return box_outputs\n\n @classmethod\n def boxes_layer(cls, separable_conv, num_anchors, data_format, name):\n \"\"\"Gets the conv2d layer in BoxNet class.\"\"\"\n if separable_conv:\n return tf.keras.layers.SeparableConv2D(\n filters=4 * num_anchors,\n depth_multiplier=1,\n pointwise_initializer=tf.initializers.variance_scaling(),\n depthwise_initializer=tf.initializers.variance_scaling(),\n data_format=data_format,\n kernel_size=3,\n activation=None,\n bias_initializer=tf.zeros_initializer(),\n padding='same',\n name=name)\n else:\n return tf.keras.layers.Conv2D(\n filters=4 * num_anchors,\n kernel_initializer=tf.random_normal_initializer(stddev=0.01),\n data_format=data_format,\n kernel_size=3,\n activation=None,\n bias_initializer=tf.zeros_initializer(),\n padding='same',\n name=name)\n\n\nclass SegmentationHead(tf.keras.layers.Layer):\n \"\"\"Keras layer for semantic segmentation head.\"\"\"\n\n def __init__(self,\n num_classes,\n num_filters,\n min_level,\n max_level,\n data_format,\n is_training_bn,\n act_type,\n strategy,\n name='segmentation_head',\n **kwargs):\n \"\"\"Initialize SegmentationHead.\n\n Args:\n num_classes: number of classes.\n num_filters: number of filters for \"intermediate\" layers.\n min_level: minimum level for features.\n max_level: maximum level for features.\n data_format: string of 'channel_first' or 'channels_last'.\n is_training_bn: True if we train the BatchNorm.\n act_type: String of the activation used.\n strategy: string to specify training strategy for TPU/GPU/CPU.\n name: string of name.\n **kwargs: other parameters.\n \"\"\"\n super().__init__(name=name, **kwargs)\n self.act_type = act_type\n self.con2d_ts = []\n self.con2d_t_bns = []\n for level in range(max_level - min_level):\n self.con2d_ts.append(\n tf.keras.layers.Conv2DTranspose(\n num_filters,\n 3,\n strides=2,\n padding='same',\n data_format=data_format,\n use_bias=False))\n self.con2d_t_bns.append(\n util_keras.build_batch_norm(\n is_training_bn=is_training_bn,\n data_format=data_format,\n strategy=strategy,\n name='bn_' + str(level)))\n self.head_transpose = tf.keras.layers.Conv2DTranspose(\n num_classes, 3, strides=2, padding='same')\n\n def call(self, feats, training):\n x = feats[-1]\n skips = list(reversed(feats[:-1]))\n\n for con2d_t, con2d_t_bn, skip in zip(self.con2d_ts, self.con2d_t_bns,\n skips):\n x = con2d_t(x)\n x = con2d_t_bn(x, training)\n x = utils.activation_fn(x, self.act_type)\n x = tf.concat([x, skip], axis=-1)\n\n # This is the last layer of the model\n return self.head_transpose(x) # 64x64 -> 128x128\n\n\nclass FPNCells(tf.keras.layers.Layer):\n \"\"\"FPN cells.\"\"\"\n\n def __init__(self, config, name='fpn_cells'):\n super().__init__(name=name)\n self.config = config\n\n if config.fpn_config:\n self.fpn_config = config.fpn_config\n else:\n self.fpn_config = fpn_configs.get_fpn_config(config.fpn_name,\n config.min_level,\n config.max_level,\n config.fpn_weight_method)\n\n self.cells = [\n FPNCell(self.config, name='cell_%d' % rep)\n for rep in range(self.config.fpn_cell_repeats)\n ]\n\n def call(self, feats, training):\n for cell in self.cells:\n cell_feats = cell(feats, training)\n min_level = self.config.min_level\n max_level = self.config.max_level\n\n feats = []\n for level in range(min_level, max_level + 1):\n for i, fnode in enumerate(reversed(self.fpn_config.nodes)):\n if fnode['feat_level'] == level:\n feats.append(cell_feats[-1 - i])\n break\n\n return feats\n\n\nclass FPNCell(tf.keras.layers.Layer):\n \"\"\"A single FPN cell.\"\"\"\n\n def __init__(self, config, name='fpn_cell'):\n super().__init__(name=name)\n self.config = config\n if config.fpn_config:\n self.fpn_config = config.fpn_config\n else:\n self.fpn_config = fpn_configs.get_fpn_config(config.fpn_name,\n config.min_level,\n config.max_level,\n config.fpn_weight_method)\n self.fnodes = []\n for i, fnode_cfg in enumerate(self.fpn_config.nodes):\n logging.info('fnode %d : %s', i, fnode_cfg)\n fnode = FNode(\n fnode_cfg['feat_level'] - self.config.min_level,\n fnode_cfg['inputs_offsets'],\n config.fpn_num_filters,\n config.apply_bn_for_resampling,\n config.is_training_bn,\n config.conv_after_downsample,\n config.conv_bn_act_pattern,\n config.separable_conv,\n config.act_type,\n strategy=config.strategy,\n weight_method=self.fpn_config.weight_method,\n data_format=config.data_format,\n model_optimizations=config.model_optimizations,\n name='fnode%d' % i)\n self.fnodes.append(fnode)\n\n def call(self, feats, training):\n @utils.recompute_grad(self.config.grad_checkpoint)\n def _call(feats):\n for fnode in self.fnodes:\n feats = fnode(feats, training)\n return feats\n return _call(feats)\n\n\nclass EfficientDetNet(tf.keras.Model):\n \"\"\"EfficientDet keras network without pre/post-processing.\"\"\"\n\n def __init__(self,\n model_name=None,\n config=None,\n name='',\n feature_only=False):\n \"\"\"Initialize model.\"\"\"\n super().__init__(name=name)\n\n config = config or hparams_config.get_efficientdet_config(model_name)\n self.config = config\n\n # Backbone.\n backbone_name = config.backbone_name\n is_training_bn = config.is_training_bn\n if 'efficientnet' in backbone_name:\n override_params = {\n 'batch_norm':\n utils.batch_norm_class(is_training_bn, config.strategy),\n 'relu_fn':\n functools.partial(utils.activation_fn, act_type=config.act_type),\n 'grad_checkpoint': self.config.grad_checkpoint\n }\n if 'b0' in backbone_name:\n override_params['survival_prob'] = 0.0\n if config.backbone_config is not None:\n override_params['blocks_args'] = (\n efficientnet_builder.BlockDecoder().encode(\n config.backbone_config.blocks))\n override_params['data_format'] = config.data_format\n self.backbone = backbone_factory.get_model(\n backbone_name, override_params=override_params)\n\n # Feature network.\n self.resample_layers = [] # additional resampling layers.\n for level in range(6, config.max_level + 1):\n # Adds a coarser level by downsampling the last feature map.\n self.resample_layers.append(\n ResampleFeatureMap(\n feat_level=(level - config.min_level),\n target_num_channels=config.fpn_num_filters,\n apply_bn=config.apply_bn_for_resampling,\n is_training_bn=config.is_training_bn,\n conv_after_downsample=config.conv_after_downsample,\n strategy=config.strategy,\n data_format=config.data_format,\n model_optimizations=config.model_optimizations,\n name='resample_p%d' % level,\n ))\n self.fpn_cells = FPNCells(config)\n\n # class/box output prediction network.\n num_anchors = len(config.aspect_ratios) * config.num_scales\n num_filters = config.fpn_num_filters\n for head in config.heads:\n if head == 'object_detection':\n self.class_net = ClassNet(\n num_classes=config.num_classes,\n num_anchors=num_anchors,\n num_filters=num_filters,\n min_level=config.min_level,\n max_level=config.max_level,\n is_training_bn=config.is_training_bn,\n act_type=config.act_type,\n repeats=config.box_class_repeats,\n separable_conv=config.separable_conv,\n survival_prob=config.survival_prob,\n strategy=config.strategy,\n grad_checkpoint=config.grad_checkpoint,\n data_format=config.data_format,\n feature_only=feature_only)\n\n self.box_net = BoxNet(\n num_anchors=num_anchors,\n num_filters=num_filters,\n min_level=config.min_level,\n max_level=config.max_level,\n is_training_bn=config.is_training_bn,\n act_type=config.act_type,\n repeats=config.box_class_repeats,\n separable_conv=config.separable_conv,\n survival_prob=config.survival_prob,\n strategy=config.strategy,\n grad_checkpoint=config.grad_checkpoint,\n data_format=config.data_format,\n feature_only=feature_only)\n\n if head == 'segmentation':\n self.seg_head = SegmentationHead(\n num_classes=config.seg_num_classes,\n num_filters=num_filters,\n min_level=config.min_level,\n max_level=config.max_level,\n is_training_bn=config.is_training_bn,\n act_type=config.act_type,\n strategy=config.strategy,\n data_format=config.data_format)\n\n def _init_set_name(self, name, zero_based=True):\n \"\"\"A hack to allow empty model name for legacy checkpoint compitability.\"\"\"\n if name == '': # pylint: disable=g-explicit-bool-comparison\n self._name = name\n else:\n self._name = super().__init__(name, zero_based)\n\n def call(self, inputs, training):\n \"\"\"Returns the network features.\n\n Args:\n inputs: Input image tensor, commonly with shape [batch, height, width, 3].\n training: bool, whether in training model.\n\n Returns:\n A list of tensors based on the heads:\n - If heads is empty, then just return fpn_features;\n - If heads includes 'object_detection', then return bounding box and\n class predictions.\n - If heads includes 'segmentation', then return per-pixel class\n predictions.\n \"\"\"\n config = self.config\n # call backbone network.\n all_feats = self.backbone(inputs, training=training, features_only=True)\n all_feats[0] = inputs # replace the [0] logits with inputs.\n feats = all_feats[config.min_level:config.max_level + 1]\n\n # Build additional input features that are not from backbone.\n for resample_layer in self.resample_layers:\n feats.append(resample_layer(feats[-1], training, None))\n\n # call feature network.\n fpn_feats = self.fpn_cells(feats, training)\n\n # call class/box/seg output network.\n outputs = []\n if 'object_detection' in config.heads:\n class_outputs = self.class_net(fpn_feats, training)\n box_outputs = self.box_net(fpn_feats, training)\n outputs.extend([class_outputs, box_outputs])\n if 'segmentation' in config.heads:\n seg_outputs = self.seg_head(fpn_feats, training)\n outputs.append(seg_outputs)\n return tuple(outputs) or fpn_feats\n\n\nclass EfficientDetModel(EfficientDetNet):\n \"\"\"EfficientDet full keras model with pre and post processing.\"\"\"\n\n def _preprocessing(self,\n raw_images,\n image_size,\n mean_rgb,\n stddev_rgb,\n mode=None):\n \"\"\"Preprocess images before feeding to the network.\"\"\"\n if not mode:\n return raw_images, None\n\n image_size = utils.parse_image_size(image_size)\n if mode != 'infer':\n # We only support inference for now.\n raise ValueError('preprocessing must be infer or empty')\n\n def map_fn(image):\n input_processor = dataloader.DetectionInputProcessor(\n image, image_size)\n input_processor.normalize_image(mean_rgb, stddev_rgb)\n input_processor.set_scale_factors_to_output_size()\n image = input_processor.resize_and_crop_image()\n image_scale = input_processor.image_scale_to_original\n return image, image_scale\n\n if raw_images.shape.as_list()[0]: # fixed batch size.\n batch_size = raw_images.shape.as_list()[0]\n outputs = [map_fn(raw_images[i]) for i in range(batch_size)]\n return [tf.stack(y) for y in zip(*outputs)]\n\n # otherwise treat it as dynamic batch size.\n return tf.vectorized_map(map_fn, raw_images)\n\n def _postprocess(self, cls_outputs, box_outputs, scales, mode='global'):\n \"\"\"Postprocess class and box predictions.\"\"\"\n if not mode:\n return cls_outputs, box_outputs\n\n if mode == 'global':\n return postprocess.postprocess_global(self.config.as_dict(), cls_outputs,\n box_outputs, scales)\n if mode == 'per_class':\n return postprocess.postprocess_per_class(self.config.as_dict(),\n cls_outputs, box_outputs, scales)\n if mode == 'combined':\n return postprocess.postprocess_combined(self.config.as_dict(),\n cls_outputs, box_outputs, scales)\n if mode == 'tflite':\n if scales is not None:\n # pre_mode should be None for TFLite.\n raise ValueError('scales not supported for TFLite post-processing')\n return postprocess.postprocess_tflite(self.config.as_dict(), cls_outputs,\n box_outputs)\n raise ValueError('Unsupported postprocess mode {}'.format(mode))\n\n def call(self, inputs, training=False, pre_mode='infer', post_mode='global'):\n \"\"\"Call this model.\n\n Args:\n inputs: a tensor with common shape [batch, height, width, channels].\n training: If true, it is training mode. Otherwise, eval mode.\n pre_mode: preprocessing mode, must be {None, 'infer'}.\n post_mode: postprrocessing mode, must be {None, 'global', 'per_class'}.\n\n Returns:\n the output tensor list.\n \"\"\"\n config = self.config\n\n # preprocess.\n inputs, scales = self._preprocessing(inputs, config.image_size,\n config.mean_rgb, config.stddev_rgb,\n pre_mode)\n # network.\n outputs = super().call(inputs, training)\n\n if 'object_detection' in config.heads and post_mode:\n # postprocess for detection\n det_outputs = self._postprocess(outputs[0], outputs[1], scales, post_mode)\n outputs = det_outputs + outputs[2:]\n\n return outputs\n",
"# Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Script to run visualize pose estimation on test data.\"\"\"\nimport argparse\nimport logging\nimport cv2\nfrom movenet import Movenet\nimport numpy as np\nimport pandas as pd\nfrom posenet import Posenet\nimport utils\n\n_MODEL_POSENET = 'posenet'\n_MODEL_LIGHTNING = 'movenet_lightning'\n_MODEL_THUNDER = 'movenet_thunder'\n_GROUND_TRUTH_CSV = 'test_data/pose_landmark_truth.csv'\n_TEST_IMAGE_PATHS = ['test_data/image1.png', 'test_data/image2.jpeg']\n\n# Load test images\n_TEST_IMAGES = [cv2.imread(path) for path in _TEST_IMAGE_PATHS]\n\n# Load pose estimation models\n_POSENET = Posenet(_MODEL_POSENET)\n_MOVENET_LIGHTNING = Movenet(_MODEL_LIGHTNING)\n_MOVENET_THUNDER = Movenet(_MODEL_THUNDER)\n\n# Load pose landmarks truth\n_POSE_LANDMARKS_TRUTH = pd.read_csv(_GROUND_TRUTH_CSV)\n_KEYPOINTS_TRUTH_LIST = [\n row.to_numpy().reshape((17, 2)) for row in _POSE_LANDMARKS_TRUTH.iloc\n]\n\n\ndef _visualize_detection_result(input_image, ground_truth):\n \"\"\"Visualize the pose estimation result and write the output image to a file.\n\n The detected keypoints follow these color codes:\n * PoseNet: blue\n * MoveNet Lightning: red\n * MoveNet Thunder: yellow\n * Ground truth (from CSV): green\n Note: This test is meant to be run by a human who want to visually verify\n the pose estimation result.\n\n Args:\n input_image: Numpy array of shape (height, width, 3)\n ground_truth: Numpy array with absolute coordiates of the keypoints to be\n plotted.\n\n Returns:\n Input image with pose estimation results.\n \"\"\"\n output_image = input_image.copy()\n\n # Draw detection result from Posenet (blue)\n keypoints_with_scores = _POSENET.detect(input_image)\n (keypoint_locs, _,\n _) = utils.keypoints_and_edges_for_display(keypoints_with_scores,\n input_image.shape[0],\n input_image.shape[1], 0)\n output_image = utils.draw_landmarks_edges(output_image, keypoint_locs, [],\n None, (255, 0, 0))\n\n # Draw detection result from Movenet Lightning (red)\n keypoints_with_scores = _MOVENET_LIGHTNING.detect(\n input_image, reset_crop_region=True)\n (keypoint_locs, _,\n _) = utils.keypoints_and_edges_for_display(keypoints_with_scores,\n input_image.shape[0],\n input_image.shape[1], 0)\n output_image = utils.draw_landmarks_edges(output_image, keypoint_locs, [],\n None, (0, 0, 255))\n\n # Draw detection result from Movenet Thunder (yellow)\n keypoints_with_scores = _MOVENET_THUNDER.detect(\n input_image, reset_crop_region=True)\n (keypoint_locs, _,\n _) = utils.keypoints_and_edges_for_display(keypoints_with_scores,\n input_image.shape[0],\n input_image.shape[1], 0)\n output_image = utils.draw_landmarks_edges(output_image, keypoint_locs, [],\n None, (0, 255, 255))\n\n # Draw ground truth detection result (green)\n output_image = utils.draw_landmarks_edges(output_image, ground_truth, [],\n None, (0, 255, 0))\n\n return output_image\n\n\ndef _create_ground_truth_csv(input_images, ground_truth_csv_path):\n \"\"\"Create ground truth CSV file from the given input images.\n\n Args:\n input_images: An array of input RGB images (height, width, 3).\n ground_truth_csv_path: path to the output CSV.\n \"\"\"\n # Create column name for CSV file\n column_names = []\n for keypoint_name in utils.KEYPOINT_DICT.keys():\n column_names.append(keypoint_name + '_x')\n column_names.append(keypoint_name + '_y')\n\n # Create ground truth data by feeding the test images through MoveNet\n # Thunder 3 times to leverage the cropping logic and improve accuracy.\n keypoints_data = []\n for input_image in input_images:\n _MOVENET_THUNDER.detect(input_image, reset_crop_region=True)\n for _ in range(3):\n keypoints_with_scores = _MOVENET_THUNDER.detect(\n input_image, reset_crop_region=False)\n\n # Convert the detected keypoints to the original image's coordinate system\n (keypoint_locs, _,\n _) = utils.keypoints_and_edges_for_display(keypoints_with_scores,\n input_image.shape[0],\n input_image.shape[1], 0)\n\n # Round the coordinate values to integer and store them\n keypoints_data.append(keypoint_locs.flatten().astype(np.int16))\n\n # Write ground truth CSV file\n keypoints_df = pd.DataFrame(keypoints_data, columns=column_names)\n keypoints_df.to_csv(ground_truth_csv_path, index=False)\n\n\ndef main():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\n '--ground_truth_csv_output',\n help='Path to generate ground truth CSV file. (Optional)',\n required=False)\n args = parser.parse_args()\n\n # Create ground truth CSV if the ground_truth_csv parameter is set\n if args.ground_truth_csv_output:\n _create_ground_truth_csv(_TEST_IMAGES, args.ground_truth_csv_output)\n logging.info('Created ground truth keypoint CSV: %s',\n args.ground_truth_csv_output)\n\n # Visualize detection result of the test images\n for index in range(len(_TEST_IMAGES)):\n test_image_path = _TEST_IMAGE_PATHS[index]\n test_image = _TEST_IMAGES[index]\n keypoint_truth = _KEYPOINTS_TRUTH_LIST[index]\n visualized_image = _visualize_detection_result(test_image, keypoint_truth)\n cv2.imshow(test_image_path, visualized_image)\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n main()\n",
"# Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Utility functions to display the pose detection results.\"\"\"\n\nimport cv2\nimport numpy as np\n\n# Dictionary that maps from joint names to keypoint indices.\nKEYPOINT_DICT = {\n 'nose': 0,\n 'left_eye': 1,\n 'right_eye': 2,\n 'left_ear': 3,\n 'right_ear': 4,\n 'left_shoulder': 5,\n 'right_shoulder': 6,\n 'left_elbow': 7,\n 'right_elbow': 8,\n 'left_wrist': 9,\n 'right_wrist': 10,\n 'left_hip': 11,\n 'right_hip': 12,\n 'left_knee': 13,\n 'right_knee': 14,\n 'left_ankle': 15,\n 'right_ankle': 16\n}\n\n# map edges to a RGB color\nKEYPOINT_EDGE_INDS_TO_COLOR = {\n (0, 1): (147, 20, 255),\n (0, 2): (255, 255, 0),\n (1, 3): (147, 20, 255),\n (2, 4): (255, 255, 0),\n (0, 5): (147, 20, 255),\n (0, 6): (255, 255, 0),\n (5, 7): (147, 20, 255),\n (7, 9): (147, 20, 255),\n (6, 8): (255, 255, 0),\n (8, 10): (255, 255, 0),\n (5, 6): (0, 255, 255),\n (5, 11): (147, 20, 255),\n (6, 12): (255, 255, 0),\n (11, 12): (0, 255, 255),\n (11, 13): (147, 20, 255),\n (13, 15): (147, 20, 255),\n (12, 14): (255, 255, 0),\n (14, 16): (255, 255, 0)\n}\n\n\ndef draw_landmarks_edges(image,\n keypoint_locs,\n keypoint_edges,\n edge_colors,\n keypoint_color=(0, 255, 0)):\n \"\"\"Draw landmarks and edges on the input image and return it.\"\"\"\n for landmark in keypoint_locs:\n landmark_x = min(landmark[0], image.shape[1] - 1)\n landmark_y = min(landmark[1], image.shape[0] - 1)\n cv2.circle(image, (int(landmark_x), int(landmark_y)), 2, keypoint_color, 4)\n\n for idx, edge in enumerate(keypoint_edges):\n cv2.line(image, (int(edge[0][0]), int(edge[0][1])),\n (int(edge[1][0]), int(edge[1][1])), edge_colors[idx], 2)\n\n return image\n\n\ndef keypoints_and_edges_for_display(keypoints_with_scores,\n height,\n width,\n keypoint_threshold=0.11):\n \"\"\"Returns high confidence keypoints and edges for visualization.\n\n Args:\n keypoints_with_scores: An numpy array with shape [17, 3] representing the\n keypoint coordinates and scores returned by the MoveNet/PoseNet models.\n height: height of the image in pixels.\n width: width of the image in pixels.\n keypoint_threshold: minimum confidence score for a keypoint to be\n visualized.\n\n Returns:\n A (keypoints_xy, edges_xy, edge_colors) containing:\n * the coordinates of all keypoints of all detected entities;\n * the coordinates of all skeleton edges of all detected entities;\n * the colors in which the edges should be plotted.\n \"\"\"\n keypoints_all = []\n keypoint_edges_all = []\n edge_colors = []\n kpts_x = keypoints_with_scores[:, 1]\n kpts_y = keypoints_with_scores[:, 0]\n kpts_scores = keypoints_with_scores[:, 2]\n kpts_absolute_xy = np.stack(\n [width * np.array(kpts_x), height * np.array(kpts_y)], axis=-1)\n kpts_above_thresh_absolute = kpts_absolute_xy[\n kpts_scores > keypoint_threshold]\n keypoints_all.append(kpts_above_thresh_absolute)\n\n for edge_pair, color in KEYPOINT_EDGE_INDS_TO_COLOR.items():\n if (kpts_scores[edge_pair[0]] > keypoint_threshold and\n kpts_scores[edge_pair[1]] > keypoint_threshold):\n x_start = kpts_absolute_xy[edge_pair[0], 0]\n y_start = kpts_absolute_xy[edge_pair[0], 1]\n x_end = kpts_absolute_xy[edge_pair[1], 0]\n y_end = kpts_absolute_xy[edge_pair[1], 1]\n line_seg = np.array([[x_start, y_start], [x_end, y_end]])\n keypoint_edges_all.append(line_seg)\n edge_colors.append(color)\n if keypoints_all:\n keypoints_xy = np.concatenate(keypoints_all, axis=0)\n else:\n num_instances, _ = keypoints_with_scores.shape\n keypoints_xy = np.zeros((0, num_instances, 2))\n\n if keypoint_edges_all:\n edges_xy = np.stack(keypoint_edges_all, axis=0)\n else:\n edges_xy = np.zeros((0, 2, 2))\n\n return keypoints_xy, edges_xy, edge_colors\n"
] |
[
[
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.vectorized_map",
"tensorflow.concat",
"numpy.log",
"tensorflow.stack",
"tensorflow.keras.layers.Conv2DTranspose",
"tensorflow.keras.layers.Conv2D",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.zeros_initializer",
"tensorflow.name_scope",
"tensorflow.random_normal_initializer",
"tensorflow.initializers.variance_scaling",
"tensorflow.keras.layers.MaxPooling2D"
],
[
"pandas.read_csv",
"pandas.DataFrame"
],
[
"numpy.concatenate",
"numpy.array",
"numpy.zeros",
"numpy.stack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LazyBanker/robinhood-resiliant-trader
|
[
"551026f1e25610e5b0efb66438fabcb10101ab18"
] |
[
"app.py"
] |
[
"from flask import Flask, request, render_template, session, flash, redirect, \\\n url_for, jsonify, make_response\n\n\n\napp = Flask(__name__)\n\[email protected]('/')\ndef index():\n import datetime\n import io\n import random\n\n from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\n from matplotlib.figure import Figure\n from matplotlib.dates import DateFormatter\n\n fig=Figure()\n ax=fig.add_subplot(111)\n x=[]\n y=[]\n now=datetime.datetime.now()\n delta=datetime.timedelta(days=1)\n for i in range(10):\n x.append(now)\n now+=delta\n y.append(random.randint(0, 1000))\n ax.plot_date(x, y, '-')\n ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))\n fig.autofmt_xdate()\n canvas=FigureCanvas(fig)\n png_output = io.BytesIO()\n canvas.print_png(png_output)\n response=make_response(png_output.getvalue())\n response.headers['Content-Type'] = 'image/png'\n return response\n\nif __name__ == '__main__':\n app.run(debug=True)\n"
] |
[
[
"matplotlib.backends.backend_agg.FigureCanvasAgg",
"matplotlib.dates.DateFormatter",
"matplotlib.figure.Figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
BoPang1996/Semi-Coupled-Structure-for-visual-sequental-tasks
|
[
"c6fe7c77d08928bb30cc8683123f978b0e877394"
] |
[
"src/network.py"
] |
[
"import torch\nimport torch.nn as nn\nimport numpy as np\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom sync_batchnorm import SynchronizedBatchNorm2d\nimport random\n\n\nclass SCS(nn.Module):\n def __init__(self, batch_norm, num_action, dropout, q, test_scheme=1, img_size=112, syn_bn=False):\n\n super(SCS, self).__init__()\n\n # Configs\n self.channels = [3, 64, 64, 64, 64, 64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512]\n self.RNN_layer = len(self.channels) - 1\n self.input_size = [img_size, img_size/4, img_size/4, img_size/4, img_size/4, img_size/4, img_size/8, img_size/8, img_size/8, img_size/8, img_size/16, img_size/16, img_size/16, img_size/16, img_size/32, img_size/32, img_size/32]\n self.out_size = [img_size/4, img_size/4, img_size/4, img_size/4, img_size/4, img_size/8, img_size/8, img_size/8, img_size/8, img_size/16, img_size/16, img_size/16, img_size/16, img_size/32, img_size/32, img_size/32, img_size/32]\n self.stride = [2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1]\n self.shortCutLayer = [ 1, 3, 5, 7, 9, 11, 13, 15]\n self.mergeShortCutLayer = [2, 4, 6, 8, 10, 12, 14, 16]\n self.not_selftrans = [6, 10, 14]\n\n # Modules\n self.dropout_RNN = nn.Dropout2d(p=dropout[0])\n\n self.RNN = nn.ModuleList([self.make_SCSCell((self.channels[i]), (self.channels[i + 1] + self.channels[i]), self.channels[i + 1], q=q, kernel_size=7 if i == 0 else 3, stride=self.stride[i], syn_bn=syn_bn, pool=(i == 0), padding=3 if i == 0 else 1) for i in range(self.RNN_layer)])\n self.init_weight(self.RNN, xavier_gain=3.0)\n\n self.ofm = nn.ModuleList([OFM(64, 16), OFM(128, 32), OFM(256, 32), OFM(512, 32)])\n\n block = [[{'convsc_1': [self.channels[5], self.channels[7], 1, 2, 0]}], [{'convsc_2': [self.channels[9], self.channels[11], 1, 2, 0]}],\n [{'convsc_3': [self.channels[13], self.channels[15], 1, 2, 0]}]]\n self.ShortCut = nn.ModuleList([self._make_layer(block[i], batch_norm, syn_bn=syn_bn) for i in range(len(block))])\n self.init_weight(self.ShortCut)\n\n self.classifier = nn.Sequential(nn.Linear(int(self.channels[15] * pow(self.out_size[-1],2)), int(self.channels[15]*self.out_size[-1])), nn.ReLU(inplace=True), nn.Dropout(p=dropout[1]), nn.Linear(int(self.channels[15]*self.out_size[-1]), num_action))#nn.Softmax(dim=1))\n self.sftmx = nn.LogSoftmax(dim=1)\n self.init_weight(self.classifier)\n\n # Parameters\n self.syn_bn = syn_bn\n self.num_action = num_action\n self.test_scheme = test_scheme\n\n def init_weight(self, model, xavier_gain=1.0):\n for m in model.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.xavier_normal_(m.weight.data, gain=xavier_gain)\n if m.bias is not None:\n m.bias.data.fill_(0)\n if isinstance(m, SynchronizedBatchNorm2d) or isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n if isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n\n def _make_layer(self, net_dict, batch_norm=False, syn_bn=False):\n layers = []\n length = len(net_dict)\n for i in range(length):\n one_layer = net_dict[i]\n key = list(one_layer.keys())[0]\n v = one_layer[key]\n\n if 'pool' in key:\n layers += [nn.MaxPool2d(kernel_size=v[0], stride=v[1], padding=v[2])]\n else:\n conv2d = nn.Conv2d(in_channels=v[0], out_channels=v[1], kernel_size=v[2], stride=v[3], padding=v[4])\n if batch_norm:\n if syn_bn:\n layers += [conv2d, SynchronizedBatchNorm2d(v[1]), nn.ReLU(inplace=True)]\n else:\n layers += [conv2d, nn.BatchNorm2d(v[1]), nn.ReLU(inplace=True)]\n else:\n layers += [conv2d, nn.ReLU(inplace=True)]\n return nn.Sequential(*layers)\n\n def make_SCSCell(self, in_channel1, in_channel2, out_channel, q, kernel_size, stride, padding, pool=False, syn_bn=False):\n class scs_cell(nn.Module):\n def __init__(self, in_channel1, in_channel2, out_channel, pool, q, kernel_size, stride, padding):\n super(scs_cell, self).__init__()\n self.outchannel = out_channel\n conv_data = nn.Conv2d(in_channels=in_channel1, out_channels=out_channel, kernel_size=kernel_size, stride=stride, padding=padding, bias=True)\n conv_ctrl = nn.Conv2d(in_channels=in_channel2, out_channels=out_channel, kernel_size=3, stride=1, padding=1, bias=True)\n self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1, ceil_mode=False)\n\n if syn_bn:\n layers_data = [conv_data, SynchronizedBatchNorm2d(out_channel), torch.nn.ReLU()]\n layers_ctrl = [conv_ctrl, SynchronizedBatchNorm2d(out_channel), torch.nn.Sigmoid()]\n else:\n layers_data = [conv_data, nn.BatchNorm2d(out_channel), torch.nn.ReLU()]\n layers_ctrl = [conv_ctrl, nn.BatchNorm2d(out_channel)]\n\n self.conv_data = nn.Sequential(*layers_data)\n self.conv_ctrl = nn.Sequential(*layers_ctrl)\n\n self.ispool = pool\n self.q = q\n self.stride = stride\n\n def forward(self, x, c, single_data, single_temp, single_c):\n input_data = x\n rand1 = random.random()\n rand2 = random.random()\n if rand1 < self.q:\n x_ctrl = x.detach()\n else:\n x_ctrl = x\n\n if rand2 < (1 - self.q):\n input_data = x.detach()\n\n if rand2 < (1 - self.q) and rand1 < self.q:\n if self.q < 0.5:\n x_ctrl = x\n else:\n input_data = x\n\n input_ctrl = torch.cat((x_ctrl, c), 1)\n\n # main stream calculate\n data = self.conv_data(input_data)\n ctrl = torch.sigmoid(self.conv_ctrl(input_ctrl))\n\n if self.stride == 1:\n output = data * ctrl\n else:\n output = data * self.pool(ctrl)\n\n # data stream calculate\n data_l = self.conv_data(single_data)\n\n # temp stream calculate\n input_temp = torch.cat((single_temp, single_c), 1)\n temp = self.conv_ctrl(input_temp)\n temp_t = torch.sigmoid(temp)\n if self.stride == 1:\n temp_l = F.relu(temp)\n else:\n temp_l = self.pool(F.relu(temp))\n\n return output, ctrl, data, data_l, temp_t, temp_l\n\n return scs_cell(in_channel1, in_channel2, out_channel, pool, q, kernel_size=kernel_size, stride=stride, padding=padding)\n\n def forward(self, x, initial, initial_single_temp):\n out_action = torch.zeros((x.shape[0], x.shape[1], self.num_action)).cuda().float()\n data_action = torch.zeros((x.shape[0], x.shape[1], self.num_action)).cuda().float()\n temp_map_4 = torch.zeros((x.shape[0], x.shape[1], 2, x.shape[3] // 4, x.shape[3] // 4)).cuda().float()\n temp_map_8 = torch.zeros((x.shape[0], x.shape[1], 2, x.shape[3] // 8, x.shape[3] // 8)).cuda().float()\n temp_map_12 = torch.zeros((x.shape[0], x.shape[1], 2, x.shape[3] // 16, x.shape[3] // 16)).cuda().float()\n temp_map_16 = torch.zeros((x.shape[0], x.shape[1], 2, x.shape[3] // 32, x.shape[3] // 32)).cuda().float()\n for frame in range(x.shape[1]):\n\n # 0\n out, initial[0], data_map, data, initial_single_temp[0], temp = self.RNN[0](x[:, frame], initial[0],\n x[:, frame], x[:, frame],\n initial_single_temp[0])\n out = self.RNN[0].pool(out)\n data = self.RNN[0].pool(data)\n temp = self.RNN[0].pool(temp)\n\n # 1\n short = out\n short_data = data\n short_temp = temp\n out, initial[1], _, data, initial_single_temp[1], temp = self.RNN[1](out, initial[1], data, temp,\n initial_single_temp[1])\n out, initial[2], _, data, initial_single_temp[2], temp = self.RNN[2](out, initial[2], data, temp,\n initial_single_temp[2])\n out = out + short\n data = data + short_data\n temp = temp + short_temp\n\n # 3\n short = out\n short_data = data\n short_temp = temp\n out, initial[3], _, data, initial_single_temp[3], temp = self.RNN[3](out, initial[3], data, temp,\n initial_single_temp[3])\n out, initial[4], data_map, data, initial_single_temp[4], temp = self.RNN[4](out, initial[4], data, temp,\n initial_single_temp[4])\n out = out + short\n data = data + short_data\n temp = temp + short_temp\n temp_map_4[:, frame] = self.ofm[0](temp)\n\n out = self.dropout_RNN(out)\n data = self.dropout_RNN(data)\n temp = self.dropout_RNN(temp)\n\n # 5\n short = out\n short_data = data\n short_temp = temp\n out, initial[5], _, data, initial_single_temp[5], temp = self.RNN[5](out, initial[5], data, temp,\n initial_single_temp[5])\n out, initial[6], _, data, initial_single_temp[6], temp = self.RNN[6](out, initial[6], data, temp,\n initial_single_temp[6])\n out = out + self.ShortCut[0](short)\n data = data + self.ShortCut[0](short_data)\n temp = temp + self.ShortCut[0](short_temp)\n\n # 7\n short = out\n short_data = data\n short_temp = temp\n out, initial[7], _, data, initial_single_temp[7], temp = self.RNN[7](out, initial[7], data, temp,\n initial_single_temp[7])\n out, initial[8], _, data, initial_single_temp[8], temp = self.RNN[8](out, initial[8], data, temp,\n initial_single_temp[8])\n out = out + short\n data = data + short_data\n temp = temp + short_temp\n temp_map_8[:, frame] = self.ofm[1](temp)\n\n # 9\n short = out\n short_data = data\n short_temp = temp\n out, initial[9], _, data, initial_single_temp[9], temp = self.RNN[9](out, initial[9], data, temp,\n initial_single_temp[9])\n out, initial[10], _, data, initial_single_temp[10], temp = self.RNN[10](out, initial[10], data, temp,\n initial_single_temp[10])\n out = out + self.ShortCut[1](short)\n data = data + self.ShortCut[1](short_data)\n temp = temp + self.ShortCut[1](short_temp)\n\n out = self.dropout_RNN(out)\n data = self.dropout_RNN(data)\n temp = self.dropout_RNN(temp)\n\n # 11\n short = out\n short_data = data\n short_temp = temp\n out, initial[11], _, data, initial_single_temp[11], temp = self.RNN[11](out, initial[11], data, temp,\n initial_single_temp[11])\n out, initial[12], _, data, initial_single_temp[12], temp = self.RNN[12](out, initial[12], data, temp,\n initial_single_temp[12])\n out = out + short\n data = data + short_data\n temp = temp + short_temp\n temp_map_12[:, frame] = self.ofm[2](temp)\n\n # 13\n short = out\n short_data = data\n short_temp = temp\n out, initial[13], _, data, initial_single_temp[13], temp = self.RNN[13](out, initial[13], data, temp,\n initial_single_temp[13])\n out, initial[14], _, data, initial_single_temp[14], temp = self.RNN[14](out, initial[14], data, temp,\n initial_single_temp[14])\n out = out + self.ShortCut[2](short)\n data = data + self.ShortCut[2](short_data)\n temp = temp + self.ShortCut[2](short_temp)\n\n # 15\n short = out\n short_data = data\n short_temp = temp\n out, initial[15], _, data, initial_single_temp[15], temp = self.RNN[15](out, initial[15], data, temp,\n initial_single_temp[15])\n out, initial[16], _, data, initial_single_temp[16], temp = self.RNN[16](out, initial[16], data, temp,\n initial_single_temp[16])\n out = out + short\n data = data + short_data\n temp = temp + short_temp\n temp_map_16[:, frame] = self.ofm[3](temp)\n\n out = self.dropout_RNN(out)\n data = self.dropout_RNN(data)\n\n # out = out.detach()\n if not self.training:\n out_action[:, frame] = self.sftmx(2*self.classifier(out.contiguous().view(x.shape[0], -1)))\n data_action[:, frame] = self.sftmx(2*self.classifier(data.contiguous().view(x.shape[0], -1)))\n\n else:\n out_action[:, frame] = self.sftmx(self.classifier(out.contiguous().view(x.shape[0], -1)))\n data_action[:, frame] = self.sftmx(self.classifier(data.contiguous().view(x.shape[0], -1)))\n\n if self.test_scheme == 1:\n out = torch.mean(out_action, 1)\n data = torch.mean(data_action, 1)\n elif self.test_scheme == 2:\n if self.training:\n out = torch.mean(out_action[:, int(out_action.shape[1]/2):out_action.shape[1]],1)\n data = torch.mean(data_action[:, int(data_action.shape[1] / 2):data_action.shape[1]], 1)\n else:\n out = torch.mean(out_action, 1)\n data = torch.mean(data_action, 1)\n else:\n print(\"Wrong test_scheme\")\n\n for i in range(len(initial)):\n initial[i] = initial[i].detach()\n for i in range(len(initial_single_temp)):\n initial_single_temp[i] = initial_single_temp[i].detach()\n temp_maps = [temp_map_4, temp_map_8, temp_map_12, temp_map_16]\n return out, out_action, data, data_action, temp_maps, initial, initial_single_temp\n\n\nclass OFM(nn.Module):\n def __init__(self, in_channel, mid_channel):\n super(OFM, self).__init__()\n self._make_block(in_channel, mid_channel)\n\n def _make_block(self, in_channel, mid_channel):\n self.a = nn.Conv2d(in_channel, mid_channel,\n kernel_size=1,\n stride=1,\n padding=0)\n self.a_bn = nn.BatchNorm2d(mid_channel)\n self.a_relu = nn.ReLU(inplace=True)\n\n self.b = nn.Conv2d(mid_channel, mid_channel,\n kernel_size=3,\n stride=1,\n padding=1)\n self.b_bn = nn.BatchNorm2d(mid_channel)\n self.b_relu = nn.ReLU(inplace=True)\n\n self.c = nn.Conv2d(mid_channel, 2,\n kernel_size=1,\n stride=1,\n padding=0)\n self.c_bn = nn.BatchNorm2d(2)\n self.c_relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n x = self.a_relu(self.a_bn(self.a(x)))\n x = self.b_relu(self.b_bn(self.b(x)))\n x = self.c_relu(self.c_bn(self.c(x)))\n return x\n\n\ndef actionModel(num_action, batch_norm=False, dropout=[0, 0], test_scheme=1, q=0.5, image_size=112, syn_bn=False):\n\n model = SCS(batch_norm, num_action, dropout=dropout, test_scheme=test_scheme, q=q, img_size=image_size, syn_bn=syn_bn)\n\n return model\n\n\n"
] |
[
[
"torch.nn.Sequential",
"torch.nn.Dropout",
"torch.nn.LogSoftmax",
"torch.nn.Dropout2d",
"torch.mean",
"torch.sigmoid",
"torch.cat",
"torch.zeros",
"torch.nn.Conv2d",
"torch.nn.init.xavier_normal_",
"torch.nn.Sigmoid",
"torch.nn.MaxPool2d",
"torch.nn.functional.relu",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sahilparekh/imgclsmob
|
[
"74d52457b4bf00c82d063b3f4a1a73fb6ba3863a",
"74d52457b4bf00c82d063b3f4a1a73fb6ba3863a",
"74d52457b4bf00c82d063b3f4a1a73fb6ba3863a",
"74d52457b4bf00c82d063b3f4a1a73fb6ba3863a",
"74d52457b4bf00c82d063b3f4a1a73fb6ba3863a",
"74d52457b4bf00c82d063b3f4a1a73fb6ba3863a"
] |
[
"tensorflow2/tf2cv/models/wrn.py",
"pytorch/pytorchcv/models/others/oth_regnet.py",
"tensorflow2/tf2cv/models/proxylessnas.py",
"tensorflow2/tf2cv/models/seresnet_cifar.py",
"tensorflow2/tf2cv/models/mobilenetb.py",
"tensorflow2/tf2cv/models/inceptionresnetv2.py"
] |
[
"\"\"\"\n WRN for ImageNet-1K, implemented in TensorFlow.\n Original paper: 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\"\"\"\n\n__all__ = ['WRN', 'wrn50_2']\n\nimport os\nimport tensorflow as tf\nimport tensorflow.keras.layers as nn\nfrom .common import Conv2d, MaxPool2d, flatten, is_channels_first\n\n\nclass WRNConv(nn.Layer):\n \"\"\"\n WRN specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n activate : bool\n Whether activate the convolution block.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n strides,\n padding,\n activate,\n data_format=\"channels_last\",\n **kwargs):\n super(WRNConv, self).__init__(**kwargs)\n self.activate = activate\n\n self.conv = Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n use_bias=True,\n data_format=data_format,\n name=\"conv\")\n if self.activate:\n self.activ = nn.ReLU()\n\n def call(self, x, training=None):\n x = self.conv(x)\n if self.activate:\n x = self.activ(x)\n return x\n\n\ndef wrn_conv1x1(in_channels,\n out_channels,\n strides,\n activate,\n data_format=\"channels_last\",\n **kwargs):\n \"\"\"\n 1x1 version of the WRN specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n activate : bool\n Whether activate the convolution block.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n return WRNConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=1,\n strides=strides,\n padding=0,\n activate=activate,\n data_format=data_format,\n **kwargs)\n\n\ndef wrn_conv3x3(in_channels,\n out_channels,\n strides,\n activate,\n data_format=\"channels_last\",\n **kwargs):\n \"\"\"\n 3x3 version of the WRN specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n activate : bool\n Whether activate the convolution block.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n return WRNConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=3,\n strides=strides,\n padding=1,\n activate=activate,\n data_format=data_format,\n **kwargs)\n\n\nclass WRNBottleneck(nn.Layer):\n \"\"\"\n WRN bottleneck block for residual path in WRN unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n width_factor : float\n Wide scale factor for width of layers.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides,\n width_factor,\n data_format=\"channels_last\",\n **kwargs):\n super(WRNBottleneck, self).__init__(**kwargs)\n mid_channels = int(round(out_channels // 4 * width_factor))\n\n self.conv1 = wrn_conv1x1(\n in_channels=in_channels,\n out_channels=mid_channels,\n strides=1,\n activate=True,\n data_format=data_format,\n name=\"conv1\")\n self.conv2 = wrn_conv3x3(\n in_channels=mid_channels,\n out_channels=mid_channels,\n strides=strides,\n activate=True,\n data_format=data_format,\n name=\"conv2\")\n self.conv3 = wrn_conv1x1(\n in_channels=mid_channels,\n out_channels=out_channels,\n strides=1,\n activate=False,\n data_format=data_format,\n name=\"conv3\")\n\n def call(self, x, training=None):\n x = self.conv1(x, training=training)\n x = self.conv2(x, training=training)\n x = self.conv3(x, training=training)\n return x\n\n\nclass WRNUnit(nn.Layer):\n \"\"\"\n WRN unit with residual connection.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n width_factor : float\n Wide scale factor for width of layers.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides,\n width_factor,\n data_format=\"channels_last\",\n **kwargs):\n super(WRNUnit, self).__init__(**kwargs)\n self.resize_identity = (in_channels != out_channels) or (strides != 1)\n\n self.body = WRNBottleneck(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n width_factor=width_factor,\n data_format=data_format,\n name=\"body\")\n if self.resize_identity:\n self.identity_conv = wrn_conv1x1(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n activate=False,\n data_format=data_format,\n name=\"identity_conv\")\n self.activ = nn.ReLU()\n\n def call(self, x, training=None):\n if self.resize_identity:\n identity = self.identity_conv(x, training=training)\n else:\n identity = x\n x = self.body(x, training=training)\n x = x + identity\n x = self.activ(x)\n return x\n\n\nclass WRNInitBlock(nn.Layer):\n \"\"\"\n WRN specific initial block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n data_format=\"channels_last\",\n **kwargs):\n super(WRNInitBlock, self).__init__(**kwargs)\n self.conv = WRNConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=7,\n strides=2,\n padding=3,\n activate=True,\n data_format=data_format,\n name=\"conv\")\n self.pool = MaxPool2d(\n pool_size=3,\n strides=2,\n padding=1,\n data_format=data_format,\n name=\"pool\")\n\n def call(self, x, training=None):\n x = self.conv(x, training=training)\n x = self.pool(x)\n return x\n\n\nclass WRN(tf.keras.Model):\n \"\"\"\n WRN model from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n width_factor : float\n Wide scale factor for width of layers.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n width_factor,\n in_channels=3,\n in_size=(224, 224),\n classes=1000,\n data_format=\"channels_last\",\n **kwargs):\n super(WRN, self).__init__(**kwargs)\n self.in_size = in_size\n self.classes = classes\n self.data_format = data_format\n\n self.features = tf.keras.Sequential(name=\"features\")\n self.features.add(WRNInitBlock(\n in_channels=in_channels,\n out_channels=init_block_channels,\n data_format=data_format,\n name=\"init_block\"))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = tf.keras.Sequential(name=\"stage{}\".format(i + 1))\n for j, out_channels in enumerate(channels_per_stage):\n strides = 2 if (j == 0) and (i != 0) else 1\n stage.add(WRNUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n width_factor=width_factor,\n data_format=data_format,\n name=\"unit{}\".format(j + 1)))\n in_channels = out_channels\n self.features.add(stage)\n self.features.add(nn.AveragePooling2D(\n pool_size=7,\n strides=1,\n data_format=data_format,\n name=\"final_pool\"))\n\n self.output1 = nn.Dense(\n units=classes,\n input_dim=in_channels,\n name=\"output1\")\n\n def call(self, x, training=None):\n x = self.features(x, training=training)\n x = flatten(x, self.data_format)\n x = self.output1(x)\n return x\n\n\ndef get_wrn(blocks,\n width_factor,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".tensorflow\", \"models\"),\n **kwargs):\n \"\"\"\n Create WRN model with specific parameters.\n\n Parameters:\n ----------\n blocks : int\n Number of blocks.\n width_factor : float\n Wide scale factor for width of layers.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n\n if blocks == 50:\n layers = [3, 4, 6, 3]\n elif blocks == 101:\n layers = [3, 4, 23, 3]\n elif blocks == 152:\n layers = [3, 8, 36, 3]\n elif blocks == 200:\n layers = [3, 24, 36, 3]\n else:\n raise ValueError(\"Unsupported WRN with number of blocks: {}\".format(blocks))\n\n init_block_channels = 64\n channels_per_layers = [256, 512, 1024, 2048]\n\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n net = WRN(\n channels=channels,\n init_block_channels=init_block_channels,\n width_factor=width_factor,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n in_channels = kwargs[\"in_channels\"] if (\"in_channels\" in kwargs) else 3\n input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == \"channels_first\" else\\\n (1,) + net.in_size + (in_channels,)\n net.build(input_shape=input_shape)\n net.load_weights(\n filepath=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root))\n\n return net\n\n\ndef wrn50_2(**kwargs):\n \"\"\"\n WRN-50-2 model from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_wrn(blocks=50, width_factor=2.0, model_name=\"wrn50_2\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import tensorflow.keras.backend as K\n\n data_format = \"channels_last\"\n pretrained = False\n\n models = [\n wrn50_2,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained, data_format=data_format)\n\n batch = 14\n x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3))\n y = net(x)\n assert (tuple(y.shape.as_list()) == (batch, 1000))\n\n weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights])\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != wrn50_2 or weight_count == 68849128)\n\n\nif __name__ == \"__main__\":\n _test()\n",
"import numpy as np\nimport torch.nn as nn\n\nfrom timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD\nfrom timm.models.helpers import build_model_with_cfg\nfrom timm.models.layers import ClassifierHead, AvgPool2dSame, ConvBnAct, SEModule, DropPath\n\n\ndef _mcfg(**kwargs):\n cfg = dict(\n se_ratio=0.,\n bottle_ratio=1.,\n stem_width=32)\n cfg.update(**kwargs)\n return cfg\n\n\n# Model FLOPS = three trailing digits * 10^8\nmodel_cfgs = dict(\n regnetx_002=_mcfg(w0=24, wa=36.44, wm=2.49, group_w=8, depth=13),\n regnetx_004=_mcfg(w0=24, wa=24.48, wm=2.54, group_w=16, depth=22),\n regnetx_006=_mcfg(w0=48, wa=36.97, wm=2.24, group_w=24, depth=16),\n regnetx_008=_mcfg(w0=56, wa=35.73, wm=2.28, group_w=16, depth=16),\n regnetx_016=_mcfg(w0=80, wa=34.01, wm=2.25, group_w=24, depth=18),\n regnetx_032=_mcfg(w0=88, wa=26.31, wm=2.25, group_w=48, depth=25),\n regnetx_040=_mcfg(w0=96, wa=38.65, wm=2.43, group_w=40, depth=23),\n regnetx_064=_mcfg(w0=184, wa=60.83, wm=2.07, group_w=56, depth=17),\n regnetx_080=_mcfg(w0=80, wa=49.56, wm=2.88, group_w=120, depth=23),\n regnetx_120=_mcfg(w0=168, wa=73.36, wm=2.37, group_w=112, depth=19),\n regnetx_160=_mcfg(w0=216, wa=55.59, wm=2.1, group_w=128, depth=22),\n regnetx_320=_mcfg(w0=320, wa=69.86, wm=2.0, group_w=168, depth=23),\n regnety_002=_mcfg(w0=24, wa=36.44, wm=2.49, group_w=8, depth=13, se_ratio=0.25),\n regnety_004=_mcfg(w0=48, wa=27.89, wm=2.09, group_w=8, depth=16, se_ratio=0.25),\n regnety_006=_mcfg(w0=48, wa=32.54, wm=2.32, group_w=16, depth=15, se_ratio=0.25),\n regnety_008=_mcfg(w0=56, wa=38.84, wm=2.4, group_w=16, depth=14, se_ratio=0.25),\n regnety_016=_mcfg(w0=48, wa=20.71, wm=2.65, group_w=24, depth=27, se_ratio=0.25),\n regnety_032=_mcfg(w0=80, wa=42.63, wm=2.66, group_w=24, depth=21, se_ratio=0.25),\n regnety_040=_mcfg(w0=96, wa=31.41, wm=2.24, group_w=64, depth=22, se_ratio=0.25),\n regnety_064=_mcfg(w0=112, wa=33.22, wm=2.27, group_w=72, depth=25, se_ratio=0.25),\n regnety_080=_mcfg(w0=192, wa=76.82, wm=2.19, group_w=56, depth=17, se_ratio=0.25),\n regnety_120=_mcfg(w0=168, wa=73.36, wm=2.37, group_w=112, depth=19, se_ratio=0.25),\n regnety_160=_mcfg(w0=200, wa=106.23, wm=2.48, group_w=112, depth=18, se_ratio=0.25),\n regnety_320=_mcfg(w0=232, wa=115.89, wm=2.53, group_w=232, depth=20, se_ratio=0.25),\n)\n\n\ndef _cfg(url=''):\n return {\n 'url': url,\n 'num_classes': 1000,\n 'input_size': (3, 224, 224),\n 'pool_size': (7, 7),\n 'crop_pct': 0.875,\n 'interpolation': 'bicubic',\n 'mean': IMAGENET_DEFAULT_MEAN,\n 'std': IMAGENET_DEFAULT_STD,\n 'first_conv': 'stem.conv',\n 'classifier': 'head.fc',\n }\n\n\ndefault_cfgs = dict(\n regnetx_002=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_002-e7e85e5c.pth'),\n regnetx_004=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_004-7d0e9424.pth'),\n regnetx_006=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_006-85ec1baa.pth'),\n regnetx_008=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_008-d8b470eb.pth'),\n regnetx_016=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_016-65ca972a.pth'),\n regnetx_032=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_032-ed0c7f7e.pth'),\n regnetx_040=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_040-73c2a654.pth'),\n regnetx_064=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_064-29278baa.pth'),\n regnetx_080=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_080-7c7fcab1.pth'),\n regnetx_120=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_120-65d5521e.pth'),\n regnetx_160=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_160-c98c4112.pth'),\n regnetx_320=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_320-8ea38b93.pth'),\n regnety_002=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnety_002-e68ca334.pth'),\n regnety_004=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnety_004-0db870e6.pth'),\n regnety_006=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnety_006-c67e57ec.pth'),\n regnety_008=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnety_008-dc900dbe.pth'),\n regnety_016=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnety_016-54367f74.pth'),\n regnety_032=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/regnety_032_ra-7f2439f9.pth'),\n regnety_040=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnety_040-f0d569f9.pth'),\n regnety_064=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnety_064-0a48325c.pth'),\n regnety_080=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnety_080-e7f3eb93.pth'),\n regnety_120=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnety_120-721ba79a.pth'),\n regnety_160=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnety_160-d64013cd.pth'),\n regnety_320=_cfg(url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnety_320-ba464b29.pth'),\n)\n\n\ndef quantize_float(f, q):\n \"\"\"Converts a float to closest non-zero int divisible by q.\"\"\"\n return int(round(f / q) * q)\n\n\ndef adjust_widths_groups_comp(widths, bottle_ratios, groups):\n \"\"\"Adjusts the compatibility of widths and groups.\"\"\"\n bottleneck_widths = [int(w * b) for w, b in zip(widths, bottle_ratios)]\n groups = [min(g, w_bot) for g, w_bot in zip(groups, bottleneck_widths)]\n bottleneck_widths = [quantize_float(w_bot, g) for w_bot, g in zip(bottleneck_widths, groups)]\n widths = [int(w_bot / b) for w_bot, b in zip(bottleneck_widths, bottle_ratios)]\n return widths, groups\n\n\ndef generate_regnet(width_slope, width_initial, width_mult, depth, q=8):\n \"\"\"Generates per block widths from RegNet parameters.\"\"\"\n assert width_slope >= 0 and width_initial > 0 and width_mult > 1 and width_initial % q == 0\n widths_cont = np.arange(depth) * width_slope + width_initial\n width_exps = np.round(np.log(widths_cont / width_initial) / np.log(width_mult))\n widths = width_initial * np.power(width_mult, width_exps)\n widths = np.round(np.divide(widths, q)) * q\n num_stages, max_stage = len(np.unique(widths)), width_exps.max() + 1\n widths, widths_cont = widths.astype(int).tolist(), widths_cont.tolist()\n return widths, num_stages, max_stage, widths_cont\n\n\nclass Bottleneck(nn.Module):\n \"\"\" RegNet Bottleneck\n\n This is almost exactly the same as a ResNet Bottlneck. The main difference is the SE block is moved from\n after conv3 to after conv2. Otherwise, it's just redefining the arguments for groups/bottleneck channels.\n \"\"\"\n\n def __init__(self, in_chs, out_chs, stride=1, dilation=1, bottleneck_ratio=1, group_width=1, se_ratio=0.25,\n downsample=None, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, aa_layer=None,\n drop_block=None, drop_path=None):\n super(Bottleneck, self).__init__()\n bottleneck_chs = int(round(out_chs * bottleneck_ratio))\n groups = bottleneck_chs // group_width\n\n cargs = dict(act_layer=act_layer, norm_layer=norm_layer, aa_layer=aa_layer, drop_block=drop_block)\n self.conv1 = ConvBnAct(in_chs, bottleneck_chs, kernel_size=1, **cargs)\n self.conv2 = ConvBnAct(\n bottleneck_chs, bottleneck_chs, kernel_size=3, stride=stride, dilation=dilation,\n groups=groups, **cargs)\n if se_ratio:\n se_channels = int(round(in_chs * se_ratio))\n self.se = SEModule(bottleneck_chs, reduction_channels=se_channels)\n else:\n self.se = None\n cargs['act_layer'] = None\n self.conv3 = ConvBnAct(bottleneck_chs, out_chs, kernel_size=1, **cargs)\n self.act3 = act_layer(inplace=True)\n self.downsample = downsample\n self.drop_path = drop_path\n\n def zero_init_last_bn(self):\n nn.init.zeros_(self.conv3.bn.weight)\n\n def forward(self, x):\n shortcut = x\n x = self.conv1(x)\n x = self.conv2(x)\n if self.se is not None:\n x = self.se(x)\n x = self.conv3(x)\n if self.drop_path is not None:\n x = self.drop_path(x)\n if self.downsample is not None:\n shortcut = self.downsample(shortcut)\n x += shortcut\n x = self.act3(x)\n return x\n\n\ndef downsample_conv(\n in_chs, out_chs, kernel_size, stride=1, dilation=1, norm_layer=None):\n norm_layer = norm_layer or nn.BatchNorm2d\n kernel_size = 1 if stride == 1 and dilation == 1 else kernel_size\n dilation = dilation if kernel_size > 1 else 1\n return ConvBnAct(\n in_chs, out_chs, kernel_size, stride=stride, dilation=dilation, norm_layer=norm_layer, act_layer=None)\n\n\ndef downsample_avg(\n in_chs, out_chs, kernel_size, stride=1, dilation=1, norm_layer=None):\n \"\"\" AvgPool Downsampling as in 'D' ResNet variants. This is not in RegNet space but I might experiment.\"\"\"\n norm_layer = norm_layer or nn.BatchNorm2d\n avg_stride = stride if dilation == 1 else 1\n pool = nn.Identity()\n if stride > 1 or dilation > 1:\n avg_pool_fn = AvgPool2dSame if avg_stride == 1 and dilation > 1 else nn.AvgPool2d\n pool = avg_pool_fn(2, avg_stride, ceil_mode=True, count_include_pad=False)\n return nn.Sequential(*[\n pool, ConvBnAct(in_chs, out_chs, 1, stride=1, norm_layer=norm_layer, act_layer=None)])\n\n\nclass RegStage(nn.Module):\n \"\"\"Stage (sequence of blocks w/ the same output shape).\"\"\"\n\n def __init__(self, in_chs, out_chs, stride, dilation, depth, bottle_ratio, group_width,\n block_fn=Bottleneck, se_ratio=0., drop_path_rates=None, drop_block=None):\n super(RegStage, self).__init__()\n block_kwargs = {} # FIXME setup to pass various aa, norm, act layer common args\n first_dilation = 1 if dilation in (1, 2) else 2\n for i in range(depth):\n block_stride = stride if i == 0 else 1\n block_in_chs = in_chs if i == 0 else out_chs\n block_dilation = first_dilation if i == 0 else dilation\n if drop_path_rates is not None and drop_path_rates[i] > 0.:\n drop_path = DropPath(drop_path_rates[i])\n else:\n drop_path = None\n if (block_in_chs != out_chs) or (block_stride != 1):\n proj_block = downsample_conv(block_in_chs, out_chs, 1, block_stride, block_dilation)\n else:\n proj_block = None\n\n name = \"b{}\".format(i + 1)\n self.add_module(\n name, block_fn(\n block_in_chs, out_chs, block_stride, block_dilation, bottle_ratio, group_width, se_ratio,\n downsample=proj_block, drop_block=drop_block, drop_path=drop_path, **block_kwargs)\n )\n\n def forward(self, x):\n for block in self.children():\n x = block(x)\n return x\n\n\nclass RegNet(nn.Module):\n \"\"\"RegNet model.\n\n Paper: https://arxiv.org/abs/2003.13678\n Original Impl: https://github.com/facebookresearch/pycls/blob/master/pycls/models/regnet.py\n \"\"\"\n\n def __init__(self, cfg, in_chans=3, num_classes=1000, output_stride=32, global_pool='avg', drop_rate=0.,\n drop_path_rate=0., zero_init_last_bn=True, in_channels=3, in_size=(224, 224)):\n super().__init__()\n # TODO add drop block, drop path, anti-aliasing, custom bn/act args\n self.in_size = in_size\n self.num_classes = num_classes\n self.drop_rate = drop_rate\n assert output_stride in (8, 16, 32)\n\n # Construct the stem\n stem_width = cfg['stem_width']\n self.stem = ConvBnAct(in_chans, stem_width, 3, stride=2)\n self.feature_info = [dict(num_chs=stem_width, reduction=2, module='stem')]\n\n # Construct the stages\n prev_width = stem_width\n curr_stride = 2\n stage_params = self._get_stage_params(cfg, output_stride=output_stride, drop_path_rate=drop_path_rate)\n se_ratio = cfg['se_ratio']\n for i, stage_args in enumerate(stage_params):\n stage_name = \"s{}\".format(i + 1)\n self.add_module(stage_name, RegStage(prev_width, se_ratio=se_ratio, **stage_args))\n prev_width = stage_args['out_chs']\n curr_stride *= stage_args['stride']\n self.feature_info += [dict(num_chs=prev_width, reduction=curr_stride, module=stage_name)]\n\n # Construct the head\n self.num_features = prev_width\n self.head = ClassifierHead(\n in_chs=prev_width, num_classes=num_classes, pool_type=global_pool, drop_rate=drop_rate)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.ones_(m.weight)\n nn.init.zeros_(m.bias)\n elif isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, mean=0.0, std=0.01)\n nn.init.zeros_(m.bias)\n if zero_init_last_bn:\n for m in self.modules():\n if hasattr(m, 'zero_init_last_bn'):\n m.zero_init_last_bn()\n\n def _get_stage_params(self, cfg, default_stride=2, output_stride=32, drop_path_rate=0.):\n # Generate RegNet ws per block\n w_a, w_0, w_m, d = cfg['wa'], cfg['w0'], cfg['wm'], cfg['depth']\n widths, num_stages, _, _ = generate_regnet(w_a, w_0, w_m, d)\n\n # Convert to per stage format\n stage_widths, stage_depths = np.unique(widths, return_counts=True)\n\n # Use the same group width, bottleneck mult and stride for each stage\n stage_groups = [cfg['group_w'] for _ in range(num_stages)]\n stage_bottle_ratios = [cfg['bottle_ratio'] for _ in range(num_stages)]\n stage_strides = []\n stage_dilations = []\n net_stride = 2\n dilation = 1\n for _ in range(num_stages):\n if net_stride >= output_stride:\n dilation *= default_stride\n stride = 1\n else:\n stride = default_stride\n net_stride *= stride\n stage_strides.append(stride)\n stage_dilations.append(dilation)\n stage_dpr = np.split(np.linspace(0, drop_path_rate, d), np.cumsum(stage_depths[:-1]))\n\n # Adjust the compatibility of ws and gws\n stage_widths, stage_groups = adjust_widths_groups_comp(stage_widths, stage_bottle_ratios, stage_groups)\n param_names = ['out_chs', 'stride', 'dilation', 'depth', 'bottle_ratio', 'group_width', 'drop_path_rates']\n stage_params = [\n dict(zip(param_names, params)) for params in\n zip(stage_widths, stage_strides, stage_dilations, stage_depths, stage_bottle_ratios, stage_groups,\n stage_dpr)]\n return stage_params\n\n def get_classifier(self):\n return self.head.fc\n\n def reset_classifier(self, num_classes, global_pool='avg'):\n self.head = ClassifierHead(self.num_features, num_classes, pool_type=global_pool, drop_rate=self.drop_rate)\n\n def forward_features(self, x):\n for block in list(self.children())[:-1]:\n x = block(x)\n return x\n\n def forward(self, x):\n for block in self.children():\n x = block(x)\n return x\n\n\ndef _create_regnet(variant, pretrained, **kwargs):\n return build_model_with_cfg(\n model_cls=RegNet,\n variant=variant,\n pretrained=pretrained,\n default_cfg=default_cfgs[variant],\n model_cfg=model_cfgs[variant],\n **kwargs)\n\n\ndef regnetx_002(pretrained=False, **kwargs):\n \"\"\"RegNetX-200MF\"\"\"\n return _create_regnet('regnetx_002', pretrained, **kwargs)\n\n\ndef regnetx_004(pretrained=False, **kwargs):\n \"\"\"RegNetX-400MF\"\"\"\n return _create_regnet('regnetx_004', pretrained, **kwargs)\n\n\ndef regnetx_006(pretrained=False, **kwargs):\n \"\"\"RegNetX-600MF\"\"\"\n return _create_regnet('regnetx_006', pretrained, **kwargs)\n\n\ndef regnetx_008(pretrained=False, **kwargs):\n \"\"\"RegNetX-800MF\"\"\"\n return _create_regnet('regnetx_008', pretrained, **kwargs)\n\n\ndef regnetx_016(pretrained=False, **kwargs):\n \"\"\"RegNetX-1.6GF\"\"\"\n return _create_regnet('regnetx_016', pretrained, **kwargs)\n\n\ndef regnetx_032(pretrained=False, **kwargs):\n \"\"\"RegNetX-3.2GF\"\"\"\n return _create_regnet('regnetx_032', pretrained, **kwargs)\n\n\ndef regnetx_040(pretrained=False, **kwargs):\n \"\"\"RegNetX-4.0GF\"\"\"\n return _create_regnet('regnetx_040', pretrained, **kwargs)\n\n\ndef regnetx_064(pretrained=False, **kwargs):\n \"\"\"RegNetX-6.4GF\"\"\"\n return _create_regnet('regnetx_064', pretrained, **kwargs)\n\n\ndef regnetx_080(pretrained=False, **kwargs):\n \"\"\"RegNetX-8.0GF\"\"\"\n return _create_regnet('regnetx_080', pretrained, **kwargs)\n\n\ndef regnetx_120(pretrained=False, **kwargs):\n \"\"\"RegNetX-12GF\"\"\"\n return _create_regnet('regnetx_120', pretrained, **kwargs)\n\n\ndef regnetx_160(pretrained=False, **kwargs):\n \"\"\"RegNetX-16GF\"\"\"\n return _create_regnet('regnetx_160', pretrained, **kwargs)\n\n\ndef regnetx_320(pretrained=False, **kwargs):\n \"\"\"RegNetX-32GF\"\"\"\n return _create_regnet('regnetx_320', pretrained, **kwargs)\n\n\ndef regnety_002(pretrained=False, **kwargs):\n \"\"\"RegNetY-200MF\"\"\"\n return _create_regnet('regnety_002', pretrained, **kwargs)\n\n\ndef regnety_004(pretrained=False, **kwargs):\n \"\"\"RegNetY-400MF\"\"\"\n return _create_regnet('regnety_004', pretrained, **kwargs)\n\n\ndef regnety_006(pretrained=False, **kwargs):\n \"\"\"RegNetY-600MF\"\"\"\n return _create_regnet('regnety_006', pretrained, **kwargs)\n\n\ndef regnety_008(pretrained=False, **kwargs):\n \"\"\"RegNetY-800MF\"\"\"\n return _create_regnet('regnety_008', pretrained, **kwargs)\n\n\ndef regnety_016(pretrained=False, **kwargs):\n \"\"\"RegNetY-1.6GF\"\"\"\n return _create_regnet('regnety_016', pretrained, **kwargs)\n\n\ndef regnety_032(pretrained=False, **kwargs):\n \"\"\"RegNetY-3.2GF\"\"\"\n return _create_regnet('regnety_032', pretrained, **kwargs)\n\n\ndef regnety_040(pretrained=False, **kwargs):\n \"\"\"RegNetY-4.0GF\"\"\"\n return _create_regnet('regnety_040', pretrained, **kwargs)\n\n\ndef regnety_064(pretrained=False, **kwargs):\n \"\"\"RegNetY-6.4GF\"\"\"\n return _create_regnet('regnety_064', pretrained, **kwargs)\n\n\ndef regnety_080(pretrained=False, **kwargs):\n \"\"\"RegNetY-8.0GF\"\"\"\n return _create_regnet('regnety_080', pretrained, **kwargs)\n\n\ndef regnety_120(pretrained=False, **kwargs):\n \"\"\"RegNetY-12GF\"\"\"\n return _create_regnet('regnety_120', pretrained, **kwargs)\n\n\ndef regnety_160(pretrained=False, **kwargs):\n \"\"\"RegNetY-16GF\"\"\"\n return _create_regnet('regnety_160', pretrained, **kwargs)\n\n\ndef regnety_320(pretrained=False, **kwargs):\n \"\"\"RegNetY-32GF\"\"\"\n return _create_regnet('regnety_320', pretrained, **kwargs)\n\n\ndef _calc_width(net):\n import numpy as np\n net_params = filter(lambda p: p.requires_grad, net.parameters())\n weight_count = 0\n for param in net_params:\n weight_count += np.prod(param.size())\n return weight_count\n\n\ndef _test():\n import torch\n\n pretrained = False\n\n models = [\n regnetx_002,\n regnetx_004,\n regnetx_006,\n regnetx_008,\n regnetx_016,\n regnetx_032,\n regnetx_040,\n regnetx_064,\n regnetx_080,\n regnetx_120,\n regnetx_160,\n regnetx_320,\n\n regnety_002,\n regnety_004,\n regnety_006,\n regnety_008,\n regnety_016,\n regnety_032,\n regnety_040,\n regnety_064,\n regnety_080,\n regnety_120,\n regnety_160,\n regnety_320,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n\n # net.train()\n net.eval()\n weight_count = _calc_width(net)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != regnetx_002 or weight_count == 2684792)\n assert (model != regnetx_004 or weight_count == 5157512)\n assert (model != regnetx_006 or weight_count == 6196040)\n assert (model != regnetx_008 or weight_count == 7259656)\n assert (model != regnetx_016 or weight_count == 9190136)\n assert (model != regnetx_032 or weight_count == 15296552)\n assert (model != regnetx_040 or weight_count == 22118248)\n assert (model != regnetx_064 or weight_count == 26209256)\n assert (model != regnetx_080 or weight_count == 39572648)\n assert (model != regnetx_120 or weight_count == 46106056)\n assert (model != regnetx_160 or weight_count == 54278536)\n assert (model != regnetx_320 or weight_count == 107811560)\n\n assert (model != regnety_002 or weight_count == 3162996)\n assert (model != regnety_004 or weight_count == 4344144)\n assert (model != regnety_006 or weight_count == 6055160)\n assert (model != regnety_008 or weight_count == 6263168)\n assert (model != regnety_016 or weight_count == 11202430)\n assert (model != regnety_032 or weight_count == 19436338)\n assert (model != regnety_040 or weight_count == 20646656)\n assert (model != regnety_064 or weight_count == 30583252)\n assert (model != regnety_080 or weight_count == 39180068)\n assert (model != regnety_120 or weight_count == 51822544)\n assert (model != regnety_160 or weight_count == 83590140)\n assert (model != regnety_320 or weight_count == 145046770)\n\n x = torch.randn(1, 3, 224, 224)\n y = net(x)\n y.sum().backward()\n assert (tuple(y.size()) == (1, 1000))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n ProxylessNAS for ImageNet-1K, implemented in TensorFlow.\n Original paper: 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'\n https://arxiv.org/abs/1812.00332.\n\"\"\"\n\n__all__ = ['ProxylessNAS', 'proxylessnas_cpu', 'proxylessnas_gpu', 'proxylessnas_mobile', 'proxylessnas_mobile14',\n 'ProxylessUnit', 'get_proxylessnas']\n\nimport os\nimport tensorflow as tf\nimport tensorflow.keras.layers as nn\nfrom .common import ConvBlock, conv1x1_block, conv3x3_block, flatten, is_channels_first\n\n\nclass ProxylessBlock(nn.Layer):\n \"\"\"\n ProxylessNAS block for residual path in ProxylessNAS unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int\n Convolution window size.\n strides : int\n Strides of the convolution.\n bn_eps : float\n Small float added to variance in Batch norm.\n expansion : int\n Expansion ratio.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n strides,\n bn_eps,\n expansion,\n data_format=\"channels_last\",\n **kwargs):\n super(ProxylessBlock, self).__init__(**kwargs)\n self.use_bc = (expansion > 1)\n mid_channels = in_channels * expansion\n\n if self.use_bc:\n self.bc_conv = conv1x1_block(\n in_channels=in_channels,\n out_channels=mid_channels,\n bn_eps=bn_eps,\n activation=\"relu6\",\n data_format=data_format,\n name=\"bc_conv\")\n\n padding = (kernel_size - 1) // 2\n self.dw_conv = ConvBlock(\n in_channels=mid_channels,\n out_channels=mid_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n groups=mid_channels,\n bn_eps=bn_eps,\n activation=\"relu6\",\n data_format=data_format,\n name=\"dw_conv\")\n self.pw_conv = conv1x1_block(\n in_channels=mid_channels,\n out_channels=out_channels,\n bn_eps=bn_eps,\n activation=None,\n data_format=data_format,\n name=\"pw_conv\")\n\n def call(self, x, training=None):\n if self.use_bc:\n x = self.bc_conv(x, training=training)\n x = self.dw_conv(x, training=training)\n x = self.pw_conv(x, training=training)\n return x\n\n\nclass ProxylessUnit(nn.Layer):\n \"\"\"\n ProxylessNAS unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int\n Convolution window size for body block.\n strides : int\n Strides of the convolution.\n bn_eps : float\n Small float added to variance in Batch norm.\n expansion : int\n Expansion ratio for body block.\n residual : bool\n Whether to use residual branch.\n shortcut : bool\n Whether to use identity branch.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n strides,\n bn_eps,\n expansion,\n residual,\n shortcut,\n data_format=\"channels_last\",\n **kwargs):\n super(ProxylessUnit, self).__init__(**kwargs)\n assert (residual or shortcut)\n self.residual = residual\n self.shortcut = shortcut\n\n if self.residual:\n self.body = ProxylessBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n strides=strides,\n bn_eps=bn_eps,\n expansion=expansion,\n data_format=data_format,\n name=\"body\")\n\n def call(self, x, training=None):\n if not self.residual:\n return x\n if not self.shortcut:\n return self.body(x, training=training)\n identity = x\n x = self.body(x, training=training)\n x = identity + x\n return x\n\n\nclass ProxylessNAS(tf.keras.Model):\n \"\"\"\n ProxylessNAS model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'\n https://arxiv.org/abs/1812.00332.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n final_block_channels : int\n Number of output channels for the final unit.\n residuals : list of list of int\n Whether to use residual branch in units.\n shortcuts : list of list of int\n Whether to use identity branch in units.\n kernel_sizes : list of list of int\n Convolution window size for each units.\n expansions : list of list of int\n Expansion ratio for each units.\n bn_eps : float, default 1e-3\n Small float added to variance in Batch norm.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n final_block_channels,\n residuals,\n shortcuts,\n kernel_sizes,\n expansions,\n bn_eps=1e-3,\n in_channels=3,\n in_size=(224, 224),\n classes=1000,\n data_format=\"channels_last\",\n **kwargs):\n super(ProxylessNAS, self).__init__(**kwargs)\n self.in_size = in_size\n self.classes = classes\n self.data_format = data_format\n\n self.features = tf.keras.Sequential(name=\"features\")\n self.features.add(conv3x3_block(\n in_channels=in_channels,\n out_channels=init_block_channels,\n strides=2,\n bn_eps=bn_eps,\n activation=\"relu6\",\n data_format=data_format,\n name=\"init_block\"))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = tf.keras.Sequential(name=\"stage{}\".format(i + 1))\n residuals_per_stage = residuals[i]\n shortcuts_per_stage = shortcuts[i]\n kernel_sizes_per_stage = kernel_sizes[i]\n expansions_per_stage = expansions[i]\n for j, out_channels in enumerate(channels_per_stage):\n residual = (residuals_per_stage[j] == 1)\n shortcut = (shortcuts_per_stage[j] == 1)\n kernel_size = kernel_sizes_per_stage[j]\n expansion = expansions_per_stage[j]\n strides = 2 if (j == 0) and (i != 0) else 1\n stage.add(ProxylessUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n strides=strides,\n bn_eps=bn_eps,\n expansion=expansion,\n residual=residual,\n shortcut=shortcut,\n data_format=data_format,\n name=\"unit{}\".format(j + 1)))\n in_channels = out_channels\n self.features.add(stage)\n self.features.add(conv1x1_block(\n in_channels=in_channels,\n out_channels=final_block_channels,\n bn_eps=bn_eps,\n activation=\"relu6\",\n data_format=data_format,\n name=\"final_block\"))\n in_channels = final_block_channels\n self.features.add(nn.AveragePooling2D(\n pool_size=7,\n strides=1,\n data_format=data_format,\n name=\"final_pool\"))\n\n self.output1 = nn.Dense(\n units=classes,\n input_dim=in_channels,\n name=\"output1\")\n\n def call(self, x, training=None):\n x = self.features(x, training=training)\n x = flatten(x, self.data_format)\n x = self.output1(x)\n return x\n\n\ndef get_proxylessnas(version,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".tensorflow\", \"models\"),\n **kwargs):\n \"\"\"\n Create ProxylessNAS model with specific parameters.\n\n Parameters:\n ----------\n version : str\n Version of ProxylessNAS ('cpu', 'gpu', 'mobile' or 'mobile14').\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n\n if version == \"cpu\":\n residuals = [[1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]\n channels = [[24], [32, 32, 32, 32], [48, 48, 48, 48], [88, 88, 88, 88, 104, 104, 104, 104],\n [216, 216, 216, 216, 360]]\n kernel_sizes = [[3], [3, 3, 3, 3], [3, 3, 3, 5], [3, 3, 3, 3, 5, 3, 3, 3], [5, 5, 5, 3, 5]]\n expansions = [[1], [6, 3, 3, 3], [6, 3, 3, 3], [6, 3, 3, 3, 6, 3, 3, 3], [6, 3, 3, 3, 6]]\n init_block_channels = 40\n final_block_channels = 1432\n elif version == \"gpu\":\n residuals = [[1], [1, 0, 0, 0], [1, 0, 0, 1], [1, 0, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1]]\n channels = [[24], [32, 32, 32, 32], [56, 56, 56, 56], [112, 112, 112, 112, 128, 128, 128, 128],\n [256, 256, 256, 256, 432]]\n kernel_sizes = [[3], [5, 3, 3, 3], [7, 3, 3, 3], [7, 5, 5, 5, 5, 3, 3, 5], [7, 7, 7, 5, 7]]\n expansions = [[1], [3, 3, 3, 3], [3, 3, 3, 3], [6, 3, 3, 3, 6, 3, 3, 3], [6, 6, 6, 6, 6]]\n init_block_channels = 40\n final_block_channels = 1728\n elif version == \"mobile\":\n residuals = [[1], [1, 1, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]\n channels = [[16], [32, 32, 32, 32], [40, 40, 40, 40], [80, 80, 80, 80, 96, 96, 96, 96],\n [192, 192, 192, 192, 320]]\n kernel_sizes = [[3], [5, 3, 3, 3], [7, 3, 5, 5], [7, 5, 5, 5, 5, 5, 5, 5], [7, 7, 7, 7, 7]]\n expansions = [[1], [3, 3, 3, 3], [3, 3, 3, 3], [6, 3, 3, 3, 6, 3, 3, 3], [6, 6, 3, 3, 6]]\n init_block_channels = 32\n final_block_channels = 1280\n elif version == \"mobile14\":\n residuals = [[1], [1, 1, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]\n channels = [[24], [40, 40, 40, 40], [56, 56, 56, 56], [112, 112, 112, 112, 136, 136, 136, 136],\n [256, 256, 256, 256, 448]]\n kernel_sizes = [[3], [5, 3, 3, 3], [7, 3, 5, 5], [7, 5, 5, 5, 5, 5, 5, 5], [7, 7, 7, 7, 7]]\n expansions = [[1], [3, 3, 3, 3], [3, 3, 3, 3], [6, 3, 3, 3, 6, 3, 3, 3], [6, 6, 3, 3, 6]]\n init_block_channels = 48\n final_block_channels = 1792\n else:\n raise ValueError(\"Unsupported ProxylessNAS version: {}\".format(version))\n\n shortcuts = [[0], [0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1, 0, 1, 1, 1], [0, 1, 1, 1, 0]]\n\n net = ProxylessNAS(\n channels=channels,\n init_block_channels=init_block_channels,\n final_block_channels=final_block_channels,\n residuals=residuals,\n shortcuts=shortcuts,\n kernel_sizes=kernel_sizes,\n expansions=expansions,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n in_channels = kwargs[\"in_channels\"] if (\"in_channels\" in kwargs) else 3\n input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == \"channels_first\" else\\\n (1,) + net.in_size + (in_channels,)\n net.build(input_shape=input_shape)\n net.load_weights(\n filepath=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root))\n\n return net\n\n\ndef proxylessnas_cpu(**kwargs):\n \"\"\"\n ProxylessNAS (CPU) model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'\n https://arxiv.org/abs/1812.00332.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_proxylessnas(version=\"cpu\", model_name=\"proxylessnas_cpu\", **kwargs)\n\n\ndef proxylessnas_gpu(**kwargs):\n \"\"\"\n ProxylessNAS (GPU) model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'\n https://arxiv.org/abs/1812.00332.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_proxylessnas(version=\"gpu\", model_name=\"proxylessnas_gpu\", **kwargs)\n\n\ndef proxylessnas_mobile(**kwargs):\n \"\"\"\n ProxylessNAS (Mobile) model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'\n https://arxiv.org/abs/1812.00332.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_proxylessnas(version=\"mobile\", model_name=\"proxylessnas_mobile\", **kwargs)\n\n\ndef proxylessnas_mobile14(**kwargs):\n \"\"\"\n ProxylessNAS (Mobile-14) model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'\n https://arxiv.org/abs/1812.00332.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_proxylessnas(version=\"mobile14\", model_name=\"proxylessnas_mobile14\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import tensorflow.keras.backend as K\n\n data_format = \"channels_last\"\n pretrained = False\n\n models = [\n proxylessnas_cpu,\n proxylessnas_gpu,\n proxylessnas_mobile,\n proxylessnas_mobile14,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained, data_format=data_format)\n\n batch = 14\n x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3))\n y = net(x)\n assert (tuple(y.shape.as_list()) == (batch, 1000))\n\n weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights])\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != proxylessnas_cpu or weight_count == 4361648)\n assert (model != proxylessnas_gpu or weight_count == 7119848)\n assert (model != proxylessnas_mobile or weight_count == 4080512)\n assert (model != proxylessnas_mobile14 or weight_count == 6857568)\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n SE-ResNet for CIFAR/SVHN, implemented in TensorFlow.\n Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\"\"\"\n\n__all__ = ['CIFARSEResNet', 'seresnet20_cifar10', 'seresnet20_cifar100', 'seresnet20_svhn',\n 'seresnet56_cifar10', 'seresnet56_cifar100', 'seresnet56_svhn',\n 'seresnet110_cifar10', 'seresnet110_cifar100', 'seresnet110_svhn',\n 'seresnet164bn_cifar10', 'seresnet164bn_cifar100', 'seresnet164bn_svhn',\n 'seresnet272bn_cifar10', 'seresnet272bn_cifar100', 'seresnet272bn_svhn',\n 'seresnet542bn_cifar10', 'seresnet542bn_cifar100', 'seresnet542bn_svhn',\n 'seresnet1001_cifar10', 'seresnet1001_cifar100', 'seresnet1001_svhn',\n 'seresnet1202_cifar10', 'seresnet1202_cifar100', 'seresnet1202_svhn']\n\nimport os\nimport tensorflow as tf\nimport tensorflow.keras.layers as nn\nfrom .common import conv3x3_block, flatten, is_channels_first\nfrom .seresnet import SEResUnit\n\n\nclass CIFARSEResNet(tf.keras.Model):\n \"\"\"\n SE-ResNet model for CIFAR from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n bottleneck : bool\n Whether to use a bottleneck or simple block in units.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (32, 32)\n Spatial size of the expected input image.\n classes : int, default 10\n Number of classification classes.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n bottleneck,\n in_channels=3,\n in_size=(32, 32),\n classes=10,\n data_format=\"channels_last\",\n **kwargs):\n super(CIFARSEResNet, self).__init__(**kwargs)\n self.in_size = in_size\n self.classes = classes\n self.data_format = data_format\n\n self.features = tf.keras.Sequential(name=\"features\")\n self.features.add(conv3x3_block(\n in_channels=in_channels,\n out_channels=init_block_channels,\n data_format=data_format,\n name=\"init_block\"))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = tf.keras.Sequential(name=\"stage{}\".format(i + 1))\n for j, out_channels in enumerate(channels_per_stage):\n strides = 2 if (j == 0) and (i != 0) else 1\n stage.add(SEResUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n bottleneck=bottleneck,\n conv1_stride=False,\n data_format=data_format,\n name=\"unit{}\".format(j + 1)))\n in_channels = out_channels\n self.features.add(stage)\n self.features.add(nn.AveragePooling2D(\n pool_size=8,\n strides=1,\n data_format=data_format,\n name=\"final_pool\"))\n\n self.output1 = nn.Dense(\n units=classes,\n input_dim=in_channels,\n name=\"output1\")\n\n def call(self, x, training=None):\n x = self.features(x, training=training)\n x = flatten(x, self.data_format)\n x = self.output1(x)\n return x\n\n\ndef get_seresnet_cifar(classes,\n blocks,\n bottleneck,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".tensorflow\", \"models\"),\n **kwargs):\n \"\"\"\n Create SE-ResNet model for CIFAR with specific parameters.\n\n Parameters:\n ----------\n classes : int\n Number of classification classes.\n blocks : int\n Number of blocks.\n bottleneck : bool\n Whether to use a bottleneck or simple block in units.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n assert (classes in [10, 100])\n\n if bottleneck:\n assert ((blocks - 2) % 9 == 0)\n layers = [(blocks - 2) // 9] * 3\n else:\n assert ((blocks - 2) % 6 == 0)\n layers = [(blocks - 2) // 6] * 3\n\n channels_per_layers = [16, 32, 64]\n init_block_channels = 16\n\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n if bottleneck:\n channels = [[cij * 4 for cij in ci] for ci in channels]\n\n net = CIFARSEResNet(\n channels=channels,\n init_block_channels=init_block_channels,\n bottleneck=bottleneck,\n classes=classes,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n in_channels = kwargs[\"in_channels\"] if (\"in_channels\" in kwargs) else 3\n input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == \"channels_first\" else\\\n (1,) + net.in_size + (in_channels,)\n net.build(input_shape=input_shape)\n net.load_weights(\n filepath=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root))\n\n return net\n\n\ndef seresnet20_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-20 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name=\"seresnet20_cifar10\", **kwargs)\n\n\ndef seresnet20_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-20 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name=\"seresnet20_cifar100\", **kwargs)\n\n\ndef seresnet20_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-20 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name=\"seresnet20_svhn\", **kwargs)\n\n\ndef seresnet56_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-56 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name=\"seresnet56_cifar10\", **kwargs)\n\n\ndef seresnet56_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-56 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name=\"seresnet56_cifar100\", **kwargs)\n\n\ndef seresnet56_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-56 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name=\"seresnet56_svhn\", **kwargs)\n\n\ndef seresnet110_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-110 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name=\"seresnet110_cifar10\", **kwargs)\n\n\ndef seresnet110_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-110 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name=\"seresnet110_cifar100\",\n **kwargs)\n\n\ndef seresnet110_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-110 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name=\"seresnet110_svhn\", **kwargs)\n\n\ndef seresnet164bn_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-164(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name=\"seresnet164bn_cifar10\",\n **kwargs)\n\n\ndef seresnet164bn_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-164(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name=\"seresnet164bn_cifar100\",\n **kwargs)\n\n\ndef seresnet164bn_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-164(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name=\"seresnet164bn_svhn\", **kwargs)\n\n\ndef seresnet272bn_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-272(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name=\"seresnet272bn_cifar10\",\n **kwargs)\n\n\ndef seresnet272bn_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-272(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name=\"seresnet272bn_cifar100\",\n **kwargs)\n\n\ndef seresnet272bn_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-272(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name=\"seresnet272bn_svhn\", **kwargs)\n\n\ndef seresnet542bn_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-542(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name=\"seresnet542bn_cifar10\",\n **kwargs)\n\n\ndef seresnet542bn_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-542(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name=\"seresnet542bn_cifar100\",\n **kwargs)\n\n\ndef seresnet542bn_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-542(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name=\"seresnet542bn_svhn\", **kwargs)\n\n\ndef seresnet1001_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-1001 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name=\"seresnet1001_cifar10\",\n **kwargs)\n\n\ndef seresnet1001_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-1001 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name=\"seresnet1001_cifar100\",\n **kwargs)\n\n\ndef seresnet1001_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-1001 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name=\"seresnet1001_svhn\", **kwargs)\n\n\ndef seresnet1202_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-1202 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name=\"seresnet1202_cifar10\",\n **kwargs)\n\n\ndef seresnet1202_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-1202 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name=\"seresnet1202_cifar100\",\n **kwargs)\n\n\ndef seresnet1202_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-1202 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name=\"seresnet1202_svhn\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import tensorflow.keras.backend as K\n\n data_format = \"channels_last\"\n # data_format = \"channels_first\"\n pretrained = False\n\n models = [\n (seresnet20_cifar10, 10),\n (seresnet20_cifar100, 100),\n (seresnet20_svhn, 10),\n (seresnet56_cifar10, 10),\n (seresnet56_cifar100, 100),\n (seresnet56_svhn, 10),\n (seresnet110_cifar10, 10),\n (seresnet110_cifar100, 100),\n (seresnet110_svhn, 10),\n (seresnet164bn_cifar10, 10),\n (seresnet164bn_cifar100, 100),\n (seresnet164bn_svhn, 10),\n (seresnet272bn_cifar10, 10),\n (seresnet272bn_cifar100, 100),\n (seresnet272bn_svhn, 10),\n (seresnet542bn_cifar10, 10),\n (seresnet542bn_cifar100, 100),\n (seresnet542bn_svhn, 10),\n (seresnet1001_cifar10, 10),\n (seresnet1001_cifar100, 100),\n (seresnet1001_svhn, 10),\n (seresnet1202_cifar10, 10),\n (seresnet1202_cifar100, 100),\n (seresnet1202_svhn, 10),\n ]\n\n for model, classes in models:\n\n net = model(pretrained=pretrained, data_format=data_format)\n\n batch = 14\n x = tf.random.normal((batch, 3, 32, 32) if is_channels_first(data_format) else (batch, 32, 32, 3))\n y = net(x)\n assert (tuple(y.shape.as_list()) == (batch, classes))\n\n weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights])\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != seresnet20_cifar10 or weight_count == 274847)\n assert (model != seresnet20_cifar100 or weight_count == 280697)\n assert (model != seresnet20_svhn or weight_count == 274847)\n assert (model != seresnet56_cifar10 or weight_count == 862889)\n assert (model != seresnet56_cifar100 or weight_count == 868739)\n assert (model != seresnet56_svhn or weight_count == 862889)\n assert (model != seresnet110_cifar10 or weight_count == 1744952)\n assert (model != seresnet110_cifar100 or weight_count == 1750802)\n assert (model != seresnet110_svhn or weight_count == 1744952)\n assert (model != seresnet164bn_cifar10 or weight_count == 1906258)\n assert (model != seresnet164bn_cifar100 or weight_count == 1929388)\n assert (model != seresnet164bn_svhn or weight_count == 1906258)\n assert (model != seresnet272bn_cifar10 or weight_count == 3153826)\n assert (model != seresnet272bn_cifar100 or weight_count == 3176956)\n assert (model != seresnet272bn_svhn or weight_count == 3153826)\n assert (model != seresnet542bn_cifar10 or weight_count == 6272746)\n assert (model != seresnet542bn_cifar100 or weight_count == 6295876)\n assert (model != seresnet542bn_svhn or weight_count == 6272746)\n assert (model != seresnet1001_cifar10 or weight_count == 11574910)\n assert (model != seresnet1001_cifar100 or weight_count == 11598040)\n assert (model != seresnet1001_svhn or weight_count == 11574910)\n assert (model != seresnet1202_cifar10 or weight_count == 19582226)\n assert (model != seresnet1202_cifar100 or weight_count == 19588076)\n assert (model != seresnet1202_svhn or weight_count == 19582226)\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n MobileNet(B) with simplified depthwise separable convolution block for ImageNet-1K, implemented in Gluon.\n Original paper: 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'\n https://arxiv.org/abs/1704.04861.\n\"\"\"\n\n__all__ = ['mobilenetb_w1', 'mobilenetb_w3d4', 'mobilenetb_wd2', 'mobilenetb_wd4']\n\nfrom .mobilenet import get_mobilenet\n\n\ndef mobilenetb_w1(**kwargs):\n \"\"\"\n 1.0 MobileNet(B)-224 model with simplified depthwise separable convolution block from 'MobileNets: Efficient\n Convolutional Neural Networks for Mobile Vision Applications,' https://arxiv.org/abs/1704.04861.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_mobilenet(width_scale=1.0, dws_simplified=True, model_name=\"mobilenetb_w1\", **kwargs)\n\n\ndef mobilenetb_w3d4(**kwargs):\n \"\"\"\n 0.75 MobileNet(B)-224 model with simplified depthwise separable convolution block from 'MobileNets: Efficient\n Convolutional Neural Networks for Mobile Vision Applications,' https://arxiv.org/abs/1704.04861.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_mobilenet(width_scale=0.75, dws_simplified=True, model_name=\"mobilenetb_w3d4\", **kwargs)\n\n\ndef mobilenetb_wd2(**kwargs):\n \"\"\"\n 0.5 MobileNet(B)-224 model with simplified depthwise separable convolution block from 'MobileNets: Efficient\n Convolutional Neural Networks for Mobile Vision Applications,' https://arxiv.org/abs/1704.04861.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_mobilenet(width_scale=0.5, dws_simplified=True, model_name=\"mobilenetb_wd2\", **kwargs)\n\n\ndef mobilenetb_wd4(**kwargs):\n \"\"\"\n 0.25 MobileNet(B)-224 model with simplified depthwise separable convolution block from 'MobileNets: Efficient\n Convolutional Neural Networks for Mobile Vision Applications,' https://arxiv.org/abs/1704.04861.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_mobilenet(width_scale=0.25, dws_simplified=True, model_name=\"mobilenetb_wd4\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import tensorflow as tf\n import tensorflow.keras.backend as K\n\n pretrained = False\n\n models = [\n mobilenetb_w1,\n mobilenetb_w3d4,\n mobilenetb_wd2,\n mobilenetb_wd4,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n\n batch = 14\n x = tf.random.normal((batch, 224, 224, 3))\n y = net(x)\n assert (tuple(y.shape.as_list()) == (batch, 1000))\n\n weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights])\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != mobilenetb_w1 or weight_count == 4222056)\n assert (model != mobilenetb_w3d4 or weight_count == 2578120)\n assert (model != mobilenetb_wd2 or weight_count == 1326632)\n assert (model != mobilenetb_wd4 or weight_count == 467592)\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n InceptionResNetV2 for ImageNet-1K, implemented in TensorFlow.\n Original paper: 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'\n https://arxiv.org/abs/1602.07261.\n\"\"\"\n\n__all__ = ['InceptionResNetV2', 'inceptionresnetv2']\n\nimport os\nimport tensorflow as tf\nimport tensorflow.keras.layers as nn\nfrom .common import MaxPool2d, AvgPool2d, Conv2d, BatchNorm, SimpleSequential, Concurrent, conv1x1, flatten,\\\n is_channels_first\n\n\nclass InceptConv(nn.Layer):\n \"\"\"\n InceptionResNetV2 specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n strides,\n padding,\n data_format=\"channels_last\",\n **kwargs):\n super(InceptConv, self).__init__(**kwargs)\n self.conv = Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n use_bias=False,\n data_format=data_format,\n name=\"conv\")\n self.bn = BatchNorm(\n momentum=0.1,\n epsilon=1e-3,\n data_format=data_format,\n name=\"bn\")\n self.activ = nn.ReLU()\n\n def call(self, x, training=None):\n x = self.conv(x)\n x = self.bn(x, training=training)\n x = self.activ(x)\n return x\n\n\ndef incept_conv1x1(in_channels,\n out_channels,\n data_format=\"channels_last\",\n **kwargs):\n \"\"\"\n 1x1 version of the InceptionResNetV2 specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n return InceptConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=1,\n strides=1,\n padding=0,\n data_format=data_format,\n **kwargs)\n\n\nclass MaxPoolBranch(nn.Layer):\n \"\"\"\n InceptionResNetV2 specific max pooling branch block.\n\n Parameters:\n ----------\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n data_format=\"channels_last\",\n **kwargs):\n super(MaxPoolBranch, self).__init__(**kwargs)\n self.pool = MaxPool2d(\n pool_size=3,\n strides=2,\n padding=0,\n data_format=data_format,\n name=\"pool\")\n\n def call(self, x, training=None):\n x = self.pool(x)\n return x\n\n\nclass AvgPoolBranch(nn.Layer):\n \"\"\"\n InceptionResNetV2 specific average pooling branch block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n data_format=\"channels_last\",\n **kwargs):\n super(AvgPoolBranch, self).__init__(**kwargs)\n self.pool = AvgPool2d(\n pool_size=3,\n strides=1,\n padding=1,\n # count_include_pad=False,\n data_format=data_format,\n name=\"pool\")\n self.conv = incept_conv1x1(\n in_channels=in_channels,\n out_channels=out_channels,\n data_format=data_format,\n name=\"conv\")\n\n def call(self, x, training=None):\n x = self.pool(x)\n x = self.conv(x, training=training)\n return x\n\n\nclass Conv1x1Branch(nn.Layer):\n \"\"\"\n InceptionResNetV2 specific convolutional 1x1 branch block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n data_format=\"channels_last\",\n **kwargs):\n super(Conv1x1Branch, self).__init__(**kwargs)\n self.conv = incept_conv1x1(\n in_channels=in_channels,\n out_channels=out_channels,\n data_format=data_format,\n name=\"conv\")\n\n def call(self, x, training=None):\n x = self.conv(x, training=training)\n return x\n\n\nclass ConvSeqBranch(nn.Layer):\n \"\"\"\n InceptionResNetV2 specific convolutional sequence branch block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels_list : list of tuple of int\n List of numbers of output channels.\n kernel_size_list : list of tuple of int or tuple of tuple/list of 2 int\n List of convolution window sizes.\n strides_list : list of tuple of int or tuple of tuple/list of 2 int\n List of strides of the convolution.\n padding_list : list of tuple of int or tuple of tuple/list of 2 int\n List of padding values for convolution layers.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels_list,\n kernel_size_list,\n strides_list,\n padding_list,\n data_format=\"channels_last\",\n **kwargs):\n super(ConvSeqBranch, self).__init__(**kwargs)\n assert (len(out_channels_list) == len(kernel_size_list))\n assert (len(out_channels_list) == len(strides_list))\n assert (len(out_channels_list) == len(padding_list))\n\n self.conv_list = SimpleSequential(name=\"conv_list\")\n for i, (out_channels, kernel_size, strides, padding) in enumerate(zip(\n out_channels_list, kernel_size_list, strides_list, padding_list)):\n self.conv_list.children.append(InceptConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n name=\"conv{}\".format(i + 1)))\n in_channels = out_channels\n\n def call(self, x, training=None):\n x = self.conv_list(x, training=training)\n return x\n\n\nclass InceptionAUnit(nn.Layer):\n \"\"\"\n InceptionResNetV2 type Inception-A unit.\n\n Parameters:\n ----------\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n data_format=\"channels_last\",\n **kwargs):\n super(InceptionAUnit, self).__init__(**kwargs)\n self.scale = 0.17\n in_channels = 320\n\n self.branches = Concurrent(\n data_format=data_format,\n name=\"branches\")\n self.branches.children.append(Conv1x1Branch(\n in_channels=in_channels,\n out_channels=32,\n data_format=data_format,\n name=\"branch1\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=(32, 32),\n kernel_size_list=(1, 3),\n strides_list=(1, 1),\n padding_list=(0, 1),\n data_format=data_format,\n name=\"branch2\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=(32, 48, 64),\n kernel_size_list=(1, 3, 3),\n strides_list=(1, 1, 1),\n padding_list=(0, 1, 1),\n data_format=data_format,\n name=\"branch3\"))\n self.conv = conv1x1(\n in_channels=128,\n out_channels=in_channels,\n use_bias=True,\n data_format=data_format,\n name=\"conv\")\n self.activ = nn.ReLU()\n\n def call(self, x, training=None):\n identity = x\n x = self.branches(x, training=training)\n x = self.conv(x, training=training)\n x = self.scale * x + identity\n x = self.activ(x)\n return x\n\n\nclass ReductionAUnit(nn.Layer):\n \"\"\"\n InceptionResNetV2 type Reduction-A unit.\n\n Parameters:\n ----------\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n data_format=\"channels_last\",\n **kwargs):\n super(ReductionAUnit, self).__init__(**kwargs)\n in_channels = 320\n\n self.branches = Concurrent(\n data_format=data_format,\n name=\"branches\")\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=(384,),\n kernel_size_list=(3,),\n strides_list=(2,),\n padding_list=(0,),\n data_format=data_format,\n name=\"branch1\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=(256, 256, 384),\n kernel_size_list=(1, 3, 3),\n strides_list=(1, 1, 2),\n padding_list=(0, 1, 0),\n data_format=data_format,\n name=\"branch2\"))\n self.branches.children.append(MaxPoolBranch(\n data_format=data_format,\n name=\"branch3\"))\n\n def call(self, x, training=None):\n x = self.branches(x, training=training)\n return x\n\n\nclass InceptionBUnit(nn.Layer):\n \"\"\"\n InceptionResNetV2 type Inception-B unit.\n\n Parameters:\n ----------\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n data_format=\"channels_last\",\n **kwargs):\n super(InceptionBUnit, self).__init__(**kwargs)\n self.scale = 0.10\n in_channels = 1088\n\n self.branches = Concurrent(\n data_format=data_format,\n name=\"branches\")\n self.branches.children.append(Conv1x1Branch(\n in_channels=in_channels,\n out_channels=192,\n data_format=data_format,\n name=\"branch1\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=(128, 160, 192),\n kernel_size_list=(1, (1, 7), (7, 1)),\n strides_list=(1, 1, 1),\n padding_list=(0, (0, 3), (3, 0)),\n data_format=data_format,\n name=\"branch2\"))\n self.conv = conv1x1(\n in_channels=384,\n out_channels=in_channels,\n use_bias=True,\n data_format=data_format,\n name=\"conv\")\n self.activ = nn.ReLU()\n\n def call(self, x, training=None):\n identity = x\n x = self.branches(x, training=training)\n x = self.conv(x, training=training)\n x = self.scale * x + identity\n x = self.activ(x)\n return x\n\n\nclass ReductionBUnit(nn.Layer):\n \"\"\"\n InceptionResNetV2 type Reduction-B unit.\n\n Parameters:\n ----------\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n data_format=\"channels_last\",\n **kwargs):\n super(ReductionBUnit, self).__init__(**kwargs)\n in_channels = 1088\n\n self.branches = Concurrent(\n data_format=data_format,\n name=\"branches\")\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=(256, 384),\n kernel_size_list=(1, 3),\n strides_list=(1, 2),\n padding_list=(0, 0),\n data_format=data_format,\n name=\"branch1\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=(256, 288),\n kernel_size_list=(1, 3),\n strides_list=(1, 2),\n padding_list=(0, 0),\n data_format=data_format,\n name=\"branch2\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=(256, 288, 320),\n kernel_size_list=(1, 3, 3),\n strides_list=(1, 1, 2),\n padding_list=(0, 1, 0),\n data_format=data_format,\n name=\"branch3\"))\n self.branches.children.append(MaxPoolBranch(\n data_format=data_format,\n name=\"branch4\"))\n\n def call(self, x, training=None):\n x = self.branches(x, training=training)\n return x\n\n\nclass InceptionCUnit(nn.Layer):\n \"\"\"\n InceptionResNetV2 type Inception-C unit.\n\n Parameters:\n ----------\n scale : float, default 1.0\n Scale value for residual branch.\n activate : bool, default True\n Whether activate the convolution block.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n scale=0.2,\n activate=True,\n data_format=\"channels_last\",\n **kwargs):\n super(InceptionCUnit, self).__init__(**kwargs)\n self.activate = activate\n self.scale = scale\n in_channels = 2080\n\n self.branches = Concurrent(\n data_format=data_format,\n name=\"branches\")\n self.branches.children.append(Conv1x1Branch(\n in_channels=in_channels,\n out_channels=192,\n data_format=data_format,\n name=\"branch1\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=(192, 224, 256),\n kernel_size_list=(1, (1, 3), (3, 1)),\n strides_list=(1, 1, 1),\n padding_list=(0, (0, 1), (1, 0)),\n data_format=data_format,\n name=\"branch2\"))\n self.conv = conv1x1(\n in_channels=448,\n out_channels=in_channels,\n use_bias=True,\n data_format=data_format,\n name=\"conv\")\n if self.activate:\n self.activ = nn.ReLU()\n\n def call(self, x, training=None):\n identity = x\n x = self.branches(x, training=training)\n x = self.conv(x, training=training)\n x = self.scale * x + identity\n if self.activate:\n x = self.activ(x)\n return x\n\n\nclass InceptBlock5b(nn.Layer):\n \"\"\"\n InceptionResNetV2 type Mixed-5b block.\n\n Parameters:\n ----------\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n data_format=\"channels_last\",\n **kwargs):\n super(InceptBlock5b, self).__init__(**kwargs)\n in_channels = 192\n\n self.branches = Concurrent(\n data_format=data_format,\n name=\"branches\")\n self.branches.children.append(Conv1x1Branch(\n in_channels=in_channels,\n out_channels=96,\n data_format=data_format,\n name=\"branch1\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=(48, 64),\n kernel_size_list=(1, 5),\n strides_list=(1, 1),\n padding_list=(0, 2),\n data_format=data_format,\n name=\"branch2\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=(64, 96, 96),\n kernel_size_list=(1, 3, 3),\n strides_list=(1, 1, 1),\n padding_list=(0, 1, 1),\n data_format=data_format,\n name=\"branch3\"))\n self.branches.children.append(AvgPoolBranch(\n in_channels=in_channels,\n out_channels=64,\n data_format=data_format,\n name=\"branch4\"))\n\n def call(self, x, training=None):\n x = self.branches(x, training=training)\n return x\n\n\nclass InceptInitBlock(nn.Layer):\n \"\"\"\n InceptionResNetV2 specific initial block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n data_format=\"channels_last\",\n **kwargs):\n super(InceptInitBlock, self).__init__(**kwargs)\n self.conv1 = InceptConv(\n in_channels=in_channels,\n out_channels=32,\n kernel_size=3,\n strides=2,\n padding=0,\n data_format=data_format,\n name=\"conv1\")\n self.conv2 = InceptConv(\n in_channels=32,\n out_channels=32,\n kernel_size=3,\n strides=1,\n padding=0,\n data_format=data_format,\n name=\"conv2\")\n self.conv3 = InceptConv(\n in_channels=32,\n out_channels=64,\n kernel_size=3,\n strides=1,\n padding=1,\n data_format=data_format,\n name=\"conv3\")\n self.pool1 = MaxPool2d(\n pool_size=3,\n strides=2,\n padding=0,\n data_format=data_format,\n name=\"pool1\")\n self.conv4 = InceptConv(\n in_channels=64,\n out_channels=80,\n kernel_size=1,\n strides=1,\n padding=0,\n data_format=data_format,\n name=\"conv4\")\n self.conv5 = InceptConv(\n in_channels=80,\n out_channels=192,\n kernel_size=3,\n strides=1,\n padding=0,\n data_format=data_format,\n name=\"conv5\")\n self.pool2 = MaxPool2d(\n pool_size=3,\n strides=2,\n padding=0,\n data_format=data_format,\n name=\"pool2\")\n self.block = InceptBlock5b(\n data_format=data_format,\n name=\"block\")\n\n def call(self, x, training=None):\n x = self.conv1(x, training=training)\n x = self.conv2(x, training=training)\n x = self.conv3(x, training=training)\n x = self.pool1(x)\n x = self.conv4(x, training=training)\n x = self.conv5(x, training=training)\n x = self.pool2(x)\n x = self.block(x, training=training)\n return x\n\n\nclass InceptionResNetV2(tf.keras.Model):\n \"\"\"\n InceptionResNetV2 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'\n https://arxiv.org/abs/1602.07261.\n\n Parameters:\n ----------\n dropout_rate : float, default 0.0\n Fraction of the input units to drop. Must be a number between 0 and 1.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (299, 299)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n dropout_rate=0.0,\n in_channels=3,\n in_size=(299, 299),\n classes=1000,\n data_format=\"channels_last\",\n **kwargs):\n super(InceptionResNetV2, self).__init__(**kwargs)\n self.in_size = in_size\n self.classes = classes\n self.data_format = data_format\n layers = [10, 21, 11]\n normal_units = [InceptionAUnit, InceptionBUnit, InceptionCUnit]\n reduction_units = [ReductionAUnit, ReductionBUnit]\n\n self.features = tf.keras.Sequential(name=\"features\")\n self.features.add(InceptInitBlock(\n in_channels=in_channels,\n data_format=data_format,\n name=\"init_block\"))\n\n for i, layers_per_stage in enumerate(layers):\n stage = tf.keras.Sequential(name=\"stage{}\".format(i + 1))\n for j in range(layers_per_stage):\n if (j == 0) and (i != 0):\n unit = reduction_units[i - 1]\n else:\n unit = normal_units[i]\n if (i == len(layers) - 1) and (j == layers_per_stage - 1):\n stage.add(unit(\n scale=1.0,\n activate=False,\n data_format=data_format,\n name=\"unit{}\".format(j + 1)))\n else:\n stage.add(unit(\n data_format=data_format,\n name=\"unit{}\".format(j + 1)))\n self.features.add(stage)\n self.features.add(incept_conv1x1(\n in_channels=2080,\n out_channels=1536,\n data_format=data_format,\n name=\"final_block\"))\n self.features.add(nn.AveragePooling2D(\n pool_size=8,\n strides=1,\n data_format=data_format,\n name=\"final_pool\"))\n\n self.output1 = tf.keras.Sequential(name=\"output1\")\n if dropout_rate > 0.0:\n self.output1.add(nn.Dropout(\n rate=dropout_rate,\n name=\"output1/dropout\"))\n self.output1.add(nn.Dense(\n units=classes,\n input_dim=1536,\n name=\"output1/fc\"))\n\n def call(self, x, training=None):\n x = self.features(x, training=training)\n x = flatten(x, self.data_format)\n x = self.output1(x)\n return x\n\n\ndef get_inceptionresnetv2(model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".tensorflow\", \"models\"),\n **kwargs):\n \"\"\"\n Create InceptionResNetV2 model with specific parameters.\n\n Parameters:\n ----------\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n\n net = InceptionResNetV2(**kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n in_channels = kwargs[\"in_channels\"] if (\"in_channels\" in kwargs) else 3\n input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == \"channels_first\" else\\\n (1,) + net.in_size + (in_channels,)\n net.build(input_shape=input_shape)\n net.load_weights(\n filepath=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root))\n\n return net\n\n\ndef inceptionresnetv2(**kwargs):\n \"\"\"\n InceptionResNetV2 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'\n https://arxiv.org/abs/1602.07261.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_inceptionresnetv2(model_name=\"inceptionresnetv2\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import tensorflow.keras.backend as K\n\n data_format = \"channels_last\"\n pretrained = False\n\n models = [\n inceptionresnetv2,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained, data_format=data_format)\n\n batch = 14\n x = tf.random.normal((batch, 3, 299, 299) if is_channels_first(data_format) else (batch, 299, 299, 3))\n y = net(x)\n assert (tuple(y.shape.as_list()) == (batch, 1000))\n\n weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights])\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != inceptionresnetv2 or weight_count == 55843464)\n\n\nif __name__ == \"__main__\":\n _test()\n"
] |
[
[
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.keras.layers.ReLU",
"tensorflow.keras.backend.get_value",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.Sequential"
],
[
"numpy.log",
"numpy.linspace",
"numpy.unique",
"numpy.power",
"torch.randn",
"numpy.arange",
"numpy.cumsum",
"torch.nn.init.ones_",
"torch.nn.Identity",
"torch.nn.init.normal_",
"torch.nn.init.zeros_",
"numpy.divide",
"torch.nn.init.kaiming_normal_"
],
[
"tensorflow.keras.backend.get_value",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.keras.Sequential"
],
[
"tensorflow.keras.backend.get_value",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.keras.Sequential"
],
[
"tensorflow.keras.backend.get_value",
"tensorflow.random.normal"
],
[
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.keras.layers.ReLU",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.backend.get_value",
"tensorflow.keras.Sequential",
"tensorflow.keras.layers.Dropout"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
GT-ZhangAcer/iann
|
[
"b5640c4909ea7fbd3f88c4d4245c2b49d7ea0b89"
] |
[
"eiseg/controller.py"
] |
[
"import time\nimport json\nimport paddle\nimport cv2\nimport numpy as np\nimport paddleseg.transforms as T\nfrom skimage.measure import label\n\nfrom inference import clicker\nfrom inference.predictor import get_predictor\nimport util\nfrom util.vis import draw_with_blend_and_clicks\nfrom util import MODELS, LabelList\n\n\n# TODO: 研究标签从0开始的时候怎么处理\nclass InteractiveController:\n def __init__(\n self,\n predictor_params: dict = None,\n prob_thresh: float = 0.5,\n ):\n \"\"\"初始化控制器.\n\n Parameters\n ----------\n predictor_params : dict\n 推理器配置\n prob_thresh : float\n 区分前景和背景结果的阈值\n\n \"\"\"\n self.predictor_params = predictor_params\n self.prob_thresh = prob_thresh\n self.model = None\n self.image = None\n self.predictor = None\n self.clicker = clicker.Clicker()\n self.states = []\n self.probs_history = []\n self.polygons = []\n\n # 用于redo\n self.undo_states = []\n self.undo_probs_history = []\n\n self.curr_label_number = 0\n self._result_mask = None\n self.labelList = LabelList()\n self.lccFilter = False\n\n def filterLargestCC(self, do_filter: bool):\n \"\"\"设置是否只保留推理结果中的最大联通块\n\n Parameters\n ----------\n do_filter : bool\n 是否只保存推理结果中的最大联通块\n \"\"\"\n if not isinstance(do_filter, bool):\n return\n self.lccFilter = do_filter\n\n def setModel(self, modelName: str):\n \"\"\"设置推理其模型.\n\n Parameters\n ----------\n modelName : str\n 模型名称,模型类中的__name__属性\n\n Returns\n -------\n bool, str\n 是否成功设置模型, 失败原因\n\n \"\"\"\n if not isinstance(modelName, str):\n return False, \"模型名应为str类型\"\n try:\n self.model = MODELS[modelName]()\n except KeyError as e:\n return False, str(e)\n return True, \"模型设置成功\"\n\n def setParam(self, paramPath: str):\n \"\"\"设置模型使用的推理参数\n\n Parameters\n ----------\n paramPath : str\n 推理参数路径\n\n Returns\n -------\n bool, str\n 是否设置成功, 失败原因\n\n \"\"\"\n if not self.modelSet:\n return False, \"模型未设置,请先设置模型\"\n try:\n self.model.load_param(paramPath)\n except Exception as e:\n return False, str(e)\n return True, \"权重设置成功\"\n\n def setImage(self, image: np.array):\n \"\"\"设置当前标注的图片\n\n Parameters\n ----------\n image : np.array\n 当前标注的图片\n\n \"\"\"\n self.image = image\n self._result_mask = np.zeros(image.shape[:2], dtype=np.uint8)\n self.resetLastObject()\n\n # 标签操作\n def setLabelList(self, labelList: json):\n \"\"\"设置标签列表,会覆盖已有的标签列表\n\n Parameters\n ----------\n labelList : json\n 标签列表格式为\n {\n {\n \"idx\" : int (like 0 or 1 or 2)\n \"name\" : str (like \"car\" or \"airplan\")\n \"color\" : list (like [255, 0, 0])\n },\n ...\n }\n\n Returns\n -------\n type\n Description of returned object.\n\n \"\"\"\n self.labelList.clear()\n labels = json.loads(labelList)\n for lab in labels:\n self.labelList.add(lab[\"id\"], lab[\"name\"], lab[\"color\"])\n\n def addLabel(self, id: int, name: str, color: list):\n self.labelList.add(id, name, color)\n\n def delLabel(self, id: int):\n self.labelList.remove(id)\n\n def clearLabel(self):\n self.labelList.clear()\n\n def readLabel(self, path):\n self.labelList.readLabel(path)\n\n def saveLabel(self, path):\n self.labelList.saveLabel(path)\n\n # 点击操作\n def addClick(self, x: int, y: int, is_positive: bool):\n print(\"click\", x, y)\n \"\"\"添加一个点并运行推理,保存历史用于undo\n\n Parameters\n ----------\n x : int\n 点击的横坐标\n y : int\n 点击的纵坐标\n is_positive : bool\n 是否点的是正点\n\n Returns\n -------\n bool, str\n 点击是否添加成功, 失败原因\n\n \"\"\"\n\n # 1. 确定可以点\n if not self.inImage(x, y):\n return False, \"点击越界\"\n if not self.modelSet:\n return False, \"模型未设置\"\n if not self.paramSet:\n return False, \"参数未设置\"\n if not self.imageSet:\n return False, \"图像未设置\"\n\n if len(self.states) == 0: # 保存一个空状态\n self.states.append(\n {\n \"clicker\": self.clicker.get_state(),\n \"predictor\": self.predictor.get_state(),\n }\n )\n\n # 2. 添加点击,跑推理\n click = clicker.Click(is_positive=is_positive, coords=(y, x))\n self.clicker.add_click(click)\n start = time.time()\n pred = self.predictor.get_prediction(self.clicker)\n end = time.time()\n print(\"cost time\", end - start)\n\n # 3. 保存状态\n self.states.append(\n {\n \"clicker\": self.clicker.get_state(),\n \"predictor\": self.predictor.get_state(),\n }\n )\n if self.probs_history:\n self.probs_history.append((self.probs_history[-1][1], pred))\n else:\n self.probs_history.append((np.zeros_like(pred), pred))\n\n # 点击之后就不能接着之前的历史redo了\n self.undo_states = []\n self.undo_probs_history = []\n return True, \"点击添加成功\"\n\n def undoClick(self):\n \"\"\"\n undo一步点击\n \"\"\"\n if len(self.states) <= 1: # == 1就只剩下一个空状态了,不用再退\n return\n self.undo_states.append(self.states.pop())\n self.clicker.set_state(self.states[-1][\"clicker\"])\n self.predictor.set_state(self.states[-1][\"predictor\"])\n self.undo_probs_history.append(self.probs_history.pop())\n if not self.probs_history:\n self.reset_init_mask()\n\n def redoClick(self):\n \"\"\"\n redo一步点击\n \"\"\"\n if len(self.undo_states) == 0: # 如果还没撤销过\n return\n if len(self.undo_probs_history) >= 1:\n next_state = self.undo_states.pop()\n self.states.append(next_state)\n self.clicker.set_state(next_state[\"clicker\"])\n self.predictor.set_state(next_state[\"predictor\"])\n self.probs_history.append(self.undo_probs_history.pop())\n\n def finishObject(self):\n \"\"\"\n 结束当前物体标注,准备标下一个\n \"\"\"\n object_prob = self.current_object_prob\n if object_prob is None:\n return None, None\n object_mask = object_prob > self.prob_thresh\n polygon = util.get_polygon(object_mask.astype(np.uint8) * 255)\n if polygon is not None:\n if self.lccFilter:\n object_mask = self.getLargestCC(object_mask)\n self._result_mask[object_mask] = self.curr_label_number\n self.resetLastObject()\n self.polygons.append([self.curr_label_number, polygon])\n return object_mask, polygon\n\n # 多边形\n def getPolygon(self):\n return self.polygon\n\n def setPolygon(self, polygon):\n self.polygon = polygon\n\n # mask\n def getMask(self):\n s = self.imgShape\n img = np.zeros([s[0], s[1]])\n for poly in self.polygons:\n pts = np.int32([np.array(poly[1])])\n cv2.fillPoly(img, pts=pts, color=poly[0])\n return img\n\n def setCurrLabelIdx(self, number):\n if not isinstance(number, int):\n return False\n self.curr_label_number = number\n # TODO: 检查是不是需要改当前mask的编号\n\n def resetLastObject(self, update_image=True):\n \"\"\"\n 重置控制器状态\n Parameters\n update_image(bool): 是否更新图像\n \"\"\"\n self.states = []\n self.probs_history = []\n self.undo_states = []\n self.undo_probs_history = []\n # self.current_object_prob = None\n self.clicker.reset_clicks()\n self.reset_predictor()\n self.reset_init_mask()\n\n def reset_predictor(self, predictor_params=None):\n \"\"\"\n 重置推理器,可以换推理配置\n Parameters\n predictor_params(dict): 推理配置\n \"\"\"\n if predictor_params is not None:\n self.predictor_params = predictor_params\n self.predictor = get_predictor(self.model.model, **self.predictor_params)\n if self.image is not None:\n self.predictor.set_input_image(self.image)\n\n def reset_init_mask(self):\n self.clicker.click_indx_offset = 0\n\n def getLargestCC(self, mask):\n # TODO: 最后返回的最大联通快一定要包含正点\n mask = label(mask)\n if mask.max() == 0:\n return mask\n mask = mask == np.argmax(np.bincount(mask.flat)[1:]) + 1\n return mask\n\n def get_visualization(self, alpha_blend: float, click_radius: int):\n if self.image is None:\n return None\n # 1. 正在标注的mask\n # results_mask_for_vis = self.result_mask # 加入之前标完的mask\n results_mask_for_vis = np.zeros_like(self.result_mask)\n results_mask_for_vis *= self.curr_label_number\n if self.probs_history:\n results_mask_for_vis[\n self.current_object_prob > self.prob_thresh\n ] = self.curr_label_number\n if self.lccFilter:\n results_mask_for_vis = (\n self.getLargestCC(results_mask_for_vis) * self.curr_label_number\n )\n vis = draw_with_blend_and_clicks(\n self.image,\n mask=results_mask_for_vis,\n alpha=alpha_blend,\n clicks_list=self.clicker.clicks_list,\n radius=click_radius,\n palette=self.palette,\n )\n return vis\n\n def inImage(self, x: int, y: int):\n s = self.image.shape\n if x < 0 or y < 0 or x >= s[1] or y >= s[0]:\n print(\"点击越界\")\n return False\n return True\n\n @property\n def result_mask(self):\n result_mask = self._result_mask.copy()\n return result_mask\n\n @property\n def palette(self):\n if self.labelList:\n colors = [ml.color for ml in self.labelList]\n colors.insert(0, [0, 0, 0])\n else:\n colors = [[0, 0, 0]]\n return colors\n\n @property\n def current_object_prob(self):\n \"\"\"\n 获取当前推理标签\n \"\"\"\n if self.probs_history:\n _, current_prob_additive = self.probs_history[-1]\n return current_prob_additive\n else:\n return None\n\n @property\n def is_incomplete_mask(self):\n \"\"\"\n Returns\n bool: 当前的物体是不是还没标完\n \"\"\"\n return len(self.probs_history) > 0\n\n @property\n def imgShape(self):\n print(self.image.shape)\n return self.image.shape[1::-1]\n\n @property\n def paramSet(self):\n return self.model.paramSet\n\n @property\n def modelSet(self):\n return self.model is not None\n\n @property\n def modelName(self):\n return self.model.__name__\n\n @property\n def imageSet(self):\n return self.image is not None\n"
] |
[
[
"numpy.bincount",
"numpy.array",
"numpy.zeros",
"numpy.zeros_like"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dkamotsky/addons
|
[
"56ff850785c6caa8c18c2859e32a32c8902defea"
] |
[
"tensorflow_addons/seq2seq/tests/beam_search_ops_test.py"
] |
[
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tfa.seq2seq.beam_search_ops.\"\"\"\n\nimport itertools\n\nimport numpy as np\nimport pytest\nimport tensorflow as tf\n\nfrom tensorflow_addons.seq2seq import gather_tree\n\n\ndef _transpose_batch_time(x):\n return np.transpose(x, [1, 0, 2]).astype(np.int32)\n\n\ndef test_gather_tree_one():\n # (max_time = 4, batch_size = 1, beams = 3)\n end_token = 10\n step_ids = _transpose_batch_time([[[1, 2, 3], [4, 5, 6], [7, 8, 9], [-1, -1, -1]]])\n parent_ids = _transpose_batch_time(\n [[[0, 0, 0], [0, 1, 1], [2, 1, 2], [-1, -1, -1]]]\n )\n max_sequence_lengths = [3]\n expected_result = _transpose_batch_time(\n [[[2, 2, 2], [6, 5, 6], [7, 8, 9], [10, 10, 10]]]\n )\n beams = gather_tree(\n step_ids=step_ids,\n parent_ids=parent_ids,\n max_sequence_lengths=max_sequence_lengths,\n end_token=end_token,\n )\n np.testing.assert_equal(expected_result, beams.numpy())\n\n\ndef test_bad_parent_values_on_cpu():\n # (batch_size = 1, max_time = 4, beams = 3)\n # bad parent in beam 1 time 1\n end_token = 10\n step_ids = _transpose_batch_time([[[1, 2, 3], [4, 5, 6], [7, 8, 9], [-1, -1, -1]]])\n parent_ids = _transpose_batch_time(\n [[[0, 0, 0], [0, -1, 1], [2, 1, 2], [-1, -1, -1]]]\n )\n max_sequence_lengths = [3]\n with tf.device(\"/cpu:0\"):\n with pytest.raises(tf.errors.InvalidArgumentError):\n _ = gather_tree(\n step_ids=step_ids,\n parent_ids=parent_ids,\n max_sequence_lengths=max_sequence_lengths,\n end_token=end_token,\n )\n\n\ndef test_bad_parent_values_on_gpu():\n # Only want to run this test on CUDA devices, as gather_tree is not\n # registered for SYCL devices.\n if not tf.test.is_gpu_available(cuda_only=True):\n return\n # (max_time = 4, batch_size = 1, beams = 3)\n # bad parent in beam 1 time 1; appears as a negative index at time 0\n end_token = 10\n step_ids = _transpose_batch_time([[[1, 2, 3], [4, 5, 6], [7, 8, 9], [-1, -1, -1]]])\n parent_ids = _transpose_batch_time(\n [[[0, 0, 0], [0, -1, 1], [2, 1, 2], [-1, -1, -1]]]\n )\n max_sequence_lengths = [3]\n expected_result = _transpose_batch_time(\n [[[2, -1, 2], [6, 5, 6], [7, 8, 9], [10, 10, 10]]]\n )\n with tf.device(\"/device:GPU:0\"):\n beams = gather_tree(\n step_ids=step_ids,\n parent_ids=parent_ids,\n max_sequence_lengths=max_sequence_lengths,\n end_token=end_token,\n )\n np.testing.assert_equal(expected_result, beams.numpy())\n\n\ndef test_gather_tree_batch():\n batch_size = 10\n beam_width = 15\n max_time = 8\n max_sequence_lengths = [0, 1, 2, 4, 7, 8, 9, 10, 11, 0]\n end_token = 5\n\n step_ids = np.random.randint(\n 0, high=end_token + 1, size=(max_time, batch_size, beam_width)\n )\n parent_ids = np.random.randint(\n 0, high=beam_width - 1, size=(max_time, batch_size, beam_width)\n )\n\n beams = gather_tree(\n step_ids=step_ids.astype(np.int32),\n parent_ids=parent_ids.astype(np.int32),\n max_sequence_lengths=max_sequence_lengths,\n end_token=end_token,\n )\n beams = beams.numpy()\n\n assert (max_time, batch_size, beam_width) == beams.shape\n for b in range(batch_size):\n # Past max_sequence_lengths[b], we emit all end tokens.\n b_value = beams[max_sequence_lengths[b] :, b, :]\n np.testing.assert_allclose(b_value, end_token * np.ones_like(b_value))\n for batch, beam in itertools.product(range(batch_size), range(beam_width)):\n v = np.squeeze(beams[:, batch, beam])\n if end_token in v:\n found_bad = np.where(v == -1)[0]\n assert 0 == len(found_bad)\n found = np.where(v == end_token)[0]\n found = found[0] # First occurrence of end_token.\n # If an end_token is found, everything before it should be a\n # valid id and everything after it should be -1.\n if found > 0:\n np.testing.assert_equal(\n v[: found - 1] >= 0, np.ones_like(v[: found - 1], dtype=bool),\n )\n np.testing.assert_allclose(\n v[found + 1 :], end_token * np.ones_like(v[found + 1 :])\n )\n"
] |
[
[
"tensorflow.device",
"numpy.ones_like",
"numpy.squeeze",
"numpy.transpose",
"tensorflow.test.is_gpu_available",
"numpy.where",
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Progitiel/Slideways
|
[
"64b8672860893eea6be245b5138f5ec48e97ed8c"
] |
[
"src/App.py"
] |
[
"import copy\nimport os\nimport random\nimport time\nimport numpy as np\n\nfrom Config import *\nfrom Record import Record\nfrom AI import AI\n\n\ndef valid_input_case(board, currentPlayerNumber, last_play, prev_boards, line, column):\n \"\"\"\n Vérifie si les données sont correctes selon les règles du jeu pour les cases\n\n Entrées :\n board [[int,int,...],[int,int,...],...] : listes de listes représentant le plateau\n currentPlayerNumber [int] : numéro du joueur actuel\n last_play [{\"line\", \"column\", \"direction\"}] : dernier coup joué\n prev_boards [[board]] : liste des board précedement jouée\n line [int] : coordonnée de la ligne\n column [int] : coordonnée de la colonne\n\n Sorties :\n [bool] : données valides\n \"\"\"\n\n valid = False\n\n valid_playable = board[line][column] != -1\n\n if valid_playable:\n\n valid_already_own = board[line][column] != currentPlayerNumber\n\n if valid_already_own:\n\n valid_last_play = not (\n line == last_play[\"line\"] and column == last_play[\"column\"])\n\n if valid_last_play or (last_play[\"line\"] == None and last_play[\"column\"] == None):\n\n nSize, nLine, nColumn = np.shape(prev_boards)\n\n valid = True\n prev = 0\n while valid and prev < nSize:\n\n prev_equal = True\n l = 0\n while prev_equal and l < nLine:\n c = 0\n while prev_equal and c < nColumn:\n if l == line and c == column:\n prev_equal = prev_boards[prev][l][c] == currentPlayerNumber\n else:\n prev_equal = board[l][c] == prev_boards[prev][l][c]\n c += 1\n l += 1\n\n valid = not prev_equal\n\n prev += 1\n\n return valid\n\n\ndef valid_input_shift(board, currentPlayerNumber, last_play, prev_boards, line, direction):\n \"\"\"\n Vérifie si les données sont correctes selon les règles du jeu pour les décallages\n\n Entrées :\n board [[int,int,...],[int,int,...],...] : listes de listes représentant le plateau\n currentPlayerNumber [int] : numéro du joueur actuel\n last_play [{\"line\", \"column\", \"direction\"}] : dernier coup joué\n prev_boards [[board]] : liste des board précedement jouée\n line [int] : coordonnée de la ligne\n direction [+1 ou -1] : direction du décalage\n\n Sorties :\n [bool] : données valides\n \"\"\"\n\n valid = False\n\n valid_format = direction in [+1, -1]\n\n if valid_format:\n\n if direction == +1:\n valid_edge = board[line][-1] == -1\n elif direction == -1:\n valid_edge = board[line][0] == -1\n\n if valid_edge:\n\n valid_last_play = not (\n line == last_play[\"line\"] and (+1 if direction == -1 else -1) == last_play[\"direction\"])\n\n if valid_last_play or (last_play[\"line\"] == None and last_play[\"direction\"] == None):\n\n nSize, nLine, nColumn = np.shape(prev_boards)\n\n valid = True\n prev = 0\n while valid and prev < nSize:\n\n prev_equal = True\n l = 0\n while prev_equal and l < nLine:\n c = 0\n while prev_equal and c < nColumn:\n if l == line:\n prev_equal = board[l][c] == prev_boards[prev][l][0 if c +\n direction == nColumn else c+direction]\n else:\n prev_equal = board[l][c] == prev_boards[prev][l][c]\n c += 1\n l += 1\n\n valid = not prev_equal\n\n prev += 1\n\n return valid\n\n\ndef playerWin(board):\n \"\"\"\n Vérifie si un ou plusieurs joueur(s) à/ont gagné(s) la partie\n\n Entrées :\n board [[int,int,...],[int,int,...],...] : listes de listes représentant le plateau\n\n Sorties :\n [(bool, int)] : (égalité, numéro du joueur gagnant (ou None))\n \"\"\"\n\n m_line = board\n m_column = np.rot90(board)\n m_diagonals = [np.diagonal(board, i) for i in range((-BOARD_SIZE+1)+NUMBER_CASE_TO_WIN-1,\n (BOARD_SIZE+(BOARD_SIZE-1)*2)-NUMBER_CASE_TO_WIN+1)] # Diagonnales de S-O vers N-E\n flipBoard = np.flipud(board)\n m_diagonals += [np.diagonal(flipBoard, i) for i in range((-BOARD_SIZE+1)+NUMBER_CASE_TO_WIN-1,\n (BOARD_SIZE+(BOARD_SIZE-1)*2)-NUMBER_CASE_TO_WIN+1)] # Diagonnales de N-O vers S-E\n\n for mat_elem in m_line:\n draw, winner = checkWin(mat_elem)\n if draw or winner != None:\n return (draw, winner)\n\n for mat_elem in m_column:\n draw, winner = checkWin(mat_elem)\n if draw or winner != None:\n return (draw, winner)\n\n for mat_elem in m_diagonals:\n draw, winner = checkWin(mat_elem)\n if draw or winner != None:\n return (draw, winner)\n\n return (False, None)\n\n\ndef checkWin(mat_elem):\n \"\"\"\n Vérifie si un nombre (NUMBER_CASE_TO_WIN) de case du même joueur sont aligné\n\n Entrées :\n mat_elem [[]] : listes\n\n Sorties :\n [(bool, int)] : (égalité, numéro du joueur gagnant (ou None))\n \"\"\"\n\n res = None\n draw = False\n\n n_find_1 = 0\n n_find_2 = 0\n\n if len(mat_elem) >= NUMBER_CASE_TO_WIN:\n\n for j in mat_elem:\n if j == 1:\n n_find_1 += 1\n else:\n n_find_1 = 0\n\n if j == 2:\n n_find_2 += 1\n else:\n n_find_2 = 0\n\n if n_find_1 == NUMBER_CASE_TO_WIN:\n if res == 2:\n draw = True\n else:\n res = 1\n elif n_find_2 == NUMBER_CASE_TO_WIN:\n if res == 1:\n draw = True\n else:\n res = 2\n\n return (draw, res)\n\n\ndef coup(board, line=None, column=None, playerNumber=None, direction=None):\n \"\"\"\n Joue le coup sur la board\n\n Entrées :\n board [[int,int,...],[int,int,...],...] : listes de listes représentant le plateau\n line [int] : coordonnée de la ligne\n column [int] : coordonnée de la colonne\n playerNumber [int] : numéro du joueur\n direction [+1 ou -1] : direction du décalage\n\n Sorties :\n [{\"line\", \"column\", \"direction\"}] : coup joué\n \"\"\"\n\n if line != None and column != None and playerNumber != None: # Coordonnées case\n\n board[line][column] = playerNumber\n\n elif line != None and direction != None: # Décalage\n\n board[line] = np.roll(board[line], direction)\n\n return {\"line\": line, \"column\": column, \"direction\": direction}\n\n\nclass App():\n def __init__(self, pyqt):\n \"\"\"\n Initialise les données de la partie\n\n Entrées :\n pyqt [pyqt] : class gérant le frontend\n \"\"\"\n\n self.pyqt = pyqt\n self.record = Record(self)\n\n self.playerNames = [\"\", \"\"]\n self.score = [0, 0]\n self.playerMode = [1, 1]\n self.aiTimer = [0, 0]\n\n self.firstGame = True\n\n self.__init()\n\n def __init(self):\n \"\"\"Définit les paramêtres d'une nouvelle manche\"\"\"\n\n ml = [-1 for x in range(BOARD_SIZE-1)]\n ca = [0 for l in range(BOARD_SIZE)]\n mr = [-1 for x in range(BOARD_SIZE-1)]\n\n self.board = np.array(\n [ml + ca + mr for l in range(BOARD_SIZE)], dtype=int)\n self.started = False\n self.currentPlayerNumber = 2\n self.last_play = {\"line\": None, \"column\": None, \"direction\": None}\n\n if not self.firstGame:\n self.record.newGame()\n else:\n self.firstGame = False\n\n def getBoard(self):\n \"\"\"Donne le plateau\"\"\"\n\n return self.board\n\n def getValidCase(self):\n \"\"\"Donne la liste des cases jouables\"\"\"\n\n playable_coups = []\n\n for l in range(BOARD_SIZE):\n for c in range(BOARD_SIZE+(BOARD_SIZE-1)*2):\n if valid_input_case(self.board, self.currentPlayerNumber, self.last_play, self.record.getCurrentBoard()[:-1], l, c):\n playable_coups.append((l, c))\n\n return playable_coups\n\n def getValidShift(self, direction):\n \"\"\"Donne la liste des décallages possibles\"\"\"\n\n playable_coups = []\n\n for l in range(BOARD_SIZE):\n if valid_input_shift(self.board, self.currentPlayerNumber, self.last_play, self.record.getCurrentBoard()[:-1], l, direction):\n playable_coups.append((l, direction))\n\n return playable_coups\n\n def getValid(self):\n valid = [(line, column, None)\n for line, column in self.getValidCase()]\n valid += [(line, None, direction)\n for line, direction in self.getValidShift(-1)]\n valid += [(line, None, direction)\n for line, direction in self.getValidShift(+1)]\n\n return valid\n\n def nextPlayer(self):\n \"\"\"Met à jour le joueur actuel et le fait jouer si c'est une ia\"\"\"\n\n if self.started:\n\n if self.currentPlayerNumber == 1:\n self.currentPlayerNumber = 2\n else:\n self.currentPlayerNumber = 1\n\n self.pyqt.initUI()\n\n if self.started and self.playerMode[self.currentPlayerNumber-1] in [-1, -2, -3]:\n\n self.playerAi()\n\n def playerAi(self):\n \"\"\"Joue un coup en tant qu'ia\"\"\"\n\n startTime = time.time()\n input_line, input_column, input_direction = AI(self).play()\n endTime = time.time()\n delta = endTime - startTime\n if delta > AI_TIME:\n self.setScore((self.currentPlayerNumber % 2)+1)\n self.restart()\n self.setStarted(True)\n self.pyqt.initUI()\n else:\n waitTime = self.aiTimer[self.currentPlayerNumber-1]\n while delta < waitTime:\n delta = time.time() - startTime\n\n if input_line != None and input_column != None:\n self.setBoardCase(input_line, input_column)\n elif input_line != None and input_direction != None:\n self.setBoardShift(input_line, input_direction)\n\n def setCoup(self, board, line=None, column=None, playerNumber=None, direction=None):\n \"\"\"Joue un coup sur la board\"\"\"\n\n pres = board[line][column] if line != None and column != None and playerNumber != None else None\n coup(board, line=line, column=column,\n playerNumber=playerNumber, direction=direction)\n return (self.board, pres)\n\n def setBoardCase(self, line, column):\n \"\"\"\n Joue une case sur le plateau\n\n Entrées :\n user_input_line [int] : ligne\n user_input_column [int] : colonne\n relative [bool] : True si les données sont sous la forme A1 ou 1+\n \"\"\"\n\n self.last_play = coup(\n self.board, line=line, column=column, playerNumber=self.currentPlayerNumber)\n\n self.record.addBoard(self.board)\n\n self.nextPlayer()\n\n def setBoardShift(self, line, direction):\n \"\"\"\n Joue un décalage sur le plateau\n\n Entrées :\n user_input_direction [+1 ou -1] : +1 à droite et -1 à gauche\n user_input_line [int] : ligne\n\n Sorties :\n \"\"\"\n\n self.last_play = coup(self.board, line=line, direction=direction)\n\n self.record.addBoard(copy.deepcopy(self.board))\n\n self.nextPlayer()\n\n def getCurrentPlayer(self):\n \"\"\"Donne le joueur actuel\"\"\"\n\n return self.currentPlayerNumber\n\n def getPlayerMode(self, playerNumber=None):\n \"\"\"\n Donne le mode du joueur\n\n Entrées :\n playerNumber [int] : numéro du joueur\n \"\"\"\n\n return self.playerMode[self.currentPlayerNumber-1] if playerNumber == None else self.playerMode[playerNumber-1]\n\n def setPlayerMode(self, playerNumber, mode):\n \"\"\"\n Modifie le mode du joueur\n\n Entrées :\n playerNumber [int] : numéro du joueur\n mode [+1 ou -1] : +1 pour humain et -1 pour ia\n \"\"\"\n\n self.playerMode[playerNumber-1] = mode\n\n def getAiTimer(self, playerNumber):\n \"\"\"\n Donne le temps d'exécution de l'ia\n\n Entrées :\n playerNumber [int] : numéro du joueur\n \"\"\"\n\n return self.aiTimer[playerNumber-1]\n\n def setAiTimer(self, playerNumber, timer):\n \"\"\"\n Modifie le temps d'exécution de l'ia\n\n Entrées :\n playerNumber [int] : numéro du joueur\n timer [int] : temps d'exécution de l'ia\n \"\"\"\n\n self.aiTimer[playerNumber-1] = timer\n\n def getWinner(self, board=None):\n \"\"\"Donne le gagnant(s) de la partie ou None\"\"\"\n\n return playerWin(self.board if board is None else board)\n\n def getStarted(self):\n \"\"\"Donne l'état de la partie\"\"\"\n\n return self.started\n\n def setStarted(self, boolVal):\n \"\"\"\n Modifie l'état de la partie\n\n Entrées :\n boolVal [int] : démarrer ou arrêter ?\n \"\"\"\n\n if boolVal == False:\n self.started = boolVal\n else:\n self.started = boolVal\n self.nextPlayer()\n\n def restart(self):\n \"\"\"Redémare une partie\"\"\"\n\n self.__init()\n\n def getPlayerName(self, playerNumber=None):\n \"\"\"\n Donne le nom du joueur en fonction de son numéro\n\n Entrées :\n playerNumber [int] : numéro du joueur\n \"\"\"\n\n return self.playerNames if playerNumber == None else self.playerNames[playerNumber-1]\n\n def setPlayerName(self, playerNumber, playerName):\n \"\"\"\n Donne le nom du joueur en fonction de son numéro\n\n Entrées :\n playerNumber [int] : numéro du joueur\n playerName [str] : nom du joueur\n \"\"\"\n\n self.playerNames[playerNumber-1] = playerName\n\n def getScore(self, playerNumber):\n \"\"\"\n Donne le score du joueur en fonction de son numéro\n\n Entrées :\n playerNumber [int] : numéro du joueur\n \"\"\"\n\n return self.score[playerNumber-1]\n\n def setScore(self, playerNumber):\n \"\"\"\n Rajoute un point au joueur\n\n Entrées :\n playerNumber [int] : numéro du joueur\n \"\"\"\n\n self.score[playerNumber-1] += 1\n"
] |
[
[
"numpy.rot90",
"numpy.flipud",
"numpy.shape",
"numpy.diagonal",
"numpy.roll"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
xvalad/ML
|
[
"baf71a32fe5c5cf8e9f79a7ec46f59b878f87965",
"baf71a32fe5c5cf8e9f79a7ec46f59b878f87965"
] |
[
"LinearRegressionWithSyntheticData.py",
"NumPyUltraQuickTutorial.py"
] |
[
"#!/usr/bin/python3\n# LinearRegressionWIthSyntheticData by Google\n# https://colab.research.google.com/github/google/eng-edu/blob/master/ml/cc/exercises/linear_regression_with_synthetic_data.ipynb\n#\nimport pandas as pd \nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\n#\n## DEFINE FUNCTIONS THAT BUILD AND TRAIN A MODEL\ndef build_model(my_learning_rate):\n \"\"\"Create and compile a simple linear regression model.\"\"\"\n # Most simple tf.keras models are sequential. \n # A sequential model contains one or more layers.\n model = tf.keras.models.Sequential()\n\n # Describe the topography of the model.\n # The topography of a simple linear regression model\n # is a single node in a single layer. \n model.add(tf.keras.layers.Dense(units=1, \n input_shape=(1,)))\n\n # Compile the model topography into code that \n # TensorFlow can efficiently execute. Configure \n # training to minimize the model's mean squared error. \n model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=my_learning_rate),\n loss=\"mean_squared_error\",\n metrics=[tf.keras.metrics.RootMeanSquaredError()])\n\n return model \n\n\ndef train_model(model, feature, label, epochs, batch_size):\n \"\"\"Train the model by feeding it data.\"\"\"\n\n # Feed the feature values and the label values to the \n # model. The model will train for the specified number \n # of epochs, gradually learning how the feature values\n # relate to the label values. \n history = model.fit(x=feature,\n y=label,\n batch_size=batch_size,\n epochs=epochs)\n\n # Gather the trained model's weight and bias.\n trained_weight = model.get_weights()[0]\n trained_bias = model.get_weights()[1]\n\n # The list of epochs is stored separately from the \n # rest of history.\n epochs = history.epoch\n \n # Gather the history (a snapshot) of each epoch.\n hist = pd.DataFrame(history.history)\n\n # Specifically gather the model's root mean \n #squared error at each epoch. \n rmse = hist[\"root_mean_squared_error\"]\n\n return trained_weight, trained_bias, epochs, rmse\n\nprint(\"Defined create_model and train_model\")\n# #\n## DEFINE PLOTTING FUNCTIONS\ndef plot_the_model(trained_weight, trained_bias, feature, label):\n \"\"\"Plot the trained model against the training feature and label.\"\"\"\n\n # Label the axes.\n plt.xlabel(\"feature\")\n plt.ylabel(\"label\")\n\n # Plot the feature values vs. label values.\n plt.scatter(feature, label)\n\n # Create a red line representing the model. The red line starts\n # at coordinates (x0, y0) and ends at coordinates (x1, y1).\n x0 = 0\n y0 = trained_bias\n x1 = my_feature[-1]\n y1 = trained_bias + (trained_weight * x1)\n plt.plot([x0, x1], [y0, y1], c='r')\n\n # Render the scatter plot and the red line.\n plt.show()\n\ndef plot_the_loss_curve(epochs, rmse):\n \"\"\"Plot the loss curve, which shows loss vs. epoch.\"\"\"\n\n plt.figure()\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Root Mean Squared Error\")\n\n plt.plot(epochs, rmse, label=\"Loss\")\n plt.legend()\n plt.ylim([rmse.min()*0.97, rmse.max()])\n plt.show()\n\nprint(\"Defined the plot_the_model and plot_the_loss_curve functions.\")\n# #\n#\nmy_feature = ([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0])\nmy_label = ([5.0, 8.8, 9.6, 14.2, 18.8, 19.5, 21.4, 26.8, 28.9, 32.0, 33.8, 38.2])\n#\nlearning_rate=0.01\nepochs = 10\nmy_batch_size = 12\n#\nmy_model = build_model(learning_rate)\ntrained_weight, trained_bias, epochs, rmse = train_model(my_model,my_feature,my_label,epochs,my_batch_size)\nplot_the_model(trained_weight,trained_bias,my_feature,my_label)\nplot_the_loss_curve(epochs,rmse)",
"#!/usr/bin/python3\n# NumpyUltraQuickTutorial by Google\n# https://colab.research.google.com/github/google/eng-edu/blob/master/ml/cc/exercises/numpy_ultraquick_tutorial.ipynb\n#\nimport numpy as np\nprint(np.version.version)\n# Examples\none_dimensional_array = np.array([1.2, 2.4, 3.5, 4.7, 6.1, 7.2, 8.3, 9.5])\nprint(\"1D array:\\n\",one_dimensional_array)\n#\ntwo_dimensional_array = np.array([[6, 5], [11, 7], [4, 8]])\nprint(\"2D array:\\n\",two_dimensional_array)\n#\nzeros_array=np.zeros((3,4))\nprint(\"Zeros array 3x4:\\n\",zeros_array)\n#\nones_array=np.ones((2,3))\nprint(\"Ones array 2x3\\n\",ones_array)\n#\nsequence_of_integers = np.arange(5,12)\nprint(\"Lower bound sequence from 5 to 12\\n\",sequence_of_integers)\n#\nrandom_integers_between_50_and_100 = np.random.randint(low=50,high= 101,size=(6))\nprint(\"Sequence of 6 random numbers between 50 and 100\\n\",random_integers_between_50_and_100)\n#\nrandom_floats_between_0_and_1 = np.random.random_sample([6]) # Updated from np.random.random()\nprint(\"Random floats between 0 and 1\\n:\",random_floats_between_0_and_1)\n#\nrandom_floats_between_2_and_3 = random_floats_between_0_and_1 + 2.0\nprint(random_floats_between_2_and_3)\n#\nrandom_integers_between_150_and_300 = random_integers_between_50_and_100 * 3\nprint(random_integers_between_150_and_300)\n#\n# Task 1: Create a linear dataset\n#\n# Assign a sequence of integers from 6 to 20 (inclusive) to a NumPy array named feature.\n#\nfeature = np.arange(6,21)\nprint(feature)\n#\n# Assign 15 values to a NumPy array named label such that;\n# label = (3)(feature) + 4\n#\nlabel = 3 * feature + 4\nprint(label)\n#\n# Task 2: Add some noise to the Dataset\n# Insert a little floating point random noise between -2 and 2 into each element of the label array \n#\nnoise = (np.random.random_sample([15]) * 4) - 2.0 # Updated from np.random.random()\nprint(noise)\nlabel = label+noise\nprint(label)"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.figure",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.optimizers.RMSprop",
"pandas.DataFrame",
"matplotlib.pyplot.plot",
"tensorflow.keras.metrics.RootMeanSquaredError",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"tensorflow.keras.models.Sequential",
"matplotlib.pyplot.ylabel"
],
[
"numpy.arange",
"numpy.random.random_sample",
"numpy.ones",
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vigilancetrent/chatbot-advanced
|
[
"2e0c72c4df2e1434da995b7105f8f0414aba6248"
] |
[
"TTS/utils/data.py"
] |
[
"import numpy as np\n\n\ndef _pad_data(x, length):\n _pad = 0\n assert x.ndim == 1\n return np.pad(\n x, (0, length - x.shape[0]), mode='constant', constant_values=_pad)\n\n\ndef prepare_data(inputs):\n max_len = max((len(x) for x in inputs))\n return np.stack([_pad_data(x, max_len) for x in inputs])\n\n\ndef _pad_tensor(x, length):\n _pad = 0\n assert x.ndim == 2\n x = np.pad(\n x, [[0, 0], [0, length - x.shape[1]]],\n mode='constant',\n constant_values=_pad)\n return x\n\n\ndef prepare_tensor(inputs, out_steps):\n max_len = max((x.shape[1] for x in inputs)) + 1 # zero-frame\n remainder = max_len % out_steps\n pad_len = max_len + (out_steps - remainder) if remainder > 0 else max_len\n return np.stack([_pad_tensor(x, pad_len) for x in inputs])\n\n\ndef _pad_stop_target(x, length):\n _pad = 1.\n assert x.ndim == 1\n return np.pad(\n x, (0, length - x.shape[0]), mode='constant', constant_values=_pad)\n\n\ndef prepare_stop_target(inputs, out_steps):\n max_len = max((x.shape[0] for x in inputs)) + 1 # zero-frame\n remainder = max_len % out_steps\n pad_len = max_len + (out_steps - remainder) if remainder > 0 else max_len\n return np.stack([_pad_stop_target(x, pad_len) for x in inputs])\n\n\ndef pad_per_step(inputs, pad_len):\n timesteps = inputs.shape[-1]\n return np.pad(\n inputs, [[0, 0], [0, 0], [0, pad_len]],\n mode='constant',\n constant_values=0.0)\n"
] |
[
[
"numpy.pad"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
delosrogers/clustergrammer-web
|
[
"14102cfca328214d3bc8285e8331663fe0e5fad4",
"14102cfca328214d3bc8285e8331663fe0e5fad4"
] |
[
"clustergrammer/upload_pages/clustergrammer/load_data.py",
"clustergrammer/upload_pages/clustergrammer_py_v112_vect_post_fix/categories.py"
] |
[
"def load_file(net, filename):\n import StringIO\n f = open(filename, 'r')\n buff = StringIO.StringIO(f.read())\n f.close()\n net.load_tsv_to_net(buff)\n\ndef load_tsv_to_net(net, file_buffer):\n import pandas as pd\n import categories\n\n lines = file_buffer.getvalue().split('\\n')\n num_labels = categories.check_categories(lines)\n\n row_arr = range(num_labels['row'])\n col_arr = range(num_labels['col'])\n tmp_df = {}\n\n # use header if there are col categories\n if len(col_arr) > 1:\n tmp_df['mat'] = pd.read_table(file_buffer, index_col=row_arr,\n header=col_arr)\n else:\n tmp_df['mat'] = pd.read_table(file_buffer, index_col=row_arr)\n\n # remove columns with all nans, occurs when there are trailing\n # tabs on rows\n tmp_df['mat'] = tmp_df['mat'].dropna(axis=1)\n\n net.df_to_dat(tmp_df) \n\ndef load_json_to_dict(filename):\n import json\n f = open(filename, 'r')\n inst_dict = json.load(f)\n f.close()\n return inst_dict\n\ndef load_gmt(filename):\n f = open(filename, 'r')\n lines = f.readlines()\n f.close()\n gmt = {}\n for i in range(len(lines)):\n inst_line = lines[i].rstrip()\n inst_term = inst_line.split('\\t')[0]\n inst_elems = inst_line.split('\\t')[2:]\n gmt[inst_term] = inst_elems\n\n return gmt \n\ndef load_data_to_net(net, inst_net):\n ''' load data into nodes and mat, also convert mat to numpy array'''\n import data_formats\n net.dat['nodes'] = inst_net['nodes']\n net.dat['mat'] = inst_net['mat']\n data_formats.mat_to_numpy_arr(net)",
"def check_categories(lines):\n '''\n find out how many row and col categories are available\n '''\n # count the number of row categories\n rcat_line = lines[0].split('\\t')\n\n # calc the number of row names and categories\n num_rc = 0\n found_end = False\n\n # skip first tab\n for inst_string in rcat_line[1:]:\n if inst_string == '':\n if found_end is False:\n num_rc = num_rc + 1\n else:\n found_end = True\n\n max_rcat = 15\n if max_rcat > len(lines):\n max_rcat = len(lines) - 1\n\n num_cc = 0\n for i in range(max_rcat):\n ccat_line = lines[i + 1].split('\\t')\n\n # make sure that line has length greater than one to prevent false cats from\n # trailing new lines at end of matrix\n if ccat_line[0] == '' and len(ccat_line) > 1:\n num_cc = num_cc + 1\n\n num_labels = {}\n num_labels['row'] = num_rc + 1\n num_labels['col'] = num_cc + 1\n\n return num_labels\n\ndef dict_cat(net):\n '''\n make a dictionary of node-category associations\n '''\n for inst_rc in ['row', 'col']:\n inst_keys = list(net.dat['node_info'][inst_rc].keys())\n all_cats = [x for x in inst_keys if 'cat-' in x]\n\n for inst_name_cat in all_cats:\n dict_cat = {}\n tmp_cats = net.dat['node_info'][inst_rc][inst_name_cat]\n tmp_nodes = net.dat['nodes'][inst_rc]\n\n for i in range(len(tmp_cats)):\n inst_cat = tmp_cats[i]\n inst_node = tmp_nodes[i]\n\n if inst_cat not in dict_cat:\n dict_cat[inst_cat] = []\n\n dict_cat[inst_cat].append(inst_node)\n\n tmp_name = 'dict_' + inst_name_cat.replace('-', '_')\n net.dat['node_info'][inst_rc][tmp_name] = dict_cat\n\ndef calc_cat_clust_order(net, inst_rc):\n '''\n cluster category subset of data\n '''\n from .__init__ import Network\n from copy import deepcopy\n from . import calc_clust, run_filter\n\n inst_keys = list(net.dat['node_info'][inst_rc].keys())\n all_cats = [x for x in inst_keys if 'cat-' in x]\n\n if len(all_cats) > 0:\n\n for inst_name_cat in all_cats:\n\n tmp_name = 'dict_' + inst_name_cat.replace('-', '_')\n dict_cat = net.dat['node_info'][inst_rc][tmp_name]\n\n unordered_cats = dict_cat.keys()\n\n ordered_cats = order_categories(unordered_cats)\n\n # this is the ordering of the columns based on their category, not\n # including their clustering ordering within category\n all_cat_orders = []\n tmp_names_list = []\n for inst_cat in ordered_cats:\n\n inst_nodes = dict_cat[inst_cat]\n\n tmp_names_list.extend(inst_nodes)\n\n # cat_net = deepcopy(Network())\n\n # cat_net.dat['mat'] = deepcopy(net.dat['mat'])\n # cat_net.dat['nodes'] = deepcopy(net.dat['nodes'])\n\n # cat_df = cat_net.dat_to_df()\n\n # sub_df = {}\n # if inst_rc == 'col':\n # sub_df['mat'] = cat_df['mat'][inst_nodes]\n # elif inst_rc == 'row':\n # # need to transpose df\n # cat_df['mat'] = cat_df['mat'].transpose()\n # sub_df['mat'] = cat_df['mat'][inst_nodes]\n # sub_df['mat'] = sub_df['mat'].transpose()\n\n # # filter matrix before clustering\n # ###################################\n # threshold = 0.0001\n # sub_df = run_filter.df_filter_row_sum(sub_df, threshold)\n # sub_df = run_filter.df_filter_col_sum(sub_df, threshold)\n\n # # load back to dat\n # cat_net.df_to_dat(sub_df)\n\n # cat_mat_shape = cat_net.dat['mat'].shape\n\n # print('***************')\n # try:\n # if cat_mat_shape[0]>1 and cat_mat_shape[1] > 1 and all_are_numbers == False:\n\n # calc_clust.cluster_row_and_col(cat_net, 'cos')\n # inst_cat_order = cat_net.dat['node_info'][inst_rc]['clust']\n # else:\n # inst_cat_order = list(range(len(cat_net.dat['nodes'][inst_rc])))\n\n # except:\n # inst_cat_order = list(range(len(cat_net.dat['nodes'][inst_rc])))\n\n\n # prev_order_len = len(all_cat_orders)\n\n # # add prev order length to the current order number\n # inst_cat_order = [i + prev_order_len for i in inst_cat_order]\n # all_cat_orders.extend(inst_cat_order)\n\n # # generate ordered list of row/col names, which will be used to\n # # assign the order to specific nodes\n # names_clust_list = [x for (y, x) in sorted(zip(all_cat_orders,\n # tmp_names_list))]\n\n names_clust_list = tmp_names_list\n\n # calc category-cluster order\n final_order = []\n\n for i in range(len(net.dat['nodes'][inst_rc])):\n\n inst_node_name = net.dat['nodes'][inst_rc][i]\n inst_node_num = names_clust_list.index(inst_node_name)\n\n final_order.append(inst_node_num)\n\n inst_index_cat = inst_name_cat.replace('-', '_') + '_index'\n\n net.dat['node_info'][inst_rc][inst_index_cat] = final_order\n\n\ndef order_categories(unordered_cats):\n '''\n If categories are strings, then simple ordering is fine.\n If categories are values then I'll need to order based on their values.\n The final ordering is given as the original categories (including titles) in a\n ordered list.\n '''\n\n no_titles = remove_titles(unordered_cats)\n\n all_are_numbers = check_all_numbers(no_titles)\n\n if all_are_numbers:\n ordered_cats = order_cats_based_on_values(unordered_cats, no_titles)\n else:\n ordered_cats = sorted(unordered_cats)\n\n return ordered_cats\n\n\ndef order_cats_based_on_values(unordered_cats, values_list):\n import pandas as pd\n\n try:\n # convert values_list to values\n values_list = [float(i) for i in values_list]\n\n inst_series = pd.Series(data=values_list, index=unordered_cats)\n\n inst_series.sort_values(inplace=True)\n\n ordered_cats = inst_series.index.tolist()\n\n # ordered_cats = unordered_cats\n except:\n # keep default ordering if error occurs\n print('error sorting cats based on values ')\n ordered_cats = unordered_cats\n\n return ordered_cats\n\ndef check_all_numbers(no_titles):\n all_numbers = True\n for tmp in no_titles:\n if is_number(tmp) == False:\n all_numbers = False\n\n return all_numbers\n\ndef remove_titles(cats):\n from copy import deepcopy\n\n # check if all have titles\n ###########################\n all_have_titles = True\n\n for inst_cat in cats:\n if is_number(inst_cat) == False:\n if ': ' not in inst_cat:\n all_have_titles = False\n else:\n all_have_titles = False\n\n if all_have_titles:\n no_titles = cats\n no_titles = [i.split(': ')[1] for i in no_titles]\n\n else:\n no_titles = cats\n\n return no_titles\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False"
] |
[
[
"pandas.read_table"
],
[
"pandas.Series"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
seo-inyoung/tensorflow
|
[
"e5dfc3bc38696060922b4d8a04d6e773467b9f08"
] |
[
"tensorflow/lite/python/lite_test.py"
] |
[
"# Lint as: python2, python3\n# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for lite.py.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport io\nimport logging\nimport os\nimport tempfile\n\nfrom absl.testing import parameterized\nimport numpy as np\nimport six\nfrom six.moves import range\n\nfrom tensorflow.lite.python import lite\nfrom tensorflow.lite.python import lite_constants\nfrom tensorflow.lite.python.convert import ConverterError\nfrom tensorflow.lite.python.convert import mlir_quantize\nfrom tensorflow.lite.python.interpreter import Interpreter\nfrom tensorflow.python import keras\nfrom tensorflow.python.client import session\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.ops.variables import global_variables_initializer as _global_variables_initializer\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import resource_loader\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.saved_model import saved_model\nfrom tensorflow.python.training.training_util import write_graph\n\n\nclass LiteTest(test_util.TensorFlowTestCase):\n \"\"\"Base class of all the tests in this module.\"\"\"\n\n def setUp(self):\n self._original_use_experimental_new_converter = (\n lite._USE_EXPERIMENTAL_NEW_CONVERTER)\n super(LiteTest, self).setUp()\n\n def tearDown(self):\n super(LiteTest, self).tearDown()\n lite._USE_EXPERIMENTAL_NEW_CONVERTER = (\n self._original_use_experimental_new_converter)\n\n\nclass TestModels(LiteTest):\n\n def assertValidDebugInfo(self, debug_info):\n \"\"\"Verify the DebugInfo is valid.\"\"\"\n file_names = set()\n for file_path in debug_info.files:\n file_names.add(os.path.basename(file_path))\n # To make the test independent on how the nodes are created, we only assert\n # the name of this test file.\n self.assertIn('lite_test.py', file_names)\n self.assertNotIn('lite_v2_test.py', file_names)\n\n\nclass FromConstructor(TestModels):\n\n # Tests invalid constructors using a dummy value for the GraphDef.\n def testInvalidConstructor(self):\n message = ('If input_tensors and output_tensors are None, both '\n 'input_arrays_with_shape and output_arrays must be defined.')\n\n # `output_arrays` is not defined.\n with self.assertRaises(ValueError) as error:\n lite.TFLiteConverter(\n None, None, [], input_arrays_with_shape=[('input', [3, 9])])\n self.assertEqual(message, str(error.exception))\n\n # `input_arrays_with_shape` is not defined.\n with self.assertRaises(ValueError) as error:\n lite.TFLiteConverter(None, [], None, output_arrays=['output'])\n self.assertEqual(message, str(error.exception))\n\n # Tests valid constructors using a dummy value for the GraphDef.\n def testValidConstructor(self):\n converter = lite.TFLiteConverter(\n None,\n None,\n None,\n input_arrays_with_shape=[('input', [3, 9])],\n output_arrays=['output'])\n self.assertFalse(converter._has_valid_tensors())\n self.assertEqual(converter.get_input_arrays(), ['input'])\n\n with self.assertRaises(ValueError) as error:\n converter._set_batch_size(1)\n self.assertEqual(\n 'The batch size cannot be set for this model. Please use '\n 'input_shapes parameter.', str(error.exception))\n\n converter = lite.TFLiteConverter(None, ['input_tensor'], ['output_tensor'])\n self.assertTrue(converter._has_valid_tensors())\n\n\nclass FromSessionTest(TestModels, parameterized.TestCase):\n\n def testFloat(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('add', output_details[0]['name'])\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n def testForgottenCallToAllocateTensors(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n input_index = interpreter.get_input_details()[0]['index']\n dummy_tensor = np.ones(shape=[1, 16, 16, 3], dtype=np.float32)\n with self.assertRaises(ValueError):\n interpreter.set_tensor(input_index, dummy_tensor)\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testString(self, enable_mlir):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(shape=[4], dtype=dtypes.string)\n out_tensor = array_ops.reshape(in_tensor, shape=[2, 2])\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.experimental_new_converter = enable_mlir\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.string_, input_details[0]['dtype'])\n self.assertTrue(([4] == input_details[0]['shape']).all())\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('Reshape', output_details[0]['name'])\n self.assertEqual(np.string_, output_details[0]['dtype'])\n self.assertTrue(([2, 2] == output_details[0]['shape']).all())\n # TODO(b/122659643): Test setting/getting string data via the python\n # interpreter API after support has been added.\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testQuantization(self, enable_mlir):\n with ops.Graph().as_default():\n in_tensor_1 = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32, name='inputA')\n in_tensor_2 = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32, name='inputB')\n out_tensor = array_ops.fake_quant_with_min_max_args(\n in_tensor_1 + in_tensor_2, min=0., max=1., name='output')\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess,\n [in_tensor_1, in_tensor_2],\n [out_tensor])\n converter.inference_type = lite_constants.QUANTIZED_UINT8\n converter.quantized_input_stats = {\n 'inputA': (0., 1.),\n 'inputB': (0., 1.)\n } # mean, std_dev\n converter.experimental_new_converter = enable_mlir\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(2, len(input_details))\n self.assertEqual('inputA', input_details[0]['name'])\n self.assertEqual(np.uint8, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertEqual((1., 0.),\n input_details[0]['quantization']) # scale, zero_point\n\n self.assertEqual('inputB', input_details[1]['name'])\n self.assertEqual(np.uint8, input_details[1]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[1]['shape']).all())\n self.assertEqual((1., 0.),\n input_details[1]['quantization']) # scale, zero_point\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual(np.uint8, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n self.assertTrue(output_details[0]['quantization'][0] > 0) # scale\n\n def testQuantizedInput(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.inference_input_type = lite_constants.QUANTIZED_UINT8\n converter.inference_type = lite_constants.FLOAT\n converter.quantized_input_stats = {'Placeholder': (0., 1.)} # mean, std_dev\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertLen(input_details, 1)\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.uint8, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertEqual((1., 0.),\n input_details[0]['quantization']) # scale, zero_point\n\n output_details = interpreter.get_output_details()\n self.assertLen(output_details, 1)\n self.assertEqual('add', output_details[0]['name'])\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization']) # float\n\n def testQuantizationInvalid(self):\n with ops.Graph().as_default():\n in_tensor_1 = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32, name='inputA')\n in_tensor_2 = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32, name='inputB')\n out_tensor = array_ops.fake_quant_with_min_max_args(\n in_tensor_1 + in_tensor_2, min=0., max=1., name='output')\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess,\n [in_tensor_1, in_tensor_2],\n [out_tensor])\n converter.inference_type = lite_constants.QUANTIZED_UINT8\n converter.quantized_input_stats = {'inputA': (0., 1.)} # mean, std_dev\n with self.assertRaises(ValueError) as error:\n converter.convert()\n self.assertEqual(\n 'Quantization input stats are not available for input tensors '\n '\\'inputB\\'.', str(error.exception))\n\n def testIntermediateInputArray(self):\n \"\"\"Convert a model from an intermediate input array.\"\"\"\n with ops.Graph().as_default():\n in_tensor_init = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n in_tensor_final = in_tensor_init + in_tensor_init\n out_tensor = in_tensor_final + in_tensor_final\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor_final],\n [out_tensor])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('add', input_details[0]['name'])\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('add_1', output_details[0]['name'])\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n def testSizeNoneInvalid(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Test None as shape when dynamic shapes are disabled. Run with TOCO in\n # order to invoke shape checking code.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.experimental_new_converter = False\n with self.assertRaises(ValueError) as error:\n converter.convert()\n self.assertEqual('Provide an input shape for input array \\'Placeholder\\'.',\n str(error.exception))\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testScalarValid(self, enable_mlir):\n # Construct a graph using a scalar (empty shape) input.\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(dtype=dtypes.float32, shape=[])\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Test conversion with the scalar input shape.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.experimental_new_converter = enable_mlir\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([] == input_details[0]['shape']).all())\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('add', output_details[0]['name'])\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([] == input_details[0]['shape']).all())\n\n # Validate inference using the scalar inputs/outputs.\n test_input = np.array(4.0, dtype=np.float32)\n expected_output = np.array(8.0, dtype=np.float32)\n interpreter.set_tensor(input_details[0]['index'], test_input)\n interpreter.invoke()\n\n output_data = interpreter.get_tensor(output_details[0]['index'])\n self.assertTrue((expected_output == output_data).all())\n\n def testSizeInvalid(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, None, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Test invalid shape. None after 1st dimension. Run with TOCO in order to\n # invoke shape checking code.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.experimental_new_converter = False\n with self.assertRaises(ValueError) as error:\n converter.convert()\n self.assertEqual(\n 'None is only supported in the 1st dimension. Tensor '\n '\\'Placeholder\\' has invalid shape \\'[1, None, 16, 3]\\'.',\n str(error.exception))\n\n def testSizeNone(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, None, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Test None after 1st dimension.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.experimental_new_converter = True\n tflite_model = converter.convert()\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n input_details = interpreter.get_input_details()\n self.assertLen(input_details, 1)\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 1, 16, 3] == input_details[0]['shape']).all())\n self.assertTrue(([1, -1, 16,\n 3] == input_details[0]['shape_signature']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n # Resize tensor with strict checking.\n with self.assertRaises(RuntimeError) as error:\n interpreter.resize_tensor_input(0, [3, 16, 16, 3], strict=True)\n self.assertIn(\n 'ResizeInputTensorStrict only allows mutating unknown dimensions '\n 'identified by -1.', str(error.exception))\n\n # Resize tensor and invoke.\n interpreter.resize_tensor_input(0, [1, 16, 16, 3], strict=True)\n interpreter.allocate_tensors()\n interpreter.invoke()\n\n input_details = interpreter.get_input_details()\n self.assertLen(input_details, 1)\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertTrue(([1, -1, 16,\n 3] == input_details[0]['shape_signature']).all())\n\n output_details = interpreter.get_output_details()\n self.assertTrue(([1, -1, 16,\n 3] == output_details[0]['shape_signature']).all())\n\n def testResizeTensorInputStrict(self):\n # Ensures that resize_tensor_input(strict=True) works as expected.\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n\n # Resize incorrect value.\n with self.assertRaises(RuntimeError) as error:\n interpreter.resize_tensor_input(0, [3, 16, 16, 3], strict=True)\n self.assertIn(\n 'ResizeInputTensorStrict only allows mutating unknown dimensions '\n 'identified by -1.', str(error.exception))\n\n # Resize correct value.\n interpreter.resize_tensor_input(0, [1, 16, 16, 3], strict=True)\n interpreter.allocate_tensors()\n\n def testBatchSizeValid(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[None, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('add', output_details[0]['name'])\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n def testBatchSizeNonZero(self):\n with ops.Graph().as_default():\n in_tensor_1 = array_ops.placeholder(\n shape=[None, 4], dtype=dtypes.float32, name='input1')\n in_tensor_2 = array_ops.placeholder(\n shape=[4, 10], dtype=dtypes.float32, name='input2')\n out_tensor = math_ops.matmul(in_tensor_1, in_tensor_2)\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess,\n [in_tensor_1, in_tensor_2],\n [out_tensor])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertLen(input_details, 2)\n self.assertEqual('input1', input_details[0]['name'])\n self.assertTrue(([1, 4] == input_details[0]['shape']).all())\n self.assertEqual('input2', input_details[1]['name'])\n self.assertTrue(([4, 10] == input_details[1]['shape']).all())\n\n def testFreezeGraph(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n var = variable_scope.get_variable(\n 'weights', shape=[1, 16, 16, 3], dtype=dtypes.float32)\n # Get the second output to ensure freezing properly processes tensor names\n # like 'X:1'.\n out_tensor = nn_ops.top_k(in_tensor + var, name='top_k')[1]\n sess = session.Session()\n sess.run(_global_variables_initializer())\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('top_k:1', output_details[0]['name'])\n self.assertEqual(np.int32, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 1] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n def testGraphviz(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.output_format = lite_constants.GRAPHVIZ_DOT\n graphviz_output = converter.convert()\n self.assertTrue(graphviz_output)\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testDumpGraphviz(self, enable_mlir):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.experimental_new_converter = enable_mlir\n graphviz_dir = self.get_temp_dir()\n converter.dump_graphviz_dir = graphviz_dir\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Ensure interpreter is able to allocate and check graphviz data.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n num_items_graphviz = len(os.listdir(graphviz_dir))\n self.assertTrue(num_items_graphviz)\n self.assertTrue(\n os.path.exists(os.path.join(graphviz_dir, 'toco_AT_IMPORT.dot')))\n self.assertTrue(\n os.path.exists(\n os.path.join(graphviz_dir, 'toco_AFTER_TRANSFORMATIONS.dot')))\n\n # new converter doesn't support `dump_graphviz_video` flag\n if not enable_mlir:\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.experimental_new_converter = enable_mlir\n graphviz_dir = self.get_temp_dir()\n converter.dump_graphviz_dir = graphviz_dir\n converter.dump_graphviz_video = True\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Ensure graphviz folder has more data after using video flag.\n num_items_graphviz_video = len(os.listdir(graphviz_dir))\n self.assertGreater(num_items_graphviz_video, num_items_graphviz)\n\n def testDumpConversionSummary(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n log_dir = self.get_temp_dir()\n converter.conversion_summary_dir = log_dir\n # Conversion logs will only be generated when the mlir converter is enabled.\n converter.experimental_new_converter = True\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n num_items_conversion_summary = len(os.listdir(log_dir))\n self.assertTrue(num_items_conversion_summary)\n\n def testDumpConversionSummaryWithOldConverter(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.experimental_new_converter = False\n log_dir = self.get_temp_dir()\n converter.conversion_summary_dir = log_dir\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n # Check nothing is generated under the conversion summary path.\n num_items_conversion_summary = len(os.listdir(log_dir))\n self.assertEqual(num_items_conversion_summary, 0)\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testInferenceInputType(self, enable_mlir):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.experimental_new_converter = enable_mlir\n converter.inference_input_type = lite_constants.QUANTIZED_UINT8\n converter.quantized_input_stats = {'Placeholder': (0., 1.)} # mean, std_dev\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.uint8, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertEqual((1., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('add', output_details[0]['name'])\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n\n def testDefaultRangesStats(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.inference_type = lite_constants.QUANTIZED_UINT8\n converter.quantized_input_stats = {'Placeholder': (0., 1.)} # mean, std_dev\n converter.default_ranges_stats = (0, 6) # min, max\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.uint8, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertEqual((1., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('add', output_details[0]['name'])\n self.assertEqual(np.uint8, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n self.assertTrue(output_details[0]['quantization'][0] > 0) # scale\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testPostTrainingQuantizeDeprecatedAttribute(self, enable_mlir):\n with ops.Graph().as_default():\n in_tensor_1 = array_ops.placeholder(\n shape=[33, 33], dtype=dtypes.float32, name='inputA')\n in_tensor_2 = constant_op.constant(\n np.random.uniform(low=-10., high=10., size=(33, 33)),\n shape=[33, 33],\n dtype=dtypes.float32,\n name='inputB')\n out_tensor = math_ops.matmul(in_tensor_1, in_tensor_2, name='output')\n sess = session.Session()\n\n quantized_converter = lite.TFLiteConverter.from_session(\n sess, [in_tensor_1], [out_tensor])\n self.assertFalse(quantized_converter.post_training_quantize)\n quantized_converter.experimental_new_converter = enable_mlir\n\n quantized_converter.post_training_quantize = True\n self.assertTrue(quantized_converter.post_training_quantize)\n self.assertEqual(quantized_converter.optimizations, [lite.Optimize.DEFAULT])\n\n quantized_tflite = quantized_converter.convert()\n self.assertTrue(quantized_tflite)\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testPostTrainingQuantize(self, enable_mlir):\n np.random.seed(0)\n with ops.Graph().as_default():\n # We need the tensor to have more than 1024 elements for quantize_weights\n # to kick in. Thus, the [33, 33] shape.\n in_tensor_1 = array_ops.placeholder(\n shape=[33, 33], dtype=dtypes.float32, name='inputA')\n in_tensor_2 = constant_op.constant(\n np.random.uniform(low=-10., high=10., size=(33, 33)),\n shape=[33, 33],\n dtype=dtypes.float32,\n name='inputB')\n out_tensor = math_ops.matmul(in_tensor_1, in_tensor_2, name='output')\n sess = session.Session()\n\n # Convert float model.\n float_converter = lite.TFLiteConverter.from_session(sess, [in_tensor_1],\n [out_tensor])\n float_converter.experimental_new_converter = enable_mlir\n float_tflite = float_converter.convert()\n self.assertTrue(float_tflite)\n\n # Convert quantized weights model.\n quantized_converter = lite.TFLiteConverter.from_session(\n sess, [in_tensor_1], [out_tensor])\n\n quantized_converter.experimental_new_converter = enable_mlir\n quantized_converter.optimizations = [lite.Optimize.DEFAULT]\n quantized_converter.experimental_new_converter = enable_mlir\n quantized_tflite = quantized_converter.convert()\n self.assertTrue(quantized_tflite)\n\n # Ensure that the quantized weights tflite model is smaller.\n self.assertTrue(len(quantized_tflite) < len(float_tflite))\n\n def _getCalibrationQuantizeModel(self):\n np.random.seed(0)\n inp = array_ops.placeholder(\n dtype=dtypes.float32, shape=(1, 5, 5, 3), name='input')\n conv = nn_ops.conv2d(\n inp,\n filter=array_ops.ones([3, 3, 3, 16]),\n strides=[1, 1, 1, 1],\n padding='SAME')\n output = nn_ops.relu(conv, name='output')\n\n def calibration_gen():\n for _ in range(5):\n yield [np.random.uniform(-1, 1, size=(1, 5, 5, 3)).astype(np.float32)]\n\n return (inp, output, calibration_gen)\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testPostTrainingCalibrateAndQuantize(self, enable_mlir):\n with ops.Graph().as_default():\n inp, output, calibration_gen = self._getCalibrationQuantizeModel()\n sess = session.Session()\n\n # Convert float model.\n float_converter = lite.TFLiteConverter.from_session(sess, [inp], [output])\n float_tflite = float_converter.convert()\n self.assertTrue(float_tflite)\n\n # Convert quantized model.\n quantized_converter = lite.TFLiteConverter.from_session(\n sess, [inp], [output])\n quantized_converter.experimental_new_converter = enable_mlir\n quantized_converter.optimizations = [lite.Optimize.DEFAULT]\n quantized_converter.representative_dataset = calibration_gen\n quantized_tflite = quantized_converter.convert()\n self.assertTrue(quantized_tflite)\n\n # The default input and output types should be float.\n interpreter = Interpreter(model_content=quantized_tflite)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual(np.float32, input_details[0]['dtype'])\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual(np.float32, output_details[0]['dtype'])\n\n # Ensure that the quantized weights tflite model is smaller.\n self.assertLess(len(quantized_tflite), len(float_tflite))\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testCalibrateAndQuantizeBuiltinInt8(self, enable_mlir):\n with ops.Graph().as_default():\n inp, output, calibration_gen = self._getCalibrationQuantizeModel()\n sess = session.Session()\n\n # Convert float model.\n float_converter = lite.TFLiteConverter.from_session(sess, [inp], [output])\n float_converter.experimental_new_converter = enable_mlir\n float_tflite = float_converter.convert()\n self.assertTrue(float_tflite)\n\n # Convert model by specifying target spec (instead of optimizations), since\n # when targeting an integer only backend, quantization is mandatory.\n quantized_converter = lite.TFLiteConverter.from_session(\n sess, [inp], [output])\n quantized_converter.experimental_new_converter = enable_mlir\n quantized_converter.target_spec.supported_ops = [\n lite.OpsSet.TFLITE_BUILTINS_INT8\n ]\n quantized_converter.representative_dataset = calibration_gen\n quantized_tflite = quantized_converter.convert()\n self.assertTrue(quantized_tflite)\n\n # The default input and output types should be float.\n interpreter = Interpreter(model_content=quantized_tflite)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual(np.float32, input_details[0]['dtype'])\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual(np.float32, output_details[0]['dtype'])\n\n # Ensure that the quantized weights tflite model is smaller.\n self.assertLess(len(quantized_tflite), len(float_tflite))\n\n @parameterized.named_parameters(\n # Quantize to Float16 even if rep data provided.\n ('UseRepresentativeData', True, False, True, False, False, False),\n # Quantize to Float16 if no rep data provided.\n ('NoRepresentativeData', False, False, True, False, False, False),\n # Post training quantization if both rep data and int8 included.\n ('UseSampleDataIncludeInt8', True, True, False, False, True, False),\n\n # Quantize to Float16 even if rep data provided with mlir.\n ('UseRepresentativeDataMlir', True, False, True, False, False, True),\n # Quantize to Float16 if no rep data provided with mlir.\n ('NoRepresentativeDataMlir', False, False, True, False, False, True),\n # Post training quantization if both rep data and int8 included with mlir.\n ('SampleDataIncludeInt8Mlir', True, True, False, False, True, True))\n def testQuantizeFloat16(self, use_rep_data, include_int8,\n is_float16_quantized, is_error,\n is_post_training_quantized, enable_mlir):\n with ops.Graph().as_default():\n inp, output, calibration_gen = self._getCalibrationQuantizeModel()\n sess = session.Session()\n\n idx = 1 if enable_mlir else 0\n node_name = 'Conv2D' if enable_mlir else 'Conv2D_bias'\n # Convert float model.\n float_converter = lite.TFLiteConverter.from_session(sess, [inp], [output])\n float_converter.experimental_new_converter = enable_mlir\n float_tflite = float_converter.convert()\n self.assertTrue(float_tflite)\n interpreter = Interpreter(model_content=float_tflite)\n interpreter.allocate_tensors()\n self.assertEqual(interpreter.get_tensor_details()[idx]['name'], node_name)\n self.assertEqual(interpreter.get_tensor_details()[idx]['dtype'],\n lite.constants.FLOAT)\n # Convert model to quantized version\n quantized_converter = lite.TFLiteConverter.from_session(\n sess, [inp], [output])\n quantized_converter.experimental_new_converter = enable_mlir\n quantized_converter.optimizations = [lite.Optimize.DEFAULT]\n quantized_converter.target_spec.supported_types = [lite.constants.FLOAT16]\n if include_int8:\n quantized_converter.target_spec.supported_types.append(\n lite.constants.INT8)\n if use_rep_data:\n quantized_converter.representative_dataset = calibration_gen\n\n if is_error:\n with self.assertRaises(ValueError) as error:\n quantized_converter.convert()\n self.assertEqual(\n 'representative_dataset is required when specifying '\n 'TFLITE_BUILTINS_INT8 or INT8 supported types.', str(error.exception))\n\n else:\n quantized_tflite = quantized_converter.convert()\n self.assertTrue(quantized_tflite)\n interpreter = Interpreter(model_content=quantized_tflite)\n interpreter.allocate_tensors()\n self.assertEqual(interpreter.get_tensor_details()[idx]['name'], node_name)\n\n if is_float16_quantized:\n # Verify that bias constant is float16 type.\n self.assertEqual(interpreter.get_tensor_details()[idx]['dtype'],\n lite.constants.FLOAT16)\n elif is_post_training_quantized:\n # Verify that bias constants is int32 type.\n self.assertEqual(interpreter.get_tensor_details()[idx]['dtype'],\n lite.constants.INT32)\n else:\n raise ValueError('Invalid test options.')\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testInvalidQuantizeFloat16(self, enable_mlir):\n with ops.Graph().as_default():\n inp, output, _ = self._getCalibrationQuantizeModel()\n sess = session.Session()\n\n # Specify float16 quantization\n quantized_converter = lite.TFLiteConverter.from_session(\n sess, [inp], [output])\n quantized_converter.experimental_new_converter = enable_mlir\n quantized_converter.optimizations = [lite.Optimize.DEFAULT]\n quantized_converter.target_spec.supported_types = [lite.constants.FLOAT16]\n # Specify only int8 builtin ops\n quantized_converter.target_spec.supported_ops = [\n lite.OpsSet.TFLITE_BUILTINS_INT8\n ]\n with self.assertRaises(ValueError) as error:\n quantized_converter.convert()\n self.assertEqual(\n 'TFLITE_BUILTINS_INT8 requires smallest supported type to be INT8.',\n str(error.exception))\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testInvalidPostTrainingQuantize(self, enable_mlir):\n np.random.seed(0)\n with ops.Graph().as_default():\n # We need the tensor to have more than 1024 elements for quantize_weights\n # to kick in. Thus, the [33, 33] shape.\n in_tensor_1 = array_ops.placeholder(\n shape=[33, 33], dtype=dtypes.float32, name='inputA')\n in_tensor_2 = constant_op.constant(\n np.random.uniform(low=-10., high=10., size=(33, 33)),\n shape=[33, 33],\n dtype=dtypes.float32,\n name='inputB')\n out_tensor = math_ops.matmul(in_tensor_1, in_tensor_2, name='output')\n sess = session.Session()\n\n # Attempt to convert to quantized weights model.\n quantized_converter = lite.TFLiteConverter.from_session(\n sess, [in_tensor_1], [out_tensor])\n quantized_converter.experimental_new_converter = enable_mlir\n quantized_converter.optimizations = [lite.Optimize.DEFAULT]\n # Restricting to int8 type only\n quantized_converter.target_spec.supported_types = [lite.constants.INT8]\n # A representative dataset is required for full fixed point quantization.\n with self.assertRaises(ValueError) as error:\n quantized_converter.convert()\n self.assertEqual(\n 'representative_dataset is required when specifying '\n 'TFLITE_BUILTINS_INT8 or INT8 supported types.', str(error.exception))\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testPostTrainingCalibrateAndQuantizeFloatNotAllowed(self, enable_mlir):\n with ops.Graph().as_default():\n inp, output, calibration_gen = self._getCalibrationQuantizeModel()\n sess = session.Session()\n\n # Convert float model.\n float_converter = lite.TFLiteConverter.from_session(sess, [inp], [output])\n float_converter.experimental_new_converter = enable_mlir\n float_tflite = float_converter.convert()\n self.assertTrue(float_tflite)\n\n # Convert quantized model.\n quantized_converter = lite.TFLiteConverter.from_session(\n sess, [inp], [output])\n quantized_converter.experimental_new_converter = enable_mlir\n quantized_converter.optimizations = [lite.Optimize.DEFAULT]\n quantized_converter.representative_dataset = calibration_gen\n quantized_converter.target_spec.supported_types = [lite.constants.INT8]\n quantized_tflite = quantized_converter.convert()\n self.assertTrue(quantized_tflite)\n\n # Ensure that the quantized weights tflite model is smaller.\n self.assertLess(len(quantized_tflite), len(float_tflite))\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testPostTrainingCalibrateAndQuantizeInt8Inputs(self, enable_mlir):\n with ops.Graph().as_default():\n inp, output, calibration_gen = self._getCalibrationQuantizeModel()\n sess = session.Session()\n\n # Convert float model.\n float_converter = lite.TFLiteConverter.from_session(sess, [inp], [output])\n float_converter.experimental_new_converter = enable_mlir\n float_tflite = float_converter.convert()\n self.assertTrue(float_tflite)\n\n # Convert quantized weights model.\n quantized_converter = lite.TFLiteConverter.from_session(\n sess, [inp], [output])\n quantized_converter.experimental_new_converter = enable_mlir\n quantized_converter.inference_input_type = lite_constants.INT8\n quantized_converter.inference_output_type = lite_constants.INT8\n quantized_converter.optimizations = [lite.Optimize.DEFAULT]\n quantized_converter.representative_dataset = calibration_gen\n quantized_tflite = quantized_converter.convert()\n self.assertTrue(quantized_tflite)\n\n # The input and output types should be int8.\n interpreter = Interpreter(model_content=quantized_tflite)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual(np.int8, input_details[0]['dtype'])\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual(np.int8, output_details[0]['dtype'])\n\n # Ensure that the quantized weights tflite model is smaller.\n self.assertLess(len(quantized_tflite), len(float_tflite))\n\n @parameterized.named_parameters(\n ('InferenceType_INT8', lite_constants.INT8),\n ('InferenceType_QUANTIZED_INT8', lite_constants.QUANTIZED_UINT8))\n def testRequiresInputStatsForTrainingTimeQuantization(self, quantized_type):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = array_ops.fake_quant_with_min_max_args(\n in_tensor + in_tensor, min=0., max=1.)\n sess = session.Session()\n\n quantized_converter = lite.TFLiteConverter.from_session(\n sess, [in_tensor], [out_tensor])\n\n with self.assertRaises(ValueError) as error:\n quantized_converter.inference_type = quantized_type\n quantized_converter.convert()\n self.assertEqual(\n 'std_dev and mean must be defined when inference_type or '\n 'inference_input_type is QUANTIZED_UINT8 or INT8.',\n str(error.exception))\n\n with self.assertRaises(ValueError) as error:\n quantized_converter.inference_type = lite_constants.FLOAT\n quantized_converter.inference_input_type = quantized_type\n quantized_converter.convert()\n self.assertEqual(\n 'std_dev and mean must be defined when inference_type or '\n 'inference_input_type is QUANTIZED_UINT8 or INT8.',\n str(error.exception))\n\n quantized_converter.inference_type = quantized_type\n quantized_converter.inference_input_type = quantized_type\n\n input_arrays = quantized_converter.get_input_arrays()\n quantized_converter.quantized_input_stats = {\n input_arrays[0]: (0., 1.)\n }\n quantized_converter.convert()\n\n def testTrainingTimeAndPostTrainingCalibrateAndQuantize(self):\n with ops.Graph().as_default():\n inp, output, calibration_gen = self._getCalibrationQuantizeModel()\n sess = session.Session()\n\n # Convert float model.\n float_converter = lite.TFLiteConverter.from_session(sess, [inp], [output])\n float_tflite = float_converter.convert()\n self.assertTrue(float_tflite)\n\n converter = lite.TFLiteConverter.from_session(sess, [inp], [output])\n\n # extra flags to trigger training time quantization conversion\n converter.inference_type = lite_constants.INT8\n converter.inference_input_type = lite_constants.FLOAT\n converter.inference_output_type = lite_constants.FLOAT\n input_arrays = converter.get_input_arrays()\n converter.quantized_input_stats = {\n input_arrays[0]: (0., 1.)\n }\n # trigger post-training quantization\n converter.optimizations = [lite.Optimize.DEFAULT]\n converter.representative_dataset = calibration_gen\n converter._experimental_new_quantizer = True\n quantized_tflite = converter.convert()\n self.assertTrue(quantized_tflite)\n self.assertLess(len(quantized_tflite), len(float_tflite))\n\n # calibration only api\n converter._experimental_calibrate_only = True\n calibrated_tflite = converter.convert()\n quantized_tflite = mlir_quantize(calibrated_tflite, fully_quantize=True)\n interpreter = Interpreter(model_content=quantized_tflite)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n self.assertEqual(np.int8, input_details[0]['dtype'])\n self.assertEqual((1., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(np.int8, output_details[0]['dtype'])\n\n def testFloatTocoConverter(self):\n \"\"\"Tests deprecated test TocoConverter.\"\"\"\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TocoConverter.from_session(sess, [in_tensor], [out_tensor])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Ensure the interpreter is able to load.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n def testMultipleOutputNodeNames(self):\n \"\"\"Tests converting a graph with an op that have multiple outputs.\"\"\"\n with ops.Graph().as_default():\n input_tensor = array_ops.placeholder(shape=[4], dtype=dtypes.float32)\n out0, out1, out2, out3 = array_ops.split(\n input_tensor, [1, 1, 1, 1], axis=0)\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [input_tensor],\n [out0, out1, out2, out3])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n interpreter.set_tensor(input_details[0]['index'],\n np.asarray([1.0, 2.0, 3.0, 4.0], dtype=np.float32))\n interpreter.invoke()\n\n output_details = interpreter.get_output_details()\n self.assertEqual(4, len(output_details))\n self.assertEqual(1.0, interpreter.get_tensor(output_details[0]['index']))\n self.assertEqual(2.0, interpreter.get_tensor(output_details[1]['index']))\n self.assertEqual(3.0, interpreter.get_tensor(output_details[2]['index']))\n self.assertEqual(4.0, interpreter.get_tensor(output_details[3]['index']))\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n @test_util.run_in_graph_and_eager_modes\n def testFunctions(self, enable_mlir):\n \"\"\"Tests tf.function in 1.X.\"\"\"\n\n @def_function.function\n def plus_placeholder(x, placeholder):\n return x + placeholder\n\n with ops.Graph().as_default():\n placeholder = array_ops.placeholder(\n dtype=dtypes.float32, shape=[1], name='input')\n variable_node = variables.Variable(1.0, name='variable_node')\n defun_node = plus_placeholder(variable_node, placeholder)\n output_node = math_ops.multiply(defun_node, 2.0, name='output_node')\n\n # Initialize variables in the model.\n sess = session.Session()\n sess.run(variables.variables_initializer([variable_node]))\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [placeholder],\n [output_node])\n converter.experimental_new_converter = enable_mlir\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('input', input_details[0]['name'])\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('output_node', output_details[0]['name'])\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n def testInferenceInputOutputTypeFloatDefault(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('add', output_details[0]['name'])\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n\n def testInferenceInputOutputTypeQuantizedUint8Default(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = array_ops.fake_quant_with_min_max_args(\n in_tensor + in_tensor, min=0., max=1., name='output')\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.inference_type = lite_constants.QUANTIZED_UINT8\n converter.quantized_input_stats = {'Placeholder': (0., 1.)} # mean, std_dev\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.uint8, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('output', output_details[0]['name'])\n self.assertEqual(np.uint8, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n\n def testReusingConverterWithDifferentPostTrainingQuantization(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n out_tensor = array_ops.fake_quant_with_min_max_args(\n in_tensor + in_tensor, min=0., max=1., name='output')\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n\n converter.post_training_quantize = True\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n converter.post_training_quantize = False\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n def testResizeWithShape(self):\n with ops.Graph().as_default():\n # Construct a graph with a dynamically shapped input and an internal node\n # that relies on the output of that input's shape.\n in_tensor = array_ops.placeholder(\n shape=[None, None], dtype=dtypes.float32)\n in_tensor2 = [[1, 2], [3, 4]]\n out_tensor = array_ops.reshape(in_tensor2, array_ops.shape(in_tensor))\n sess = session.Session()\n\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.experimental_new_converter = True\n tflite_model = converter.convert()\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n input_details = interpreter.get_input_details()\n self.assertLen(input_details, 1)\n self.assertTrue(([1, 1] == input_details[0]['shape']).all())\n self.assertTrue(([-1, -1] == input_details[0]['shape_signature']).all())\n\n # Resize tensor and invoke.\n interpreter.resize_tensor_input(0, [4])\n interpreter.allocate_tensors()\n interpreter.invoke()\n\n # The output should be reshaped properly according to the resized input.\n output_details = interpreter.get_output_details()\n self.assertLen(output_details, 1)\n self.assertEqual(np.int32, output_details[0]['dtype'])\n self.assertTrue(([4] == output_details[0]['shape']).all())\n output_data = interpreter.get_tensor(output_details[0]['index'])\n self.assertTrue(([1, 2, 3, 4] == output_data).all())\n\n def testResizingIntermediateDynamicTensor(self):\n # This is a regression test for the case where shape of dynamic output\n # tensors changes between invocations.\n # See also https://github.com/tensorflow/tensorflow/issues/26549\n with ops.Graph().as_default():\n input_tensor = array_ops.placeholder(shape=[1, 1], dtype=dtypes.float32)\n input2_tensor = array_ops.placeholder(shape=[1], dtype=dtypes.float32)\n\n # The bug is triggered only when dynamic tensor is intermediate. Putting\n # some other ops around it.\n neg = math_ops.negative(input2_tensor)\n padding = array_ops.placeholder(shape=[2, 2], dtype=dtypes.int32)\n output_tensor = array_ops.pad(input_tensor, padding) + neg\n\n sess = session.Session()\n\n converter = lite.TFLiteConverter.from_session(\n sess, [input_tensor, padding, input2_tensor], [output_tensor])\n tflite_model = converter.convert()\n\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n interpreter.set_tensor(input_details[1]['index'],\n np.array([[1, 1], [1, 1]], dtype=np.int32))\n interpreter.invoke()\n\n # Without the fix, invocation will fail when changing the shape of\n # intermediate dynamic tensors.\n interpreter.set_tensor(input_details[1]['index'],\n np.array([[2, 2], [2, 2]], dtype=np.int32))\n interpreter.invoke()\n\n def testGraphDebugInfo(self):\n \"\"\"Test a session has debug info captured.\"\"\"\n\n @def_function.function\n def plus_placeholder(x, placeholder):\n return x + placeholder\n\n with ops.Graph().as_default():\n placeholder = array_ops.placeholder(\n dtype=dtypes.float32, shape=[1], name='input')\n variable_node = variables.Variable(1.0, name='variable_node')\n defun_node = plus_placeholder(variable_node, placeholder)\n output_node = math_ops.multiply(defun_node, 2.0, name='output_node')\n\n # Initialize variables in the model.\n sess = session.Session()\n sess.run(variables.variables_initializer([variable_node]))\n\n converter = lite.TFLiteConverter.from_session(sess, [placeholder],\n [output_node])\n converter.convert()\n self.assertValidDebugInfo(converter._debug_info)\n\n # Check the add node in the inlined function is included.\n func = sess.graph.as_graph_def().library.function[0].signature.name\n self.assertIn(('add@' + six.ensure_str(func)), converter._debug_info.traces)\n\n\nclass FromFrozenGraphFile(LiteTest):\n\n def testFloat(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n _ = in_tensor + in_tensor\n sess = session.Session()\n\n # Write graph to file.\n graph_def_file = os.path.join(self.get_temp_dir(), 'model.pb')\n write_graph(sess.graph_def, '', graph_def_file, False)\n sess.close()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_frozen_graph(graph_def_file,\n ['Placeholder'], ['add'])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('add', output_details[0]['name'])\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n def testFloatWithShapesArray(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n _ = in_tensor + in_tensor\n sess = session.Session()\n\n # Write graph to file.\n graph_def_file = os.path.join(self.get_temp_dir(), 'model.pb')\n write_graph(sess.graph_def, '', graph_def_file, False)\n sess.close()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_frozen_graph(\n graph_def_file, ['Placeholder'], ['add'],\n input_shapes={'Placeholder': [1, 16, 16, 3]})\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n\n def testFreezeGraph(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n var = variable_scope.get_variable(\n 'weights', shape=[1, 16, 16, 3], dtype=dtypes.float32)\n _ = in_tensor + var\n sess = session.Session()\n\n # Write graph to file.\n graph_def_file = os.path.join(self.get_temp_dir(), 'model.pb')\n write_graph(sess.graph_def, '', graph_def_file, False)\n sess.close()\n\n # Ensure the graph with variables cannot be converted.\n with self.assertRaises(ValueError) as error:\n lite.TFLiteConverter.from_frozen_graph(graph_def_file, ['Placeholder'],\n ['add'])\n self.assertEqual('Please freeze the graph using freeze_graph.py.',\n str(error.exception))\n\n def testPbtxt(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n _ = in_tensor + in_tensor\n sess = session.Session()\n\n # Write graph to file.\n graph_def_file = os.path.join(self.get_temp_dir(), 'model.pbtxt')\n write_graph(sess.graph_def, '', graph_def_file, True)\n sess.close()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_frozen_graph(graph_def_file,\n ['Placeholder'], ['add'])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('add', output_details[0]['name'])\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n def testInvalidFileNotFound(self):\n with self.assertRaises(IOError) as error:\n lite.TFLiteConverter.from_frozen_graph('invalid_file', ['Placeholder'],\n ['add'])\n self.assertEqual('File \\'invalid_file\\' does not exist.',\n str(error.exception))\n\n def testInvalidFileBadData(self):\n graph_def_file = os.path.join(self.get_temp_dir(), 'invalid_file')\n with gfile.Open(graph_def_file, 'wb') as temp_file:\n temp_file.write('bad data')\n temp_file.flush()\n\n # Attempts to convert the invalid model.\n with self.assertRaises(IOError) as error:\n lite.TFLiteConverter.from_frozen_graph(graph_def_file, ['Placeholder'],\n ['add'])\n self.assertEqual(\n 'Unable to parse input file \\'{}\\'.'.format(graph_def_file),\n str(error.exception))\n\n def testFloatTocoConverter(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n _ = in_tensor + in_tensor\n sess = session.Session()\n\n # Write graph to file.\n graph_def_file = os.path.join(self.get_temp_dir(), 'model.pb')\n write_graph(sess.graph_def, '', graph_def_file, False)\n sess.close()\n\n # Convert model and ensure model is not None.\n converter = lite.TocoConverter.from_frozen_graph(graph_def_file,\n ['Placeholder'], ['add'])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Ensure the model is able to load.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n def testGraphDebugInfo(self):\n \"\"\"Test a frozen graph doesn't have debug info captured.\"\"\"\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(\n shape=[1, 16, 16, 3], dtype=dtypes.float32)\n _ = in_tensor + in_tensor\n sess = session.Session()\n\n # Write graph to file.\n graph_def_file = os.path.join(self.get_temp_dir(), 'model.pb')\n write_graph(sess.graph_def, '', graph_def_file, False)\n sess.close()\n\n # Convert model and ensure model is not None.\n converter = lite.TocoConverter.from_frozen_graph(graph_def_file,\n ['Placeholder'], ['add'])\n converter.convert()\n # GraphDebugInfo should be none for frozen graph.\n self.assertTrue(not converter._debug_info)\n\n\nclass FromFrozenGraphObjectDetection(LiteTest):\n\n def _initObjectDetectionArgs(self):\n # Initializes the arguments required for the object detection model.\n # Looks for the model file which is saved in a different location internally\n # and externally.\n filename = resource_loader.get_path_to_datafile('testdata/tflite_graph.pb')\n if not os.path.exists(filename):\n filename = os.path.join(\n resource_loader.get_root_dir_with_all_resources(),\n '../tflite_mobilenet_ssd_quant_protobuf/tflite_graph.pb')\n if not os.path.exists(filename):\n raise IOError(\"File '{0}' does not exist.\".format(filename))\n\n self._graph_def_file = filename\n self._input_arrays = ['normalized_input_image_tensor']\n self._output_arrays = [\n 'TFLite_Detection_PostProcess', 'TFLite_Detection_PostProcess:1',\n 'TFLite_Detection_PostProcess:2', 'TFLite_Detection_PostProcess:3'\n ]\n self._input_shapes = {'normalized_input_image_tensor': [1, 300, 300, 3]}\n\n def testTFLiteGraphDef(self):\n # Tests the object detection model that cannot be loaded in TensorFlow.\n self._initObjectDetectionArgs()\n\n converter = lite.TFLiteConverter.from_frozen_graph(self._graph_def_file,\n self._input_arrays,\n self._output_arrays,\n self._input_shapes)\n converter.allow_custom_ops = True\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('normalized_input_image_tensor', input_details[0]['name'])\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 300, 300, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(4, len(output_details))\n self.assertEqual('TFLite_Detection_PostProcess', output_details[0]['name'])\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 10, 4] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n self.assertEqual('TFLite_Detection_PostProcess:1',\n output_details[1]['name'])\n self.assertTrue(([1, 10] == output_details[1]['shape']).all())\n self.assertEqual('TFLite_Detection_PostProcess:2',\n output_details[2]['name'])\n self.assertTrue(([1, 10] == output_details[2]['shape']).all())\n self.assertEqual('TFLite_Detection_PostProcess:3',\n output_details[3]['name'])\n self.assertTrue(([1] == output_details[3]['shape']).all())\n\n\nclass FromSavedModelTest(TestModels):\n\n def _createSavedModel(self, shape):\n \"\"\"Create a simple SavedModel.\"\"\"\n saved_model_dir = os.path.join(self.get_temp_dir(), 'simple_savedmodel')\n with ops.Graph().as_default():\n with session.Session() as sess:\n in_tensor_1 = array_ops.placeholder(\n shape=shape, dtype=dtypes.float32, name='inputB')\n in_tensor_2 = array_ops.placeholder(\n shape=shape, dtype=dtypes.float32, name='inputA')\n out_tensor = in_tensor_1 + in_tensor_2\n inputs = {'x': in_tensor_1, 'y': in_tensor_2}\n outputs = {'z': out_tensor}\n saved_model.simple_save(sess, saved_model_dir, inputs, outputs)\n return saved_model_dir\n\n def testSimpleModel(self):\n \"\"\"Test a SavedModel.\"\"\"\n saved_model_dir = self._createSavedModel(shape=[1, 16, 16, 3])\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_saved_model(saved_model_dir)\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(2, len(input_details))\n self.assertStartsWith(input_details[0]['name'], 'inputA')\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n self.assertStartsWith(input_details[1]['name'], 'inputB')\n self.assertEqual(np.float32, input_details[1]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[1]['shape']).all())\n self.assertEqual((0., 0.), input_details[1]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertStartsWith(output_details[0]['name'], 'add')\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n def testOldConverterWarning(self):\n \"\"\"Test if the warning message when using TOCO is logged.\"\"\"\n saved_model_dir = self._createSavedModel(shape=[1, 16, 16, 3])\n log = io.BytesIO() if six.PY2 else io.StringIO()\n handler = logging.StreamHandler(log)\n logging.root.addHandler(handler)\n warning_message = 'Please consider switching to use new converter'\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_saved_model(saved_model_dir)\n converter.experimental_new_converter = False\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n self.assertIn(warning_message, log.getvalue())\n logging.root.removeHandler(handler)\n\n def testNewConverterOptOut(self):\n \"\"\"Test if the opt out message when using New converter is logged.\"\"\"\n saved_model_dir = self._createSavedModel(shape=[1, 16, 16, 3])\n log = io.BytesIO() if six.PY2 else io.StringIO()\n handler = logging.StreamHandler(log)\n logging.root.addHandler(handler)\n optout_message = ('Using experimental converter: '\n 'If you encountered a problem')\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_saved_model(saved_model_dir)\n converter.experimental_new_converter = True\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n self.assertIn(optout_message, log.getvalue())\n logging.root.removeHandler(handler)\n\n def testNoneBatchSize(self):\n \"\"\"Test a SavedModel, with None in input tensor's shape.\"\"\"\n saved_model_dir = self._createSavedModel(shape=[None, 16, 16, 3])\n\n converter = lite.TFLiteConverter.from_saved_model(saved_model_dir)\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(2, len(input_details))\n self.assertStartsWith(input_details[0]['name'], 'inputA')\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n self.assertStartsWith(input_details[1]['name'], 'inputB')\n self.assertEqual(np.float32, input_details[1]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[1]['shape']).all())\n self.assertEqual((0., 0.), input_details[1]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertStartsWith(output_details[0]['name'], 'add')\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n def testOrderInputArrays(self):\n \"\"\"Test a SavedModel ordering of input arrays.\"\"\"\n saved_model_dir = self._createSavedModel(shape=[1, 16, 16, 3])\n\n converter = lite.TFLiteConverter.from_saved_model(\n saved_model_dir, input_arrays=['inputB', 'inputA'])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(2, len(input_details))\n self.assertStartsWith(input_details[0]['name'], 'inputA')\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n self.assertStartsWith(input_details[1]['name'], 'inputB')\n self.assertEqual(np.float32, input_details[1]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == input_details[1]['shape']).all())\n self.assertEqual((0., 0.), input_details[1]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertStartsWith(output_details[0]['name'], 'add')\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n def testSubsetInputArrays(self):\n \"\"\"Test a SavedModel with a subset of the input array names of the model.\"\"\"\n saved_model_dir = self._createSavedModel(shape=[1, 16, 16, 3])\n\n # Check case where input shape is given.\n converter = lite.TFLiteConverter.from_saved_model(\n saved_model_dir,\n input_arrays=['inputA'],\n input_shapes={'inputA': [1, 16, 16, 3]})\n\n # Since we only partially specify the input, this is not allowed.\n with self.assertRaises(ConverterError):\n _ = converter.convert()\n\n # Check case where input shape is None.\n converter = lite.TFLiteConverter.from_saved_model(\n saved_model_dir, input_arrays=['inputA'], input_shapes={'inputA': None})\n\n # Since we only partially specify the input, this is not allowed.\n with self.assertRaises(ConverterError):\n _ = converter.convert()\n\n def testSimpleModelTocoConverter(self):\n \"\"\"Test a SavedModel with deprecated TocoConverter.\"\"\"\n saved_model_dir = self._createSavedModel(shape=[1, 16, 16, 3])\n\n # Convert model and ensure model is not None.\n converter = lite.TocoConverter.from_saved_model(saved_model_dir)\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Ensure the model is able to load.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n def testGraphDebugInfo(self):\n \"\"\"Test a SavedModel has debug info captured.\"\"\"\n saved_model_dir = self._createSavedModel(shape=[1, 16, 16, 3])\n converter = lite.TFLiteConverter.from_saved_model(saved_model_dir)\n converter.convert()\n self.assertValidDebugInfo(converter._debug_info)\n\n\nclass MyAddLayer(keras.layers.Layer):\n\n def __init__(self, increment, **kwargs):\n super(MyAddLayer, self).__init__(**kwargs)\n self._increment = increment\n\n def call(self, inputs):\n return inputs + self._increment\n\n def get_config(self):\n config = super(MyAddLayer, self).get_config()\n config['increment'] = self._increment\n return config\n\n\nclass FromKerasFile(TestModels, parameterized.TestCase):\n\n def setUp(self):\n super(FromKerasFile, self).setUp()\n self._keras_file = None\n self._custom_objects = None\n if not context.executing_eagerly():\n keras.backend.clear_session()\n\n def tearDown(self):\n if self._keras_file:\n os.remove(self._keras_file)\n super(FromKerasFile, self).tearDown()\n\n def _getSequentialModel(self, include_custom_layer=False):\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(2, input_shape=(3,)))\n if include_custom_layer:\n model.add(MyAddLayer(1.0))\n model.add(keras.layers.RepeatVector(3))\n model.add(keras.layers.TimeDistributed(keras.layers.Dense(3)))\n model.compile(\n loss=keras.losses.MSE,\n optimizer='sgd',\n metrics=[keras.metrics.categorical_accuracy],\n sample_weight_mode='temporal')\n x = np.random.random((1, 3))\n y = np.random.random((1, 3, 3))\n model.train_on_batch(x, y)\n model.predict(x)\n\n try:\n fd, self._keras_file = tempfile.mkstemp('.h5')\n keras.models.save_model(model, self._keras_file)\n finally:\n os.close(fd)\n\n if include_custom_layer:\n self._custom_objects = {'MyAddLayer': MyAddLayer}\n\n @parameterized.named_parameters(('_graph', context.graph_mode),\n ('_eager', context.eager_mode))\n def testSequentialModel(self, test_context):\n \"\"\"Test a Sequential tf.keras model with default inputs.\"\"\"\n with test_context():\n self._getSequentialModel()\n\n converter = lite.TFLiteConverter.from_keras_model_file(self._keras_file)\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check tensor details of converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertLen(input_details, 1)\n self.assertEndsWith(input_details[0]['name'], 'dense_input')\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertLen(output_details, 1)\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 3, 3] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n # Check inference of converted model.\n input_data = np.array([[1, 2, 3]], dtype=np.float32)\n interpreter.set_tensor(input_details[0]['index'], input_data)\n interpreter.invoke()\n tflite_result = interpreter.get_tensor(output_details[0]['index'])\n\n keras_model = keras.models.load_model(self._keras_file)\n keras_result = keras_model.predict(input_data)\n\n np.testing.assert_almost_equal(tflite_result, keras_result, 5)\n\n @parameterized.named_parameters(('_graph', context.graph_mode),\n ('_eager', context.eager_mode))\n def testCustomLayer(self, test_context):\n \"\"\"Test a Sequential tf.keras model with default inputs.\"\"\"\n with test_context():\n self._getSequentialModel(include_custom_layer=True)\n\n converter = lite.TFLiteConverter.from_keras_model_file(\n self._keras_file, custom_objects=self._custom_objects)\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check tensor details of converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n\n # Check inference of converted model.\n input_data = np.array([[1, 2, 3]], dtype=np.float32)\n interpreter.set_tensor(input_details[0]['index'], input_data)\n interpreter.invoke()\n tflite_result = interpreter.get_tensor(output_details[0]['index'])\n\n keras_model = keras.models.load_model(\n self._keras_file, custom_objects=self._custom_objects)\n keras_result = keras_model.predict(input_data)\n\n np.testing.assert_almost_equal(tflite_result, keras_result, 5)\n\n def testSequentialModelInputArray(self):\n \"\"\"Test a Sequential tf.keras model testing input arrays argument.\"\"\"\n ops.disable_eager_execution()\n self._getSequentialModel()\n\n # Invalid input array raises error.\n with self.assertRaises(ValueError) as error:\n lite.TFLiteConverter.from_keras_model_file(\n self._keras_file, input_arrays=['invalid-input'])\n self.assertEqual(\"Invalid tensors 'invalid-input' were found.\",\n str(error.exception))\n\n # Valid input array.\n converter = lite.TFLiteConverter.from_keras_model_file(\n self._keras_file, input_arrays=['dense_input'])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n def testSequentialModelInputShape(self):\n \"\"\"Test a Sequential tf.keras model testing input shapes argument.\"\"\"\n self._getSequentialModel()\n\n # Passing in shape of invalid input array raises error.\n with self.assertRaises(ValueError) as error:\n converter = lite.TFLiteConverter.from_keras_model_file(\n self._keras_file, input_shapes={'invalid-input': [2, 3]})\n self.assertEqual(\n \"Invalid tensor 'invalid-input' found in tensor shapes map.\",\n str(error.exception))\n\n # Passing in shape of valid input array.\n converter = lite.TFLiteConverter.from_keras_model_file(\n self._keras_file, input_shapes={'dense_input': [2, 3]})\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check input shape from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertLen(input_details, 1)\n self.assertEndsWith(input_details[0]['name'], 'dense_input')\n self.assertTrue(([2, 3] == input_details[0]['shape']).all())\n\n def testSequentialModelOutputArray(self):\n \"\"\"Test a Sequential tf.keras model testing output arrays argument.\"\"\"\n ops.disable_eager_execution()\n self._getSequentialModel()\n\n # Invalid output array raises error.\n with self.assertRaises(ValueError) as error:\n lite.TFLiteConverter.from_keras_model_file(\n self._keras_file, output_arrays=['invalid-output'])\n self.assertEqual(\"Invalid tensors 'invalid-output' were found.\",\n str(error.exception))\n\n # Valid output array.\n converter = lite.TFLiteConverter.from_keras_model_file(\n self._keras_file, output_arrays=['time_distributed/Reshape_1'])\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n @parameterized.named_parameters(('_graph', context.graph_mode),\n ('_eager', context.eager_mode))\n def testFunctionalModel(self, test_context):\n \"\"\"Test a Functional tf.keras model with default inputs.\"\"\"\n with test_context():\n inputs = keras.layers.Input(shape=(3,), name='input')\n x = keras.layers.Dense(2)(inputs)\n output = keras.layers.Dense(3)(x)\n\n model = keras.models.Model(inputs, output)\n model.compile(\n loss=keras.losses.MSE,\n optimizer='sgd',\n metrics=[keras.metrics.categorical_accuracy])\n x = np.random.random((1, 3))\n y = np.random.random((1, 3))\n model.train_on_batch(x, y)\n\n model.predict(x)\n fd, self._keras_file = tempfile.mkstemp('.h5')\n try:\n keras.models.save_model(model, self._keras_file)\n finally:\n os.close(fd)\n\n # Convert to TFLite model.\n converter = lite.TFLiteConverter.from_keras_model_file(self._keras_file)\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check tensor details of converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertLen(input_details, 1)\n self.assertEqual('input', input_details[0]['name'])\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertLen(output_details, 1)\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 3] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n # Check inference of converted model.\n input_data = np.array([[1, 2, 3]], dtype=np.float32)\n interpreter.set_tensor(input_details[0]['index'], input_data)\n interpreter.invoke()\n tflite_result = interpreter.get_tensor(output_details[0]['index'])\n\n keras_model = keras.models.load_model(self._keras_file)\n keras_result = keras_model.predict(input_data)\n\n np.testing.assert_almost_equal(tflite_result, keras_result, 5)\n\n def testFunctionalModelMultipleInputs(self):\n \"\"\"Test a Functional tf.keras model with multiple inputs and outputs.\"\"\"\n a = keras.layers.Input(shape=(3,), name='input_a')\n b = keras.layers.Input(shape=(3,), name='input_b')\n dense = keras.layers.Dense(4, name='dense')\n c = dense(a)\n d = dense(b)\n e = keras.layers.Dropout(0.5, name='dropout')(c)\n\n model = keras.models.Model([a, b], [d, e])\n model.compile(\n loss=keras.losses.MSE,\n optimizer='sgd',\n metrics=[keras.metrics.mae],\n loss_weights=[1., 0.5])\n\n input_a_np = np.random.random((10, 3))\n input_b_np = np.random.random((10, 3))\n output_d_np = np.random.random((10, 4))\n output_e_np = np.random.random((10, 4))\n model.train_on_batch([input_a_np, input_b_np], [output_d_np, output_e_np])\n\n model.predict([input_a_np, input_b_np], batch_size=5)\n fd, self._keras_file = tempfile.mkstemp('.h5')\n try:\n keras.models.save_model(model, self._keras_file)\n finally:\n os.close(fd)\n\n # Convert to TFLite model.\n converter = lite.TFLiteConverter.from_keras_model_file(self._keras_file)\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertLen(input_details, 2)\n self.assertEndsWith(input_details[0]['name'], 'input_a')\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n self.assertEndsWith(input_details[1]['name'], 'input_b')\n self.assertEqual(np.float32, input_details[1]['dtype'])\n self.assertTrue(([1, 3] == input_details[1]['shape']).all())\n self.assertEqual((0., 0.), input_details[1]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertLen(output_details, 2)\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 4] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n self.assertEqual(np.float32, output_details[1]['dtype'])\n self.assertTrue(([1, 4] == output_details[1]['shape']).all())\n self.assertEqual((0., 0.), output_details[1]['quantization'])\n\n def testFunctionalSequentialModel(self):\n \"\"\"Test a Functional tf.keras model containing a Sequential model.\"\"\"\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(2, input_shape=(3,)))\n model.add(keras.layers.RepeatVector(3))\n model.add(keras.layers.TimeDistributed(keras.layers.Dense(3)))\n model = keras.models.Model(model.input, model.output)\n\n model.compile(\n loss=keras.losses.MSE,\n optimizer='sgd',\n metrics=[keras.metrics.categorical_accuracy],\n sample_weight_mode='temporal')\n x = np.random.random((1, 3))\n y = np.random.random((1, 3, 3))\n model.train_on_batch(x, y)\n model.predict(x)\n\n model.predict(x)\n fd, self._keras_file = tempfile.mkstemp('.h5')\n try:\n keras.models.save_model(model, self._keras_file)\n finally:\n os.close(fd)\n\n # Convert to TFLite model.\n converter = lite.TFLiteConverter.from_keras_model_file(self._keras_file)\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check tensor details of converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertLen(input_details, 1)\n self.assertEndsWith(input_details[0]['name'], 'dense_input')\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([1, 3] == input_details[0]['shape']).all())\n self.assertEqual((0., 0.), input_details[0]['quantization'])\n\n output_details = interpreter.get_output_details()\n self.assertLen(output_details, 1)\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([1, 3, 3] == output_details[0]['shape']).all())\n self.assertEqual((0., 0.), output_details[0]['quantization'])\n\n # Check inference of converted model.\n input_data = np.array([[1, 2, 3]], dtype=np.float32)\n interpreter.set_tensor(input_details[0]['index'], input_data)\n interpreter.invoke()\n tflite_result = interpreter.get_tensor(output_details[0]['index'])\n\n keras_model = keras.models.load_model(self._keras_file)\n keras_result = keras_model.predict(input_data)\n\n np.testing.assert_almost_equal(tflite_result, keras_result, 5)\n\n def testSequentialModelTocoConverter(self):\n \"\"\"Test a Sequential tf.keras model with deprecated TocoConverter.\"\"\"\n self._getSequentialModel()\n\n converter = lite.TocoConverter.from_keras_model_file(self._keras_file)\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Ensure the model is able to load.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n @parameterized.named_parameters(('_graph', context.graph_mode),\n ('_eager', context.eager_mode))\n def testGraphDebugInfo(self, test_context):\n \"\"\"Test a Sequential tf.keras model has debug info captured.\"\"\"\n with test_context():\n self._getSequentialModel()\n converter = lite.TFLiteConverter.from_keras_model_file(self._keras_file)\n converter.convert()\n self.assertValidDebugInfo(converter._debug_info)\n\n def testExperimentalSparsifyModel(self):\n self._getSequentialModel()\n\n converter = lite.TocoConverter.from_keras_model_file(self._keras_file)\n converter._experimental_sparsify_model = True\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n\nclass GrapplerTest(TestModels, parameterized.TestCase):\n\n def testConstantFolding(self):\n ops.disable_eager_execution()\n # Constant folding handles the tf.broadcast_to operation which was not\n # supported by the TFLite at the time this test was added.\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(shape=[3, 3], dtype=dtypes.float32)\n y_const = constant_op.constant([1., 2., 3.])\n y_broadcast = gen_array_ops.broadcast_to(y_const, [3, 3])\n out_tensor = math_ops.matmul(in_tensor, y_broadcast, name='output')\n sess = session.Session()\n\n # Convert model.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n tflite_model = converter.convert()\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertEqual(1, len(input_details))\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual(np.float32, input_details[0]['dtype'])\n self.assertTrue(([3, 3] == input_details[0]['shape']).all())\n\n output_details = interpreter.get_output_details()\n self.assertEqual(1, len(output_details))\n self.assertEqual('output', output_details[0]['name'])\n self.assertEqual(np.float32, output_details[0]['dtype'])\n self.assertTrue(([3, 3] == output_details[0]['shape']).all())\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testInputNodeIsNotFolded(self, enable_mlir):\n ops.disable_eager_execution()\n # Constant folding handles the tf.broadcast_to operation which was not\n # supported by the TFLite at the time this test was added.\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(shape=[3], dtype=dtypes.float32)\n y_const = constant_op.constant([1., 2., 3.])\n y_add = y_const + y_const\n out_tensor = in_tensor * y_add\n sess = session.Session()\n\n # Convert model.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor, y_const],\n [out_tensor])\n converter.experimental_new_converter = enable_mlir\n tflite_model = converter.convert()\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertLen(input_details, 2)\n self.assertEqual('Placeholder', input_details[0]['name'])\n self.assertEqual('Const', input_details[1]['name'])\n\n def testGrapplerConstFolding(self):\n # Constant folding converts the following add operation to tf.broadcast_to\n # operation which was not supported by the TFLite at the time this test was\n # added.\n @def_function.function\n def plus_placeholder(x, placeholder):\n return x + placeholder\n\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(shape=[2, 2], dtype=dtypes.float32)\n out_tensor = plus_placeholder(\n array_ops.zeros([2, 2, 2]),\n array_ops.reshape(in_tensor, shape=[2, 2]))\n sess = session.Session()\n\n # Convert model.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n # Only disable this path in MLIR conversion for toco compatibility.\n converter.experimental_new_converter = True\n tflite_model = converter.convert()\n\n # Check values from converted model.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n self.assertLen(input_details, 1)\n self.assertEqual('Placeholder', input_details[0]['name'])\n\n\nclass ImportOpsUtilTest(LiteTest):\n\n def testGetPotentiallySupportedOps(self):\n self.assertIsNotNone(lite.get_potentially_supported_ops())\n\n\nclass DefaultConverterAttrsTest(LiteTest):\n\n def testAttrs(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(shape=[2, 2], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n\n # Assert output format.\n self.assertEqual(converter.output_format, lite_constants.TFLITE)\n\n # Assert the default inference type is float.\n self.assertEqual(converter.inference_type, lite_constants.FLOAT)\n\n # Assert the default inference type overrides are None.\n self.assertIsNone(converter.inference_input_type)\n self.assertIsNone(converter.inference_output_type)\n\n # Assert the default quantization options are not set.\n self.assertEqual(converter.quantized_input_stats, {})\n self.assertIsNone(converter.default_ranges_stats)\n self.assertFalse(converter.reorder_across_fake_quant)\n self.assertFalse(converter.change_concat_input_ranges)\n\n # Assert dropping control dependency is enabled by default.\n self.assertTrue(converter.drop_control_dependency)\n\n # Assert dumping extra information is disabled by default.\n self.assertIsNone(converter.dump_graphviz_dir)\n self.assertFalse(converter.dump_graphviz_video)\n self.assertIsNone(converter.conversion_summary_dir)\n\n\nif __name__ == '__main__':\n test.main()\n"
] |
[
[
"tensorflow.lite.python.lite.TocoConverter.from_keras_model_file",
"tensorflow.python.keras.models.save_model",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.keras.layers.Dense",
"tensorflow.lite.python.lite.TocoConverter.from_frozen_graph",
"tensorflow.python.ops.array_ops.split",
"numpy.asarray",
"tensorflow.python.ops.gen_array_ops.broadcast_to",
"tensorflow.lite.python.lite.TocoConverter.from_saved_model",
"tensorflow.lite.python.interpreter.Interpreter",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.ops.variables.Variable",
"tensorflow.lite.python.lite.TFLiteConverter.from_keras_model_file",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.platform.resource_loader.get_root_dir_with_all_resources",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.saved_model.saved_model.simple_save",
"tensorflow.python.ops.array_ops.fake_quant_with_min_max_args",
"tensorflow.lite.python.lite.TFLiteConverter.from_session",
"numpy.testing.assert_almost_equal",
"tensorflow.python.platform.test.main",
"tensorflow.lite.python.lite.TFLiteConverter.from_saved_model",
"tensorflow.python.ops.array_ops.ones",
"tensorflow.python.ops.math_ops.matmul",
"tensorflow.python.platform.resource_loader.get_path_to_datafile",
"tensorflow.python.ops.array_ops.pad",
"tensorflow.lite.python.lite.get_potentially_supported_ops",
"tensorflow.python.ops.math_ops.negative",
"tensorflow.python.keras.models.Sequential",
"tensorflow.python.keras.models.load_model",
"tensorflow.lite.python.lite.TFLiteConverter.from_frozen_graph",
"tensorflow.python.client.session.Session",
"tensorflow.lite.python.lite.TocoConverter.from_session",
"tensorflow.python.keras.layers.Dropout",
"tensorflow.python.ops.variables.global_variables_initializer",
"numpy.array",
"tensorflow.python.keras.layers.Input",
"tensorflow.python.keras.layers.RepeatVector",
"tensorflow.lite.python.lite.TFLiteConverter",
"tensorflow.python.ops.variables.variables_initializer",
"numpy.random.random",
"numpy.random.seed",
"tensorflow.python.framework.ops.Graph",
"tensorflow.lite.python.convert.mlir_quantize",
"tensorflow.python.ops.variable_scope.get_variable",
"numpy.ones",
"tensorflow.python.training.training_util.write_graph",
"tensorflow.python.ops.array_ops.reshape",
"numpy.random.uniform",
"tensorflow.python.keras.models.Model",
"tensorflow.python.ops.math_ops.multiply",
"tensorflow.python.ops.nn_ops.relu",
"tensorflow.python.keras.backend.clear_session",
"tensorflow.python.ops.nn_ops.top_k",
"tensorflow.python.framework.ops.disable_eager_execution",
"tensorflow.python.platform.gfile.Open",
"tensorflow.python.framework.constant_op.constant"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"1.12",
"2.7",
"2.6",
"1.4",
"1.13",
"2.3",
"2.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.2",
"1.2",
"2.10"
]
}
] |
yDon96/pepper_assistant
|
[
"cc079e9c6e93afae513625ee4803e3c5c75ce5b6"
] |
[
"src/utils/utils.py"
] |
[
"import numpy as np\n\ndef batch_cosine_similarity(x1, x2):\n '''\n x1,x2 must be l2 normalized\n '''\n\n # https://en.wikipedia.org/wiki/Cosine_similarity\n # 1 = equal direction ; -1 = opposite direction\n mul = np.multiply(x1, x2)\n s = np.sum(mul, axis=1)\n\n # l1 = np.sum(np.multiply(x1, x1),axis=1)\n # l2 = np.sum(np.multiply(x2, x2), axis=1)\n # as values have have length 1, we don't need to divide by norm (as it is 1)\n return s\n\n\ndef dist2id(distance, y, ths, norm=False, mode='avg', filter_under_th=True):\n d = distance.copy()\n ths = np.array([ths]*len(y))\n y = np.array(y)\n\n # remove elements under the threshold\n if filter_under_th:\n idx = d >= ths\n d = d[idx]\n y = y[idx]\n ths = ths[idx]\n\n if d.shape[0] == 0:\n return None\n\n if norm:\n # norm in case of different thresholds\n d = (d - ths)/(1-ths)\n\n ids = list(set(y.tolist()))\n\n ids_prob = []\n for i in ids:\n if mode == 'max':\n ids_prob.append(np.max(d[y == i]))\n if mode == 'avg':\n ids_prob.append(np.mean(d[y == i]))\n if mode == 'min':\n ids_prob.append(np.min(d[y == i]))\n\n ids_prob = np.array(ids_prob)\n return ids[np.argmax(ids_prob)]\n"
] |
[
[
"numpy.multiply",
"numpy.min",
"numpy.max",
"numpy.argmax",
"numpy.mean",
"numpy.array",
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MandoGuardado/2022-01-04-Python
|
[
"abceb619c1fad9c55e6023b57fbb35d9a8f0e640"
] |
[
"pandas_23/pandabear03.py"
] |
[
"#!/usr/bin/python3\n\nimport pandas as pd\n\n\ndef main():\n # create a dataframe ciscocsv\n ciscocsv = pd.read_csv(\"ciscodata.csv\")\n # create a dataframe ciscojson\n ciscojson = pd.read_json(\"ciscodata2.json\")\n\n # The line below concats and reapplies the index value\n ciscodf = pd.concat([ciscocsv, ciscojson], ignore_index=True, sort=False)\n\n ## print to the screen the re-indexed dataframe\n print(ciscodf)\n\n ## print a blankline\n print()\n\n ## export to json\n ciscodf.to_json(\"combined_ciscodata.json\")\n\n ## export to csv\n ciscodf.to_csv(\"combined_ciscodata.csv\")\n\n ## export to Excel\n ciscodf.to_excel(\"combined_ciscodata.xls\")\n\n ## create a python dictionary\n x = ciscodf.to_dict()\n print(x)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"pandas.read_json"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
thabbott/RRTMG_SW
|
[
"1a3fb6a9aac3d602280e6979a1791a7e54cf3916"
] |
[
"python/test.py"
] |
[
"import rrtmg_sw_wrapper as sw\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Constants\ncp = 1e3\ng = 9.80\nLv = 2.5e6\nRv = 460e0\nRd = 287e0\ne0 = 610e0\nT0 = 273e0\nMair = 29e0\nMh2o = 18e0\nMco2 = 44e0\nh = 6.626e-34\nkB = 1.381e-23\nc = 3.00e8\nNUM_BANDS = 14\nNUM_AER = 6\n\n\n# Atmospheric profiles\ndef calc_qsat(T, p):\n esat = e0*np.exp(-Lv/Rv*(1/T - 1/T0))\n return esat*Rd/(p*Rv)\n\ndef calc_profiles(Ts, Gamma, zt, RH, \n n = 1000, ps = 101325e0, ztop = 25e3):\n \n # Set height grid\n zf = np.linspace(0, ztop, n+1)\n zc = 0.5*(zf[1:] + zf[:-1])\n \n # Calculate temperatures\n Tt = Ts - Gamma*zt\n Tf = Ts - Gamma*zf\n Tf[zf >= zt] = Tt\n Tc = Ts - Gamma*zc\n Tc[zc >= zt] = Tt\n\n # Calculate pressures\n pt = ps*((Ts - Gamma*zt)/Ts)**(g/(Rd*Gamma))\n pf = ps*(Tf/Ts)**(g/(Rd*Gamma))\n pf[zf >= zt] = pt*np.exp(-g*(zf[zf >= zt] - zt)/(Rd*Tt))\n pc = ps*(Tc/Ts)**(g/(Rd*Gamma))\n pc[zc >= zt] = pt*np.exp(-g*(zc[zc >= zt] - zt)/(Rd*Tt))\n\n # Calculate humidity\n qc = RH*calc_qsat(Tc, pc)\n\n # Return profiles\n return (zc, zf, pc, pf, Tc, Tf, qc)\n\n# Planck function\ndef calc_B(nu, T):\n return 2*h*c**2*nu**3/(np.exp(h*c*nu/(kB*T)) - 1)\n\n# RRTMG interface\ndef rrtmg_zeros(shape):\n return np.zeros(shape, dtype = float, order = 'F')\n\ndef run_rrtmg_sw(Ts, Gamma, zt, pco2, pch4, RH, \n n = 1000, ps = 101325e0, ztop = 25e3):\n\n # Generate profiles\n zc, zf, pc, pf, Tc, Tf, q = calc_profiles(\n Ts, Gamma, zt, RH, n = n, ps = ps, ztop = ztop)\n\n # Set inputs\n ncol = 1\n nlay = n\n icld = 0\n iaer = 0\n play = rrtmg_zeros((ncol,nlay))\n play[0,:] = pc/1e2\n plev = rrtmg_zeros((ncol,nlay+1))\n plev[0,:] = pf/1e2\n tlay = rrtmg_zeros((ncol,nlay))\n tlay[0,:] = Tc\n tlev = rrtmg_zeros((ncol,nlay+1))\n tlev[0,:] = Tf\n tsfc = rrtmg_zeros((ncol,))\n tsfc[0] = Ts\n h2ovmr = rrtmg_zeros((ncol,nlay))\n h2ovmr[0,:] = q*Rv/Rd\n o3vmr = rrtmg_zeros((ncol,nlay))\n co2vmr = rrtmg_zeros((ncol,nlay))\n co2vmr[0,:] = pco2\n ch4vmr = rrtmg_zeros((ncol,nlay))\n ch4vmr[0,:] = pch4\n n2ovmr = rrtmg_zeros((ncol,nlay))\n o2vmr = rrtmg_zeros((ncol,nlay))\n o2vmr[0,:] = 0.2\n asdir = rrtmg_zeros((ncol,))\n asdir[:] = 0.1\n aldir = rrtmg_zeros((ncol,))\n aldir[:] = 0.1\n asdif = rrtmg_zeros((ncol,))\n asdif[:] = 0.1\n aldif = rrtmg_zeros((ncol,))\n aldif[:] = 0.1\n dyofyr = 0\n adjes = 1.0\n coszen = rrtmg_zeros((ncol,))\n coszen[:] = 0.667\n scon = 510.0\n isolvar = 0\n indsolvar = rrtmg_zeros((2,))\n indsolvar[:] = 1.0\n bndsolvar = rrtmg_zeros((NUM_BANDS,))\n bndsolvar[:] = 1.0\n solcycfrac = 0.0\n\n\n\n inflgsw = 2 # provide cloud water paths and droplet radii,\n # treat water and ice clouds separately\n iceflgsw = 1 # Ebert & Curry 1992\n liqflgsw = 1 # radius-dependent optical properties\n cldfr = rrtmg_zeros((ncol,nlay))\n taucld = rrtmg_zeros((NUM_BANDS,ncol,nlay))\n ssacld = rrtmg_zeros((NUM_BANDS,ncol,nlay))\n asmcld = rrtmg_zeros((NUM_BANDS,ncol,nlay))\n fsfcld = rrtmg_zeros((NUM_BANDS,ncol,nlay))\n cicewp = rrtmg_zeros((ncol,nlay))\n cliqwp = rrtmg_zeros((ncol,nlay))\n reice = rrtmg_zeros((ncol,nlay))\n reliq = rrtmg_zeros((ncol,nlay))\n tauaer = rrtmg_zeros((ncol,nlay,NUM_BANDS))\n ssaaer = rrtmg_zeros((ncol,nlay,NUM_BANDS))\n asmaer = rrtmg_zeros((ncol,nlay,NUM_BANDS))\n ecaer = rrtmg_zeros((ncol,nlay,NUM_AER))\n \n # Output arrays\n swuflx = rrtmg_zeros((ncol,nlay+1))\n swdflx = rrtmg_zeros((ncol,nlay+1))\n swhr = rrtmg_zeros((ncol,nlay))\n swuflxc = rrtmg_zeros((ncol,nlay+1))\n swdflxc = rrtmg_zeros((ncol,nlay+1))\n swhrc = rrtmg_zeros((ncol,nlay))\n wavenumber_range = rrtmg_zeros((2,))\n\n # Run RRTM\n SWNS = np.zeros((NUM_BANDS,))\n SWDT = np.zeros((NUM_BANDS,))\n nu_low = np.zeros((NUM_BANDS,))\n nu_high = np.zeros((NUM_BANDS,))\n for iband in range(16,16+NUM_BANDS):\n sw.rrtmg_sw_wrapper(\n ncol, nlay, icld, iaer, \n play, plev, tlay, tlev, tsfc, \n h2ovmr, o3vmr, co2vmr, ch4vmr, n2ovmr, o2vmr, \n asdir, asdif, aldir, aldif, \n coszen, adjes, dyofyr, scon, isolvar, \n inflgsw, iceflgsw, liqflgsw, cldfr, \n taucld, ssacld, asmcld, fsfcld, \n cicewp, cliqwp, reice, reliq, \n tauaer, ssaaer, asmaer, ecaer, \n iband, iband, \n swuflx, swdflx, swhr, swuflxc, swdflxc, swhrc, \n wavenumber_range, \n bndsolvar, indsolvar, solcycfrac )\n SWNS[iband-16] = swdflx[0,0] - swuflx[0,0]\n SWDT[iband-16] = swdflx[0,-1]\n nu_low[iband-16] = wavenumber_range[0]\n nu_high[iband-16] = wavenumber_range[1]\n\n # Return results\n return SWNS, SWDT, nu_low, nu_high\n\n# Initialize\nsw.rrtmg_sw_ini_wrapper(cp)\n\n# Compute spectrally-resolved surface net flux\n# Use reference state from UChicago RRTM page\n# http://climatemodels.uchicago.edu/rrtm/\nSWNS, SWDT, nu_low, nu_high = run_rrtmg_sw(\n 284.42, 6e-3, 15e3, 400e-6, 1.7e-6, 0.8)\nisort = np.argsort(nu_low)\nSWNS = SWNS[isort]\nSWDT = SWDT[isort]\nnu_low = nu_low[isort]\nnu_high = nu_high[isort]\n\nprint(SWNS)\nprint(nu_low)\nprint(nu_high)\n\n# Create arrays for boxy plots\nSWNS_nu = SWNS/(nu_high - nu_low)\nSWDT_nu = SWDT/(nu_high - nu_low)\nSWNS_nu_box = np.stack((SWNS_nu, SWNS_nu), axis = -1).ravel()\nSWDT_nu_box = np.stack((SWDT_nu, SWDT_nu), axis = -1).ravel()\nnu_box = np.stack((nu_low, nu_high), axis = -1).ravel()\n\n# Plot\nplt.rc('font', size = 8)\nfig, axes = plt.subplots(figsize = (3.25, 3), nrows = 1, ncols = 1,\n constrained_layout = True, dpi = 200)\naxes = np.array(axes)[np.newaxis,np.newaxis]\naxes[0,0].plot(nu_box, SWNS_nu_box, 'k-', \n label = 'surface (net)')\naxes[0,0].plot(nu_box, SWDT_nu_box, '-', \n color = 'gray', label = 'TOA (down)')\naxes[0,0].set_title(\n 'Surface heating: %.1f W m$^{-2}$' % (np.sum(SWNS)), fontsize = 8)\naxes[0,0].set_xlabel(r'$\\nu$ (cm $^{-1}$)')\naxes[0,0].set_ylabel('Flux (W m$^{-2}$ cm, positive downward)')\naxes[0,0].set_xlim([nu_box[0], nu_box[-1]])\naxes[0,0].legend(loc = 'upper right', frameon = False)\naxes[0,0].set_ylim([0, axes[0,0].get_ylim()[1]])\n\nplt.savefig('test.pdf')\nplt.show()\n"
] |
[
[
"numpy.linspace",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"numpy.stack",
"numpy.exp",
"numpy.argsort",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.zeros",
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ItzBraveNoob/sports-betting
|
[
"521d4ef6bd0e079d508f40609681124edc2c6805"
] |
[
"sportsbet/datasets/_soccer/_dummy.py"
] |
[
"\"\"\"\nDataloder for dummy data.\n\"\"\"\n\n# Author: Georgios Douzas <[email protected]>\n# License: MIT\n\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import ParameterGrid\n\nfrom sportsbet.datasets._base import _BaseDataLoader\n\n\nclass DummySoccerDataLoader(_BaseDataLoader):\n \"\"\"Dataloader for dummy data.\"\"\"\n\n DATE = pd.Timestamp(datetime.now()) + pd.to_timedelta(1, 'd')\n PARAMS = [\n {'league': ['Greece'], 'division': [1], 'year': [2017, 2019]},\n {'league': ['Spain'], 'division': [1], 'year': [1997]},\n {'league': ['Spain'], 'division': [2], 'year': [1999]},\n {'league': ['England'], 'division': [2], 'year': [1997]},\n {'league': ['England'], 'division': [3], 'year': [1998]},\n {'league': ['France'], 'division': [1], 'year': [2000]},\n {'league': ['France'], 'division': [1], 'year': [2001]},\n ]\n SCHEMA = [\n ('division', int),\n ('league', object),\n ('date', np.datetime64),\n ('home_team', object),\n ('away_team', object),\n ('home_team__full_time_goals', int),\n ('away_team__full_time_goals', int),\n ('interwetten__home_win__odds', float),\n ('interwetten__draw__odds', float),\n ('interwetten__away_win__odds', float),\n ('williamhill__home_win__odds', float),\n ('williamhill__draw__odds', float),\n ('williamhill__away_win__odds', float),\n ('year', int),\n ]\n OUTCOMES = [\n (\n 'home_win__full_time_goals',\n lambda outputs: outputs['home_team__full_time_goals']\n > outputs['away_team__full_time_goals'],\n ),\n (\n 'away_win__full_time_goals',\n lambda outputs: outputs['home_team__full_time_goals']\n < outputs['away_team__full_time_goals'],\n ),\n (\n 'draw__full_time_goals',\n lambda outputs: outputs['home_team__full_time_goals']\n == outputs['away_team__full_time_goals'],\n ),\n (\n 'over_2.5_goals__full_time_goals',\n lambda outputs: outputs['home_team__full_time_goals']\n + outputs['away_team__full_time_goals']\n > 2.5,\n ),\n (\n 'under_2.5_goals__full_time_goals',\n lambda outputs: outputs['home_team__full_time_goals']\n + outputs['away_team__full_time_goals']\n < 2.5,\n ),\n ]\n DATA = pd.DataFrame(\n {\n 'division': [1.0, 2.0, 1.0, 1.0, 2.0, 2.0, 3.0, 1.0, 4.0, 3.0, 1.0, 1.0],\n 'league': [\n 'Greece',\n 'Greece',\n 'Greece',\n 'Spain',\n 'Spain',\n 'England',\n 'England',\n np.nan,\n np.nan,\n 'France',\n 'France',\n 'France',\n ],\n 'date': [\n pd.Timestamp('17/3/2017'),\n np.nan,\n pd.Timestamp('17/3/2019'),\n pd.Timestamp('5/4/1997'),\n pd.Timestamp('3/4/1999'),\n pd.Timestamp('5/7/1997'),\n pd.Timestamp('3/4/1998'),\n pd.Timestamp('3/4/1998'),\n DATE,\n DATE,\n pd.Timestamp('3/4/2000'),\n pd.Timestamp('6/4/2001'),\n ],\n 'year': [\n 2017,\n np.nan,\n 2019,\n 1997,\n 1999,\n 1997,\n 1998,\n 1998,\n DATE.year,\n DATE.year,\n 2000,\n 2001,\n ],\n 'home_team': [\n 'Olympiakos',\n np.nan,\n 'Panathinaikos',\n 'Real Madrid',\n 'Barcelona',\n 'Arsenal',\n 'Liverpool',\n 'Liverpool',\n 'Barcelona',\n 'Monaco',\n 'Lens',\n 'PSG',\n ],\n 'away_team': [\n 'Panathinaikos',\n np.nan,\n 'AEK',\n 'Barcelona',\n 'Real Madrid',\n 'Liverpool',\n 'Arsenal',\n 'Arsenal',\n 'Real Madrid',\n 'PSG',\n 'Monaco',\n 'Lens',\n ],\n 'home_team__full_time_goals': [\n 1,\n np.nan,\n 1,\n 2,\n 2,\n np.nan,\n 1,\n 1,\n np.nan,\n np.nan,\n 2,\n 1,\n ],\n 'away_team__full_time_goals': [\n 1,\n np.nan,\n 0,\n 1,\n 2,\n 2,\n 3,\n 2,\n np.nan,\n np.nan,\n 1,\n 2,\n ],\n 'interwetten__home_win__odds': [\n 2.0,\n 1.5,\n 2,\n 1.5,\n 2.5,\n 3,\n 2,\n np.nan,\n 3,\n 1.5,\n 2.0,\n 3.0,\n ],\n 'interwetten__draw__odds': [\n 2,\n 2,\n 2,\n 3.5,\n 4.5,\n 2.5,\n 4.5,\n 2.5,\n 2.5,\n 3.5,\n 2.5,\n 2.5,\n ],\n 'interwetten__away_win__odds': [\n 2,\n 2,\n 3,\n 2.5,\n 2,\n 2,\n 3.5,\n 3.5,\n 2,\n 2.5,\n 3.0,\n 2.0,\n ],\n 'williamhill__home_win__odds': [\n 2,\n 1.5,\n 3.5,\n 2.5,\n 2.0,\n 3.0,\n 2.0,\n 4.0,\n 3.5,\n 2.5,\n 2.5,\n 2.5,\n ],\n 'williamhill__draw__odds': [\n 2,\n np.nan,\n 1.5,\n 2.5,\n np.nan,\n np.nan,\n np.nan,\n np.nan,\n 2.5,\n 1.5,\n 2.5,\n 3.0,\n ],\n 'williamhill__away_win__odds': [\n 2,\n np.nan,\n np.nan,\n np.nan,\n np.nan,\n np.nan,\n np.nan,\n np.nan,\n 2.0,\n 2.5,\n 3.0,\n 2.5,\n ],\n 'fixtures': [\n False,\n False,\n False,\n False,\n False,\n False,\n False,\n False,\n True,\n True,\n False,\n False,\n ],\n }\n )\n\n @classmethod\n def _get_schema(cls):\n return cls.SCHEMA\n\n @classmethod\n def _get_outcomes(cls):\n return cls.OUTCOMES\n\n @classmethod\n def _get_params(cls):\n return ParameterGrid(cls.PARAMS)\n\n def _get_data(self):\n return self.DATA\n\n def set_data(self, data):\n self.DATA = data\n return self\n"
] |
[
[
"pandas.to_timedelta",
"sklearn.model_selection.ParameterGrid",
"pandas.Timestamp"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bruceli-rw0/edge2pic-generation
|
[
"e9ee6f89361d1a12b044c0ab665a09fca4a47089",
"e9ee6f89361d1a12b044c0ab665a09fca4a47089"
] |
[
"generator/models/networksHD.py",
"generator/util/visualizer.py"
] |
[
"import numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom .helper import *\n\n###############################################################################\n# Functions\n###############################################################################\ndef define_G(\n input_nc, \n output_nc, \n ngf, \n netG, \n n_downsample_global=3, \n n_blocks_global=9, \n n_local_enhancers=1, \n n_blocks_local=3, \n norm='instance', \n init_type='normal', \n init_gain=0.02, \n device='cpu',\n gpu_ids=[]\n):\n norm_layer = get_norm_layer(norm_type=norm)\n if netG == 'global':\n netG = GlobalGenerator(input_nc, output_nc, ngf, n_downsample_global, n_blocks_global, norm_layer)\n elif netG == 'local':\n netG = LocalEnhancer(input_nc, output_nc, ngf, n_downsample_global, n_blocks_global, n_local_enhancers, n_blocks_local, norm_layer)\n elif netG == 'encoder':\n netG = Encoder(input_nc, output_nc, ngf, n_downsample_global, norm_layer)\n else:\n raise('generator not implemented!')\n return init_net(netG, init_type, init_gain, device, gpu_ids)\n\ndef define_D(\n input_nc, \n ndf, \n n_layers_D, \n num_D=1, \n norm='instance', \n init_type='normal', \n init_gain=0.02, \n use_sigmoid=False, \n getIntermFeat=False, \n device='cpu',\n gpu_ids=[],\n):\n norm_layer = get_norm_layer(norm_type=norm)\n netD = MultiscaleDiscriminator(input_nc, ndf, n_layers_D, norm_layer, use_sigmoid, num_D, getIntermFeat)\n return init_net(netD, init_type, init_gain, device, gpu_ids)\n\n\n##############################################################################\n# Losses\n##############################################################################\nclass GANLoss(nn.Module):\n def __init__(self, use_lsgan=True, target_real_label=1.0, target_fake_label=0.0, device=None):\n super(GANLoss, self).__init__()\n self.real_label = target_real_label\n self.fake_label = target_fake_label\n self.real_label_var = None\n self.fake_label_var = None\n self.device = device\n self.loss = nn.MSELoss() if use_lsgan else nn.BCELoss()\n\n def forward(self, input, target_is_real):\n if isinstance(input[0], list):\n loss = 0\n for input_i in input:\n pred = input_i[-1]\n target_tensor = self.get_target_tensor(pred, target_is_real)\n loss += self.loss(pred, target_tensor)\n return loss\n else: \n target_tensor = self.get_target_tensor(input[-1], target_is_real)\n return self.loss(input[-1], target_tensor)\n\n def get_target_tensor(self, input, target_is_real):\n target_tensor = None\n if target_is_real:\n create_label = ((self.real_label_var is None) or (self.real_label_var.numel() != input.numel()))\n if create_label:\n real_tensor = torch.FloatTensor(input.size()).fill_(self.real_label).to(self.device)\n self.real_label_var = Variable(real_tensor, requires_grad=False)\n target_tensor = self.real_label_var\n else:\n create_label = ((self.fake_label_var is None) or (self.fake_label_var.numel() != input.numel()))\n if create_label:\n fake_tensor = torch.FloatTensor(input.size()).fill_(self.fake_label).to(self.device)\n self.fake_label_var = Variable(fake_tensor, requires_grad=False)\n target_tensor = self.fake_label_var\n return target_tensor\n\n\nclass VGGLoss(nn.Module):\n def __init__(self, device):\n super(VGGLoss, self).__init__()\n self.vgg = Vgg19()\n self.vgg.to(device)\n self.criterion = nn.L1Loss()\n self.weights = [1.0/32, 1.0/16, 1.0/8, 1.0/4, 1.0] \n\n def forward(self, x, y): \n x_vgg, y_vgg = self.vgg(x), self.vgg(y)\n loss = 0\n for i in range(len(x_vgg)):\n loss += self.weights[i] * self.criterion(x_vgg[i], y_vgg[i].detach()) \n return loss\n\n##############################################################################\n# Generator\n##############################################################################\nclass ResnetBlock(nn.Module):\n def __init__(self, dim, padding_type, norm_layer, activation=nn.ReLU(True), use_dropout=False):\n super().__init__()\n self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, activation, use_dropout)\n\n def build_conv_block(self, dim, padding_type, norm_layer, activation, use_dropout):\n conv_block = []\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n\n conv_block += [\n nn.Conv2d(dim, dim, kernel_size=3, padding=p),\n norm_layer(dim),\n activation\n ]\n if use_dropout:\n conv_block += [nn.Dropout(0.5)]\n\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n conv_block += [\n nn.Conv2d(dim, dim, kernel_size=3, padding=p),\n norm_layer(dim)\n ]\n return nn.Sequential(*conv_block)\n\n def forward(self, x):\n out = x + self.conv_block(x)\n return out\n\n\nclass GlobalGenerator(nn.Module):\n def __init__(\n self, \n input_nc, \n output_nc, \n ngf=64, \n n_downsampling=3, \n n_blocks=9, \n norm_layer=nn.BatchNorm2d, \n padding_type='reflect'\n ):\n assert(n_blocks >= 0)\n super().__init__()\n\n model = [\n nn.ReflectionPad2d(3), \n nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0), \n norm_layer(ngf), \n nn.ReLU(True)\n ]\n ### downsample\n for i in range(n_downsampling):\n mult = 2**i\n model += [\n nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1),\n norm_layer(ngf * mult * 2), \n nn.ReLU(True)\n ]\n\n ### resnet blocks\n mult = 2**n_downsampling\n for i in range(n_blocks):\n model += [ResnetBlock(ngf * mult, padding_type=padding_type, activation=nn.ReLU(True), norm_layer=norm_layer)]\n \n ### upsample \n for i in range(n_downsampling):\n mult = 2**(n_downsampling - i)\n model += [\n nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=2, padding=1, output_padding=1),\n norm_layer(int(ngf * mult / 2)), \n nn.ReLU(True)\n ]\n model += [\n nn.ReflectionPad2d(3), \n nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0), \n nn.Tanh()\n ] \n self.model = nn.Sequential(*model)\n \n def forward(self, input):\n return self.model(input) \n\n\nclass LocalEnhancer(nn.Module):\n def __init__(\n self, \n input_nc, \n output_nc, \n ngf=32, \n n_downsample_global=3, \n n_blocks_global=9, \n n_local_enhancers=1, \n n_blocks_local=3, \n norm_layer=nn.BatchNorm2d, \n padding_type='reflect'\n ):\n super().__init__()\n self.n_local_enhancers = n_local_enhancers\n \n ###### global generator model #####\n ngf_global = ngf * (2**n_local_enhancers)\n model_global = GlobalGenerator(input_nc, output_nc, ngf_global, n_downsample_global, n_blocks_global, norm_layer).model\n model_global = [model_global[i] for i in range(len(model_global)-3)] # get rid of final convolution layers\n self.globalG = nn.Sequential(*model_global)\n\n ###### local enhancer layers #####\n for n in range(1, n_local_enhancers+1):\n ### downsample \n ngf_global = ngf * (2**(n_local_enhancers-n))\n model_downsample = [\n nn.ReflectionPad2d(3), \n nn.Conv2d(input_nc, ngf_global, kernel_size=7, padding=0), \n norm_layer(ngf_global), \n nn.ReLU(True),\n nn.Conv2d(ngf_global, ngf_global * 2, kernel_size=3, stride=2, padding=1), \n norm_layer(ngf_global * 2), \n nn.ReLU(True)\n ]\n ### residual blocks\n model_upsample = []\n for i in range(n_blocks_local):\n model_upsample += [ResnetBlock(ngf_global * 2, padding_type=padding_type, norm_layer=norm_layer)]\n\n ### upsample\n model_upsample += [\n nn.ConvTranspose2d(ngf_global * 2, ngf_global, kernel_size=3, stride=2, padding=1, output_padding=1), \n norm_layer(ngf_global), \n nn.ReLU(True)\n ] \n\n ### final convolution\n if n == n_local_enhancers:\n model_upsample += [\n nn.ReflectionPad2d(3), \n nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0),\n nn.Tanh()\n ]\n \n setattr(self, f'localG_{n}_F', nn.Sequential(*model_downsample))\n setattr(self, f'localG_{n}_B', nn.Sequential(*model_upsample))\n\n self.downsample = nn.AvgPool2d(3, stride=2, padding=[1, 1], count_include_pad=False)\n\n def forward(self, input): \n ### create input pyramid\n input_downsampled = [input]\n for i in range(self.n_local_enhancers):\n input_downsampled.append(self.downsample(input_downsampled[-1]))\n\n ### output at coarest level\n output_prev = self.globalG(input_downsampled[-1])\n ### build up one layer at a time\n for n_local_enhancers in range(1, self.n_local_enhancers+1):\n model_downsample = getattr(self, f'localG_{n_local_enhancers}_F')\n model_upsample = getattr(self, f'localG_{n_local_enhancers}_B')\n input_i = input_downsampled[self.n_local_enhancers-n_local_enhancers]\n output_prev = model_upsample(model_downsample(input_i) + output_prev)\n return output_prev\n\n\nclass Encoder(nn.Module):\n def __init__(self, input_nc, output_nc, ngf=32, n_downsampling=4, norm_layer=nn.BatchNorm2d):\n super(Encoder, self).__init__()\n self.output_nc = output_nc\n\n model = [\n nn.ReflectionPad2d(3), \n nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0), \n norm_layer(ngf), \n nn.ReLU(True)\n ] \n ### downsample\n for i in range(n_downsampling):\n mult = 2**i\n model += [\n nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1),\n norm_layer(ngf * mult * 2), \n nn.ReLU(True)\n ]\n\n ### upsample \n for i in range(n_downsampling):\n mult = 2**(n_downsampling - i)\n model += [\n nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=2, padding=1, output_padding=1),\n norm_layer(int(ngf * mult / 2)), \n nn.ReLU(True)\n ]\n\n model += [\n nn.ReflectionPad2d(3), \n nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0), \n nn.Tanh()\n ]\n self.model = nn.Sequential(*model) \n\n def forward(self, image, inst):\n outputs = self.model(image)\n\n # instance-wise average pooling\n outputs_mean = outputs.clone()\n inst_list = np.unique(inst.cpu().numpy().astype(int)) \n for i in inst_list:\n for b in range(image.size()[0]):\n indices = (inst[b:b+1] == int(i)).nonzero() # n x 4 \n for j in range(self.output_nc):\n output_ins = outputs[indices[:,0] + b, indices[:,1] + j, indices[:,2], indices[:,3]] \n mean_feat = torch.mean(output_ins).expand_as(output_ins) \n outputs_mean[indices[:,0] + b, indices[:,1] + j, indices[:,2], indices[:,3]] = mean_feat \n return outputs_mean\n\n##############################################################################\n# Discriminator\n##############################################################################\nclass MultiscaleDiscriminator(nn.Module):\n def __init__(\n self, \n input_nc, \n ndf=64, \n n_layers=3, \n norm_layer=nn.BatchNorm2d, \n use_sigmoid=False, \n num_D=3, \n getIntermFeat=False\n ):\n super().__init__()\n self.num_D = num_D\n self.n_layers = n_layers\n self.getIntermFeat = getIntermFeat\n \n for i in range(num_D):\n netD = NLayerDiscriminator(input_nc, ndf, n_layers, norm_layer, use_sigmoid, getIntermFeat)\n if getIntermFeat: \n for j in range(n_layers+2):\n setattr(self, 'scale'+str(i)+'_layer'+str(j), getattr(netD, 'model'+str(j))) \n else:\n setattr(self, 'layer'+str(i), netD.model)\n\n self.downsample = nn.AvgPool2d(3, stride=2, padding=[1, 1], count_include_pad=False)\n\n def singleD_forward(self, model, input):\n if self.getIntermFeat:\n result = [input]\n for i in range(len(model)):\n result.append(model[i](result[-1]))\n return result[1:]\n else:\n return [model(input)]\n\n def forward(self, input): \n num_D = self.num_D\n result = []\n input_downsampled = input\n for i in range(num_D):\n if self.getIntermFeat:\n model = [getattr(self, 'scale'+str(num_D-1-i)+'_layer'+str(j)) for j in range(self.n_layers+2)]\n else:\n model = getattr(self, 'layer'+str(num_D-1-i))\n result.append(self.singleD_forward(model, input_downsampled))\n if i != (num_D-1):\n input_downsampled = self.downsample(input_downsampled)\n return result\n\n\n# Defines the PatchGAN discriminator with the specified arguments.\nclass NLayerDiscriminator(nn.Module):\n def __init__(\n self, \n input_nc, \n ndf=64, \n n_layers=3, \n norm_layer=nn.BatchNorm2d, \n use_sigmoid=False, \n getIntermFeat=False\n ):\n super().__init__()\n self.getIntermFeat = getIntermFeat\n self.n_layers = n_layers\n\n kw = 4\n padw = int(np.ceil((kw-1.0)/2))\n sequence = [[\n nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), \n nn.LeakyReLU(0.2, True)\n ]]\n\n nf = ndf\n for n in range(1, n_layers):\n nf_prev = nf\n nf = min(nf * 2, 512)\n sequence += [[\n nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=2, padding=padw),\n norm_layer(nf), \n nn.LeakyReLU(0.2, True)\n ]]\n\n nf_prev = nf\n nf = min(nf * 2, 512)\n sequence += [[\n nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=1, padding=padw),\n norm_layer(nf),\n nn.LeakyReLU(0.2, True)\n ]]\n\n sequence += [[nn.Conv2d(nf, 1, kernel_size=kw, stride=1, padding=padw)]]\n\n if use_sigmoid:\n sequence += [[nn.Sigmoid()]]\n\n if getIntermFeat:\n for n in range(len(sequence)):\n setattr(self, 'model'+str(n), nn.Sequential(*sequence[n]))\n else:\n sequence_stream = []\n for n in range(len(sequence)):\n sequence_stream += sequence[n]\n self.model = nn.Sequential(*sequence_stream)\n\n def forward(self, input):\n if self.getIntermFeat:\n res = [input]\n for n in range(self.n_layers+2):\n model = getattr(self, 'model'+str(n))\n res.append(model(res[-1]))\n return res[1:]\n else:\n return self.model(input) \n\n\nfrom torchvision import models\nclass Vgg19(torch.nn.Module):\n def __init__(self, requires_grad=False):\n super().__init__()\n vgg_pretrained_features = models.vgg19(pretrained=True).features\n self.slice1 = torch.nn.Sequential()\n self.slice2 = torch.nn.Sequential()\n self.slice3 = torch.nn.Sequential()\n self.slice4 = torch.nn.Sequential()\n self.slice5 = torch.nn.Sequential()\n for x in range(2):\n self.slice1.add_module(str(x), vgg_pretrained_features[x])\n for x in range(2, 7):\n self.slice2.add_module(str(x), vgg_pretrained_features[x])\n for x in range(7, 12):\n self.slice3.add_module(str(x), vgg_pretrained_features[x])\n for x in range(12, 21):\n self.slice4.add_module(str(x), vgg_pretrained_features[x])\n for x in range(21, 30):\n self.slice5.add_module(str(x), vgg_pretrained_features[x])\n if not requires_grad:\n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, X):\n h_relu1 = self.slice1(X)\n h_relu2 = self.slice2(h_relu1) \n h_relu3 = self.slice3(h_relu2) \n h_relu4 = self.slice4(h_relu3) \n h_relu5 = self.slice5(h_relu4) \n out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5]\n return out\n",
"import os\nimport matplotlib.pyplot as plt\n\ndef save_generations(\n args,\n edges: list, \n reals: list, \n fakes: list, \n paths: list, \n epoch: str\n) -> None:\n if args.results_dir not in os.listdir(args.root_dir, ):\n os.mkdir(os.path.join(args.root_dir, args.results_dir))\n\n for edge, real, fake, path in zip(edges, reals, fakes, paths):\n fig, axes = plt.subplots(nrows=1, ncols=3)\n\n axes[0].imshow(edge); axes[0].axis('off'); axes[0].set_title('Edge')\n axes[1].imshow(real); axes[1].axis('off'); axes[1].set_title('Real')\n axes[2].imshow(fake); axes[2].axis('off'); axes[2].set_title('Fake')\n\n dataset_name = os.path.normpath(path).split(os.sep)[1] + args.model_id\n file_name = os.path.normpath(path).split(os.sep)[-1]\n if dataset_name not in os.listdir(os.path.join(args.root_dir, args.results_dir)):\n os.mkdir(os.path.join(args.root_dir, args.results_dir, dataset_name))\n if epoch not in os.listdir(os.path.join(args.root_dir, args.results_dir, dataset_name)):\n os.mkdir(os.path.join(args.root_dir, args.results_dir, dataset_name, epoch))\n \n fig.savefig(os.path.join(args.root_dir, args.results_dir, dataset_name, epoch, file_name), bbox_inches='tight')\n plt.close()\n"
] |
[
[
"torch.nn.Sequential",
"torch.nn.Dropout",
"torch.nn.ReflectionPad2d",
"torch.mean",
"torch.nn.ConvTranspose2d",
"torch.nn.Conv2d",
"torch.nn.BCELoss",
"torch.nn.Tanh",
"numpy.ceil",
"torch.nn.AvgPool2d",
"torch.nn.ReplicationPad2d",
"torch.nn.Sigmoid",
"torch.nn.LeakyReLU",
"torch.nn.L1Loss",
"torch.nn.ReLU",
"torch.nn.MSELoss",
"torch.autograd.Variable"
],
[
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.close"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ggapp1/microinfl-instagram
|
[
"e3fefbc09f9ee1bc5010618ccae647e4d763f503",
"e3fefbc09f9ee1bc5010618ccae647e4d763f503"
] |
[
"models/dataset.py",
"models/siamese_nn.py"
] |
[
"from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler\nimport numpy as np\nimport networkx as nx\nimport random\nimport pickle as pk\nimport torch\nimport torch.nn.functional as F\n\n\nclass Node:\n\tdef __init__(self, node, embedding, features, walk):\n\t\tself.node = node\n\t\tself.embedding = embedding\n\t\tself.features = features\n\t\tself.walk = walk\n\nclass InstagramDataset(Dataset):\n\tdef __init__(self, graph, features):\n\t\tself.graph = graph\n\t\tself.features = features\n\t\n\tdef __getitem__(self, index):\n\t\tnodes = random.choice(self.features)\n\t\treturn torch.tensor(nodes[0]), torch.tensor(nodes[1]).float(), torch.tensor(nodes[2]), torch.tensor(nodes[3]).float(), nodes[4]\n\n\tdef __len__(self):\n\t\treturn len(self.graph)\n\ndef split_dataset(dataset, batch_size, validation_split):\n\t\"\"\"\n\tGenerates training and validation splits\n\n\tArguments:\n\tdataset -- A InstagramDataset object dataset, based torch's class Dataset\n\tbatch_size -- size of the batch of the datasets\n\tvalidation_split -- percentage of the dataset that will be used in validation.\n\tReturn:\n\ttrain_dataloader -- training torch dataloader \n\ttest_dataloader -- test torch dataloader \n\t\"\"\"\t\n\n\t# Creating data indexes for training and validation splits:\n\tdataset_size = len(dataset)\n\tindexes = list(range(dataset_size))\n\tsplit = int(np.floor(validation_split * dataset_size))\n\n\tnp.random.shuffle(indexes)\n\ttrain_indexes, val_indexes = indexes[split:], indexes[:split]\n\n\t# Creating data samplers and loaders:\n\ttrain_sampler = SubsetRandomSampler(train_indexes)\n\tvalid_sampler = SubsetRandomSampler(val_indexes)\n\ttrain_dataloader = DataLoader(dataset, batch_size=batch_size, \n\t\t\t\t\t\tsampler=train_sampler, num_workers=8,)\n\tvalidation_dataloader = DataLoader(dataset, batch_size=1,\n\t\t\t\t\t\t\tsampler=valid_sampler, num_workers=8)\n\n\treturn train_dataloader, validation_dataloader\n\ndef get_features(node_features, no_features): \n\t\"\"\"\n\tFor a given node, returns its features shaped to the convolutional matrix features\n\n\tArguments:\n\tnode_features -- list of lists containing the features of a node\n\tno_features -- Which set of features will be used\n\tReturn:\n\tnp array containing the features of a node\n\t\"\"\"\t\n\tif(no_features==1):\n\t\treturn node_features.embedding\n\tfeatures = np.concatenate((node_features.features))\t\n\tif(no_features==2):\n\t\treturn np.concatenate((node_features.embedding, features))\n\telse:\n\t\twalk = np.concatenate((node_features.walk[0], node_features.walk[1], node_features.walk[2]))\n\t\treturn np.concatenate((node_features.embedding, features, walk))\n\ndef sample_graph_features(graph, graph_features, no_edges, no_features=1, siamese=0):\n\t\"\"\"\n\tGenerates sampled nodes to train the models.\n\n\tArguments:\n\tgraph -- graph file used.\n\tgraph_features -- A list where the indexes are the node's id and the values are the node'srepresentation\n\tno_edges -- no_edges of each class to be sampled\n\tno_features -- Which set of features will be used. \n\tsiamese -- 1 If the dataset is for a siamese network, else 0\n\tReturn:\n\tsampled_graph -- a list with 2*no_edges pairs of nodes (no_edges adjacent and no_edges non adjacent nodes)\n\t\"\"\"\t\n\tsampled_graph = []\n\n\tedges = list(graph.edges)\n\tnodes = list(graph.nodes)\n\t\n\tfor i in range(no_edges):\n\t\tr = np.random.randint(0,len(edges) - 1)\n\t\tnode1_pos = edges[r][0]\n\t\tnode2_pos = edges[r][1]\n\n\t\tnode1_pos_features = get_features(graph_features[node1_pos], no_features)\n\t\tnode2_pos_features = get_features(graph_features[node2_pos], no_features)\n\t\t\t\t\t\t\t\t\t\t\t \n\t\tsampled_graph.append([node1_pos, node1_pos_features, node2_pos, node2_pos_features, 1]) \n\t\t\t\t\t\t\t\t\t\t\t \n\t\tnode1_neg = nodes[np.random.randint(0,len(nodes) - 1)]\n\t\tnode2_neg = nodes[np.random.randint(0,len(nodes) - 1)]\n\t\t\t\t\t\t\t\t\t\t\t \n\t\twhile(graph.has_edge(node1_neg, node2_neg)):\n\t\t\tnode1_neg = nodes[np.random.randint(0,len(nodes) - 1)]\n\t\t\tnode2_neg = nodes[np.random.randint(0,len(nodes) - 1)]\n\n\t\tnode1_neg_features = get_features(graph_features[node1_neg], no_features)\n\t\tnode2_neg_features = get_features(graph_features[node2_neg], no_features)\n\n\t\tneg_edge = -1 if (siamese == 1) else 0\n\t\tsampled_graph.append([node1_neg, node1_neg_features, node2_neg, node2_neg_features, neg_edge])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \n\treturn sampled_graph\n\t\ndef gcn_features(graph, graph_features, no_features, size):\n\t\"\"\"\n\tGenerates the matrix features used on convolutional models.\n\n\tArguments:\n\tgraph -- graph file used.\n\tgraph_features -- A list where the indexes are the node's id and the values are the node'srepresentation\n\tno_features -- Which set of features will be used. \n\tsize -- size of the feature array\n\tReturn:\n\tfeatures -- A special matrix, mode of numpy arrays, of features used on convolutional models, similar to the graph_features\n\t\"\"\"\t\n\tnodes = list(graph.nodes)\n\tfeatures = np.zeros((len(nodes),size))\n\n\tfor i in nodes:\n\t\tfeatures[i] = get_features(graph_features[i], no_features)\n\treturn features \n\ndef generate_dataset(graph_name, no_edges, no_features, siamese=0):\n\t\"\"\"\n\tGenerates all the necessary data to train the models.\n\n\tArguments:\n\tgraph_name -- Name of the graph file used.\n\tno_edges -- No. of edges that will be sampled to the dataset\n\tno_features -- Which set of features will be used. \n\tsiamese -- 1 If the dataset is for a siamese network, else 0\n\tReturn:\n\tdataset -- A InstagramDataset object dataset, based torch's class Dataset\n\tgraph_features -- A list where the indexes are the node's id and the values are a list of lists with node's representation\n\tedge_index -- A COO adjacency matrix of the graph\n\tfeatures -- A special matrix of features used on convolutional models, similar to the graph_features\n\t\"\"\"\t\n\tprint('Generating dataset... ', end='\\r')\n\tfile = open(graph_name, 'rb')\n\tgraph = pk.load(file)\n\tfile.close()\n\n\tfile = open(graph_name+'_features', 'rb')\n\tfull_graph_features = pk.load(file)\n\tfile.close()\n\n\tgraph = graph.to_directed()\n\tgraph = nx.convert_node_labels_to_integers(graph)\n\n\tgraph_features = sample_graph_features(graph, full_graph_features, no_edges, no_features, siamese)\n\tdataset = InstagramDataset(graph, graph_features)\n\n\tedge_index = torch.tensor(list(graph.edges)).t().contiguous()\n\tfeatures = gcn_features(graph, full_graph_features, no_features, len(graph_features[0][1]))\n\tprint('Dataset ok! ')\n\n\treturn dataset, graph_features, edge_index, features\t\t\t\t\t\t\t ",
"import pickle\nimport sys\nimport random\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import optim\nfrom torch.autograd import Variable\nfrom dataset import generate_dataset, split_dataset, Node\nfrom scipy.spatial.distance import cosine\nfrom sklearn.metrics import accuracy_score, f1_score, average_precision_score, roc_curve, precision_recall_curve\nimport matplotlib.pyplot as plt\n\nclass SiameseNN(torch.nn.Module):\n\tdef __init__(self, num_features, size_emb):\n\t\tsuper(SiameseNN, self).__init__()\n\t\tself.fc1 = nn.Linear(num_features, num_features)\n\t\tself.drp = nn.Dropout(p=0.1)\n\t\tself.fc2 = nn.Linear(num_features,256)\n\t\tself.fcc = nn.Linear(256, 128)\n\t\tself.fc3 = nn.Linear(128, 128)\n\t\tself.fc4 = nn.Linear(128, 64)\n\t\tself.fc5 = nn.Linear(64, size_emb)\n\n\tdef forward_once(self, x):\n\t\tx = F.rrelu(self.fc1(x))\n\t\tx = F.rrelu(self.drp(x))\n\t\tx = F.rrelu(self.fc2(x))\n\t\tx = F.rrelu(self.fcc(x))\n\t\tx = F.rrelu(self.fc3(x))\n\t\tx = F.rrelu(self.fc4(x))\n\t\treturn self.fc5(x)\n\n\tdef forward(self, input1, input2):\n\t\toutput1 = self.forward_once(input1)\n\t\toutput2 = self.forward_once(input2)\n\t\treturn output1, output2\n\ndef test_model(model, test_dataloader):\n\typred = []\n\tytest = []\n\tprint('\\nTesting... ')\n\tfor data in test_dataloader:\n\t\tnode0, node0_features, node1, node1_features, label = data\n\t\toutput1, output2 = model(Variable(node0_features).cuda(),Variable(node1_features).cuda())\n\t\toutput = F.cosine_similarity(output1, output2)\n\t\toutput = output.item()\n\t\tlabel = label.item()\n\t\toutput = 1 if (output>=0) else -1\n\t\typred.append(output)\n\t\tytest.append(label)\n\n\tprint('Accuracy: {}'.format(accuracy_score(ytest,ypred)))\n\tprint('F1-score: {}'.format(f1_score(ytest,ypred)))\n\tprint('Avg precision score: {}'.format(average_precision_score(ytest,ypred)))\n\ndef train_model(model, train_dataloader, test_dataloader):\n\tcriterion = nn.CosineEmbeddingLoss()\n\toptimizer = optim.Adam(model.parameters(),lr = 0.001)\n\tnumber_epochs = 10\n\tprint('\\nTraining... ')\n\tfor epoch in range(number_epochs):\n\t\tfor i, data in enumerate(train_dataloader,0):\n\t\t\tnode0, node0_features, node1, node1_features, label = data\n\t\t\tnode0_features = node0_features.cuda()\n\t\t\tnode1_features = node1_features.cuda()\n\t\t\tlabel = label.cuda()\n\t\t\toptimizer.zero_grad()\n\t\t\toutput1, output2 = model.forward(node0_features, node1_features)\n\t\t\tloss = criterion(output1, output2, label.float())\n\t\t\tloss.backward()\n\t\t\toptimizer.step()\n\n\t\tprint(\"Epoch number {}. Current loss {} \".format(epoch+1,loss.item()))\n\n\treturn model\n\ndef main():\n\tif(len(sys.argv) < 4) :\n\t\tprint('Usage : python siamese_nn.py graphfile no_nodes no_features')\n\t\texit()\n\n\tgraph, no_nodes, no_features = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])\t\n\tdataset, graph_features, edge_index, features = generate_dataset(graph, no_nodes, no_features, siamese=1)\n\tnum_features = len(graph_features[0][1])\n\t#these parameters can be changed\n\tsize_emb = 64\n\tbatch_size = 64\n\tval_split = .2\n\n\ttrain_dataloader, val_dataloader = split_dataset(dataset, batch_size, val_split)\n\tmodel = SiameseNN(num_features, size_emb).cuda()\n\tmodel = train_model(model, train_dataloader, val_dataloader)\n\n\ttest_model(model, val_dataloader)\n\n\nif __name__ == '__main__':\n\tmain()"
] |
[
[
"torch.utils.data.SubsetRandomSampler",
"torch.utils.data.DataLoader",
"numpy.random.shuffle",
"torch.tensor",
"numpy.concatenate",
"numpy.floor"
],
[
"torch.nn.Dropout",
"torch.autograd.Variable",
"torch.nn.Linear",
"torch.nn.CosineEmbeddingLoss",
"torch.nn.functional.cosine_similarity",
"sklearn.metrics.average_precision_score",
"sklearn.metrics.f1_score",
"sklearn.metrics.accuracy_score"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ShaikAsifullah/distributed-tellurium
|
[
"007e9b3842b614edd34908c001119c6da1d41897",
"007e9b3842b614edd34908c001119c6da1d41897"
] |
[
"tellurium/tests/test_examples.py",
"examples/tellurium-files/phrasedml/results/oneStep.pycode.py"
] |
[
"\"\"\"\nUnittests for examples.\nAll examples are executed to check against latest code base.\n\"\"\"\nfrom __future__ import print_function, division\nimport unittest\n\nimport os\nimport imp\nfrom helpers import filesInDirectory\n\n# ----------------------------------------------------------------\n# List of python files to test\n# ----------------------------------------------------------------\n\nexamples_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'examples')\nnotebookdir = os.path.join(examples_dir, 'notebooks-py')\ntedir = os.path.join(examples_dir, 'tellurium-files')\npy_files = []\npy_files.extend(filesInDirectory(notebookdir, suffix='.sedml'))\npy_files.extend(filesInDirectory(tedir, suffix='.sedml'))\n\n# ----------------------------------------------------------------\n# Test class\n# ----------------------------------------------------------------\nclass PythonExampleTestCase(unittest.TestCase):\n\n def setUp(self):\n # switch the backend of matplotlib, so plots can be tested\n import matplotlib\n matplotlib.pyplot.switch_backend(\"Agg\")\n\n# ----------------------------------------------------------------\n# Dynamic generation of tests from python files\n# ----------------------------------------------------------------\ndef ftest_generator(filePath):\n def test(self=None):\n \"\"\" Test failes if Exception in execution of f. \"\"\"\n if self is not None:\n print(filePath)\n imp.load_source(os.path.basename(filePath)[:-3], filePath)\n return test\n\nfor k, f in enumerate(py_files):\n test_name = 'test_{:03d}_{}'.format(k, os.path.basename(f)[:-3])\n test_name = test_name.replace('.', '_')\n test = ftest_generator(f)\n setattr(PythonExampleTestCase, test_name, test)\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"\"\"\"\n tellurium 1.3.5\n\n auto-generated code\n sedmlDoc: L1V2 \n workingDir: /home/mkoenig/git/tellurium/examples/tellurium-files/phrasedml/results/_te_oneStep\n inputType: COMBINE_FILE\n\"\"\"\nfrom __future__ import print_function, division\nimport tellurium as te\nfrom roadrunner import Config\nfrom tellurium.sedml.mathml import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d\nimport libsedml\nimport pandas\nimport os.path\nConfig.LOADSBMLOPTIONS_RECOMPILE = True\n\nworkingDir = r'/home/mkoenig/git/tellurium/examples/tellurium-files/phrasedml/results/_te_oneStep'\n\n# --------------------------------------------------------\n# Models\n# --------------------------------------------------------\n# Model <model1>\nmodel1 = te.loadSBMLModel(os.path.join(workingDir, 'oneStep.xml'))\n\n# --------------------------------------------------------\n# Tasks\n# --------------------------------------------------------\n# Task <task0>\n# not part of any DataGenerator: task0\n\n# Task <task1>\n\ntask1 = []\n__range__x = np.linspace(start=0.0, stop=10.0, num=101)\nfor __k__x, __value__x in enumerate(__range__x):\n if __k__x == 0:\n model1.reset()\n # Task: <task0>\n task0 = [None]\n model1.setIntegrator('cvode')\n model1['J0_v0'] = piecewise(8, __value__x < 4, 0.1, (4 <= __value__x) and (__value__x < 6), 8)\n model1.timeCourseSelections = ['[S1]', '[S2]', 'J0_v0', 'time']\n task0[0] = model1.simulate(start=0.0, end=0.1, points=2)\n\n task1.extend(task0)\n\n# --------------------------------------------------------\n# DataGenerators\n# --------------------------------------------------------\n# DataGenerator <plot_0_0_0>\n__offsets__task1 = np.cumsum(np.array([sim['time'][-1] for sim in task1]))\n__offsets__task1 = np.insert(__offsets__task1, 0, 0)\n__var__task1_____time = np.transpose(np.array([sim['time']+__offsets__task1[k] for k, sim in enumerate(task1)]))\n__var__task1_____time = np.concatenate(np.transpose(__var__task1_____time))\nif len(__var__task1_____time.shape) == 1:\n __var__task1_____time.shape += (1,)\nplot_0_0_0 = __var__task1_____time\n\n# DataGenerator <plot_0_0_1>\n__var__task1_____S1 = np.transpose(np.array([sim['[S1]'] for sim in task1]))\n__var__task1_____S1 = np.concatenate(np.transpose(__var__task1_____S1))\nif len(__var__task1_____S1.shape) == 1:\n __var__task1_____S1.shape += (1,)\nplot_0_0_1 = __var__task1_____S1\n\n# DataGenerator <plot_0_1_1>\n__var__task1_____S2 = np.transpose(np.array([sim['[S2]'] for sim in task1]))\n__var__task1_____S2 = np.concatenate(np.transpose(__var__task1_____S2))\nif len(__var__task1_____S2.shape) == 1:\n __var__task1_____S2.shape += (1,)\nplot_0_1_1 = __var__task1_____S2\n\n# DataGenerator <plot_0_2_1>\n__var__task1_____J0_v0 = np.transpose(np.array([sim['J0_v0'] for sim in task1]))\n__var__task1_____J0_v0 = np.concatenate(np.transpose(__var__task1_____J0_v0))\nif len(__var__task1_____J0_v0.shape) == 1:\n __var__task1_____J0_v0.shape += (1,)\nplot_0_2_1 = __var__task1_____J0_v0\n\n# --------------------------------------------------------\n# Outputs\n# --------------------------------------------------------\n# Output <plot_0>\nplt.figure(num=None, figsize=(9, 5), dpi=80, facecolor='w', edgecolor='k')\nfrom matplotlib import gridspec\n__gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])\nplt.subplot(__gs[0])\nfor k in range(plot_0_0_0.shape[1]):\n if k == 0:\n plt.plot(plot_0_0_0[:,k], plot_0_0_1[:,k], marker = '.', color='r', linewidth=1.5, markersize=3.0, alpha=0.8, label='task1.S1')\n else:\n plt.plot(plot_0_0_0[:,k], plot_0_0_1[:,k], marker = '.', color='r', linewidth=1.5, markersize=3.0, alpha=0.8)\nfor k in range(plot_0_0_0.shape[1]):\n if k == 0:\n plt.plot(plot_0_0_0[:,k], plot_0_1_1[:,k], marker = '.', color='b', linewidth=1.5, markersize=3.0, alpha=0.8, label='task1.S2')\n else:\n plt.plot(plot_0_0_0[:,k], plot_0_1_1[:,k], marker = '.', color='b', linewidth=1.5, markersize=3.0, alpha=0.8)\nfor k in range(plot_0_0_0.shape[1]):\n if k == 0:\n plt.plot(plot_0_0_0[:,k], plot_0_2_1[:,k], marker = '.', color='g', linewidth=1.5, markersize=3.0, alpha=0.8, label='task1.J0_v0')\n else:\n plt.plot(plot_0_0_0[:,k], plot_0_2_1[:,k], marker = '.', color='g', linewidth=1.5, markersize=3.0, alpha=0.8)\nplt.title('One Step Simulation', fontweight='bold')\nplt.xlabel('task1.time', fontweight='bold')\n__lg = plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n__lg.draw_frame(False)\nplt.setp(__lg.get_texts(), fontsize='small')\nplt.setp(__lg.get_texts(), fontweight='bold')\nplt.savefig(os.path.join(workingDir, 'plot_0.png'), dpi=100)\nplt.show()\n\n# Output <report_1>\n__dfs__report_1 = []\nfor k in range(plot_0_0_0.shape[1]):\n print('-'*80)\n print('report_1, Repeat:', k)\n print('-'*80)\n __df__k = pandas.DataFrame(np.column_stack([plot_0_0_0[:,k], plot_0_0_1[:,k], plot_0_1_1[:,k], plot_0_2_1[:,k]]), \n columns=['task1.time', 'task1.S1', 'task1.S2', 'task1.J0_v0'])\n print(__df__k.head(5))\n __dfs__report_1.append(__df__k)\n __df__k.to_csv(os.path.join(workingDir, 'report_1_{}.csv'.format(k)), sep='\t', index=False)\n\n"
] |
[
[
"matplotlib.pyplot.switch_backend"
],
[
"matplotlib.pyplot.legend",
"numpy.linspace",
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.subplot",
"matplotlib.gridspec.GridSpec",
"numpy.insert",
"numpy.transpose",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.column_stack",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
detecttechnologies/datumaro
|
[
"a00a4ec6807787d341c71f75f5e337c3cb7be119"
] |
[
"tests/test_image_dir_format.py"
] |
[
"import numpy as np\n\nfrom unittest import TestCase\n\nfrom datumaro.components.project import Dataset\nfrom datumaro.components.extractor import DatasetItem\nfrom datumaro.plugins.image_dir import ImageDirConverter\nfrom datumaro.util.test_utils import TestDir, test_save_and_load\n\n\nclass ImageDirFormatTest(TestCase):\n def test_can_load(self):\n dataset = Dataset.from_iterable([\n DatasetItem(id=1, image=np.ones((10, 6, 3))),\n DatasetItem(id=2, image=np.ones((5, 4, 3))),\n ])\n\n with TestDir() as test_dir:\n test_save_and_load(self, dataset, ImageDirConverter.convert,\n test_dir, importer='image_dir')\n\n def test_relative_paths(self):\n dataset = Dataset.from_iterable([\n DatasetItem(id='1', image=np.ones((4, 2, 3))),\n DatasetItem(id='subdir1/1', image=np.ones((2, 6, 3))),\n DatasetItem(id='subdir2/1', image=np.ones((5, 4, 3))),\n ])\n\n with TestDir() as test_dir:\n test_save_and_load(self, dataset, ImageDirConverter.convert,\n test_dir, importer='image_dir')"
] |
[
[
"numpy.ones"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
crb479/mcdevitt-trauma-ml
|
[
"9ed7ed7cd1e4be0071a18f9bbf375414088d5ed2",
"9ed7ed7cd1e4be0071a18f9bbf375414088d5ed2"
] |
[
"mtml/modeling/vte/mixed_models.py",
"PubMed/pubmed_movePDF.py"
] |
[
"__doc__ = \"\"\"Training routines containing mixed classifier types.\n\n.. note::\n\n This file has the potential to get cluttered like the\n :mod:`mtml.modeling._vte_models` module that is now deprecated.\n\nMixed classifier training.\n\"\"\"\n\n# pylint: disable=import-error\nimport numpy as np\nimport pandas as pd\nfrom sklearn.decomposition import PCA\nfrom sklearn.ensemble import BaggingClassifier, RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import (\n accuracy_score, precision_score, recall_score, roc_auc_score\n)\nfrom sklearn.svm import LinearSVC, SVC\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.preprocessing import StandardScaler\nimport sys\nfrom xgboost import XGBClassifier\n\n# pylint: disable=relative-beyond-top-level\nfrom .. import BASE_RESULTS_DIR\nfrom ... import VTE_CONT_INPUT_COLS, VTE_OUTPUT_COLS\nfrom ...data.vte import vte_slp_factory\nfrom .data_transforms import replace_hdl_tot_chol_with_ratio\nfrom ...utils.persist import persist_csv, persist_json, persist_pickle\n\n\n@persist_csv(\n target = BASE_RESULTS_DIR + \"/vte_whitened_scores.csv\",\n enabled = True, out_transform = lambda x: x[2]\n)\n@persist_json(\n target = BASE_RESULTS_DIR + \"/vte_whitened_params.json\",\n enabled = True, out_transform = lambda x: x[1]\n)\n@persist_pickle(\n target = BASE_RESULTS_DIR + \"/vte_whitened.pickle\",\n enabled = True, out_transform = lambda x: x[0]\n)\ndef fit_pca_whitened_classifiers(\n cv = 5, n_jobs = -1, verbose = False, report = False, random_seed = None\n):\n \"\"\"Fit classifiers to [non-]undersampled PCA-whitened input data.\n \n .. note:: Spits a lot of ``liblinear`` convergence warnings.\n\n We start with the top 7 columns by univariate ROC AUC for the VTE data.\n We perform a whitening PCA transform of the data and then fit classifiers\n with balanced class weights. Formerly oversampling of the minority class\n was done with the use of a :class:`sklearn.model_selection.PredefinedSplit`\n to prevent the oversampled data from leaking into the validation sets\n during the grid search (all oversampled data appended to end of training\n set and now allowed to be part of validation sets), but the improvement was\n not as much as one would have hoped (actually worse). So we ended up going\n back to just using balanced class weights.\n\n Use 5-fold (by default) cross-validation to choose the best parameters,\n refit on best, evaluate accuracy, precision, recall, ROC AUC.\n\n Note that we need a scaler before doing PCA. Use F1 score to pick model.\n\n :param cv: Number of CV splits to make when doing grid search.\n :type cv: int, optional\n :param n_jobs: Number of jobs to run in parallel when grid searching.\n Defaults to ``-1`` to distribute load to all threads.\n :type n_jobs: int, optional\n :param verbose: Verbosity of the\n :class:`~sklearn.model_selection.GridSearchCV` during searching/fitting.\n :type verbose: bool, optional\n :param report: If ``True``, print to stdout a report on model scores.\n :type report: bool, optional\n :param random_seed: A int seed to pass for multiple calls to this function\n to be reproducible. Leave ``None`` for stochastic behavior.\n :type random_state: int, optional\n :rtype: tuple\n \"\"\"\n if cv < 3:\n raise ValueError(\"cv folds must be 3 or more\")\n # use only the top seven columns selected by univariate AUC\n best_cols = list(\n pd.read_csv(\n BASE_RESULTS_DIR + \"/vte_selected_cols.csv\", index_col = 0\n ).index\n )\n # get data set of continuous features from vte_slp_factory\n X_train, X_test, y_train, y_test = vte_slp_factory(\n data_transform = replace_hdl_tot_chol_with_ratio,\n inputs = best_cols, targets = VTE_OUTPUT_COLS, dropna = True,\n random_state = random_seed\n )\n # fit StandardScaler and use to transform data\n scaler = StandardScaler()\n scaler.fit(X_train)\n X_train, X_test = scaler.transform(X_train), scaler.transform(X_test)\n # fit PCA and transform data yet again (whiten)\n pca = PCA(whiten = True, random_state = random_seed)\n pca.fit(X_train)\n X_train, X_test = pca.transform(X_train), pca.transform(X_test)\n # list of base estimator names for use in Pipeline and parameter naming\n base_names = (\n \"l2_logistic\", \"l2_linsvc\", \"bagged_l2_logistic\", \"bagged_l2_linsvc\",\n \"rbf_svc\", \"xgboost\", \"random_forest\"\n )\n ## hyperparameter grids for each model ##\n # note that intercepts are not fitted since data are centered + scaled.\n # l2-regularized logistic regression (baseline model)\n lrc_l2_grid = dict(\n penalty = [\"l2\"],\n C = [1],\n fit_intercept = [True],\n max_iter = [100],\n class_weight = [\"balanced\"]\n )\n # linear SVM with l2 penalty (baseline model)\n lsvc_l2_grid = dict(\n penalty = [\"l2\"],\n loss = [\"hinge\", \"squared_hinge\"],\n dual = [True],\n random_state = [random_seed],\n C = [1, 5, 10],\n fit_intercept = [True],\n class_weight = [\"balanced\"]\n )\n # bagged logistic regression model with l2 penalty\n bag_lrc_l2_grid = dict(\n base_estimator = [\n LogisticRegression(fit_intercept = True, class_weight = \"balanced\")\n ],\n n_estimators = [100, 200, 400],\n random_state = [random_seed]\n )\n # bagged linear SVM with l2 penalty (use default parameters + hinge loss)\n bag_lsvc_l2_grid = dict(\n base_estimator = [\n LinearSVC(loss = \"hinge\", fit_intercept = True,\n class_weight = \"balanced\", random_state = random_seed)\n ],\n n_estimators = [100, 200, 400],\n random_state = [random_seed]\n )\n # RBF support vector classifier\n rbf_svc_grid = dict(\n C = [0.1, 1, 5],\n kernel = [\"rbf\"],\n gamma = [\"scale\", \"auto\"],\n class_weight = [\"balanced\"]\n )\n # compute ratio of 0 instances to 1 instances to get XGBoost\n # scale_pos_weight parameter (use training data only! don't be biased)\n neg_pos_ratio = (y_train == 0).sum() / (y_train == 1).sum()\n # XGBoost classifier\n xgb_grid = dict(\n max_depth = [3],\n n_estimators = [400, 600, 800],\n learning_rate = [0.1],\n booster = [\"gbtree\"],\n subsample = [0.5],\n reg_lambda = [0.1, 1],\n random_state = [random_seed],\n scale_pos_weight = [neg_pos_ratio]\n )\n # random forest classifier. note that according to ESL II, full trees are\n # fine to grow and allow you to have one less tuning parameter, but it's\n # still better to limit the overall tree depth.\n rf_grid = dict(\n max_depth = [6, 12, 24],\n n_estimators = [100, 200, 400],\n criterion = [\"entropy\"],\n random_state = [random_seed],\n class_weight = [\"balanced\"]\n )\n # models to use in our grid searches\n base_models = (\n LogisticRegression(), LinearSVC(), BaggingClassifier(),\n BaggingClassifier(), SVC(), XGBClassifier(), RandomForestClassifier()\n )\n base_names = (\n \"l2_logistic\", \"l2_linsvc\", \"bagged_l2_logistic\", \"bagged_l2_linsvc\",\n \"rbf_svc\", \"xgboost\", \"random_forest\"\n )\n # grid search parameters for all the models\n param_grids = (\n lrc_l2_grid, lsvc_l2_grid, bag_lrc_l2_grid, bag_lsvc_l2_grid,\n rbf_svc_grid, xgb_grid, rf_grid\n )\n # dictionary to hold saved model results for VTE classification problem.\n mdata = {}\n # dictionary to hold saved model hyperparameters for plaintext persistence.\n mparams = {}\n # DataFrame indexed by name of the model where columns are accuracy,\n # precision, and recall for each model\n mscores = pd.DataFrame(\n index = base_names, \n columns = [\"accuracy\", \"precision\", \"recall\", \"roc_auc\"]\n )\n # for each model, train + record results into mdata, mparams, and mscores\n for base_name, base_model, param_grid, in zip(\n base_names, base_models, param_grids):\n # instantiate and fit the GridSearchCV object. may spit mad warnings.\n model = GridSearchCV(\n base_model, param_grid, scoring = \"f1\", cv = cv,\n n_jobs = n_jobs, verbose = int(verbose)\n )\n # fit\n model.fit(X_train, y_train)\n # save model to mdata using model name\n mdata[base_name] = model\n # get hyperparameters of the best estimated model\n params = model.best_estimator_.get_params()\n # if there are any predictors as a parameter, replace them with their\n # parameters from get_params (for ensemble models)\n for name in params.keys():\n if hasattr(params[name], \"get_params\"):\n params[name] = params[name].get_params()\n # save hyperparameters to mparams\n mparams[base_name] = params\n # compute test predictions using refit model on X_test\n y_pred = model.predict(X_test)\n # get decision function values for computing ROC AUC. if it isn't\n # present, try the predict_proba method\n if hasattr(model, \"decision_function\"): \n y_pred_scores = model.decision_function(X_test)\n elif hasattr(model, \"predict_proba\"):\n # we only want probabilities for the greater class\n y_pred_scores = model.predict_proba(X_test)[:, 1]\n else:\n print(\n f\"warning: {model.__class__.__name__} can't compute ROC AUC \"\n \"score; does not have decision_function or predict_proba\",\n file = sys.stderr\n )\n y_pred_scores = None\n # save accuracy, precision, and recall to in mscores\n mscores.loc[base_name, :] = (\n accuracy_score(y_test, y_pred), precision_score(y_test, y_pred),\n recall_score(y_test, y_pred),\n np.nan if y_pred_scores is None else roc_auc_score(\n y_test, y_pred_scores\n )\n )\n # if report is True, print mscores to stdout\n if report:\n print(\"---- classifier quality metrics \", end = \"\")\n print(\"-\" * 48, end = \"\\n\\n\")\n print(mscores)\n # return results that can get picked up by decorators\n return mdata, mparams, mscores\n\n\nif __name__ == \"__main__\":\n # fit_pca_whitened_classifiers(report = True, random_seed = 7)\n pass",
"import os\r\nimport pandas as pd \r\n\r\ndef movePDF(FILEPATH, PAPER_TYPE, STUDY_TYPE, rejected):\r\n\tdest = FILEPATH\r\n\t# When STUDY_TYPE is None, it is read as float for some reason.\r\n\tif FILEPATH and PAPER_TYPE and STUDY_TYPE:\r\n\t\tif type(FILEPATH) == float:\r\n\t\t\treturn dest \r\n\r\n\t\tsource_folder = os.path.dirname(FILEPATH)\r\n\r\n\t\tif type(STUDY_TYPE) != float:\r\n\t\t\tdest_folder = os.path.join(dir_map[STUDY_TYPE], PAPER_TYPE)\r\n\t\telse:\r\n\t\t\tdest_folder = os.path.join(dir_map['unlabelled'], PAPER_TYPE)\r\n\t\t\r\n\t\tif not os.path.exists(dest_folder):\r\n\t\t\tos.mkdir(dest_folder)\r\n\r\n\t\tif os.path.exists(FILEPATH):\r\n\t\t\tcmd = 'move \"{}\" \"{}\"'.format(source_folder, dest_folder)\r\n\t\t\tprint(cmd)\r\n\t\t\tos.system(cmd) #Windows\r\n\t\t\r\n\t\tdest = os.path.join(dest_folder, os.path.basename(FILEPATH))\r\n\t\t\r\n\treturn dest\r\n\r\ndef main():\r\n\tsummary = pd.read_csv('downloads_summary.csv')\r\n\tsummary['SORTED_FILEPATH'] = summary[['FILEPATH', 'PAPER_TYPE', 'STUDY_TYPE', 'rejected']].apply(lambda x: movePDF(*x), axis=1)\r\n\tsummary.to_csv('downloads_summary.csv')\r\n\r\nif __name__ == '__main__':\r\n\tdir_map = {\r\n\t\t'human': 'Human Studies',\r\n\t\t'animal': 'Animal Studies',\r\n\t\t'both': 'Both',\r\n\t\t'unlabelled': 'Others'\r\n\t}\r\n\r\n\tfor folder in dir_map.values():\r\n\t\tif not os.path.exists(folder):\r\n\t\t\tos.mkdir(folder)\r\n\r\n\tmain()\r\n"
] |
[
[
"sklearn.ensemble.BaggingClassifier",
"sklearn.metrics.roc_auc_score",
"pandas.read_csv",
"sklearn.linear_model.LogisticRegression",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.metrics.precision_score",
"pandas.DataFrame",
"sklearn.svm.LinearSVC",
"sklearn.svm.SVC",
"sklearn.preprocessing.StandardScaler",
"sklearn.metrics.recall_score",
"sklearn.decomposition.PCA",
"sklearn.metrics.accuracy_score"
],
[
"pandas.read_csv"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
johndpope/ext3DLBP
|
[
"0704ae6a9dda7e74f1f52b45acd71d1b6f622efd"
] |
[
"python_wrapper/test_functional/test_RD_LBP_P252g_R3.py"
] |
[
"'''\r\n=========================================================================\r\nAuthor: Leonardo Citraro\r\nCompany:\r\nFilename: \r\nLast modifed: 06.04.2017 by Leonardo Citraro\r\nDescription: Functional test\r\n\r\n=========================================================================\r\n\r\n=========================================================================\r\n'''\r\nimport numpy as np\r\nimport ext3DLBPpy\r\n \r\n\r\nprint(\"=============================================\")\r\ntest = \"RD_LBP_P252g_R3\"\r\narray = np.array([\r\n\t[[4,62,9,218,14,207,231],[28,28,32,70,169,207,55],[145,53,26,190,196,162,145],[144,167,142,67,223,153,105],[161,11,163,198,189,22,95],[123,107,248,61,205,169,155],[238,70,58,113,0,28,5]],\r\n\t[[8,78,202,78,144,84,71],[218,103,217,64,82,53,109],[204,244,202,110,170,249,52],[56,229,230,104,13,157,62],[86,131,230,201,170,102,2],[183,188,212,24,31,66,157],[178,49,29,103,95,82,13]],\r\n\t[[151,206,75,100,163,133,93],[147,113,7,20,169,90,42],[122,82,120,76,30,77,44],[204,156,61,214,190,83,13],[195,143,205,241,16,164,242],[81,236,236,16,124,11,101],[45,237,6,141,52,209,60]],\r\n\t[[143,167,193,140,151,111,34],[168,153,42,8,133,127,25],[125,114,221,234,4,123,120],[71,162,132,73,117,176,173],[118,45,104,57,178,25,226],[211,141,44,215,217,52,44],[76,216,203,99,6,58,79]],\r\n\t[[70,94,198,40,207,192,118],[170,234,123,206,76,118,58],[55,118,243,201,41,54,70],[191,171,124,216,246,8,236],[169,246,98,159,175,150,82],[8,98,151,114,184,170,20],[208,60,195,188,175,163,15]],\r\n\t[[3,75,89,31,224,123,116],[134,58,43,219,197,140,252],[12,71,237,49,18,165,177],[151,94,141,198,27,62,13],[217,157,149,242,166,32,107],[210,34,125,247,244,39,193],[70,252,25,236,69,26,37]],\r\n\t[[13,127,24,250,2,26,203],[247,241,97,184,222,18,108],[213,92,172,186,8,215,214],[206,219,217,94,93,251,95],[34,32,175,245,168,239,145],[46,220,116,124,8,138,197],[183,20,52,19,49,137,31]]\r\n\t\t], dtype=np.int)\r\nmur = 170\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 0 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 0 passed!\")\r\narray = np.array([\r\n\t[[56,177,131,250,236,153,69],[158,23,23,57,187,249,52],[23,71,133,254,181,86,110],[202,117,108,40,190,148,162],[20,164,202,93,200,45,52],[190,235,193,206,168,100,83],[122,186,233,66,143,189,90]],\r\n\t[[198,200,36,121,196,32,37],[26,239,58,113,245,75,59],[4,44,247,194,247,189,176],[73,68,240,184,213,128,247],[61,81,72,21,87,74,220],[80,22,246,49,209,196,32],[166,133,212,191,218,137,204]],\r\n\t[[154,131,203,207,174,142,16],[114,246,149,98,147,104,151],[132,75,252,238,129,222,102],[138,154,43,43,201,62,65],[146,190,14,2,24,174,63],[118,40,62,171,191,142,213],[170,137,183,204,130,117,251]],\r\n\t[[172,199,188,46,179,28,117],[160,238,104,16,111,18,201],[204,231,50,7,6,146,104],[4,163,128,127,222,127,13],[182,229,138,169,198,192,13],[59,143,46,165,144,190,186],[102,167,12,127,216,19,102]],\r\n\t[[33,52,144,140,211,33,132],[154,109,34,205,157,232,190],[69,193,131,116,196,2,251],[155,116,212,141,228,131,112],[232,237,57,145,250,223,65],[45,47,116,241,102,237,59],[212,11,241,124,237,77,21]],\r\n\t[[68,89,121,131,27,48,141],[17,202,96,91,76,123,63],[197,253,219,169,153,228,248],[137,127,62,30,233,54,204],[146,247,197,237,3,193,142],[173,237,13,246,250,118,116],[210,227,91,15,89,210,223]],\r\n\t[[139,43,40,223,203,209,111],[164,39,184,191,52,32,116],[87,33,1,27,59,215,162],[75,142,156,196,107,182,194],[5,4,103,202,130,178,245],[150,33,35,141,126,167,143],[46,244,41,15,230,90,167]]\r\n\t\t], dtype=np.int)\r\nmur = 38\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 1 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 1 passed!\")\r\narray = np.array([\r\n\t[[111,95,151,39,73,55,253],[21,31,99,24,0,237,221],[155,6,74,124,1,160,48],[158,138,225,75,231,60,148],[135,95,20,18,203,185,23],[230,227,9,115,213,139,236],[250,232,210,88,0,224,51]],\r\n\t[[189,161,219,28,66,178,34],[144,119,245,93,93,99,225],[92,133,110,180,63,16,158],[52,48,41,52,213,98,54],[71,164,147,225,221,99,27],[156,241,13,141,243,0,114],[155,202,178,96,90,76,67]],\r\n\t[[105,174,29,223,152,100,190],[218,101,2,245,15,47,225],[211,96,67,87,43,52,158],[34,1,97,189,204,165,18],[33,162,220,120,31,228,238],[98,94,74,61,126,118,181],[42,134,167,210,93,147,57]],\r\n\t[[223,123,151,214,43,10,143],[14,116,25,241,211,241,85],[175,249,55,53,197,41,238],[121,26,109,14,216,236,25],[95,131,62,155,85,100,240],[247,11,222,138,71,183,210],[166,61,30,20,208,104,240]],\r\n\t[[234,109,250,59,88,202,205],[52,62,107,225,33,160,87],[42,123,67,151,107,47,2],[17,32,188,17,70,29,30],[216,33,150,55,184,56,234],[220,72,177,194,250,90,59],[77,6,61,198,103,231,244]],\r\n\t[[234,60,253,9,115,124,203],[229,118,133,8,209,31,203],[51,81,111,8,126,119,147],[204,140,205,168,231,176,170],[7,94,149,72,230,23,216],[43,208,141,89,122,203,149],[171,27,6,216,150,29,32]],\r\n\t[[28,197,158,231,137,193,245],[167,86,138,234,2,15,128],[149,71,106,194,200,209,235],[81,45,43,2,69,114,17],[249,120,143,23,105,11,170],[14,33,115,239,230,233,38],[64,12,2,78,103,49,212]]\r\n\t\t], dtype=np.int)\r\nmur = 102\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 2 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 2 passed!\")\r\narray = np.array([\r\n\t[[40,83,180,0,144,129,98],[98,83,243,145,153,92,135],[27,74,156,232,181,165,99],[30,127,106,179,108,14,231],[14,90,91,140,72,224,150],[174,247,209,142,161,180,64],[16,230,231,225,166,220,245]],\r\n\t[[97,66,154,76,13,126,230],[231,240,76,142,217,236,207],[239,138,246,153,31,252,175],[200,128,157,213,131,75,66],[147,156,81,162,76,72,100],[154,31,205,182,93,157,217],[153,231,203,119,125,236,231]],\r\n\t[[36,110,161,94,74,62,40],[101,1,150,13,240,98,140],[69,230,185,49,23,27,25],[58,22,51,153,161,133,104],[102,167,42,234,146,39,152],[81,21,108,201,90,236,2],[3,160,76,219,0,209,77]],\r\n\t[[237,174,197,174,98,197,179],[108,41,44,114,223,221,219],[7,35,168,22,72,75,113],[36,143,219,33,83,76,132],[79,199,109,65,115,16,184],[230,51,222,170,61,110,38],[237,238,195,92,114,106,247]],\r\n\t[[106,170,92,105,26,224,115],[173,106,23,223,137,3,191],[196,118,194,95,89,66,8],[2,244,223,14,112,168,40],[50,129,244,252,154,57,39],[59,188,28,155,193,59,171],[203,249,207,130,62,203,191]],\r\n\t[[90,198,177,68,172,221,243],[180,6,53,169,1,19,79],[3,54,197,189,162,247,172],[197,0,250,140,222,32,79],[168,50,79,81,231,123,53],[111,147,222,138,175,199,84],[5,211,157,82,98,38,85]],\r\n\t[[220,3,170,158,48,162,189],[49,232,244,27,14,137,223],[30,126,15,178,7,123,113],[91,93,110,73,200,145,36],[36,155,27,235,139,23,59],[220,121,245,101,214,112,57],[60,157,206,114,109,189,177]]\r\n\t\t], dtype=np.int)\r\nmur = 60\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 3 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 3 passed!\")\r\narray = np.array([\r\n\t[[22,136,14,85,128,94,25],[107,17,149,237,145,241,154],[31,227,61,239,12,202,27],[92,172,137,250,108,51,7],[83,49,89,69,238,77,222],[52,148,53,241,218,235,250],[58,3,99,36,169,249,226]],\r\n\t[[23,147,157,143,189,21,86],[169,15,158,162,191,134,5],[42,248,62,240,90,90,114],[169,250,179,18,207,10,97],[34,18,116,62,250,190,47],[92,1,172,96,37,240,158],[235,75,43,67,204,208,27]],\r\n\t[[213,168,123,216,200,77,10],[123,48,128,195,58,104,27],[156,152,190,60,75,82,188],[140,39,194,95,177,32,93],[142,91,123,170,106,42,158],[27,163,37,116,93,23,183],[142,56,191,65,253,247,204]],\r\n\t[[37,220,129,39,174,141,65],[174,233,93,233,83,119,194],[222,242,182,93,201,145,202],[147,195,167,80,110,52,251],[167,149,132,73,73,167,220],[215,194,192,67,98,247,54],[208,111,230,69,0,89,26]],\r\n\t[[56,33,227,117,231,38,247],[65,232,254,154,138,253,13],[224,110,52,133,200,93,200],[115,166,10,206,4,146,147],[24,145,75,214,212,156,60],[82,51,174,135,212,152,190],[37,159,41,216,209,228,162]],\r\n\t[[140,37,140,247,86,206,161],[180,113,54,239,144,132,177],[175,183,160,239,240,56,82],[237,232,122,104,129,7,132],[77,191,101,123,186,154,73],[47,145,91,232,122,243,218],[179,22,165,83,62,172,214]],\r\n\t[[126,207,199,97,251,67,35],[9,78,209,144,130,114,239],[243,142,9,100,77,176,123],[29,214,96,90,121,1,138],[55,125,215,4,254,180,181],[110,196,254,227,113,167,113],[120,181,37,160,155,102,252]]\r\n\t\t], dtype=np.int)\r\nmur = 166\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 4 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 4 passed!\")\r\narray = np.array([\r\n\t[[62,39,11,195,158,61,169],[125,213,48,88,58,10,115],[164,195,210,93,246,176,207],[129,13,8,148,67,234,75],[123,45,30,105,42,221,95],[31,16,206,79,15,29,14],[175,195,243,25,190,92,7]],\r\n\t[[154,120,136,56,235,172,146],[242,72,6,30,35,78,22],[136,181,224,11,119,158,169],[156,64,215,2,15,220,69],[33,221,211,94,39,53,252],[48,101,171,177,172,234,48],[221,151,12,62,243,131,87]],\r\n\t[[253,233,46,83,209,73,101],[241,137,133,160,89,203,40],[121,196,80,26,122,90,204],[110,8,163,109,183,132,30],[163,44,35,218,171,151,76],[22,158,199,192,102,101,48],[61,216,37,172,27,11,221]],\r\n\t[[102,100,104,240,236,81,174],[65,140,119,146,226,168,121],[143,149,139,119,83,42,175],[245,56,221,215,78,103,93],[119,89,241,29,224,190,172],[116,138,43,241,43,224,218],[104,183,216,23,140,167,192]],\r\n\t[[222,32,31,30,9,168,236],[245,146,24,133,244,61,208],[24,234,29,91,60,239,252],[79,102,220,147,205,194,152],[198,219,10,75,179,189,188],[253,15,59,187,15,219,92],[156,20,223,146,58,222,152]],\r\n\t[[128,137,46,145,147,25,90],[107,154,82,235,112,99,15],[230,219,63,203,206,154,239],[216,160,191,103,188,71,13],[97,122,23,227,132,242,21],[243,163,122,20,41,138,86],[246,243,145,123,221,237,14]],\r\n\t[[151,172,171,117,76,12,64],[248,173,131,248,186,99,203],[90,212,33,149,56,150,186],[244,5,109,9,24,182,212],[240,85,122,10,206,206,197],[18,236,232,55,188,189,49],[117,109,176,9,210,149,189]]\r\n\t\t], dtype=np.int)\r\nmur = 158\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 5 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 5 passed!\")\r\narray = np.array([\r\n\t[[220,15,87,192,137,222,51],[197,62,96,138,6,91,163],[104,196,220,57,60,157,23],[62,79,45,106,58,17,243],[210,183,56,210,23,77,118],[55,156,45,56,78,181,240],[56,133,179,208,243,26,76]],\r\n\t[[7,124,187,250,77,133,189],[12,148,45,192,71,97,62],[116,163,167,9,222,246,181],[227,167,98,204,111,163,130],[133,63,20,219,212,154,127],[62,183,150,247,169,209,106],[124,2,172,25,29,64,70]],\r\n\t[[164,231,189,191,62,252,164],[1,208,157,92,35,9,204],[113,63,114,87,246,124,34],[127,72,114,181,192,27,13],[140,18,121,152,79,224,216],[254,89,39,8,179,60,174],[40,129,61,12,115,37,187]],\r\n\t[[249,56,40,5,167,49,242],[151,143,2,190,163,218,226],[222,74,212,91,74,14,188],[68,226,91,164,152,150,176],[91,65,3,226,224,189,24],[50,172,134,14,4,246,190],[149,206,17,236,79,87,64]],\r\n\t[[160,49,161,248,179,199,192],[213,10,121,182,232,241,22],[36,111,171,89,112,195,85],[218,87,58,200,45,80,112],[166,166,27,161,86,247,88],[70,56,239,17,114,226,146],[40,119,129,48,109,11,146]],\r\n\t[[167,182,160,129,233,70,118],[148,25,128,236,251,215,25],[3,238,203,83,219,48,70],[122,197,52,32,192,210,254],[11,57,240,228,111,54,133],[138,153,2,42,86,32,0],[159,127,13,150,176,250,182]],\r\n\t[[158,67,212,29,72,21,49],[233,212,180,36,55,173,168],[106,15,77,124,8,211,175],[150,109,79,81,186,235,233],[6,254,31,122,115,57,14],[84,140,106,133,93,84,72],[60,203,28,34,245,6,118]]\r\n\t\t], dtype=np.int)\r\nmur = 60\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 6 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 6 passed!\")\r\narray = np.array([\r\n\t[[232,194,197,157,206,131,245],[252,8,70,232,241,226,7],[211,116,144,131,88,245,240],[130,89,225,115,197,76,18],[97,235,253,142,3,89,57],[218,189,71,188,87,80,232],[86,127,185,142,208,201,216]],\r\n\t[[227,126,62,92,170,144,220],[10,5,35,69,99,14,22],[123,194,22,59,47,252,56],[189,146,74,52,103,42,228],[173,231,13,88,238,112,52],[115,182,92,185,158,208,112],[146,253,190,45,128,95,70]],\r\n\t[[120,180,252,70,46,127,197],[179,11,186,201,58,26,101],[197,94,20,146,43,38,57],[106,241,198,117,180,22,90],[98,67,15,137,30,32,170],[177,206,43,183,89,127,109],[251,97,84,14,109,133,145]],\r\n\t[[96,127,232,219,231,238,246],[236,244,181,67,154,22,192],[204,160,57,93,94,139,0],[220,156,79,3,90,183,66],[226,33,180,40,245,120,155],[90,12,71,139,88,202,108],[68,76,105,84,51,146,236]],\r\n\t[[50,162,109,62,26,38,149],[103,6,174,235,99,52,55],[145,114,81,106,79,32,137],[92,138,79,196,118,185,213],[104,37,78,232,50,185,221],[43,149,38,145,198,239,52],[247,151,3,77,28,110,44]],\r\n\t[[10,16,198,124,85,20,142],[3,148,163,134,186,26,38],[19,57,114,158,169,194,198],[79,152,134,24,90,182,143],[35,32,100,111,193,89,115],[156,106,90,251,61,140,127],[144,96,105,127,173,85,186]],\r\n\t[[189,249,119,165,19,75,182],[183,18,207,143,89,68,18],[143,160,86,36,178,206,240],[163,213,234,77,18,245,143],[231,225,118,112,85,4,156],[115,241,186,69,216,64,4],[78,195,202,241,164,213,55]]\r\n\t\t], dtype=np.int)\r\nmur = 165\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 7 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 7 passed!\")\r\narray = np.array([\r\n\t[[250,2,53,191,226,184,232],[96,245,237,11,181,123,52],[235,3,220,124,18,252,14],[128,74,65,35,147,40,55],[165,22,144,17,84,199,179],[28,54,60,146,238,88,108],[181,31,246,232,14,104,190]],\r\n\t[[9,200,25,128,153,37,114],[197,157,153,24,23,189,135],[116,62,116,4,52,92,77],[219,27,232,56,31,8,102],[80,240,53,242,40,220,126],[29,83,169,155,131,18,42],[60,106,123,157,4,138,156]],\r\n\t[[215,1,158,201,166,202,4],[169,138,226,250,142,31,19],[251,221,172,162,213,15,33],[117,192,202,115,105,89,137],[113,41,32,176,70,215,202],[143,144,201,98,18,57,56],[54,45,27,250,187,143,174]],\r\n\t[[208,223,225,226,241,130,4],[39,185,208,110,196,140,0],[123,58,207,0,196,102,188],[134,12,250,44,35,155,207],[100,49,50,134,216,22,144],[62,46,12,16,250,232,228],[178,102,153,130,206,84,83]],\r\n\t[[163,103,91,202,179,209,38],[105,137,28,124,12,78,173],[178,73,23,8,230,233,75],[246,240,104,218,42,127,128],[41,231,183,64,131,142,109],[18,39,118,14,5,201,138],[45,72,185,149,229,71,14]],\r\n\t[[221,15,77,187,136,113,175],[240,205,243,154,80,236,72],[179,210,72,98,143,61,41],[224,36,187,205,66,3,0],[136,104,237,87,230,186,230],[168,126,161,147,54,209,160],[215,23,241,132,170,168,220]],\r\n\t[[86,173,26,53,57,120,202],[56,81,50,162,84,184,220],[71,0,123,1,28,214,92],[54,119,220,133,209,87,188],[65,8,2,97,89,77,24],[161,122,18,51,111,197,145],[190,23,16,29,24,105,173]]\r\n\t\t], dtype=np.int)\r\nmur = 200\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 137;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 8 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 8 passed!\")\r\narray = np.array([\r\n\t[[127,175,216,237,100,231,73],[145,54,131,188,37,206,56],[223,249,178,165,127,15,168],[203,239,173,208,103,48,239],[166,117,55,173,224,75,144],[151,10,55,42,96,163,12],[47,39,211,12,48,89,229]],\r\n\t[[250,209,113,148,217,158,22],[168,27,35,244,127,192,166],[128,150,20,244,187,89,81],[79,135,247,134,113,217,70],[41,95,137,97,49,117,207],[242,253,219,214,25,67,42],[238,185,214,45,26,253,212]],\r\n\t[[169,125,104,210,232,95,236],[20,249,242,250,19,193,253],[33,81,112,129,37,66,239],[161,130,228,153,112,93,69],[214,182,129,113,139,221,82],[30,52,60,16,204,178,208],[219,119,141,141,170,234,47]],\r\n\t[[41,162,124,131,149,98,171],[128,113,186,132,201,140,29],[127,31,52,32,237,79,19],[100,42,142,251,58,99,155],[235,235,43,47,106,55,63],[190,29,63,223,152,174,191],[193,57,94,244,249,130,17]],\r\n\t[[30,57,243,34,11,60,50],[3,208,229,252,120,214,39],[69,55,224,60,65,109,176],[238,122,129,119,14,46,10],[124,15,216,96,24,184,5],[85,12,193,31,81,182,66],[200,113,196,43,0,23,154]],\r\n\t[[25,90,64,92,142,78,26],[44,30,253,73,112,151,51],[125,235,242,199,91,246,188],[31,22,60,47,168,46,159],[171,124,92,11,0,52,58],[43,50,2,133,164,62,248],[28,128,15,249,10,105,54]],\r\n\t[[193,25,212,235,47,154,152],[43,97,154,138,220,251,205],[209,207,123,228,61,114,170],[210,112,8,52,22,108,250],[59,82,83,230,228,43,189],[109,27,150,212,21,167,221],[168,170,229,188,204,151,99]]\r\n\t\t], dtype=np.int)\r\nmur = 240\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 9 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 9 passed!\")\r\narray = np.array([\r\n\t[[214,140,53,9,90,253,205],[36,180,98,45,189,131,24],[62,30,19,3,178,72,138],[122,45,145,188,134,27,2],[69,68,29,171,99,117,233],[92,119,92,10,83,164,45],[155,116,21,199,67,79,91]],\r\n\t[[221,185,153,54,0,65,213],[172,41,123,175,23,7,40],[221,114,186,177,111,189,238],[124,47,161,215,106,203,128],[35,197,129,55,32,214,101],[27,226,205,243,3,238,109],[75,145,73,45,246,136,144]],\r\n\t[[175,30,200,241,145,95,213],[66,22,236,230,124,133,115],[103,115,88,175,51,203,247],[160,31,229,160,55,168,220],[69,186,229,198,50,165,86],[168,128,244,111,98,61,155],[210,72,224,218,153,19,20]],\r\n\t[[76,229,22,49,117,152,220],[25,200,20,251,239,50,81],[210,206,48,24,224,72,96],[218,198,100,121,244,214,92],[244,184,86,167,87,135,118],[72,238,254,13,202,33,49],[157,94,75,195,22,150,158]],\r\n\t[[46,4,20,248,69,93,200],[61,29,156,204,158,158,252],[186,151,68,201,93,136,43],[145,46,65,74,235,206,254],[103,125,115,198,231,99,48],[224,65,143,121,161,1,65],[16,157,129,1,22,188,97]],\r\n\t[[223,65,221,188,251,24,178],[12,123,127,193,252,100,39],[139,245,103,58,28,79,8],[37,114,188,251,208,164,175],[214,187,240,116,169,12,26],[96,19,43,173,57,251,207],[220,245,65,210,216,163,11]],\r\n\t[[7,112,227,152,185,168,72],[252,161,233,135,92,219,48],[24,171,78,220,125,251,197],[179,136,226,135,214,243,140],[219,118,23,79,181,85,141],[0,70,226,92,248,14,84],[130,33,230,144,119,124,119]]\r\n\t\t], dtype=np.int)\r\nmur = 228\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 10 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 10 passed!\")\r\narray = np.array([\r\n\t[[185,57,119,210,141,141,110],[117,48,52,95,116,246,191],[127,42,30,41,73,84,250],[146,167,91,201,166,166,234],[124,240,73,170,121,21,128],[13,191,40,150,231,163,77],[214,201,228,62,114,82,19]],\r\n\t[[127,40,241,128,49,26,69],[2,121,23,112,95,24,251],[204,105,49,157,164,79,83],[246,8,226,137,25,17,199],[124,87,130,20,55,104,232],[128,91,118,218,167,238,88],[149,14,194,152,185,216,206]],\r\n\t[[210,156,232,106,246,176,180],[10,75,246,88,143,62,125],[0,82,30,97,44,191,12],[168,132,2,253,220,143,163],[150,251,142,211,35,247,116],[200,1,211,81,64,15,129],[94,68,253,163,51,123,228]],\r\n\t[[232,155,70,85,119,108,36],[2,60,180,31,21,192,67],[17,156,111,42,220,85,20],[20,126,140,135,59,225,100],[7,126,147,177,163,108,89],[66,41,136,17,98,191,163],[228,35,21,222,138,160,86]],\r\n\t[[137,109,201,49,186,23,251],[115,223,248,133,141,248,98],[7,119,242,24,94,99,162],[153,84,122,47,55,173,219],[20,9,151,17,8,214,232],[19,87,92,252,212,81,205],[133,206,176,242,186,111,81]],\r\n\t[[205,92,209,14,58,75,101],[5,122,196,219,197,96,221],[140,24,219,174,87,158,86],[39,0,145,99,14,90,146],[105,12,165,38,29,193,174],[190,242,37,3,195,78,214],[247,197,147,37,64,147,165]],\r\n\t[[18,220,81,119,32,160,101],[45,23,98,172,42,178,122],[92,143,208,181,220,175,43],[99,66,53,40,23,26,223],[191,12,38,30,221,157,10],[22,233,25,60,89,18,147],[112,79,146,89,113,69,134]]\r\n\t\t], dtype=np.int)\r\nmur = 93\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 11 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 11 passed!\")\r\narray = np.array([\r\n\t[[234,30,5,24,126,44,33],[155,133,15,140,166,21,187],[68,127,76,215,172,72,161],[191,157,225,146,168,165,39],[244,205,96,71,202,74,41],[234,22,119,77,110,113,159],[248,100,74,20,26,13,193]],\r\n\t[[160,73,86,5,171,29,179],[201,149,180,248,205,15,36],[115,107,47,211,237,93,30],[5,113,72,83,253,41,149],[37,24,122,124,63,95,126],[49,168,145,62,52,138,216],[240,121,171,196,240,61,68]],\r\n\t[[219,119,169,222,51,72,20],[206,32,175,130,15,43,162],[225,14,196,212,107,39,122],[179,102,145,99,132,133,234],[235,2,24,60,201,254,28],[95,190,169,33,72,173,134],[127,78,197,161,221,165,32]],\r\n\t[[165,38,32,126,220,181,103],[189,66,175,32,42,193,241],[145,33,132,208,8,236,80],[154,244,123,186,70,64,194],[218,67,115,20,223,193,26],[137,75,112,81,12,230,113],[187,27,233,120,233,113,63]],\r\n\t[[20,65,9,57,112,101,251],[251,32,238,163,108,237,131],[212,214,140,64,59,232,34],[234,16,14,137,122,239,169],[246,191,10,114,29,27,163],[140,147,3,178,96,103,225],[213,71,35,94,235,85,245]],\r\n\t[[65,44,197,251,32,64,27],[74,139,230,9,17,105,109],[135,3,30,193,172,147,43],[65,99,248,137,32,220,226],[98,143,186,190,166,116,51],[245,197,83,56,170,14,192],[6,172,195,230,82,121,220]],\r\n\t[[82,38,70,100,160,247,108],[155,118,179,152,7,11,68],[50,102,171,228,176,35,28],[136,254,90,165,207,37,231],[249,63,8,169,79,146,185],[94,204,85,105,108,74,122],[39,88,3,243,33,103,122]]\r\n\t\t], dtype=np.int)\r\nmur = 136\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 12 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 12 passed!\")\r\narray = np.array([\r\n\t[[129,26,199,152,196,0,185],[16,103,45,93,236,228,23],[71,241,162,68,107,180,28],[237,163,135,223,8,99,173],[5,80,151,31,247,38,187],[212,100,236,56,117,22,17],[161,75,54,0,192,200,47]],\r\n\t[[157,240,32,58,47,238,157],[148,156,193,115,100,162,107],[21,205,114,206,0,251,127],[106,7,34,193,234,163,216],[173,216,60,90,181,68,79],[152,120,74,54,6,170,14],[118,162,93,74,36,162,112]],\r\n\t[[197,16,27,26,114,73,10],[254,14,113,244,179,203,239],[23,199,10,168,74,120,172],[145,28,62,11,118,18,246],[29,158,124,89,168,37,90],[214,222,84,136,140,248,246],[94,79,96,91,21,148,26]],\r\n\t[[228,228,184,109,225,34,46],[152,107,104,100,163,230,131],[220,48,4,98,122,89,9],[65,67,253,254,1,34,26],[18,113,138,96,246,235,249],[11,241,248,94,239,174,163],[15,28,140,117,206,150,121]],\r\n\t[[150,193,197,36,3,23,43],[57,71,190,58,153,95,104],[50,64,222,80,12,141,111],[181,197,57,116,126,104,224],[51,24,136,228,215,250,79],[40,207,244,27,228,212,221],[28,133,47,117,46,47,97]],\r\n\t[[90,134,43,61,195,196,119],[153,93,132,50,199,138,56],[102,169,120,12,221,46,111],[61,15,101,15,115,187,160],[77,233,59,167,166,25,74],[112,210,162,3,252,52,243],[87,137,137,131,161,175,160]],\r\n\t[[239,213,221,96,130,173,7],[43,24,89,195,52,148,42],[119,186,29,149,82,109,236],[38,89,151,36,115,216,110],[223,190,29,230,167,214,2],[130,39,32,40,62,47,38],[50,83,157,82,6,120,243]]\r\n\t\t], dtype=np.int)\r\nmur = 229\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 13 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 13 passed!\")\r\narray = np.array([\r\n\t[[102,242,238,22,1,24,250],[29,202,2,26,231,179,30],[110,124,0,227,85,144,94],[121,159,101,53,88,219,9],[141,182,99,206,87,54,247],[46,42,15,5,101,180,129],[82,221,2,142,200,1,98]],\r\n\t[[70,197,198,40,76,94,125],[31,63,55,163,159,100,108],[243,130,218,249,114,225,40],[77,254,130,166,97,77,245],[28,247,123,218,14,158,205],[250,44,122,28,122,93,70],[133,5,136,205,148,11,241]],\r\n\t[[218,175,10,151,240,161,9],[114,97,37,50,215,131,7],[178,147,84,7,165,27,104],[166,188,117,174,189,35,41],[170,89,148,233,21,25,218],[140,109,231,155,24,117,167],[67,32,192,90,77,207,35]],\r\n\t[[175,6,78,130,46,131,12],[165,52,197,169,223,226,57],[215,139,248,30,180,108,184],[90,199,49,197,144,28,17],[43,42,167,222,72,165,136],[239,252,159,142,46,174,38],[157,50,67,223,57,128,144]],\r\n\t[[224,213,207,160,64,23,102],[37,181,6,253,50,181,177],[92,126,211,138,68,227,28],[117,41,127,136,228,199,186],[84,57,215,125,185,28,13],[202,129,39,141,196,240,187],[47,126,179,84,22,79,109]],\r\n\t[[223,201,75,146,61,193,248],[31,231,83,189,15,16,10],[200,13,1,139,88,107,3],[153,44,16,27,91,103,20],[129,77,26,222,240,83,57],[121,221,235,198,199,51,127],[109,10,209,157,70,76,218]],\r\n\t[[168,41,86,67,254,187,230],[139,111,138,148,120,61,3],[92,221,148,54,237,26,89],[32,224,207,85,113,97,220],[7,88,194,9,117,168,120],[195,142,92,112,50,101,240],[82,112,105,253,76,208,227]]\r\n\t\t], dtype=np.int)\r\nmur = 153\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 14 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 14 passed!\")\r\narray = np.array([\r\n\t[[56,102,103,202,252,17,176],[116,249,201,15,63,137,36],[187,114,138,69,161,8,56],[34,246,26,28,176,33,64],[73,220,167,123,135,206,157],[57,54,28,97,120,24,48],[181,122,213,221,26,234,205]],\r\n\t[[170,52,93,19,135,131,202],[145,224,82,112,43,217,2],[37,128,217,57,124,178,51],[47,2,129,83,165,201,168],[60,147,217,84,102,215,94],[69,69,135,205,232,135,165],[98,203,52,61,98,118,72]],\r\n\t[[121,33,87,234,208,64,40],[240,96,14,20,240,232,150],[107,175,202,118,80,165,19],[115,235,235,9,5,96,217],[159,149,201,228,133,62,24],[56,9,2,81,193,0,104],[10,143,21,110,223,58,145]],\r\n\t[[190,63,163,45,191,135,211],[48,181,62,89,116,84,190],[238,23,153,32,209,232,246],[71,175,154,182,74,157,176],[58,114,144,193,99,131,124],[187,149,98,11,9,158,58],[46,225,65,126,244,197,15]],\r\n\t[[103,213,191,75,198,11,191],[249,22,94,243,48,67,174],[150,15,174,9,156,116,111],[162,187,132,14,45,200,178],[55,145,209,157,46,36,236],[52,58,238,201,30,201,111],[17,47,226,72,211,118,111]],\r\n\t[[31,179,81,24,243,38,156],[249,29,4,61,18,50,249],[61,226,238,146,195,25,173],[152,173,162,55,199,253,252],[100,15,130,155,71,40,37],[192,246,161,45,52,81,170],[16,74,211,60,184,112,113]],\r\n\t[[151,63,253,138,152,136,253],[40,229,18,105,49,174,230],[0,218,1,200,162,140,221],[39,186,254,126,88,56,157],[146,152,237,149,119,109,204],[39,84,22,163,154,0,98],[42,38,91,33,200,199,51]]\r\n\t\t], dtype=np.int)\r\nmur = 234\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 15 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 15 passed!\")\r\narray = np.array([\r\n\t[[193,126,53,211,141,30,110],[207,14,153,30,199,177,130],[90,147,142,5,112,15,82],[248,216,226,55,69,124,84],[40,86,207,104,187,73,227],[81,102,222,138,3,221,77],[15,236,235,13,65,199,244]],\r\n\t[[213,226,111,82,28,219,12],[217,51,195,200,244,123,241],[210,58,114,122,20,160,48],[162,151,20,63,200,128,218],[123,126,229,106,221,233,237],[90,171,144,108,216,204,5],[121,206,18,33,161,186,149]],\r\n\t[[11,171,250,230,42,181,37],[226,160,131,20,10,226,21],[231,200,237,234,189,73,59],[133,251,176,194,53,48,54],[122,114,191,169,252,95,126],[62,76,5,26,81,25,166],[249,150,230,87,109,93,136]],\r\n\t[[202,102,11,12,150,28,147],[54,229,117,214,73,232,213],[85,2,0,131,133,179,57],[56,204,106,124,149,24,144],[61,46,159,206,160,102,192],[248,128,204,34,242,34,43],[54,124,69,189,206,87,181]],\r\n\t[[237,87,236,163,79,82,104],[99,84,95,9,104,148,208],[70,12,69,48,41,205,232],[150,231,146,36,230,55,175],[149,78,132,5,154,208,142],[26,4,180,109,197,178,154],[25,81,103,54,27,147,137]],\r\n\t[[138,67,7,127,232,188,111],[195,132,40,42,226,44,51],[80,3,147,31,121,140,194],[48,61,163,217,226,161,177],[63,146,231,22,157,209,213],[167,142,75,156,101,111,177],[239,130,253,54,18,251,130]],\r\n\t[[57,153,219,23,205,252,206],[127,172,58,58,160,29,33],[244,223,127,111,223,44,36],[119,191,12,8,48,81,11],[22,205,156,128,56,230,236],[15,147,39,58,133,167,86],[121,182,109,189,121,239,25]]\r\n\t\t], dtype=np.int)\r\nmur = 202\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 16 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 16 passed!\")\r\narray = np.array([\r\n\t[[239,211,15,212,98,253,36],[221,52,25,165,152,151,131],[15,34,216,130,160,160,137],[192,57,5,163,152,205,66],[127,48,172,86,149,95,85],[233,200,208,89,221,229,149],[198,13,55,14,181,6,179]],\r\n\t[[189,80,39,64,160,26,211],[60,202,107,5,199,236,143],[165,238,85,93,105,50,195],[65,167,34,164,42,178,98],[205,190,161,151,204,31,84],[11,119,242,100,53,36,232],[90,132,238,161,46,134,187]],\r\n\t[[172,177,68,149,70,195,119],[21,125,95,113,96,85,35],[119,237,253,47,41,54,161],[251,31,159,216,226,21,173],[121,140,125,194,176,78,112],[164,220,190,105,180,222,21],[184,244,176,99,77,9,26]],\r\n\t[[197,187,254,170,188,200,227],[23,233,41,122,229,253,251],[151,47,22,58,32,142,186],[64,119,12,12,76,235,221],[81,65,134,7,116,24,145],[97,202,156,49,28,23,40],[192,191,92,51,115,172,19]],\r\n\t[[228,180,38,0,102,251,222],[6,30,31,31,110,142,27],[13,83,78,60,20,140,40],[13,204,99,254,180,54,75],[136,157,27,166,167,140,21],[39,249,248,6,195,138,82],[164,232,115,227,144,236,47]],\r\n\t[[230,5,30,203,1,116,144],[66,121,74,132,220,149,166],[190,33,223,198,5,97,103],[204,152,72,65,70,151,116],[83,84,53,151,40,242,96],[30,57,11,106,252,99,133],[2,30,247,60,47,213,122]],\r\n\t[[148,121,48,44,184,52,179],[150,166,202,140,19,107,105],[158,83,110,28,10,223,222],[225,64,14,27,33,208,249],[180,86,17,120,14,152,226],[177,143,51,0,54,127,41],[22,169,47,140,69,229,47]]\r\n\t\t], dtype=np.int)\r\nmur = 114\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 17 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 17 passed!\")\r\narray = np.array([\r\n\t[[75,135,6,72,240,88,62],[178,11,186,110,102,37,169],[67,24,37,61,133,166,245],[119,193,248,136,183,163,202],[48,185,210,11,203,182,93],[18,22,120,95,143,158,194],[44,164,196,25,77,119,225]],\r\n\t[[148,141,253,117,37,236,74],[22,246,131,18,120,179,107],[186,164,141,253,59,5,128],[148,36,237,129,252,171,122],[219,247,125,222,51,132,212],[3,162,15,108,60,96,46],[112,177,229,98,177,202,202]],\r\n\t[[40,52,45,204,113,229,79],[130,207,32,29,179,8,77],[20,116,225,151,131,70,156],[3,234,31,176,233,68,147],[105,50,249,17,113,78,23],[94,228,212,155,210,228,55],[72,60,84,153,43,160,129]],\r\n\t[[172,11,33,104,110,189,194],[66,165,110,76,83,150,149],[213,91,204,31,120,236,225],[33,9,123,232,3,176,133],[65,73,245,222,141,154,196],[101,231,141,189,11,251,117],[218,207,124,30,198,27,25]],\r\n\t[[111,187,61,104,241,68,47],[188,169,130,116,178,119,85],[205,199,211,139,77,222,42],[98,102,247,193,186,161,194],[26,122,239,153,29,38,91],[138,105,31,173,24,46,122],[38,66,178,11,204,60,5]],\r\n\t[[46,131,4,164,122,168,25],[214,194,166,186,178,57,19],[0,58,117,89,87,81,176],[226,52,172,152,231,121,37],[91,140,202,89,169,75,155],[131,184,235,203,184,109,23],[221,12,115,201,128,26,253]],\r\n\t[[179,195,15,254,31,207,48],[63,200,238,169,31,117,10],[31,38,111,254,55,92,114],[114,229,172,135,63,219,154],[19,181,156,119,73,28,34],[182,138,120,24,124,178,199],[94,42,54,181,159,108,34]]\r\n\t\t], dtype=np.int)\r\nmur = 213\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 18 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 18 passed!\")\r\narray = np.array([\r\n\t[[186,114,61,177,31,72,219],[121,188,166,53,254,130,51],[5,173,185,164,205,222,151],[208,199,198,142,28,164,2],[198,235,116,51,248,164,59],[140,10,145,241,215,57,182],[20,100,3,206,10,246,85]],\r\n\t[[174,205,230,235,114,117,188],[208,204,137,20,207,184,17],[99,29,51,60,94,96,217],[32,114,175,246,31,114,19],[221,147,217,208,50,225,70],[149,99,18,89,39,80,207],[126,196,234,141,221,126,117]],\r\n\t[[251,111,215,23,109,86,26],[16,70,158,41,72,54,74],[38,222,214,79,64,84,183],[49,178,167,33,109,204,177],[114,185,46,87,58,222,115],[143,179,82,141,84,174,250],[242,201,26,111,123,146,126]],\r\n\t[[131,197,58,148,21,52,194],[4,145,123,184,4,73,89],[156,37,82,145,85,180,120],[0,132,140,25,166,11,193],[212,200,78,102,106,158,6],[136,198,109,188,16,31,54],[190,34,16,71,74,169,112]],\r\n\t[[246,159,196,154,35,53,174],[253,97,211,105,196,250,38],[54,46,30,193,209,115,194],[241,130,50,109,76,194,17],[9,82,250,9,48,118,218],[204,64,246,211,21,232,95],[45,151,141,166,221,122,198]],\r\n\t[[178,177,21,230,66,239,122],[239,216,161,30,93,135,46],[254,135,1,143,143,5,216],[135,114,195,24,61,31,150],[168,162,112,183,178,171,166],[234,110,225,49,199,160,144],[26,142,72,83,243,149,163]],\r\n\t[[77,86,120,173,196,221,156],[186,60,25,4,236,24,22],[34,93,165,91,142,19,126],[7,203,149,113,39,39,121],[25,226,149,112,47,50,105],[11,253,188,200,215,71,220],[69,25,181,78,67,245,107]]\r\n\t\t], dtype=np.int)\r\nmur = 103\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 19 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 19 passed!\")\r\narray = np.array([\r\n\t[[227,72,56,55,254,43,40],[211,216,78,163,215,238,190],[33,39,160,83,32,17,238],[113,248,96,240,193,187,223],[39,175,174,129,214,133,30],[210,152,85,63,247,149,6],[205,17,124,249,215,121,250]],\r\n\t[[153,109,251,153,55,212,29],[196,152,126,180,212,109,9],[137,114,250,7,220,76,56],[206,176,182,151,59,29,142],[28,73,82,101,191,254,110],[36,37,8,248,17,101,89],[65,193,113,122,48,1,78]],\r\n\t[[165,77,183,219,13,59,89],[120,26,231,203,246,60,8],[162,242,90,118,167,19,80],[204,154,54,50,174,201,176],[23,122,208,81,29,157,0],[101,212,98,16,173,26,143],[123,64,160,154,114,44,92]],\r\n\t[[136,53,78,138,240,150,254],[241,99,75,7,59,33,199],[156,97,91,78,176,202,150],[85,92,60,16,7,237,173],[7,233,130,105,231,82,153],[223,235,164,210,234,5,102],[227,114,11,140,221,252,163]],\r\n\t[[151,90,226,107,24,101,145],[123,44,150,69,76,79,90],[98,143,188,122,216,163,41],[102,179,120,153,15,146,240],[129,84,175,102,31,172,21],[77,76,99,76,235,80,169],[245,24,143,246,188,199,166]],\r\n\t[[33,150,74,122,158,120,160],[47,71,202,0,79,143,248],[101,30,219,65,137,13,176],[95,2,87,234,166,220,67],[142,10,190,203,117,221,172],[251,110,0,2,211,94,225],[187,170,139,79,37,209,147]],\r\n\t[[85,39,218,240,63,201,136],[241,145,106,140,23,236,66],[64,36,241,92,57,13,134],[223,93,84,92,53,247,124],[219,222,227,212,132,105,194],[66,84,4,174,24,198,148],[1,179,236,184,140,148,201]]\r\n\t\t], dtype=np.int)\r\nmur = 207\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 20 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 20 passed!\")\r\narray = np.array([\r\n\t[[92,218,194,90,146,196,85],[12,152,58,187,176,134,20],[21,206,179,244,185,113,98],[31,25,148,9,203,57,119],[52,136,199,17,238,54,143],[101,110,54,220,74,51,74],[186,165,104,150,67,87,251]],\r\n\t[[202,66,102,104,30,244,89],[237,168,133,21,200,148,22],[192,223,83,29,209,30,222],[60,55,94,236,154,232,251],[15,230,20,100,130,237,190],[63,187,227,230,3,0,225],[238,229,50,182,187,142,117]],\r\n\t[[184,240,214,32,142,31,142],[46,26,221,114,153,226,108],[237,160,106,116,140,99,24],[54,61,234,37,79,252,0],[191,122,144,246,63,108,130],[225,178,140,163,83,145,57],[54,68,143,248,108,116,105]],\r\n\t[[233,0,237,76,237,80,72],[3,3,155,160,3,25,58],[17,31,43,18,174,63,135],[166,185,110,162,60,217,155],[231,18,197,163,206,199,107],[214,49,50,9,64,235,125],[165,82,155,69,13,5,51]],\r\n\t[[82,135,130,209,223,17,110],[124,216,34,44,214,180,223],[16,133,64,112,241,206,11],[118,190,81,30,44,155,119],[174,71,151,42,61,14,116],[124,172,208,141,8,134,251],[199,108,248,105,138,56,3]],\r\n\t[[190,122,108,91,159,13,19],[125,69,101,18,117,135,100],[204,175,227,150,126,183,181],[49,244,183,116,165,106,2],[163,248,200,169,228,214,177],[188,214,185,179,232,219,16],[132,108,26,84,114,69,24]],\r\n\t[[225,163,64,212,193,63,111],[202,26,185,152,2,172,212],[179,179,102,193,242,254,231],[107,101,204,230,31,245,107],[90,63,191,198,10,110,11],[165,249,45,203,200,5,214],[251,248,74,4,51,186,153]]\r\n\t\t], dtype=np.int)\r\nmur = 204\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 21 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 21 passed!\")\r\narray = np.array([\r\n\t[[251,45,3,238,78,64,97],[92,205,133,133,208,152,69],[74,31,231,190,136,33,177],[0,79,46,203,211,97,79],[28,53,41,89,176,197,164],[179,59,56,249,32,24,36],[103,5,230,81,188,41,119]],\r\n\t[[140,2,68,217,206,47,100],[11,158,193,45,34,104,136],[242,45,20,79,37,147,133],[51,151,95,196,95,141,163],[235,15,105,141,254,153,160],[48,22,188,96,203,124,14],[248,228,239,42,55,244,183]],\r\n\t[[167,155,81,98,129,88,203],[42,77,160,18,28,30,37],[187,237,234,129,228,253,165],[32,211,69,6,138,120,208],[141,107,130,27,120,124,128],[57,54,134,81,186,185,103],[149,15,235,51,200,5,89]],\r\n\t[[2,117,74,26,224,233,230],[63,125,172,172,162,110,59],[239,72,239,244,151,125,252],[238,238,120,129,212,29,201],[183,233,141,128,149,98,60],[60,223,238,140,226,129,231],[111,46,171,15,248,143,92]],\r\n\t[[205,213,222,22,158,82,167],[34,142,161,81,27,136,61],[18,22,144,164,198,4,102],[9,186,244,197,241,120,5],[124,21,111,69,116,107,201],[198,233,170,6,201,40,50],[65,154,213,61,24,246,40]],\r\n\t[[212,189,169,243,75,96,176],[25,73,69,199,132,101,158],[166,71,65,243,158,15,36],[214,173,61,104,222,127,200],[222,206,66,94,191,18,67],[202,196,124,94,131,178,116],[61,92,210,1,225,142,179]],\r\n\t[[79,245,251,194,100,110,170],[205,100,186,250,218,34,49],[22,241,79,2,62,147,250],[129,106,214,28,239,237,121],[160,97,162,212,3,77,185],[26,64,197,1,194,101,35],[147,41,4,196,41,77,2]]\r\n\t\t], dtype=np.int)\r\nmur = 25\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 22 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 22 passed!\")\r\narray = np.array([\r\n\t[[117,142,107,177,97,172,172],[91,71,76,29,217,7,37],[100,226,167,127,123,166,109],[4,213,246,83,106,157,253],[123,222,41,247,84,161,24],[246,23,118,187,70,109,95],[215,159,233,101,237,234,132]],\r\n\t[[122,226,222,179,154,123,86],[41,15,191,178,205,154,247],[9,26,60,48,23,234,70],[112,57,238,77,95,205,21],[79,79,78,117,254,39,98],[196,228,88,52,32,0,202],[10,7,245,106,77,161,69]],\r\n\t[[251,212,51,118,194,200,125],[40,231,193,227,118,218,192],[57,155,108,25,93,127,28],[42,135,19,96,235,82,234],[51,252,140,159,238,157,39],[248,116,79,152,245,71,236],[52,38,135,45,95,9,25]],\r\n\t[[83,44,218,46,252,88,247],[208,169,61,251,39,68,76],[241,102,71,23,202,228,208],[227,239,151,140,170,216,216],[211,51,234,156,197,83,140],[101,160,151,152,138,63,135],[128,241,73,160,250,165,184]],\r\n\t[[65,102,169,228,112,126,121],[192,194,50,95,159,162,222],[88,136,56,154,192,9,241],[111,202,134,22,10,99,185],[12,68,27,113,121,32,238],[201,198,118,65,48,36,250],[192,135,103,144,154,159,27]],\r\n\t[[41,130,9,18,114,44,33],[242,169,97,55,73,141,139],[128,243,194,170,12,83,5],[94,143,254,59,210,202,3],[17,8,242,189,131,137,157],[204,77,243,99,33,28,243],[246,98,5,46,176,254,74]],\r\n\t[[34,139,93,196,215,198,67],[12,56,247,134,57,148,120],[108,35,51,32,128,16,70],[23,227,196,165,149,184,138],[133,25,68,132,87,30,59],[66,235,253,168,74,74,106],[239,114,141,121,247,44,251]]\r\n\t\t], dtype=np.int)\r\nmur = 133\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 23 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 23 passed!\")\r\narray = np.array([\r\n\t[[239,243,104,195,252,66,85],[28,79,46,47,114,33,14],[233,182,134,241,95,190,189],[141,52,96,230,99,57,247],[104,95,13,49,40,145,51],[199,52,77,153,14,141,253],[252,90,95,214,40,83,178]],\r\n\t[[197,120,175,190,71,212,63],[76,138,4,57,21,43,218],[224,71,137,243,96,5,45],[213,135,78,247,109,225,208],[37,107,151,122,13,251,156],[235,10,108,224,9,111,154],[216,22,79,252,143,78,99]],\r\n\t[[66,116,160,58,191,2,130],[109,9,241,27,87,195,165],[230,185,251,137,173,165,207],[71,56,19,69,59,185,153],[32,155,174,2,103,65,191],[160,110,254,100,236,144,104],[153,36,8,150,32,145,21]],\r\n\t[[6,141,153,196,119,125,209],[31,140,246,9,214,132,131],[41,203,96,216,29,143,220],[187,69,152,159,10,159,123],[193,11,66,243,225,60,115],[204,29,162,72,215,29,233],[222,185,77,245,110,219,84]],\r\n\t[[220,250,23,122,245,83,91],[11,62,84,233,188,226,63],[77,253,157,66,230,131,103],[182,152,158,105,12,252,207],[110,51,65,180,200,232,45],[152,186,153,167,204,87,240],[85,177,168,221,166,7,8]],\r\n\t[[26,218,23,37,242,161,218],[29,24,50,175,93,46,21],[6,236,175,209,114,132,209],[241,167,219,53,86,139,114],[237,161,144,222,181,191,166],[126,45,102,206,206,108,170],[105,151,86,177,26,122,230]],\r\n\t[[193,28,210,108,80,204,235],[0,90,230,193,71,199,154],[111,223,182,247,15,171,82],[3,28,101,217,80,176,0],[203,85,134,241,41,243,10],[129,53,43,187,163,98,75],[158,179,117,184,215,236,183]]\r\n\t\t], dtype=np.int)\r\nmur = 164\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 24 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 24 passed!\")\r\narray = np.array([\r\n\t[[40,132,121,215,117,152,149],[82,135,44,133,113,2,7],[210,140,229,121,230,12,47],[181,0,95,55,253,246,173],[130,142,217,114,223,101,124],[15,148,245,26,229,30,54],[215,81,53,117,203,8,68]],\r\n\t[[180,50,36,159,100,116,149],[183,29,142,10,150,112,156],[61,206,140,174,19,75,173],[233,20,48,62,219,211,57],[248,15,137,109,40,17,43],[197,206,239,107,114,159,247],[242,7,107,136,231,36,59]],\r\n\t[[224,172,162,32,3,64,141],[138,89,130,205,134,13,52],[145,230,226,50,95,178,151],[136,158,42,178,182,220,210],[188,65,194,84,253,248,136],[144,225,100,23,164,114,48],[247,153,73,46,109,27,53]],\r\n\t[[124,161,203,19,158,211,62],[5,165,84,30,133,232,182],[103,203,233,232,87,231,5],[76,175,204,78,224,22,2],[84,181,222,199,118,237,71],[62,254,127,42,104,154,242],[2,52,59,253,217,228,72]],\r\n\t[[113,241,104,34,209,20,253],[79,204,233,219,56,163,102],[139,112,15,119,87,192,86],[118,213,181,214,31,188,203],[187,55,185,38,169,73,115],[24,170,178,152,137,74,199],[96,249,76,153,104,49,197]],\r\n\t[[85,131,117,158,186,196,29],[241,218,4,143,124,44,85],[243,117,207,137,99,20,29],[116,187,37,29,158,29,207],[251,85,132,118,22,134,72],[166,95,194,71,176,3,162],[227,104,3,51,58,218,75]],\r\n\t[[56,80,242,58,190,118,4],[46,33,119,72,49,146,121],[202,119,150,158,221,216,62],[216,138,84,171,218,102,93],[164,4,189,216,87,178,51],[66,217,167,247,129,132,175],[88,93,77,169,49,166,119]]\r\n\t\t], dtype=np.int)\r\nmur = 11\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 25 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 25 passed!\")\r\narray = np.array([\r\n\t[[230,46,190,198,129,127,226],[11,16,118,13,81,203,212],[162,19,32,83,73,5,68],[128,194,204,181,228,11,60],[63,208,232,218,67,154,236],[31,42,68,157,103,7,179],[202,91,5,171,234,134,86]],\r\n\t[[50,128,121,222,228,14,19],[182,76,121,209,182,248,44],[90,228,188,85,67,88,156],[106,143,132,59,4,111,31],[224,183,84,186,111,62,157],[148,29,31,74,192,76,153],[136,59,239,83,57,8,24]],\r\n\t[[117,205,88,90,8,148,169],[35,237,169,66,127,35,131],[153,143,23,195,228,178,146],[180,83,33,186,81,110,189],[103,160,156,124,16,11,151],[172,244,157,76,35,52,22],[157,224,112,156,173,156,32]],\r\n\t[[227,6,29,68,28,172,75],[223,56,226,253,45,214,55],[197,31,114,135,118,161,57],[1,125,134,8,199,124,29],[132,142,151,239,218,131,220],[9,70,249,229,217,14,105],[183,183,5,192,6,148,139]],\r\n\t[[60,4,219,253,32,34,92],[187,97,143,135,226,250,11],[216,95,8,145,4,224,95],[97,114,55,33,134,182,5],[72,85,66,2,90,226,165],[100,188,120,154,43,201,242],[82,244,36,62,146,150,35]],\r\n\t[[74,57,243,43,245,122,181],[38,102,92,168,240,246,108],[176,54,162,152,150,168,251],[73,135,162,76,204,169,101],[47,159,143,84,169,100,81],[68,119,112,137,249,2,206],[77,199,184,217,157,22,251]],\r\n\t[[42,236,57,252,17,98,160],[222,197,189,175,168,127,251],[45,239,44,242,133,170,227],[149,101,78,58,33,240,131],[109,86,213,154,228,79,19],[120,6,176,143,61,54,195],[214,43,65,207,113,47,23]]\r\n\t\t], dtype=np.int)\r\nmur = 83\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 26 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 26 passed!\")\r\narray = np.array([\r\n\t[[57,54,23,166,197,111,4],[114,199,22,45,200,253,237],[252,245,243,253,38,95,6],[41,226,111,171,89,119,191],[220,151,12,25,40,83,157],[123,89,113,108,186,57,32],[220,167,111,99,246,47,102]],\r\n\t[[215,39,35,95,216,140,16],[138,110,86,85,196,108,104],[225,175,47,10,144,212,109],[114,204,220,33,112,194,175],[204,43,240,90,225,180,18],[193,182,44,181,230,79,242],[85,66,31,22,237,151,53]],\r\n\t[[41,201,114,129,26,158,36],[223,29,163,127,62,220,157],[10,46,160,30,3,82,28],[43,127,198,30,250,196,163],[101,156,66,56,175,54,112],[94,57,27,249,179,151,242],[176,38,87,226,80,80,108]],\r\n\t[[189,163,230,177,130,39,95],[248,24,62,43,98,100,163],[61,209,49,50,171,253,136],[137,96,24,66,108,139,127],[237,25,213,104,203,7,55],[252,161,169,254,164,162,214],[252,157,159,22,249,47,106]],\r\n\t[[170,29,65,37,174,81,165],[185,49,152,28,92,220,239],[202,85,133,81,1,215,233],[115,62,120,7,187,238,193],[31,141,55,43,29,43,90],[83,175,32,199,39,229,237],[244,123,71,163,80,96,230]],\r\n\t[[135,103,185,102,5,42,98],[213,215,0,64,32,172,195],[251,48,54,194,163,0,208],[157,57,39,14,231,193,58],[100,246,154,0,230,75,177],[192,251,224,82,226,60,79],[73,116,6,209,6,90,141]],\r\n\t[[244,139,190,128,12,138,87],[51,39,73,243,188,50,1],[11,32,174,24,218,48,185],[239,4,127,197,219,140,151],[254,55,239,194,25,201,10],[140,175,92,224,95,76,43],[29,240,102,158,115,153,65]]\r\n\t\t], dtype=np.int)\r\nmur = 91\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 137;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 27 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 27 passed!\")\r\narray = np.array([\r\n\t[[163,52,17,95,236,28,212],[12,57,170,164,56,144,3],[15,19,101,63,210,145,230],[179,60,49,184,201,16,234],[166,150,2,123,142,189,37],[161,170,23,69,145,219,242],[124,111,251,29,121,4,208]],\r\n\t[[222,120,13,179,26,101,99],[220,120,228,108,245,89,184],[198,69,168,2,105,193,211],[235,112,54,214,82,67,163],[83,80,53,162,132,115,242],[125,57,244,240,31,103,104],[67,55,122,137,144,189,141]],\r\n\t[[91,102,42,142,245,43,142],[151,172,40,80,109,234,5],[233,247,88,51,189,152,229],[245,3,246,70,220,42,233],[39,58,27,196,218,248,110],[53,247,200,184,193,166,69],[30,5,23,141,186,89,158]],\r\n\t[[54,59,108,18,189,151,158],[250,54,218,203,15,65,243],[149,189,130,212,216,208,224],[168,219,43,151,44,1,206],[186,164,33,124,165,145,116],[225,146,204,127,90,183,125],[33,221,26,157,22,93,165]],\r\n\t[[9,3,163,203,4,185,95],[65,63,84,73,123,43,3],[109,186,97,0,66,150,115],[247,18,234,191,191,140,22],[156,122,33,0,104,162,144],[202,51,163,235,246,16,176],[57,82,43,100,176,79,145]],\r\n\t[[156,134,246,242,5,6,161],[78,95,239,74,166,249,139],[237,86,139,101,185,66,117],[229,67,189,225,188,41,133],[160,88,6,141,7,250,144],[55,125,253,199,80,178,119],[180,180,26,17,123,147,179]],\r\n\t[[53,60,49,192,19,240,1],[216,217,218,50,222,219,94],[118,154,26,41,97,143,50],[135,136,163,206,223,166,21],[2,250,127,242,111,204,43],[161,98,168,213,26,229,161],[247,184,52,18,249,23,142]]\r\n\t\t], dtype=np.int)\r\nmur = 70\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 28 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 28 passed!\")\r\narray = np.array([\r\n\t[[156,123,191,250,152,101,227],[168,83,215,48,26,148,231],[96,76,193,34,47,216,196],[43,63,242,176,96,238,138],[107,153,13,40,250,215,107],[41,96,41,192,55,207,63],[75,128,121,240,231,79,150]],\r\n\t[[97,62,121,186,137,15,223],[237,141,92,100,79,173,59],[11,2,153,206,139,245,115],[159,135,217,2,87,192,69],[183,4,68,179,117,235,89],[131,200,162,128,131,116,224],[70,216,252,48,112,103,116]],\r\n\t[[2,85,57,93,230,139,167],[216,63,1,61,4,234,147],[190,93,184,191,218,69,101],[185,180,37,149,38,178,187],[93,125,154,213,179,101,71],[108,243,184,67,209,252,42],[43,192,237,157,172,126,34]],\r\n\t[[153,67,59,95,32,52,10],[190,162,221,47,147,26,168],[187,112,93,164,52,145,62],[224,159,149,144,169,29,125],[21,239,63,248,118,107,169],[83,56,61,213,107,145,71],[162,242,108,133,73,27,148]],\r\n\t[[233,173,162,33,135,34,152],[164,92,242,165,146,140,116],[227,203,242,41,234,22,179],[113,92,5,177,235,131,208],[175,111,54,170,195,62,18],[43,12,205,174,23,95,148],[77,247,30,217,183,150,155]],\r\n\t[[47,236,31,81,144,150,68],[204,17,63,1,230,69,50],[92,75,207,3,195,39,125],[131,128,114,104,145,252,170],[109,83,55,228,196,131,240],[145,55,135,18,10,122,80],[44,149,170,92,93,162,131]],\r\n\t[[147,180,51,26,176,115,42],[224,170,218,139,76,201,81],[19,90,251,139,175,157,227],[26,128,185,14,192,84,249],[113,144,137,85,41,27,189],[194,229,188,172,152,50,106],[202,49,14,8,244,237,154]]\r\n\t\t], dtype=np.int)\r\nmur = 193\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 115;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 29 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 29 passed!\")\r\narray = np.array([\r\n\t[[131,7,86,218,37,148,96],[155,167,156,96,219,192,105],[64,25,134,140,222,210,212],[186,170,149,235,249,1,231],[133,73,66,13,225,75,28],[187,157,243,61,247,43,176],[74,46,212,51,148,230,7]],\r\n\t[[84,173,33,95,219,3,61],[136,127,243,128,204,76,182],[58,214,204,180,33,67,207],[85,252,157,36,134,109,204],[179,214,253,135,189,178,199],[49,199,19,218,189,130,236],[230,118,3,192,31,233,164]],\r\n\t[[62,33,112,30,252,167,88],[196,226,178,74,182,159,65],[244,98,152,113,74,108,165],[194,23,91,202,11,176,188],[3,154,18,248,187,238,83],[37,108,218,194,140,225,163],[145,208,66,214,238,210,136]],\r\n\t[[81,58,116,184,13,108,55],[73,173,5,178,106,219,57],[211,205,105,234,105,29,101],[111,63,132,219,134,108,58],[163,151,142,213,108,228,221],[160,32,211,138,61,16,252],[105,74,90,191,5,77,150]],\r\n\t[[20,154,214,19,53,232,77],[57,24,174,207,221,217,234],[21,202,132,226,224,242,121],[171,167,19,217,109,231,112],[191,239,93,222,228,195,198],[21,221,207,140,38,242,243],[145,107,78,212,209,3,76]],\r\n\t[[174,178,127,211,120,94,40],[112,8,142,199,70,3,44],[47,223,38,137,137,154,246],[72,43,150,89,191,137,213],[193,6,167,154,111,89,81],[82,10,2,24,69,29,103],[9,202,42,146,157,148,38]],\r\n\t[[246,201,199,185,168,147,148],[166,19,125,145,109,248,129],[77,5,194,247,236,13,62],[86,113,138,20,76,175,175],[241,86,250,86,15,15,40],[76,1,45,132,126,203,80],[66,5,62,209,172,30,125]]\r\n\t\t], dtype=np.int)\r\nmur = 36\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 30 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 30 passed!\")\r\narray = np.array([\r\n\t[[87,202,43,93,16,154,250],[66,147,135,6,36,140,64],[210,131,127,254,220,186,148],[237,250,27,169,233,149,89],[242,148,157,237,207,249,241],[161,240,222,219,178,141,163],[214,129,77,158,46,86,169]],\r\n\t[[229,211,229,254,187,91,39],[17,166,177,239,57,173,172],[57,88,42,95,75,98,65],[8,188,248,25,30,80,118],[211,12,169,44,119,238,253],[38,106,120,122,209,224,250],[73,196,148,111,186,139,182]],\r\n\t[[5,3,160,135,59,15,198],[146,6,25,1,40,13,32],[251,70,127,63,132,97,66],[130,122,146,17,180,120,10],[142,61,141,237,139,32,36],[196,187,156,1,162,238,196],[15,47,148,119,26,70,229]],\r\n\t[[86,211,216,195,226,219,9],[87,94,243,91,57,64,7],[136,162,118,234,172,39,27],[45,25,16,10,177,209,113],[40,134,55,55,100,122,53],[143,155,172,254,210,220,109],[202,133,17,60,183,178,207]],\r\n\t[[233,61,201,76,201,136,126],[234,54,178,35,226,159,184],[126,34,108,25,127,12,229],[7,23,59,44,117,241,135],[186,160,17,228,254,97,133],[234,79,215,163,144,68,13],[29,123,182,252,154,14,116]],\r\n\t[[220,226,63,9,59,213,197],[229,130,9,170,62,151,22],[137,111,104,13,49,73,163],[120,127,3,126,183,51,218],[113,204,75,182,110,248,203],[129,19,88,203,144,216,72],[167,6,75,130,103,249,93]],\r\n\t[[14,77,110,91,149,141,22],[76,120,249,177,192,40,131],[5,31,56,138,218,231,2],[251,114,228,142,251,195,212],[248,154,84,187,9,13,96],[251,214,125,169,231,132,136],[13,38,161,4,132,43,160]]\r\n\t\t], dtype=np.int)\r\nmur = 13\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 31 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 31 passed!\")\r\narray = np.array([\r\n\t[[130,53,75,106,13,57,22],[30,73,173,100,124,56,246],[4,159,222,55,63,148,26],[163,68,32,242,151,209,77],[45,94,84,185,121,30,53],[210,65,222,201,68,111,10],[47,236,46,97,214,61,142]],\r\n\t[[146,156,168,125,126,63,183],[114,250,48,183,167,236,252],[87,124,42,141,222,57,246],[20,196,101,198,133,129,234],[172,131,181,167,3,158,246],[80,72,170,244,148,181,104],[123,205,251,93,4,227,76]],\r\n\t[[246,22,52,55,115,13,7],[248,193,123,232,175,215,199],[100,247,234,46,56,204,236],[32,220,179,182,210,24,48],[136,18,186,206,222,182,193],[64,209,166,85,195,199,13],[127,92,49,134,144,74,47]],\r\n\t[[242,252,17,129,68,44,115],[124,219,103,8,150,197,18],[80,146,169,223,189,18,165],[16,191,17,59,195,51,114],[13,51,215,101,99,116,67],[249,230,53,80,94,52,52],[155,158,46,124,222,221,152]],\r\n\t[[197,233,32,206,73,112,106],[214,216,140,32,27,56,189],[250,254,46,86,177,9,254],[121,9,94,58,180,21,80],[211,60,187,56,131,28,79],[54,218,10,84,239,235,117],[190,93,74,215,48,140,23]],\r\n\t[[224,224,127,251,178,240,175],[191,42,20,110,92,34,73],[79,52,31,200,178,78,241],[72,66,134,26,221,5,91],[233,168,111,226,242,233,7],[237,174,226,91,93,170,102],[91,206,16,157,120,141,165]],\r\n\t[[71,45,72,38,234,44,123],[96,200,76,175,120,146,54],[147,129,83,128,231,136,228],[86,86,49,202,116,157,249],[114,37,216,194,209,15,108],[223,40,167,78,33,139,38],[109,107,62,193,242,69,224]]\r\n\t\t], dtype=np.int)\r\nmur = 165\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 32 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 32 passed!\")\r\narray = np.array([\r\n\t[[250,123,129,144,111,73,143],[57,158,0,37,100,33,25],[171,150,222,88,231,150,20],[143,230,23,207,75,106,44],[54,150,243,199,220,142,180],[66,26,175,142,201,196,77],[43,161,235,7,231,10,242]],\r\n\t[[59,177,149,183,235,193,19],[236,247,135,86,14,233,245],[122,135,26,174,6,98,175],[228,244,38,37,65,208,22],[253,155,16,140,25,182,243],[228,90,179,172,240,187,86],[160,128,71,157,106,151,160]],\r\n\t[[62,117,123,18,48,153,220],[207,69,188,152,145,205,144],[169,178,231,198,28,57,211],[17,88,60,30,132,249,198],[162,32,238,190,142,88,31],[141,133,185,1,149,71,0],[21,28,192,117,238,143,114]],\r\n\t[[47,234,20,254,68,67,71],[80,98,47,222,168,253,231],[66,158,218,64,68,163,178],[227,37,178,1,47,197,4],[231,149,148,84,96,221,57],[242,192,127,108,7,31,188],[69,51,6,4,70,98,219]],\r\n\t[[190,251,221,82,77,50,120],[221,212,162,72,70,226,209],[130,59,32,225,23,54,231],[26,64,248,250,97,138,21],[156,193,82,187,119,238,56],[26,199,48,94,86,36,83],[121,87,9,224,200,73,87]],\r\n\t[[227,102,238,216,170,30,122],[187,59,76,208,160,86,69],[132,235,111,136,46,171,15],[250,177,208,86,187,207,32],[45,176,83,252,205,169,100],[99,102,160,106,80,191,102],[29,196,204,108,189,141,61]],\r\n\t[[240,74,112,181,156,152,7],[120,195,159,158,249,145,151],[70,113,153,178,16,124,229],[106,5,10,83,14,108,206],[47,146,128,156,152,171,114],[194,216,220,14,105,16,223],[12,155,31,86,85,7,15]]\r\n\t\t], dtype=np.int)\r\nmur = 114\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 33 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 33 passed!\")\r\narray = np.array([\r\n\t[[194,246,9,64,133,122,245],[97,80,77,60,39,149,30],[107,102,82,106,206,235,0],[250,21,33,196,116,136,78],[0,81,31,136,27,64,187],[158,68,2,200,154,215,108],[42,118,0,196,54,133,49]],\r\n\t[[19,63,135,18,179,81,29],[37,147,122,180,180,112,124],[158,205,175,65,89,1,201],[143,127,40,242,186,157,225],[182,86,131,210,130,250,18],[200,158,237,214,122,125,39],[13,197,208,59,132,199,124]],\r\n\t[[217,68,0,3,49,51,225],[208,55,122,43,147,98,9],[89,100,238,80,24,93,252],[52,185,117,57,41,42,177],[78,72,104,71,186,173,62],[40,140,226,176,2,104,136],[26,128,97,133,13,101,228]],\r\n\t[[211,15,50,111,49,94,214],[205,19,160,112,167,155,253],[185,243,117,251,225,167,107],[182,178,165,155,246,88,16],[227,158,206,4,89,87,219],[213,114,61,69,142,11,127],[15,174,82,209,105,30,66]],\r\n\t[[62,40,9,1,227,183,169],[124,128,240,196,89,192,167],[219,35,163,157,149,202,194],[74,245,158,23,242,107,193],[48,105,65,138,80,76,128],[114,194,56,87,88,219,89],[178,214,128,201,234,105,244]],\r\n\t[[45,29,28,141,149,36,11],[205,191,144,108,56,228,239],[224,244,200,224,101,41,63],[106,138,112,185,64,136,163],[224,106,210,27,106,109,169],[250,95,83,228,171,67,73],[95,175,97,21,137,102,131]],\r\n\t[[119,201,162,156,155,69,139],[195,237,238,0,50,200,153],[184,218,117,36,61,49,215],[76,39,65,231,39,83,249],[149,187,241,57,20,139,178],[151,232,66,13,98,177,181],[148,239,48,31,1,174,185]]\r\n\t\t], dtype=np.int)\r\nmur = 19\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 34 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 34 passed!\")\r\narray = np.array([\r\n\t[[204,254,43,136,204,19,146],[58,59,227,186,5,116,131],[121,132,38,234,177,146,2],[152,250,166,220,109,31,182],[205,89,4,153,46,234,252],[218,156,181,168,148,75,157],[223,133,77,68,81,92,97]],\r\n\t[[44,110,77,10,17,230,168],[97,231,123,79,203,122,199],[179,22,215,38,219,249,83],[61,32,230,88,129,211,252],[18,55,69,116,188,212,149],[239,29,164,65,175,5,55],[50,3,21,18,20,120,242]],\r\n\t[[2,130,165,44,138,53,198],[5,167,91,218,159,224,136],[25,212,2,58,33,32,89],[28,197,30,245,5,105,26],[237,180,234,174,93,32,41],[163,44,136,49,42,97,70],[93,115,228,155,221,130,249]],\r\n\t[[197,49,49,140,213,84,183],[82,184,115,223,180,172,251],[91,200,28,98,197,109,41],[14,188,104,66,26,46,220],[220,184,249,45,58,74,221],[145,244,23,9,142,218,191],[37,111,90,235,48,71,87]],\r\n\t[[3,76,205,29,57,94,212],[176,83,232,80,99,163,237],[175,135,234,70,72,36,94],[16,212,117,191,185,211,50],[131,247,114,62,37,239,154],[176,251,69,98,26,55,102],[22,129,138,194,238,253,201]],\r\n\t[[63,138,109,142,177,92,190],[199,227,232,63,216,9,137],[3,113,240,162,246,133,201],[97,33,138,246,43,79,31],[131,88,94,144,1,131,108],[178,124,134,73,17,33,212],[95,205,23,77,230,168,39]],\r\n\t[[126,20,121,128,75,78,134],[145,226,4,90,199,90,220],[222,193,203,215,200,180,2],[150,20,87,1,71,29,172],[47,243,137,156,56,101,248],[78,173,174,93,107,181,35],[154,192,8,182,19,83,80]]\r\n\t\t], dtype=np.int)\r\nmur = 239\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 35 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 35 passed!\")\r\narray = np.array([\r\n\t[[168,121,11,59,10,199,67],[31,122,47,114,80,218,45],[103,244,180,110,34,79,65],[170,86,193,33,7,66,19],[174,120,5,85,30,212,190],[133,11,138,107,149,0,97],[82,57,66,101,241,130,128]],\r\n\t[[87,160,41,196,79,177,183],[35,142,28,117,61,144,142],[184,91,164,222,47,87,39],[106,10,191,161,92,96,59],[70,173,236,187,60,119,56],[172,201,80,158,25,130,161],[126,37,57,200,46,3,86]],\r\n\t[[170,188,69,32,131,187,67],[113,242,26,115,171,231,131],[51,22,229,219,59,11,9],[129,64,87,228,54,89,187],[248,198,216,62,35,223,187],[47,40,164,147,167,46,243],[9,69,242,7,132,189,5]],\r\n\t[[12,41,157,233,232,4,145],[171,159,212,116,86,189,166],[110,33,37,204,142,91,30],[198,56,27,83,221,218,166],[212,212,48,14,69,89,216],[97,35,232,62,19,26,138],[196,99,227,29,48,71,246]],\r\n\t[[243,242,190,30,112,247,111],[54,38,146,205,145,176,28],[157,247,105,44,71,71,149],[68,219,5,77,172,89,241],[138,178,192,25,205,234,215],[112,10,124,153,163,65,241],[70,128,226,178,112,111,122]],\r\n\t[[29,254,230,248,231,194,210],[61,68,107,239,58,94,120],[11,151,97,124,129,109,210],[37,1,95,147,135,77,110],[89,163,172,234,250,224,193],[198,150,227,129,218,214,132],[177,197,72,210,170,75,142]],\r\n\t[[115,43,39,164,219,15,15],[13,124,227,250,152,66,206],[215,147,51,210,139,46,80],[57,146,88,112,252,235,183],[174,182,86,74,51,133,203],[226,141,172,123,163,122,226],[80,85,190,27,45,145,146]]\r\n\t\t], dtype=np.int)\r\nmur = 87\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 36 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 36 passed!\")\r\narray = np.array([\r\n\t[[118,49,239,146,181,237,45],[3,187,177,200,46,184,40],[142,11,42,248,119,112,19],[55,215,60,138,116,150,231],[166,61,140,195,220,23,93],[51,167,7,13,137,95,8],[189,103,147,53,127,142,128]],\r\n\t[[170,140,94,12,77,67,166],[126,151,7,90,210,227,64],[92,40,172,26,140,164,195],[241,65,168,248,149,21,148],[241,199,69,108,223,130,183],[182,153,107,159,250,71,236],[231,190,168,75,158,144,186]],\r\n\t[[187,58,166,139,236,90,10],[90,153,182,72,158,57,195],[132,236,139,54,230,216,151],[60,162,159,39,35,86,52],[88,61,103,131,62,246,208],[17,29,227,104,152,132,58],[118,73,68,79,68,145,45]],\r\n\t[[114,155,18,205,241,113,176],[67,212,15,242,39,39,50],[106,147,86,149,57,137,222],[207,83,246,211,196,135,196],[87,172,167,190,199,80,119],[191,176,172,31,99,64,236],[172,241,204,232,198,223,234]],\r\n\t[[79,144,84,95,180,248,26],[47,18,33,215,135,78,133],[197,249,189,117,134,193,225],[186,215,91,141,83,191,184],[36,184,101,127,7,84,220],[244,116,32,30,68,5,88],[4,128,211,144,96,46,82]],\r\n\t[[195,96,122,76,230,134,31],[56,119,78,53,188,59,83],[8,236,47,12,17,38,129],[69,132,17,83,217,64,63],[36,125,148,150,3,19,140],[243,188,221,14,26,115,76],[203,140,7,182,5,144,193]],\r\n\t[[57,49,151,65,47,0,253],[203,73,192,189,104,206,215],[242,136,32,11,191,211,109],[95,32,164,249,99,32,152],[28,39,24,84,242,164,138],[252,91,203,143,184,61,133],[54,170,56,52,0,208,68]]\r\n\t\t], dtype=np.int)\r\nmur = 139\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 37 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 37 passed!\")\r\narray = np.array([\r\n\t[[41,246,87,29,69,147,150],[137,167,163,55,71,223,75],[204,70,101,109,69,209,166],[168,235,221,16,26,222,231],[214,121,217,58,63,171,221],[92,88,148,149,241,84,125],[251,155,71,201,38,239,154]],\r\n\t[[92,126,70,190,7,128,57],[191,143,77,12,77,44,26],[112,98,116,34,154,75,156],[137,121,221,201,51,139,35],[171,43,231,246,8,186,173],[208,72,132,70,42,27,173],[194,103,1,167,187,121,218]],\r\n\t[[118,49,21,146,13,15,205],[16,109,52,106,144,189,195],[171,18,159,237,150,207,141],[148,202,150,25,207,158,148],[59,251,180,168,113,231,247],[175,30,153,195,186,217,14],[58,212,77,65,75,124,164]],\r\n\t[[22,86,154,104,24,137,68],[109,92,141,26,83,210,78],[105,69,82,91,241,22,158],[66,200,177,188,109,225,215],[174,206,230,78,31,136,143],[93,57,233,219,155,134,151],[175,213,226,8,96,142,211]],\r\n\t[[234,199,81,73,172,253,45],[35,247,103,234,75,198,248],[39,22,169,177,201,162,224],[1,220,14,107,161,97,49],[13,85,136,127,21,249,185],[218,86,201,102,144,55,79],[71,243,15,99,99,232,76]],\r\n\t[[21,105,160,130,102,245,163],[90,126,203,253,23,254,103],[17,221,234,198,174,248,127],[27,200,197,23,226,129,19],[218,201,74,26,50,182,251],[61,54,210,161,15,243,53],[128,12,136,183,27,250,8]],\r\n\t[[67,99,236,71,90,8,213],[82,62,103,152,238,205,58],[158,174,78,237,185,109,203],[8,142,212,51,235,79,80],[143,92,218,212,9,181,180],[2,153,179,186,17,19,151],[2,148,118,87,1,95,14]]\r\n\t\t], dtype=np.int)\r\nmur = 223\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 38 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 38 passed!\")\r\narray = np.array([\r\n\t[[30,64,194,209,102,137,124],[75,232,6,73,94,167,230],[232,67,58,184,54,196,60],[152,155,54,19,138,90,198],[96,14,5,221,133,139,76],[217,15,3,22,227,32,63],[85,1,185,120,147,47,142]],\r\n\t[[143,92,49,246,173,214,16],[237,155,212,237,169,12,14],[106,206,71,242,129,242,157],[240,187,3,101,246,222,141],[28,176,43,128,241,107,129],[63,17,134,161,10,168,131],[216,186,180,252,80,5,224]],\r\n\t[[126,128,235,96,167,252,38],[5,202,201,48,205,83,219],[40,117,97,243,120,56,167],[133,116,43,221,190,227,91],[239,92,187,139,217,58,140],[4,126,73,137,53,193,186],[89,125,204,53,123,83,216]],\r\n\t[[53,27,233,98,63,229,171],[208,123,176,232,162,144,111],[189,162,54,137,65,117,214],[61,219,237,236,104,100,200],[105,115,48,71,118,164,39],[64,163,30,188,79,46,46],[16,220,219,203,77,135,42]],\r\n\t[[29,158,116,30,134,162,156],[238,79,136,51,129,237,115],[244,159,156,187,34,243,195],[67,68,172,207,58,40,208],[115,86,242,252,253,59,124],[108,165,167,233,17,226,193],[146,94,221,223,234,229,84]],\r\n\t[[153,184,116,244,197,36,124],[125,238,6,5,119,242,49],[129,168,88,6,17,24,87],[135,217,72,235,105,15,4],[73,46,19,61,36,204,97],[176,134,226,74,196,115,192],[17,46,142,82,140,49,155]],\r\n\t[[172,81,29,103,101,198,26],[213,168,110,35,115,170,187],[115,240,189,192,155,179,253],[69,42,203,235,46,191,226],[130,125,194,13,53,148,124],[80,248,43,226,23,120,223],[108,116,238,51,117,10,138]]\r\n\t\t], dtype=np.int)\r\nmur = 53\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 39 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 39 passed!\")\r\narray = np.array([\r\n\t[[178,117,235,227,58,247,108],[167,137,43,105,142,191,98],[158,213,245,118,129,162,198],[208,101,187,68,197,153,60],[173,67,248,241,71,183,226],[41,208,45,149,139,57,196],[120,225,112,31,97,166,117]],\r\n\t[[208,130,201,8,84,195,211],[30,195,193,140,148,116,197],[190,14,90,28,99,136,245],[108,228,177,40,1,44,171],[244,184,184,222,43,148,40],[230,65,131,253,158,59,73],[145,136,244,9,143,254,96]],\r\n\t[[174,247,32,254,82,78,250],[104,49,164,76,75,85,26],[44,137,112,105,186,22,221],[23,135,113,165,46,174,130],[182,180,101,240,156,178,181],[157,193,88,41,233,18,142],[185,2,148,47,180,186,104]],\r\n\t[[15,233,229,209,77,199,98],[168,235,254,191,179,201,52],[55,6,33,50,52,101,207],[239,149,203,78,241,137,250],[165,187,187,44,14,215,51],[134,189,215,68,198,247,169],[121,70,64,239,103,90,96]],\r\n\t[[46,101,250,166,64,67,215],[33,86,12,55,212,141,84],[144,241,7,112,7,115,124],[193,73,174,84,16,77,103],[177,85,168,206,219,126,92],[74,159,224,211,16,203,140],[162,11,32,63,197,204,114]],\r\n\t[[117,254,187,49,87,164,218],[160,206,72,116,126,202,51],[161,217,198,9,125,54,29],[205,32,136,249,216,1,44],[254,112,25,97,212,117,92],[180,253,33,220,215,24,77],[89,115,173,50,106,209,169]],\r\n\t[[33,166,103,169,26,64,165],[245,15,49,221,79,54,1],[85,116,162,83,5,167,31],[240,172,68,67,196,189,22],[249,234,226,53,78,217,16],[132,238,247,224,139,238,162],[112,151,19,88,251,169,219]]\r\n\t\t], dtype=np.int)\r\nmur = 124\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 150;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 40 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 40 passed!\")\r\narray = np.array([\r\n\t[[230,60,9,79,100,36,149],[43,122,207,8,151,37,47],[186,34,83,241,216,241,164],[125,230,96,142,207,8,165],[213,216,58,201,130,237,237],[92,207,146,244,43,106,39],[237,191,250,242,139,192,53]],\r\n\t[[123,237,65,161,218,175,162],[121,237,105,112,87,8,136],[185,115,162,75,212,78,149],[27,230,139,100,58,194,43],[30,149,10,11,16,131,44],[83,214,206,166,132,114,2],[211,122,216,238,116,69,76]],\r\n\t[[211,43,3,159,51,7,125],[38,92,176,237,4,235,199],[220,67,208,75,200,220,221],[102,142,108,217,150,123,108],[15,148,226,199,126,56,227],[125,227,20,210,76,136,177],[185,216,7,7,7,128,66]],\r\n\t[[92,107,113,209,225,5,150],[20,97,29,36,56,207,33],[184,136,59,173,26,236,246],[144,91,196,228,150,28,146],[235,48,4,105,100,213,44],[7,132,156,124,188,149,157],[215,178,82,155,11,138,136]],\r\n\t[[113,249,34,121,159,111,124],[117,198,102,199,74,179,228],[164,125,122,34,166,35,44],[88,115,0,87,0,116,87],[188,87,57,159,170,76,172],[236,16,47,254,145,166,185],[155,19,211,205,92,110,15]],\r\n\t[[211,199,25,196,17,161,75],[110,5,193,56,33,82,113],[141,2,237,170,23,4,147],[54,115,183,134,5,111,221],[123,106,144,207,150,76,58],[181,191,36,198,72,195,16],[239,5,236,215,141,183,103]],\r\n\t[[251,92,142,157,235,194,41],[165,211,217,224,202,153,175],[233,100,86,73,126,75,179],[234,138,116,18,39,83,194],[131,223,61,181,237,36,241],[167,120,109,217,123,106,81],[135,123,165,236,154,51,198]]\r\n\t\t], dtype=np.int)\r\nmur = 132\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 41 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 41 passed!\")\r\narray = np.array([\r\n\t[[34,248,142,227,167,147,243],[152,13,52,91,95,57,84],[84,45,181,64,39,20,224],[15,132,53,9,193,222,82],[48,138,251,100,221,216,134],[26,224,21,201,199,54,95],[107,28,91,10,148,238,95]],\r\n\t[[152,95,110,154,210,44,192],[139,167,229,112,246,162,187],[63,116,228,166,113,161,69],[78,29,41,234,194,187,216],[54,157,187,5,185,207,240],[161,93,49,212,79,118,182],[201,180,20,191,141,252,76]],\r\n\t[[49,203,16,82,60,85,240],[184,181,75,150,106,47,141],[140,176,84,194,128,70,30],[204,10,242,24,89,45,228],[216,146,34,32,180,33,180],[225,54,142,3,41,206,202],[247,17,24,8,142,141,202]],\r\n\t[[236,216,98,155,62,23,53],[154,128,6,10,111,135,237],[201,11,237,47,176,150,110],[59,202,66,220,5,228,185],[162,135,36,153,223,253,44],[250,42,91,79,201,155,131],[97,201,22,119,233,205,14]],\r\n\t[[79,223,125,205,246,20,85],[100,209,250,243,109,250,128],[151,136,145,55,128,220,16],[245,174,227,76,152,229,32],[43,95,114,51,158,208,22],[100,45,85,99,204,38,108],[94,111,207,254,43,58,63]],\r\n\t[[118,31,132,76,40,251,23],[159,60,235,234,147,56,144],[252,238,202,69,229,155,238],[238,219,125,208,242,32,88],[162,121,210,131,143,209,34],[208,121,97,72,167,237,33],[115,37,213,48,88,16,2]],\r\n\t[[138,106,41,75,231,156,95],[54,82,109,211,116,9,63],[9,186,64,183,163,136,40],[171,186,220,121,207,213,210],[90,236,112,163,93,207,246],[203,45,163,31,201,180,116],[132,105,240,17,246,53,102]]\r\n\t\t], dtype=np.int)\r\nmur = 122\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 42 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 42 passed!\")\r\narray = np.array([\r\n\t[[99,76,244,170,27,197,125],[125,133,113,127,45,4,103],[43,209,131,107,93,194,33],[222,163,167,176,6,232,59],[132,220,128,110,185,79,35],[76,166,225,96,120,119,173],[217,25,87,161,124,115,73]],\r\n\t[[198,25,254,132,136,18,214],[248,159,149,11,204,120,186],[242,44,157,204,181,55,152],[10,220,160,189,59,128,14],[3,185,198,183,107,139,163],[37,245,71,128,119,20,100],[121,4,31,242,226,193,228]],\r\n\t[[156,224,76,110,118,122,137],[37,89,97,88,9,133,34],[219,59,51,11,150,176,210],[152,240,84,203,51,209,82],[71,83,200,174,251,98,0],[227,173,238,242,216,46,151],[9,55,100,164,218,200,49]],\r\n\t[[71,80,215,239,183,151,228],[102,133,19,27,107,24,226],[206,45,217,6,12,198,27],[246,27,21,42,86,202,57],[140,111,201,33,55,209,153],[73,245,221,78,54,4,48],[152,80,59,205,209,65,238]],\r\n\t[[69,179,137,214,252,56,31],[39,77,249,178,214,101,236],[87,193,226,174,59,152,146],[42,79,176,238,223,62,47],[211,231,163,108,175,112,38],[34,170,43,114,87,156,11],[248,254,207,216,93,83,216]],\r\n\t[[229,237,60,143,245,237,57],[45,179,61,68,216,50,124],[252,204,86,25,82,47,63],[152,230,42,139,36,217,104],[119,248,13,130,99,38,146],[229,126,87,85,194,92,176],[29,184,60,104,65,75,56]],\r\n\t[[211,198,233,78,250,59,188],[170,201,160,85,24,73,230],[3,116,116,221,221,225,120],[173,59,195,49,126,118,18],[99,78,39,192,33,13,252],[72,197,174,238,75,211,126],[164,130,162,184,21,136,119]]\r\n\t\t], dtype=np.int)\r\nmur = 241\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 43 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 43 passed!\")\r\narray = np.array([\r\n\t[[163,16,235,144,96,188,6],[218,59,91,64,223,68,162],[194,177,136,223,113,203,161],[53,101,214,94,231,121,14],[159,150,27,164,58,10,222],[247,204,122,97,242,132,181],[170,96,130,51,22,72,253]],\r\n\t[[214,193,175,7,10,221,182],[222,56,167,1,157,128,176],[245,45,190,114,97,83,82],[157,21,73,142,12,245,202],[11,77,88,57,170,5,101],[95,169,224,8,68,182,105],[156,149,110,16,216,95,200]],\r\n\t[[14,139,102,237,82,244,67],[187,84,228,196,7,145,114],[126,211,242,26,40,63,198],[16,64,70,36,13,89,51],[30,192,191,154,38,226,202],[96,0,109,195,91,109,161],[185,105,150,235,39,93,92]],\r\n\t[[183,17,147,170,216,220,218],[153,111,171,54,3,93,184],[89,214,249,6,244,40,183],[243,12,170,18,62,190,168],[158,73,146,210,13,15,176],[199,117,185,96,61,240,217],[30,138,173,194,164,0,215]],\r\n\t[[51,201,200,110,54,197,225],[147,75,152,40,113,22,148],[23,129,19,184,195,125,186],[246,168,204,10,47,206,245],[185,110,135,184,35,159,35],[98,81,143,114,245,52,166],[59,154,99,176,113,16,215]],\r\n\t[[23,12,189,61,209,252,162],[53,97,215,206,141,93,137],[135,214,214,190,238,231,145],[27,227,36,91,193,122,182],[232,29,149,131,69,50,15],[45,145,117,201,27,88,242],[99,50,242,140,200,222,56]],\r\n\t[[72,94,46,123,153,52,249],[124,211,220,107,238,11,129],[46,107,166,118,120,50,114],[206,45,245,99,37,43,239],[232,252,233,165,144,92,214],[96,65,184,10,230,41,227],[64,216,5,211,206,48,247]]\r\n\t\t], dtype=np.int)\r\nmur = 214\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 44 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 44 passed!\")\r\narray = np.array([\r\n\t[[246,4,189,206,247,146,162],[125,109,159,6,112,147,197],[48,41,246,216,37,63,138],[166,249,54,61,201,165,138],[139,244,24,41,81,124,220],[42,114,251,79,16,151,152],[112,219,131,225,172,137,174]],\r\n\t[[12,185,218,157,60,34,63],[247,227,195,23,170,39,222],[71,226,13,66,208,215,143],[32,165,216,55,110,218,151],[213,55,56,39,248,114,5],[103,146,1,98,135,117,163],[104,41,211,30,52,237,225]],\r\n\t[[245,48,123,96,221,101,25],[205,37,97,230,162,206,198],[87,206,54,12,0,244,233],[181,231,198,154,40,106,65],[249,170,3,239,57,91,175],[153,70,32,180,14,147,77],[204,26,74,105,84,108,116]],\r\n\t[[152,163,254,249,192,114,100],[202,165,155,221,103,164,170],[232,29,176,166,27,65,48],[216,218,5,145,74,120,56],[159,25,126,60,144,179,230],[17,154,138,201,38,79,193],[62,17,178,58,45,51,58]],\r\n\t[[3,188,88,81,44,41,39],[110,156,101,54,49,127,174],[37,37,70,213,24,175,48],[244,53,80,129,48,49,131],[128,50,204,80,171,211,150],[236,111,73,47,170,117,197],[140,41,169,87,85,6,73]],\r\n\t[[101,90,219,12,0,151,165],[230,48,222,16,191,93,120],[78,46,160,156,69,30,208],[83,210,220,15,236,165,168],[33,16,6,134,188,174,214],[133,109,223,225,188,252,135],[111,139,53,221,132,199,56]],\r\n\t[[59,183,21,121,223,4,44],[2,11,156,88,51,49,140],[27,181,244,18,39,125,132],[227,40,171,206,167,177,53],[139,154,194,55,144,178,62],[79,187,81,36,171,40,31],[233,2,152,126,244,251,218]]\r\n\t\t], dtype=np.int)\r\nmur = 168\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 45 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 45 passed!\")\r\narray = np.array([\r\n\t[[163,10,198,62,128,104,153],[113,153,178,26,156,38,220],[183,77,230,200,74,147,228],[163,21,214,17,45,68,53],[104,149,194,190,108,32,200],[192,94,62,248,223,12,227],[134,49,131,191,230,110,132]],\r\n\t[[34,15,204,54,134,121,182],[170,184,154,100,220,163,64],[67,198,159,195,124,235,104],[72,179,84,105,167,214,149],[215,3,171,67,43,206,104],[82,27,85,143,149,251,42],[74,136,242,83,217,254,67]],\r\n\t[[98,28,88,95,111,95,210],[84,119,236,202,161,76,227],[214,14,224,92,185,139,216],[74,248,250,18,85,198,249],[28,54,101,14,162,101,130],[79,219,103,128,167,228,36],[39,203,99,117,145,162,144]],\r\n\t[[82,11,82,93,89,22,232],[235,234,26,52,152,216,152],[125,33,132,143,146,55,205],[202,26,195,117,100,177,81],[21,21,38,230,28,247,240],[21,221,160,126,213,45,65],[35,250,201,219,192,2,58]],\r\n\t[[2,37,195,161,196,82,92],[94,247,191,178,212,184,40],[122,254,86,112,90,138,93],[63,91,205,133,174,24,170],[177,140,205,159,39,37,40],[129,194,185,174,17,61,60],[220,227,53,235,232,235,21]],\r\n\t[[12,119,200,144,193,171,92],[162,79,9,55,21,233,222],[36,152,194,86,75,146,115],[166,87,238,214,130,7,11],[82,124,244,244,147,71,66],[51,45,253,60,19,53,198],[182,250,59,233,76,46,33]],\r\n\t[[57,146,8,15,91,130,244],[216,197,156,190,186,4,181],[103,98,127,92,55,54,67],[43,135,38,249,147,217,186],[105,232,92,205,200,55,25],[181,89,151,63,131,69,30],[240,91,178,247,224,178,115]]\r\n\t\t], dtype=np.int)\r\nmur = 178\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 46 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 46 passed!\")\r\narray = np.array([\r\n\t[[207,25,235,85,183,158,219],[153,247,139,232,58,74,123],[82,107,55,142,208,83,26],[44,170,202,119,16,105,58],[63,185,31,84,110,86,176],[230,65,197,141,231,12,72],[88,62,149,40,212,16,232]],\r\n\t[[27,161,169,138,37,65,227],[51,192,45,150,212,95,91],[190,50,145,239,69,180,212],[32,237,206,241,251,30,194],[138,46,159,221,252,150,227],[207,116,80,64,233,206,229],[53,61,82,31,165,213,134]],\r\n\t[[72,61,135,71,71,33,176],[120,146,203,254,223,205,182],[235,41,196,27,75,10,175],[228,225,89,65,86,103,107],[84,139,102,66,170,53,227],[245,96,238,98,254,170,208],[237,178,203,46,82,12,7]],\r\n\t[[103,152,246,179,77,212,132],[48,80,107,54,227,169,177],[102,57,176,192,143,231,13],[235,64,247,6,134,37,161],[67,129,89,79,223,86,154],[62,132,131,82,158,227,128],[38,213,157,243,118,70,235]],\r\n\t[[249,129,135,133,202,140,102],[188,149,219,0,149,29,141],[193,9,101,27,93,108,250],[16,211,78,163,228,36,242],[201,121,31,96,38,193,194],[133,5,195,91,192,202,248],[211,235,238,60,60,105,58]],\r\n\t[[99,16,243,47,208,198,87],[51,152,140,67,44,176,207],[133,154,8,161,148,111,27],[128,144,230,119,161,165,198],[184,220,74,244,4,57,119],[188,151,215,145,246,181,152],[195,231,195,22,28,25,104]],\r\n\t[[216,17,124,141,87,220,86],[178,70,4,99,53,250,92],[16,211,135,254,164,106,129],[123,206,192,70,48,115,147],[217,241,55,45,61,11,0],[88,31,249,144,167,79,44],[155,213,160,173,218,4,56]]\r\n\t\t], dtype=np.int)\r\nmur = 59\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 47 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 47 passed!\")\r\narray = np.array([\r\n\t[[144,36,232,62,122,152,125],[65,65,159,188,129,183,89],[252,236,194,105,200,15,31],[151,199,50,111,133,203,160],[217,17,234,113,147,136,65],[1,195,157,155,147,224,183],[49,71,189,33,176,231,139]],\r\n\t[[120,36,220,199,31,37,69],[27,13,165,52,248,132,170],[38,0,193,196,177,188,92],[11,95,197,171,123,176,82],[101,32,116,118,25,72,75],[153,26,189,172,79,110,42],[43,143,65,28,128,41,167]],\r\n\t[[105,8,55,20,173,24,31],[110,177,4,208,100,253,153],[58,182,127,154,184,184,128],[160,94,65,119,8,201,128],[160,77,202,96,52,125,108],[15,124,83,10,163,239,212],[224,55,245,175,216,65,171]],\r\n\t[[37,139,152,25,165,170,132],[95,142,156,180,68,85,40],[133,234,93,201,198,23,72],[100,118,213,128,59,9,138],[38,73,37,95,93,185,187],[194,148,150,45,226,52,167],[125,24,177,137,2,235,184]],\r\n\t[[132,75,204,64,31,25,119],[231,116,201,1,206,220,193],[78,145,150,94,185,213,72],[254,49,204,248,12,246,200],[181,3,206,45,63,85,224],[113,140,37,59,130,205,83],[248,37,131,62,242,109,12]],\r\n\t[[56,194,235,51,248,212,198],[186,167,43,131,235,61,30],[186,224,107,202,139,34,141],[63,199,114,61,193,87,225],[252,59,48,83,213,38,140],[95,202,251,229,251,64,147],[34,79,117,201,222,25,84]],\r\n\t[[177,156,227,207,230,101,191],[53,13,197,222,81,22,168],[46,78,92,246,90,191,30],[128,27,146,158,55,125,200],[149,227,84,54,199,13,225],[42,64,41,141,100,70,82],[188,41,244,191,1,213,222]]\r\n\t\t], dtype=np.int)\r\nmur = 182\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 48 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 48 passed!\")\r\narray = np.array([\r\n\t[[158,179,242,232,103,100,96],[205,243,21,17,105,62,151],[6,167,229,195,253,57,198],[244,201,54,114,44,249,108],[197,54,78,99,68,42,56],[44,112,173,19,0,18,227],[139,36,112,157,73,241,58]],\r\n\t[[182,254,137,55,172,243,238],[1,73,52,154,179,161,71],[137,173,8,143,47,186,112],[249,185,28,201,100,69,2],[194,246,98,86,48,111,50],[254,79,11,88,223,143,233],[131,133,174,74,83,64,129]],\r\n\t[[12,151,246,158,24,215,95],[92,203,116,229,142,195,183],[29,120,168,156,24,100,165],[91,120,212,33,228,27,219],[85,203,110,129,171,174,90],[52,168,84,12,159,47,202],[21,62,82,196,5,3,196]],\r\n\t[[162,173,178,220,101,129,128],[234,46,78,235,119,249,214],[74,70,206,225,211,24,237],[127,112,120,145,248,13,221],[90,0,177,72,251,126,104],[53,155,234,17,250,194,81],[246,51,65,217,115,216,3]],\r\n\t[[44,190,42,11,60,157,230],[4,166,163,206,164,249,95],[186,92,75,223,147,20,209],[149,224,5,142,195,90,88],[1,64,159,3,173,115,186],[43,140,249,29,193,156,214],[166,96,161,67,8,144,242]],\r\n\t[[211,65,125,119,187,218,69],[220,22,153,243,121,165,49],[193,213,61,102,42,24,177],[67,175,32,198,141,145,98],[109,163,11,234,121,47,64],[114,51,30,21,92,171,19],[117,25,102,113,133,85,193]],\r\n\t[[107,43,21,13,102,122,244],[55,254,72,106,132,167,31],[54,253,13,78,123,130,230],[240,155,93,200,172,53,179],[173,43,138,44,94,175,42],[219,84,244,149,2,200,88],[254,218,248,186,132,127,145]]\r\n\t\t], dtype=np.int)\r\nmur = 244\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 49 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 49 passed!\")\r\narray = np.array([\r\n\t[[66,97,128,34,217,251,134],[187,50,215,69,93,209,212],[131,243,60,131,155,3,248],[195,168,104,76,28,224,200],[173,244,105,217,87,106,88],[163,74,36,20,11,177,48],[91,132,70,103,84,142,199]],\r\n\t[[163,174,135,64,140,43,107],[193,91,215,253,187,149,178],[32,182,160,1,123,152,202],[85,164,137,92,95,190,239],[188,67,245,199,117,198,15],[22,123,211,203,56,216,16],[146,198,1,21,17,98,186]],\r\n\t[[76,231,44,194,113,27,25],[176,85,229,89,102,233,144],[174,124,91,253,145,180,214],[117,108,18,21,235,11,92],[168,118,149,138,44,6,117],[108,58,173,135,194,118,74],[53,37,104,229,170,84,142]],\r\n\t[[83,192,138,126,67,46,27],[40,223,161,107,108,230,74],[249,146,169,129,162,229,165],[114,12,87,126,245,205,21],[8,117,104,47,166,19,143],[23,238,208,132,63,213,21],[85,252,157,99,84,110,38]],\r\n\t[[243,92,147,19,224,57,245],[201,43,53,183,80,13,249],[156,131,184,201,144,89,138],[6,152,130,182,102,137,174],[89,70,241,24,76,211,233],[231,51,190,72,132,234,126],[253,194,96,75,57,114,70]],\r\n\t[[75,152,20,126,167,103,223],[135,105,63,212,241,252,68],[148,156,91,58,54,89,91],[66,37,245,229,195,231,41],[241,52,52,246,221,126,13],[114,30,248,236,88,173,88],[39,40,13,246,230,177,53]],\r\n\t[[140,217,242,138,17,170,92],[65,163,240,200,127,16,90],[62,95,223,101,86,95,102],[87,61,215,94,181,13,17],[77,14,146,247,2,245,234],[168,247,80,83,71,3,154],[155,219,220,161,36,44,79]]\r\n\t\t], dtype=np.int)\r\nmur = 115\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 50 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 50 passed!\")\r\narray = np.array([\r\n\t[[63,77,192,59,100,186,219],[83,54,222,232,49,56,231],[46,167,170,25,77,72,51],[190,239,189,222,224,130,122],[155,24,14,69,158,241,158],[80,161,78,74,101,195,164],[40,200,218,59,165,162,214]],\r\n\t[[211,18,194,43,221,138,130],[30,186,206,249,209,46,153],[95,171,239,7,91,73,214],[96,246,25,214,168,64,89],[195,170,31,53,182,222,83],[31,21,14,25,74,244,30],[98,81,64,235,106,65,223]],\r\n\t[[102,152,99,104,173,160,134],[3,210,166,49,81,235,76],[27,188,161,79,44,168,69],[5,21,83,155,181,158,143],[130,50,17,51,176,167,175],[236,38,173,230,113,43,69],[62,125,219,72,90,97,59]],\r\n\t[[67,93,9,47,84,43,247],[4,29,38,181,132,162,253],[169,227,145,98,221,76,160],[161,95,4,140,56,150,127],[48,59,250,11,87,212,207],[215,74,156,211,222,92,32],[1,175,187,152,86,238,1]],\r\n\t[[126,59,251,248,195,89,124],[41,50,10,208,98,253,27],[74,60,113,252,49,201,120],[215,147,128,206,203,72,123],[85,70,105,220,20,25,201],[16,173,215,215,170,223,86],[176,224,102,71,140,239,70]],\r\n\t[[157,79,127,81,27,75,141],[17,182,249,210,17,228,131],[22,65,37,94,213,4,30],[202,163,132,59,84,106,145],[88,26,105,166,171,226,57],[231,78,207,75,147,242,173],[166,10,159,235,41,78,20]],\r\n\t[[176,115,54,109,104,64,179],[203,77,61,20,224,127,43],[199,23,90,100,81,166,49],[234,153,24,38,193,68,56],[245,14,126,240,172,197,57],[90,138,57,97,225,129,121],[44,10,90,83,224,103,8]]\r\n\t\t], dtype=np.int)\r\nmur = 117\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 51 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 51 passed!\")\r\narray = np.array([\r\n\t[[32,80,169,196,153,240,36],[59,134,37,97,110,233,158],[118,102,222,20,127,62,249],[21,40,194,28,173,55,202],[105,25,200,121,21,75,78],[181,116,87,239,174,136,248],[183,137,231,121,115,13,7]],\r\n\t[[77,142,177,206,131,207,41],[42,243,107,182,217,215,133],[173,113,213,192,168,225,99],[138,0,153,8,128,177,16],[118,19,238,105,34,136,66],[213,81,69,28,173,158,195],[51,30,38,79,159,67,138]],\r\n\t[[9,121,121,111,46,233,181],[114,41,236,188,218,65,230],[112,133,29,231,70,216,231],[237,184,50,231,134,49,6],[157,83,127,41,109,191,246],[219,100,162,186,207,224,170],[194,29,180,98,232,176,43]],\r\n\t[[83,134,166,65,91,220,200],[187,73,125,46,199,166,202],[252,241,95,31,69,230,64],[103,198,159,200,228,162,2],[22,219,67,175,60,219,147],[154,254,159,69,225,113,206],[140,112,90,183,17,46,168]],\r\n\t[[131,247,14,93,146,187,49],[113,201,199,179,56,143,201],[239,0,155,127,165,186,31],[179,245,171,159,101,135,4],[227,216,124,213,80,207,70],[191,176,227,100,45,43,69],[146,232,115,44,29,44,140]],\r\n\t[[244,22,94,179,17,203,243],[117,61,2,102,47,100,181],[45,21,98,82,190,23,111],[112,144,15,222,26,171,139],[117,31,204,2,183,103,97],[157,101,17,21,252,46,147],[25,205,243,182,158,143,160]],\r\n\t[[145,199,195,13,105,252,16],[49,193,50,45,245,53,38],[253,198,190,187,22,231,49],[21,147,13,13,174,91,18],[3,215,82,157,242,93,14],[195,146,80,206,57,143,191],[36,254,33,18,208,151,122]]\r\n\t\t], dtype=np.int)\r\nmur = 89\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 52 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 52 passed!\")\r\narray = np.array([\r\n\t[[67,110,150,111,202,45,51],[185,6,155,32,82,2,11],[63,73,73,224,247,163,184],[238,92,146,75,104,175,197],[80,63,43,205,167,7,237],[147,59,149,36,169,138,33],[126,59,103,222,65,129,105]],\r\n\t[[90,87,51,74,1,141,97],[147,159,43,53,160,23,86],[237,172,184,171,240,134,221],[9,124,237,56,108,241,227],[164,99,81,141,189,44,123],[219,241,79,47,207,229,191],[131,195,35,208,212,121,72]],\r\n\t[[66,207,206,221,79,98,238],[165,68,184,49,193,104,244],[140,70,200,32,204,204,176],[78,188,199,178,21,46,158],[80,7,233,164,65,14,170],[69,19,59,65,226,4,61],[226,178,36,146,251,79,200]],\r\n\t[[46,246,150,4,21,67,192],[166,1,179,196,9,25,59],[51,165,175,88,202,131,130],[0,99,224,152,110,225,131],[16,16,67,229,58,92,101],[248,146,142,108,26,12,74],[1,52,17,6,230,115,158]],\r\n\t[[20,2,154,70,120,15,125],[142,110,160,120,29,56,195],[77,5,84,187,204,104,188],[9,55,219,240,179,137,12],[82,202,200,189,235,253,150],[53,234,182,204,245,82,142],[2,35,168,205,238,177,27]],\r\n\t[[157,6,178,34,71,130,77],[151,69,156,106,12,32,35],[176,178,69,142,176,104,114],[202,31,67,68,177,50,252],[129,182,161,176,66,153,19],[228,25,198,5,179,192,111],[91,102,53,50,13,4,121]],\r\n\t[[129,184,56,171,40,90,59],[167,63,53,202,113,65,86],[86,212,183,120,169,137,157],[157,174,148,188,70,244,113],[141,30,24,235,190,186,61],[177,187,246,154,203,191,50],[136,11,90,154,53,157,235]]\r\n\t\t], dtype=np.int)\r\nmur = 170\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 53 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 53 passed!\")\r\narray = np.array([\r\n\t[[36,124,147,128,62,248,240],[209,38,113,68,106,42,202],[206,239,75,136,232,104,175],[81,147,74,144,87,237,156],[28,60,39,86,89,26,154],[186,92,81,224,114,216,203],[118,199,174,20,7,63,161]],\r\n\t[[70,87,41,14,200,120,107],[66,186,226,24,38,138,75],[107,106,93,221,156,183,37],[97,72,54,229,69,128,211],[11,53,12,100,70,3,235],[110,119,99,115,226,85,244],[174,0,1,94,106,178,127]],\r\n\t[[88,232,175,245,73,45,166],[77,170,67,80,222,17,88],[135,31,213,100,195,33,178],[192,138,219,71,102,133,162],[95,132,107,241,36,21,131],[87,103,183,66,170,100,12],[62,230,191,66,130,187,205]],\r\n\t[[200,213,205,81,97,211,22],[131,126,155,180,57,156,222],[127,178,109,233,135,228,159],[165,29,235,180,198,173,152],[239,106,4,217,124,75,193],[88,203,177,230,43,122,5],[155,172,28,30,244,72,154]],\r\n\t[[170,193,156,13,200,229,211],[234,191,191,187,199,149,112],[45,178,4,176,18,6,84],[133,188,5,62,47,147,149],[85,2,135,207,178,176,73],[193,5,236,182,49,28,99],[188,164,163,186,38,138,156]],\r\n\t[[165,95,187,212,111,170,8],[90,124,118,36,87,180,50],[136,254,9,9,232,42,193],[17,195,3,102,110,243,108],[239,126,195,15,61,99,161],[237,34,140,65,175,137,25],[240,124,121,234,206,107,187]],\r\n\t[[236,85,41,94,226,188,198],[240,251,180,223,178,96,254],[217,179,46,125,62,79,122],[114,86,55,122,158,3,211],[198,246,250,16,213,178,97],[175,63,132,104,53,126,169],[179,78,224,212,19,251,139]]\r\n\t\t], dtype=np.int)\r\nmur = 57\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 54 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 54 passed!\")\r\narray = np.array([\r\n\t[[39,134,119,38,175,242,115],[33,153,52,226,201,208,58],[148,77,34,110,93,242,240],[26,108,222,111,183,63,215],[89,25,163,183,153,99,156],[111,153,34,155,205,2,42],[179,177,26,249,68,49,245]],\r\n\t[[17,217,6,194,20,224,53],[91,77,94,166,76,84,78],[62,17,146,235,31,119,47],[118,242,55,44,195,126,194],[98,147,6,71,88,214,251],[26,133,46,240,65,91,136],[162,239,25,137,190,30,180]],\r\n\t[[56,61,105,219,65,227,142],[23,225,157,100,22,68,66],[152,178,142,200,103,33,219],[163,43,30,83,183,6,122],[15,42,151,183,189,132,42],[208,219,251,103,117,99,172],[39,164,41,33,103,63,79]],\r\n\t[[123,30,85,116,82,79,156],[220,19,117,237,79,96,135],[192,180,65,156,153,173,176],[13,200,19,18,113,156,88],[188,84,116,75,36,85,74],[114,104,48,236,6,244,69],[65,32,240,145,57,59,184]],\r\n\t[[187,101,76,86,119,214,104],[131,19,253,4,241,53,133],[155,15,61,120,197,115,187],[91,23,214,80,8,224,206],[237,203,139,130,62,122,176],[171,86,211,88,89,233,243],[90,142,213,104,29,49,180]],\r\n\t[[207,249,1,8,206,212,213],[84,114,202,8,204,5,73],[132,180,87,206,49,131,248],[227,185,230,89,95,36,141],[247,85,193,74,70,80,141],[96,19,228,252,216,86,96],[53,129,189,102,43,183,175]],\r\n\t[[117,204,98,188,107,254,143],[32,246,228,121,196,180,236],[252,81,49,235,126,141,59],[117,107,69,70,159,156,88],[223,32,243,64,218,154,242],[160,202,166,17,254,207,124],[54,207,78,209,186,192,9]]\r\n\t\t], dtype=np.int)\r\nmur = 123\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 55 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 55 passed!\")\r\narray = np.array([\r\n\t[[132,231,109,13,103,139,134],[66,209,52,44,66,48,234],[141,177,156,25,120,15,112],[207,111,183,234,89,203,240],[127,10,202,172,46,253,162],[234,203,168,157,172,181,218],[141,134,170,105,226,22,95]],\r\n\t[[89,80,74,131,76,193,250],[71,182,188,13,83,102,155],[243,88,203,14,183,138,226],[20,105,23,78,195,160,32],[46,127,174,213,146,96,184],[105,165,233,88,31,0,179],[56,72,165,8,196,45,100]],\r\n\t[[212,220,74,42,184,87,48],[16,105,16,99,18,15,144],[165,136,172,123,132,95,185],[141,7,197,179,83,52,95],[115,185,119,223,24,103,203],[161,153,84,174,53,181,236],[181,64,173,215,243,91,184]],\r\n\t[[159,246,75,32,101,191,156],[67,93,121,99,124,167,12],[253,34,150,244,54,195,129],[122,173,245,25,197,133,198],[129,240,155,12,196,36,134],[138,250,120,161,131,61,188],[162,164,128,143,245,19,28]],\r\n\t[[24,1,191,78,95,251,247],[29,149,32,24,8,37,124],[120,108,175,27,32,178,171],[185,99,79,162,100,123,122],[102,76,59,72,100,160,48],[129,149,88,184,57,212,30],[110,197,100,209,117,117,33]],\r\n\t[[28,181,227,150,189,128,191],[33,205,232,77,202,247,160],[169,121,172,111,81,187,223],[210,41,225,251,109,219,106],[123,140,9,147,88,11,42],[43,191,90,68,100,39,31],[252,125,63,225,21,81,233]],\r\n\t[[70,99,74,146,226,63,75],[162,3,7,10,244,64,102],[229,177,237,106,95,189,74],[203,136,123,8,109,1,218],[106,250,64,172,54,140,137],[100,68,103,203,64,254,34],[89,98,33,67,219,91,47]]\r\n\t\t], dtype=np.int)\r\nmur = 7\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 56 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 56 passed!\")\r\narray = np.array([\r\n\t[[26,237,144,182,159,157,144],[148,133,189,34,196,227,224],[81,187,60,230,38,6,90],[84,113,169,20,38,239,121],[228,147,243,47,192,231,36],[86,117,171,48,239,232,245],[244,128,128,194,154,154,25]],\r\n\t[[56,97,31,94,151,186,211],[16,81,165,14,112,229,248],[211,71,187,53,40,13,250],[44,164,145,94,64,173,99],[133,122,184,95,132,169,212],[236,244,204,251,56,97,205],[246,45,224,220,122,219,50]],\r\n\t[[127,53,3,250,189,160,157],[187,3,45,109,87,73,141],[201,219,141,202,68,112,148],[110,52,211,54,37,205,105],[66,113,122,120,171,230,87],[78,254,99,26,197,159,132],[94,188,253,95,5,234,13]],\r\n\t[[19,99,29,230,204,21,192],[239,40,125,126,131,30,160],[53,80,223,179,239,214,168],[211,172,162,151,81,213,73],[122,90,228,150,230,251,100],[236,226,55,198,77,26,197],[59,68,143,206,41,230,118]],\r\n\t[[136,68,200,250,177,58,164],[176,148,189,6,35,105,112],[207,132,121,171,132,13,20],[64,153,227,109,163,127,82],[86,189,244,111,199,94,140],[251,134,10,58,233,97,194],[76,43,174,53,168,206,51]],\r\n\t[[55,126,44,5,250,39,187],[102,237,118,111,101,99,113],[223,170,38,47,94,163,131],[242,84,70,26,168,74,145],[175,38,206,38,40,240,198],[254,170,227,209,86,156,30],[132,245,7,27,93,157,117]],\r\n\t[[205,32,182,54,175,172,214],[28,45,218,204,77,28,137],[30,220,225,222,186,235,114],[215,86,199,237,71,170,111],[206,169,12,177,91,104,169],[163,3,206,231,121,150,216],[102,228,8,249,88,173,40]]\r\n\t\t], dtype=np.int)\r\nmur = 164\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 57 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 57 passed!\")\r\narray = np.array([\r\n\t[[5,185,16,139,88,159,252],[222,97,136,88,118,106,213],[248,181,56,26,75,163,73],[184,43,214,93,226,101,218],[162,225,142,151,27,69,67],[154,162,122,163,61,171,188],[27,86,217,178,156,114,146]],\r\n\t[[220,29,235,230,100,146,46],[233,111,126,231,181,205,19],[65,6,181,253,149,254,13],[159,229,14,245,155,192,213],[220,31,164,10,134,197,217],[144,52,163,10,1,66,60],[252,159,230,100,12,245,1]],\r\n\t[[221,72,228,14,74,194,81],[159,196,117,198,150,170,217],[78,219,5,32,39,224,10],[175,94,217,74,18,235,7],[207,231,134,87,174,16,6],[219,29,133,106,200,58,226],[213,51,164,183,93,103,160]],\r\n\t[[158,17,20,58,24,59,134],[228,83,251,46,211,29,70],[174,76,214,168,120,84,205],[103,192,89,97,124,96,75],[207,102,55,28,64,125,34],[157,196,244,214,31,168,197],[120,229,166,162,150,141,184]],\r\n\t[[189,203,28,111,168,3,232],[92,251,61,156,81,237,213],[152,24,100,93,67,192,19],[188,223,127,46,141,107,21],[156,8,0,231,22,193,199],[254,35,101,221,27,65,3],[92,142,73,213,147,45,166]],\r\n\t[[128,1,18,57,198,187,175],[168,186,62,133,62,180,225],[58,30,64,218,37,190,123],[208,27,214,55,21,125,83],[88,34,181,162,30,20,72],[181,139,194,45,44,26,195],[216,251,181,216,202,226,91]],\r\n\t[[114,180,192,162,192,174,231],[10,225,85,193,42,55,204],[212,20,148,202,29,130,152],[228,70,206,236,145,30,74],[156,157,253,119,129,47,36],[55,128,19,99,144,136,146],[52,38,147,140,58,189,54]]\r\n\t\t], dtype=np.int)\r\nmur = 195\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 125;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 58 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 58 passed!\")\r\narray = np.array([\r\n\t[[239,20,170,227,141,246,210],[103,250,120,181,113,86,221],[35,72,144,156,77,0,106],[204,2,162,22,127,202,52],[100,164,12,121,200,188,206],[23,195,22,251,102,120,56],[5,42,217,24,82,38,125]],\r\n\t[[218,61,240,254,224,190,18],[149,253,28,246,18,23,240],[214,42,112,220,162,156,73],[109,201,111,154,62,112,152],[220,125,157,202,177,187,101],[177,226,240,214,8,183,244],[244,119,17,97,167,141,19]],\r\n\t[[147,28,143,55,198,190,185],[81,177,15,115,9,211,37],[29,227,20,180,183,210,217],[74,194,153,23,184,185,166],[242,224,62,82,133,23,29],[193,55,194,198,161,249,123],[33,237,153,18,129,244,95]],\r\n\t[[22,86,56,234,27,55,43],[97,199,201,52,42,64,84],[55,229,25,98,66,122,228],[65,70,97,122,73,148,252],[8,103,26,236,77,208,23],[80,75,114,16,228,131,153],[16,231,213,172,224,58,243]],\r\n\t[[37,248,81,155,38,75,2],[171,23,144,251,128,61,162],[184,68,167,217,209,78,91],[161,77,164,245,122,104,176],[128,178,231,162,235,251,12],[197,241,52,23,85,124,118],[102,138,220,191,230,149,220]],\r\n\t[[77,64,172,124,7,121,146],[42,152,208,155,219,91,202],[197,35,198,63,38,149,24],[66,145,222,240,54,48,189],[140,96,194,198,83,127,21],[86,183,171,92,202,209,8],[54,30,82,251,115,52,151]],\r\n\t[[231,145,245,159,163,211,92],[9,163,146,216,143,93,83],[49,59,19,97,251,7,111],[72,172,210,233,15,98,46],[125,59,239,101,204,118,57],[252,92,3,10,219,86,95],[72,120,47,203,218,123,205]]\r\n\t\t], dtype=np.int)\r\nmur = 77\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 107;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 59 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 59 passed!\")\r\narray = np.array([\r\n\t[[100,22,221,73,156,75,193],[242,193,246,61,110,188,151],[149,193,134,147,182,9,15],[209,49,88,44,246,75,128],[97,252,34,30,167,139,224],[23,78,167,144,180,33,226],[37,141,114,91,40,131,238]],\r\n\t[[38,131,75,181,94,167,233],[166,249,190,132,175,154,98],[96,10,87,48,115,6,31],[188,130,244,230,127,234,197],[203,34,144,207,110,138,91],[158,166,194,92,118,200,90],[225,223,85,24,157,251,147]],\r\n\t[[157,195,229,169,204,144,246],[13,116,223,142,246,136,181],[169,18,78,242,202,1,198],[200,254,216,227,54,77,36],[2,237,57,236,0,152,120],[193,38,54,181,31,106,23],[153,215,100,83,69,110,91]],\r\n\t[[241,24,144,49,182,15,240],[239,108,13,165,64,239,151],[42,146,201,28,141,86,49],[209,110,29,55,109,69,68],[157,51,244,7,249,236,91],[168,66,248,182,205,4,134],[24,190,98,106,181,55,212]],\r\n\t[[66,173,164,26,226,94,163],[131,24,126,249,232,31,62],[61,68,120,193,241,112,192],[7,105,69,143,81,101,45],[126,34,131,95,191,190,153],[109,174,83,29,53,224,115],[20,49,254,234,180,224,211]],\r\n\t[[6,184,250,93,149,193,148],[117,135,138,219,118,88,3],[111,243,221,248,23,48,120],[15,218,196,203,44,243,12],[116,164,95,57,95,119,213],[116,24,65,49,148,201,130],[224,163,149,28,80,208,187]],\r\n\t[[85,142,220,108,208,167,35],[150,199,133,54,151,60,109],[36,69,23,136,135,249,207],[138,50,124,49,172,128,136],[180,125,248,38,236,129,97],[142,84,243,222,246,170,57],[195,137,59,101,103,102,190]]\r\n\t\t], dtype=np.int)\r\nmur = 230\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 60 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 60 passed!\")\r\narray = np.array([\r\n\t[[175,91,18,250,54,239,138],[130,175,104,73,57,0,254],[229,76,72,233,16,206,44],[237,184,235,212,28,145,189],[219,175,59,108,205,2,120],[116,198,74,245,251,174,229],[131,200,198,236,200,75,160]],\r\n\t[[152,197,125,226,83,65,159],[91,123,122,224,104,94,2],[0,212,96,101,204,69,240],[92,60,178,99,10,113,116],[196,39,54,185,57,130,233],[55,183,44,143,250,11,205],[216,9,6,185,214,19,207]],\r\n\t[[189,129,43,115,120,12,6],[141,64,223,213,216,216,208],[158,55,223,145,241,243,60],[120,34,237,41,146,88,71],[88,22,144,161,167,193,120],[254,79,59,221,54,166,140],[249,114,7,180,240,122,246]],\r\n\t[[173,108,243,171,214,157,65],[217,111,38,217,60,220,201],[254,143,42,52,5,71,154],[92,92,251,238,137,6,37],[84,148,150,127,37,11,123],[50,238,77,17,240,109,177],[55,205,191,48,17,23,71]],\r\n\t[[191,138,239,43,6,203,75],[198,51,200,188,131,89,163],[116,118,27,14,181,63,83],[186,135,84,70,181,173,101],[182,179,77,111,235,254,199],[225,228,175,3,12,227,16],[43,139,71,166,92,65,249]],\r\n\t[[240,18,14,89,43,95,52],[22,64,110,100,43,178,208],[47,208,129,240,234,57,159],[241,20,42,246,0,83,151],[61,107,142,133,49,7,170],[0,31,46,101,88,1,219],[104,51,229,215,113,38,168]],\r\n\t[[202,168,186,142,34,132,177],[139,9,157,61,212,209,155],[248,137,222,212,131,138,194],[75,199,55,24,184,59,108],[15,195,27,37,199,112,153],[189,118,227,158,123,109,128],[239,180,65,217,141,236,247]]\r\n\t\t], dtype=np.int)\r\nmur = 241\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 61 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 61 passed!\")\r\narray = np.array([\r\n\t[[235,161,0,6,187,49,150],[217,35,96,190,234,74,33],[10,225,195,149,97,232,6],[182,28,242,66,212,77,204],[216,162,80,40,195,144,49],[112,250,1,46,77,168,225],[70,161,123,173,129,253,191]],\r\n\t[[170,120,47,23,83,116,211],[187,20,220,76,153,85,70],[70,171,29,177,126,197,160],[29,113,39,37,232,67,41],[38,187,232,60,231,221,108],[208,80,32,105,67,194,202],[43,223,130,130,180,124,13]],\r\n\t[[186,160,228,39,189,128,222],[230,196,17,27,41,207,131],[113,155,237,150,98,117,25],[25,153,230,140,47,150,183],[9,26,201,43,142,173,188],[215,17,17,247,88,188,35],[187,130,168,90,95,73,203]],\r\n\t[[53,193,21,61,126,106,214],[188,107,95,221,197,69,188],[140,9,125,254,212,247,216],[3,134,6,212,0,151,232],[183,76,195,201,219,214,234],[6,39,122,224,115,9,37],[0,153,224,141,4,246,183]],\r\n\t[[212,195,187,146,31,46,85],[11,239,197,152,163,1,137],[133,222,206,251,12,205,145],[59,79,167,99,148,210,117],[85,117,40,195,176,63,228],[132,250,135,9,65,111,183],[212,195,9,254,9,210,183]],\r\n\t[[71,1,251,240,117,239,154],[91,199,243,159,14,169,192],[85,85,158,13,141,62,239],[144,108,224,231,60,81,9],[90,10,87,10,194,54,216],[148,240,44,223,36,59,197],[205,189,165,209,232,207,94]],\r\n\t[[156,145,231,69,168,125,183],[205,193,71,198,70,181,178],[100,250,181,51,226,43,76],[216,181,7,107,91,98,160],[192,204,129,251,59,61,100],[27,200,3,25,69,230,54],[253,91,228,67,201,79,194]]\r\n\t\t], dtype=np.int)\r\nmur = 22\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 62 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 62 passed!\")\r\narray = np.array([\r\n\t[[183,173,16,59,63,11,13],[77,19,125,16,5,146,10],[150,199,145,229,127,98,182],[108,167,81,108,143,5,142],[253,104,244,31,61,214,237],[161,254,14,89,22,26,33],[46,149,51,223,221,118,233]],\r\n\t[[74,59,123,46,38,223,156],[34,5,132,245,179,15,213],[192,33,190,25,201,83,177],[170,34,226,217,21,164,134],[208,34,156,246,2,117,8],[174,47,77,234,178,2,86],[90,134,41,248,34,252,26]],\r\n\t[[144,194,247,185,105,19,205],[50,104,227,163,55,179,135],[49,5,119,75,231,156,175],[130,206,2,145,231,207,79],[8,198,7,33,208,60,223],[71,37,85,57,215,50,143],[21,219,244,211,111,161,132]],\r\n\t[[138,1,104,184,98,33,31],[53,223,97,7,149,206,207],[230,202,211,64,176,44,60],[180,175,125,4,83,92,244],[202,130,184,248,126,172,19],[108,123,139,187,175,55,95],[205,31,162,61,157,57,170]],\r\n\t[[49,237,195,149,37,164,232],[235,88,196,116,173,62,215],[97,211,220,189,116,78,242],[63,24,9,234,228,72,227],[31,169,220,101,97,234,238],[210,48,30,31,237,242,87],[0,249,249,122,32,206,170]],\r\n\t[[92,72,38,73,43,142,133],[58,215,230,227,29,223,144],[247,184,7,70,190,26,53],[237,201,136,230,114,202,43],[23,182,114,197,171,192,25],[77,214,140,211,227,229,45],[164,198,239,128,249,121,253]],\r\n\t[[130,104,120,5,35,168,154],[202,156,196,49,91,70,78],[142,102,172,162,138,14,232],[168,142,161,77,116,84,170],[62,253,171,9,7,76,239],[153,222,105,142,15,86,178],[82,39,47,118,64,78,236]]\r\n\t\t], dtype=np.int)\r\nmur = 110\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 63 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 63 passed!\")\r\narray = np.array([\r\n\t[[85,39,129,204,90,62,209],[75,96,54,187,252,242,165],[16,208,43,4,146,247,206],[88,46,244,77,103,107,184],[65,67,32,217,36,222,180],[20,195,59,242,67,180,122],[220,94,5,179,250,29,98]],\r\n\t[[171,233,130,206,157,84,215],[78,9,113,114,171,212,180],[240,226,3,133,10,224,107],[148,181,179,5,191,233,141],[3,159,192,137,83,222,168],[1,19,29,70,9,181,6],[71,172,53,152,168,182,63]],\r\n\t[[97,208,41,211,5,139,77],[177,243,247,112,46,91,9],[249,52,144,150,159,170,112],[189,127,165,117,23,56,163],[119,198,44,99,77,91,211],[237,116,223,51,251,90,118],[215,60,12,221,190,37,110]],\r\n\t[[181,193,1,22,202,237,203],[107,148,34,234,248,7,141],[199,196,83,171,221,109,102],[125,38,56,47,47,208,167],[58,4,1,13,56,63,41],[167,51,158,34,157,42,102],[159,80,96,5,113,210,229]],\r\n\t[[60,246,44,55,35,108,6],[228,214,226,10,150,131,155],[222,35,0,196,228,33,222],[140,13,112,72,87,236,227],[196,7,34,248,193,191,247],[48,195,130,103,209,176,66],[94,95,49,69,210,220,188]],\r\n\t[[148,6,73,172,240,98,49],[62,58,204,29,128,110,186],[126,168,212,9,5,176,175],[14,225,29,127,67,252,239],[167,154,193,89,96,101,37],[75,40,44,40,14,207,105],[37,83,143,21,180,109,38]],\r\n\t[[235,119,38,39,128,2,105],[88,86,213,172,184,214,78],[35,172,5,220,14,241,147],[156,239,13,230,68,187,167],[80,227,61,192,192,190,32],[64,182,250,118,220,193,214],[90,165,48,31,167,204,169]]\r\n\t\t], dtype=np.int)\r\nmur = 102\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 64 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 64 passed!\")\r\narray = np.array([\r\n\t[[54,169,222,236,133,238,33],[220,188,173,43,166,248,28],[242,94,90,112,67,246,121],[194,246,139,248,111,248,98],[13,113,89,162,197,122,69],[202,136,21,173,29,183,204],[44,55,56,22,193,11,177]],\r\n\t[[18,235,206,215,181,188,96],[177,171,53,76,221,116,164],[204,247,57,41,96,193,69],[214,157,192,89,89,203,2],[160,4,144,57,38,152,43],[98,224,163,67,179,185,235],[35,43,170,174,218,191,43]],\r\n\t[[236,11,116,245,245,192,128],[161,62,76,197,144,254,122],[171,77,51,252,160,182,232],[166,195,224,200,64,165,130],[198,120,43,238,137,59,73],[181,219,101,242,55,120,197],[225,16,110,184,7,185,244]],\r\n\t[[156,122,242,213,6,157,78],[160,15,247,92,139,90,247],[132,24,42,184,114,248,39],[204,126,77,91,36,160,228],[126,107,254,111,37,39,56],[38,91,131,160,73,211,236],[101,169,219,189,16,125,47]],\r\n\t[[197,18,135,74,203,100,189],[206,5,48,145,160,113,202],[93,85,31,169,166,151,249],[177,16,254,116,217,66,200],[136,58,73,123,190,67,249],[246,189,14,26,192,172,198],[156,50,208,40,217,242,143]],\r\n\t[[101,100,251,204,178,246,145],[13,80,14,137,215,123,96],[44,162,214,96,22,93,55],[200,64,146,183,66,46,171],[235,208,25,193,247,108,161],[172,15,200,132,220,247,56],[159,161,55,22,89,51,253]],\r\n\t[[47,111,22,108,235,171,169],[239,145,181,56,208,51,54],[192,122,194,22,191,126,227],[252,227,193,40,206,34,226],[234,153,205,92,130,143,90],[57,164,67,93,71,230,21],[239,4,29,221,188,174,125]]\r\n\t\t], dtype=np.int)\r\nmur = 132\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 159;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 65 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 65 passed!\")\r\narray = np.array([\r\n\t[[134,236,122,168,165,82,239],[51,112,133,105,1,76,192],[175,253,180,189,121,244,202],[215,187,180,133,175,186,127],[12,19,199,120,51,197,125],[56,146,19,173,100,165,126],[129,3,80,46,115,176,222]],\r\n\t[[238,90,52,86,115,36,187],[44,60,161,57,23,9,108],[171,114,193,81,130,238,139],[7,8,89,115,119,41,245],[118,111,213,89,73,57,96],[33,26,151,158,122,214,170],[26,108,117,195,137,3,56]],\r\n\t[[243,71,229,134,212,6,66],[228,188,174,238,120,32,85],[126,16,208,218,205,253,212],[141,4,106,159,113,116,92],[216,161,88,178,58,69,103],[73,99,124,1,153,92,238],[180,151,67,38,228,116,29]],\r\n\t[[180,121,21,8,62,54,112],[102,185,58,112,216,186,103],[153,80,119,43,245,46,18],[21,182,210,225,68,83,243],[254,117,33,46,34,26,213],[56,221,38,207,28,135,131],[16,99,25,188,85,120,109]],\r\n\t[[140,215,230,214,107,14,234],[75,143,188,145,217,165,99],[10,44,2,203,43,6,71],[240,232,92,26,95,254,79],[103,31,192,226,240,216,208],[184,65,240,46,204,103,28],[23,222,226,5,58,118,12]],\r\n\t[[210,174,129,90,228,159,207],[106,245,33,178,94,185,180],[134,136,62,152,129,166,89],[190,56,217,108,217,93,59],[62,37,189,120,121,191,31],[240,176,71,143,90,221,158],[53,178,155,46,207,250,37]],\r\n\t[[108,84,129,62,31,172,16],[6,216,220,223,132,54,88],[183,153,191,171,218,213,115],[142,1,133,152,66,56,23],[146,150,91,37,198,113,43],[94,84,91,197,151,9,72],[83,68,143,92,82,234,189]]\r\n\t\t], dtype=np.int)\r\nmur = 10\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 66 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 66 passed!\")\r\narray = np.array([\r\n\t[[242,154,219,115,131,206,140],[12,237,225,153,118,166,179],[28,159,66,82,231,160,10],[23,201,164,231,221,1,53],[227,198,141,160,198,129,74],[112,223,51,21,80,176,171],[217,6,4,214,3,61,222]],\r\n\t[[138,166,130,36,231,168,49],[211,227,41,121,7,189,208],[114,78,41,96,207,126,29],[253,127,231,152,121,137,248],[4,71,129,53,221,123,125],[36,72,71,124,212,19,201],[83,86,164,57,199,198,120]],\r\n\t[[77,141,199,140,32,173,54],[113,177,47,183,188,178,64],[228,184,221,243,175,156,43],[120,100,15,16,130,56,46],[225,234,67,106,9,208,254],[8,165,135,242,241,43,13],[100,102,45,221,27,93,57]],\r\n\t[[192,191,163,186,212,122,105],[231,15,229,29,8,111,132],[93,159,150,240,159,117,231],[11,149,169,222,185,131,144],[169,146,230,191,203,119,87],[223,159,218,171,66,106,123],[115,212,138,138,3,178,107]],\r\n\t[[209,58,56,249,33,196,76],[170,215,89,114,129,183,69],[230,19,175,50,250,214,226],[142,254,236,7,122,222,223],[156,199,178,13,119,131,171],[249,156,4,121,154,16,85],[131,2,129,57,191,7,77]],\r\n\t[[57,13,39,4,222,244,215],[83,164,34,36,50,80,105],[88,171,68,229,44,180,126],[78,4,189,234,67,246,82],[193,198,183,208,66,15,125],[177,10,134,157,253,199,253],[232,206,218,3,64,196,64]],\r\n\t[[92,166,166,254,223,148,32],[30,56,30,223,244,49,251],[102,88,230,91,252,94,153],[117,216,170,49,179,9,138],[173,166,93,251,232,152,213],[34,60,46,110,120,251,238],[237,164,177,218,68,200,166]]\r\n\t\t], dtype=np.int)\r\nmur = 171\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 67 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 67 passed!\")\r\narray = np.array([\r\n\t[[57,6,188,123,247,169,238],[246,88,185,83,93,212,187],[237,6,185,234,140,107,197],[250,227,132,147,96,197,6],[243,141,9,120,177,119,9],[178,208,5,187,29,142,119],[113,221,186,119,0,66,210]],\r\n\t[[153,235,228,25,12,214,8],[146,52,96,75,45,37,133],[148,64,189,244,86,86,177],[164,98,33,240,99,79,243],[15,101,173,182,94,198,99],[213,247,111,215,174,52,94],[132,245,219,171,101,85,167]],\r\n\t[[129,227,236,135,133,81,208],[128,197,39,162,223,156,200],[239,252,212,92,139,19,232],[175,143,166,175,221,107,11],[210,81,102,229,184,69,15],[168,202,74,211,208,175,178],[76,122,32,236,168,39,217]],\r\n\t[[63,14,132,238,22,61,207],[147,204,219,74,89,2,233],[36,30,239,53,230,61,77],[69,175,208,52,2,48,99],[118,207,161,37,42,74,7],[3,212,121,91,132,210,246],[235,174,53,141,248,151,153]],\r\n\t[[69,215,110,13,230,190,82],[70,74,220,203,32,8,136],[113,3,84,198,159,166,243],[26,23,248,49,144,23,22],[102,166,90,254,42,137,6],[179,214,7,15,241,73,17],[124,102,75,144,62,36,62]],\r\n\t[[236,221,228,126,205,22,249],[119,234,94,19,177,50,213],[241,126,13,166,208,88,2],[73,226,27,179,153,113,101],[59,246,164,213,128,28,174],[76,184,216,84,219,117,195],[63,9,40,237,51,147,66]],\r\n\t[[198,148,150,20,99,33,116],[242,229,68,210,125,56,215],[18,189,237,41,45,218,247],[210,221,201,66,225,10,52],[185,113,116,83,243,105,89],[233,198,76,204,89,228,136],[110,199,55,38,131,193,144]]\r\n\t\t], dtype=np.int)\r\nmur = 226\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 68 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 68 passed!\")\r\narray = np.array([\r\n\t[[233,243,54,172,141,10,198],[104,174,90,89,236,63,16],[121,188,94,76,66,130,35],[83,222,127,5,212,74,146],[85,1,160,111,29,200,103],[155,135,80,69,188,0,175],[195,210,124,220,83,153,186]],\r\n\t[[248,198,113,155,157,94,15],[179,215,220,2,66,51,197],[97,29,170,42,113,33,158],[201,211,193,56,165,112,83],[187,234,180,102,227,156,213],[120,125,178,174,53,9,158],[213,105,112,1,1,41,13]],\r\n\t[[6,43,226,234,143,177,223],[228,2,170,95,14,137,73],[206,75,154,215,49,79,151],[197,137,116,187,171,253,40],[61,99,4,87,27,182,93],[97,118,174,216,142,198,59],[58,72,31,204,78,121,193]],\r\n\t[[167,140,153,134,47,60,246],[26,234,251,209,16,192,237],[97,91,88,161,239,118,164],[2,241,103,55,77,247,94],[184,59,92,92,98,182,98],[11,238,63,161,247,79,5],[93,250,36,152,76,189,13]],\r\n\t[[65,240,11,6,135,171,133],[98,247,220,39,132,217,141],[18,224,92,189,125,123,75],[226,14,159,9,2,22,40],[134,249,5,131,0,93,206],[145,60,134,232,126,24,103],[216,52,236,156,235,110,46]],\r\n\t[[173,119,189,46,65,95,80],[220,218,110,14,218,196,253],[199,156,74,43,98,32,196],[71,124,240,5,203,234,161],[232,128,33,210,242,197,208],[202,50,44,64,200,146,132],[217,223,174,193,166,63,35]],\r\n\t[[218,252,148,241,46,21,134],[246,91,88,97,195,211,143],[183,66,202,76,114,5,86],[79,150,238,97,203,40,142],[16,102,220,126,53,133,114],[6,221,8,66,106,238,83],[81,124,134,141,133,44,129]]\r\n\t\t], dtype=np.int)\r\nmur = 5\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 69 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 69 passed!\")\r\narray = np.array([\r\n\t[[19,107,227,138,10,231,211],[8,100,161,47,187,170,219],[231,241,30,194,115,70,178],[188,114,173,89,26,240,76],[58,200,34,248,145,152,161],[119,173,50,208,134,28,38],[35,32,97,210,49,148,198]],\r\n\t[[115,243,52,227,196,175,131],[150,84,81,5,171,153,83],[185,196,140,163,54,120,242],[235,149,229,36,39,45,131],[34,13,86,225,121,97,217],[75,143,240,50,239,248,114],[109,13,19,89,126,13,42]],\r\n\t[[117,3,79,238,174,188,13],[27,72,247,165,95,4,17],[243,159,99,86,111,33,160],[237,136,64,79,76,246,215],[215,104,10,39,145,208,88],[70,222,126,243,61,91,25],[197,180,245,220,178,43,1]],\r\n\t[[136,206,63,16,107,146,233],[118,4,212,2,28,163,47],[236,144,169,210,196,28,197],[161,66,10,135,107,151,238],[221,123,140,58,45,71,210],[248,227,84,117,24,85,222],[43,103,180,229,45,166,53]],\r\n\t[[22,68,192,139,100,126,33],[12,145,153,197,171,177,211],[26,77,39,170,51,167,214],[119,88,62,36,133,26,13],[246,224,182,229,237,229,85],[224,69,9,63,114,164,22],[106,150,185,8,39,118,165]],\r\n\t[[228,139,250,47,183,254,176],[113,55,115,37,176,112,120],[90,37,41,203,101,199,53],[81,140,18,159,243,240,103],[170,151,227,250,55,96,62],[117,111,77,4,85,86,241],[183,231,177,156,117,250,254]],\r\n\t[[40,202,186,41,196,138,128],[61,191,152,179,188,125,55],[222,193,31,127,199,40,201],[227,68,167,182,101,54,178],[118,165,148,92,90,251,232],[43,103,128,7,6,44,222],[70,229,124,157,33,95,244]]\r\n\t\t], dtype=np.int)\r\nmur = 84\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 70 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 70 passed!\")\r\narray = np.array([\r\n\t[[54,235,66,43,20,148,229],[162,167,69,196,223,61,178],[43,197,106,141,198,94,67],[236,127,206,111,65,159,100],[220,118,234,96,110,102,22],[118,101,162,233,184,86,76],[64,226,132,61,97,155,63]],\r\n\t[[203,81,214,249,104,214,144],[147,91,189,116,105,250,211],[143,134,159,40,93,189,20],[70,88,240,89,100,95,121],[158,230,47,154,105,118,183],[41,192,14,245,132,20,81],[40,239,147,147,236,104,235]],\r\n\t[[101,5,51,146,134,203,8],[216,128,85,86,213,171,148],[79,47,27,178,64,175,66],[167,117,90,74,213,114,198],[66,6,94,30,21,213,218],[102,129,243,99,52,160,137],[250,168,123,8,112,121,69]],\r\n\t[[186,243,167,179,57,44,52],[128,33,174,75,206,132,167],[82,101,166,219,204,242,32],[125,65,219,152,248,66,90],[4,91,108,2,41,47,247],[234,48,243,92,226,161,19],[234,147,71,25,187,77,160]],\r\n\t[[55,108,27,187,236,77,110],[147,226,136,186,144,81,9],[22,139,240,77,193,241,17],[94,225,175,51,124,248,9],[205,19,125,15,164,203,169],[200,89,200,119,83,75,147],[217,11,229,12,169,12,208]],\r\n\t[[63,49,115,161,1,207,27],[42,248,98,58,178,143,32],[104,173,170,57,237,189,93],[112,79,198,29,63,53,226],[211,204,19,209,155,54,215],[103,55,69,11,51,238,62],[94,192,66,199,95,251,205]],\r\n\t[[236,36,244,39,65,115,217],[122,45,176,55,104,96,21],[6,225,102,49,140,139,184],[36,100,2,173,233,88,109],[110,144,179,174,167,197,65],[145,82,82,9,134,148,148],[252,64,90,196,48,141,97]]\r\n\t\t], dtype=np.int)\r\nmur = 70\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 71 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 71 passed!\")\r\narray = np.array([\r\n\t[[168,136,129,100,188,155,73],[97,142,178,9,188,144,69],[29,18,195,81,101,20,230],[21,141,189,11,215,185,179],[215,72,29,205,180,213,61],[97,117,243,107,87,163,103],[65,165,200,62,51,20,29]],\r\n\t[[10,90,89,44,230,159,36],[12,162,110,230,102,227,250],[229,118,127,212,158,234,40],[3,125,235,113,161,90,20],[187,147,242,89,155,162,12],[36,161,35,165,51,143,180],[29,51,195,142,194,163,152]],\r\n\t[[67,247,238,252,73,75,18],[178,155,57,7,101,39,186],[114,26,123,149,67,110,253],[85,25,38,66,73,71,105],[3,42,63,11,127,126,158],[42,130,135,195,117,127,80],[0,207,171,207,247,188,16]],\r\n\t[[178,168,159,192,151,46,52],[137,23,169,213,225,123,24],[169,251,191,227,173,46,155],[177,180,22,66,137,80,153],[191,139,245,211,16,15,166],[45,4,133,240,203,252,69],[27,85,42,176,218,117,161]],\r\n\t[[138,131,167,145,199,159,142],[114,173,54,87,74,169,79],[29,116,182,194,251,42,54],[210,100,135,66,127,40,47],[2,137,30,169,146,160,141],[161,203,142,97,254,141,222],[124,113,102,63,182,199,150]],\r\n\t[[173,169,130,91,213,234,175],[47,48,211,61,11,138,141],[135,22,226,50,47,13,75],[105,146,63,206,246,146,185],[78,110,75,117,212,168,153],[66,247,207,157,184,58,175],[96,177,76,249,103,134,144]],\r\n\t[[95,87,181,25,174,90,136],[46,145,206,182,253,73,188],[49,1,237,246,92,185,51],[112,61,128,52,42,141,26],[182,181,12,236,74,226,1],[107,192,130,22,234,144,96],[76,229,142,165,56,71,69]]\r\n\t\t], dtype=np.int)\r\nmur = 6\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 72 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 72 passed!\")\r\narray = np.array([\r\n\t[[59,3,88,150,29,243,225],[176,122,155,141,174,32,206],[213,56,188,250,69,218,168],[124,119,78,201,197,168,53],[19,77,64,104,89,76,188],[44,131,38,22,113,74,193],[111,246,16,172,233,21,39]],\r\n\t[[141,76,54,218,95,175,156],[19,3,47,156,127,44,102],[92,237,92,152,104,218,133],[154,97,230,31,86,150,64],[48,211,221,53,229,172,113],[135,146,211,81,39,244,161],[23,52,126,199,182,4,109]],\r\n\t[[40,111,79,98,140,78,28],[126,94,145,0,178,159,250],[199,183,209,16,87,83,75],[20,188,29,85,126,175,182],[208,3,158,243,53,121,197],[107,154,185,162,185,154,23],[205,81,192,254,42,239,243]],\r\n\t[[234,95,142,216,160,5,38],[165,57,163,103,168,32,96],[150,44,134,214,17,142,189],[247,33,160,178,93,146,138],[245,118,19,53,222,78,170],[229,149,155,48,139,128,202],[21,206,8,197,103,228,69]],\r\n\t[[53,237,92,237,152,152,206],[117,249,247,157,40,186,198],[18,35,82,218,240,79,225],[123,139,203,1,205,30,131],[251,69,56,249,181,201,136],[168,171,91,14,88,141,7],[239,77,143,244,230,254,136]],\r\n\t[[183,19,7,209,190,179,164],[241,126,32,33,220,235,124],[105,10,119,24,225,241,122],[4,181,221,129,63,175,10],[55,187,196,78,44,162,82],[242,158,199,206,204,25,171],[64,32,205,222,26,57,133]],\r\n\t[[27,110,134,106,250,118,12],[233,101,99,250,190,61,197],[102,227,14,163,85,173,247],[190,206,14,217,171,28,162],[58,237,103,90,174,176,71],[163,6,77,249,109,99,35],[18,147,126,250,197,57,158]]\r\n\t\t], dtype=np.int)\r\nmur = 32\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 73 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 73 passed!\")\r\narray = np.array([\r\n\t[[241,249,200,88,3,123,226],[119,55,188,70,57,144,117],[129,214,39,140,62,217,115],[19,12,161,76,151,21,207],[193,248,132,53,55,152,71],[80,81,45,63,244,73,0],[87,98,224,145,56,156,226]],\r\n\t[[105,17,11,213,165,53,139],[174,55,43,183,227,223,183],[199,202,234,56,170,169,48],[82,223,68,166,68,1,223],[128,77,204,46,142,131,71],[57,68,154,63,146,80,130],[195,251,167,192,239,184,192]],\r\n\t[[195,204,98,86,53,53,239],[248,160,244,241,51,126,199],[233,126,235,56,231,35,87],[56,19,33,71,0,4,224],[189,133,19,49,188,20,204],[138,81,142,122,251,243,182],[59,49,88,92,190,62,136]],\r\n\t[[98,168,232,246,31,11,173],[97,206,140,61,21,90,214],[122,171,43,24,177,131,33],[162,152,164,54,13,41,32],[199,48,79,48,92,211,175],[171,225,238,131,227,8,227],[155,146,15,5,67,41,67]],\r\n\t[[194,167,190,118,106,70,196],[148,226,74,101,10,53,57],[203,78,185,143,50,176,195],[65,248,159,206,119,78,129],[190,183,159,146,85,133,121],[125,154,218,47,32,18,162],[145,175,150,73,229,89,76]],\r\n\t[[222,224,181,10,38,88,53],[58,165,6,137,6,75,216],[127,140,78,95,29,8,140],[125,143,62,23,10,183,221],[51,218,91,36,54,100,167],[109,118,52,89,146,91,107],[183,219,87,124,37,159,182]],\r\n\t[[210,82,73,28,184,148,57],[126,139,196,190,72,176,41],[168,244,120,35,122,31,8],[68,184,193,39,223,142,132],[99,227,215,246,42,220,73],[92,188,207,81,153,90,12],[197,239,151,232,7,246,222]]\r\n\t\t], dtype=np.int)\r\nmur = 44\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 74 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 74 passed!\")\r\narray = np.array([\r\n\t[[142,102,157,53,236,20,183],[86,163,71,77,241,166,165],[215,23,226,11,216,165,19],[154,208,156,236,118,76,12],[205,93,119,157,167,90,244],[130,232,35,222,143,94,195],[154,177,50,146,95,182,165]],\r\n\t[[138,170,227,162,94,65,16],[253,19,68,17,143,217,206],[140,59,24,92,76,38,92],[166,86,149,172,80,240,59],[100,55,193,175,68,8,170],[218,233,76,243,149,5,100],[16,192,155,63,179,222,248]],\r\n\t[[236,20,156,187,162,213,236],[80,107,65,177,87,224,208],[196,96,104,112,123,181,214],[247,67,85,225,140,133,220],[226,153,113,238,55,23,18],[199,249,51,214,136,200,31],[38,110,42,236,160,175,208]],\r\n\t[[50,106,168,190,125,105,228],[119,123,66,240,173,175,141],[33,79,217,56,184,58,219],[46,254,191,42,109,16,129],[6,2,180,140,181,127,163],[18,197,161,98,214,36,97],[138,179,10,165,209,93,126]],\r\n\t[[157,139,163,30,123,250,228],[108,119,244,82,39,151,5],[218,45,33,74,175,141,178],[105,159,248,204,46,102,115],[209,227,160,225,179,10,185],[93,232,153,215,204,199,29],[131,76,44,3,64,232,148]],\r\n\t[[201,19,112,7,148,91,35],[34,186,245,225,113,73,70],[247,99,30,144,167,210,75],[33,132,238,65,1,138,154],[22,33,143,160,219,74,209],[95,3,233,52,184,98,39],[19,81,97,35,129,147,250]],\r\n\t[[177,237,67,221,249,191,28],[253,153,62,184,254,93,162],[9,48,189,144,248,21,25],[33,240,138,196,142,176,189],[98,74,65,97,103,131,62],[89,1,59,2,46,191,70],[237,14,249,107,175,159,162]]\r\n\t\t], dtype=np.int)\r\nmur = 16\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 75 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 75 passed!\")\r\narray = np.array([\r\n\t[[87,219,89,109,203,23,116],[109,150,110,223,2,55,98],[6,189,59,192,171,197,103],[181,220,34,232,175,63,95],[61,52,19,106,224,172,50],[176,31,211,38,6,163,33],[153,57,196,108,124,102,226]],\r\n\t[[191,193,169,27,169,27,20],[177,120,171,119,144,185,207],[249,214,42,165,100,147,240],[111,56,220,188,137,57,171],[94,33,87,115,191,191,13],[107,237,46,196,97,163,102],[117,177,164,33,95,227,199]],\r\n\t[[17,82,218,182,215,44,120],[144,35,161,118,192,7,250],[253,96,114,41,196,31,194],[55,147,145,52,217,21,143],[21,38,20,217,50,34,113],[17,90,206,7,237,105,181],[239,87,58,89,155,0,6]],\r\n\t[[58,2,193,189,19,249,147],[222,136,29,165,160,45,172],[200,124,64,178,174,130,110],[55,155,14,30,242,5,107],[82,111,202,139,177,254,209],[220,91,175,29,63,182,234],[108,124,75,31,188,0,3]],\r\n\t[[227,3,102,43,233,41,147],[46,217,96,24,195,186,125],[222,154,169,244,68,55,189],[197,196,237,171,139,160,7],[52,34,247,106,13,100,32],[134,144,22,95,9,129,188],[48,248,136,57,89,198,252]],\r\n\t[[86,48,201,71,123,146,146],[102,191,75,218,87,41,148],[70,192,41,16,251,168,102],[112,235,250,16,237,253,106],[48,202,111,17,176,173,32],[106,130,103,79,106,32,121],[240,238,133,198,46,141,20]],\r\n\t[[220,180,216,221,246,100,151],[204,46,59,161,33,233,183],[73,163,94,75,214,187,44],[0,185,212,195,237,73,246],[48,36,151,215,172,136,43],[139,177,36,30,49,55,194],[223,134,114,47,251,210,127]]\r\n\t\t], dtype=np.int)\r\nmur = 150\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 76 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 76 passed!\")\r\narray = np.array([\r\n\t[[131,22,136,162,59,179,89],[70,18,253,13,5,146,234],[42,108,52,162,49,230,53],[169,6,176,198,88,116,94],[176,21,247,72,207,109,171],[60,173,229,190,74,51,161],[38,196,47,226,16,56,25]],\r\n\t[[157,190,211,175,252,10,231],[202,135,57,209,101,125,73],[3,193,100,231,220,200,75],[231,150,49,189,160,112,8],[6,132,40,49,142,222,125],[217,182,250,72,215,175,130],[174,81,7,161,161,44,110]],\r\n\t[[206,138,241,3,104,98,62],[254,99,246,144,202,137,64],[70,220,120,221,26,172,170],[119,211,246,33,37,35,200],[129,207,30,163,69,47,167],[149,252,81,153,167,153,16],[53,203,94,178,228,83,181]],\r\n\t[[159,165,162,94,239,155,92],[226,210,122,42,186,108,32],[169,29,205,1,184,52,177],[198,242,24,225,79,86,164],[103,152,24,163,57,221,16],[188,170,254,70,129,95,75],[113,129,248,90,248,6,139]],\r\n\t[[142,170,69,168,125,215,151],[172,70,137,52,113,241,41],[6,186,19,170,244,221,172],[90,178,3,182,80,92,106],[65,184,30,101,244,35,26],[47,41,41,102,3,46,25],[92,118,246,49,155,210,54]],\r\n\t[[33,147,253,79,15,58,81],[193,211,213,246,51,32,76],[148,187,218,225,131,58,116],[7,222,186,245,70,162,69],[134,253,151,120,127,254,0],[113,148,161,218,221,30,88],[60,181,59,62,190,138,175]],\r\n\t[[64,59,68,93,147,32,148],[142,72,168,134,67,182,126],[217,243,61,31,27,225,179],[165,170,250,124,40,90,153],[140,212,125,26,148,53,111],[167,86,168,158,5,57,245],[48,86,181,9,165,157,93]]\r\n\t\t], dtype=np.int)\r\nmur = 222\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 77 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 77 passed!\")\r\narray = np.array([\r\n\t[[199,112,53,78,20,149,41],[124,15,118,246,228,215,156],[103,39,124,73,240,37,100],[77,178,47,31,75,204,71],[238,158,227,65,1,242,100],[223,87,53,133,108,147,57],[160,32,11,142,222,186,158]],\r\n\t[[73,3,197,42,135,60,158],[67,36,210,228,151,148,59],[187,177,113,108,56,214,35],[131,158,37,6,104,5,108],[157,157,55,72,165,65,241],[251,130,178,31,7,194,117],[140,28,135,113,42,204,39]],\r\n\t[[229,54,37,227,35,132,42],[203,33,81,33,189,197,99],[56,161,163,135,77,85,191],[134,232,218,140,122,234,142],[39,104,17,245,156,162,186],[169,229,216,141,99,201,222],[140,242,182,67,181,107,193]],\r\n\t[[36,39,206,167,77,70,79],[134,93,119,216,190,36,247],[78,62,30,144,187,71,77],[230,158,161,120,104,96,165],[76,247,134,32,97,28,205],[116,135,18,111,76,184,171],[58,201,32,209,98,207,226]],\r\n\t[[249,165,41,225,15,4,179],[30,149,211,213,54,111,150],[185,134,35,175,67,107,176],[65,45,28,14,135,61,153],[217,189,19,250,61,171,243],[97,107,223,176,20,44,209],[251,66,132,166,191,216,211]],\r\n\t[[13,160,185,173,13,140,111],[26,32,15,58,66,11,167],[106,242,239,232,231,169,71],[233,242,50,109,41,16,235],[75,155,128,176,36,224,178],[180,67,117,252,61,229,143],[174,142,194,153,3,231,5]],\r\n\t[[217,14,39,113,235,135,244],[134,33,184,124,29,197,222],[175,92,161,120,100,84,80],[158,87,159,190,38,210,74],[250,141,37,70,116,127,95],[144,101,208,245,230,90,170],[57,23,115,158,22,7,252]]\r\n\t\t], dtype=np.int)\r\nmur = 177\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 78 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 78 passed!\")\r\narray = np.array([\r\n\t[[111,228,156,80,148,184,142],[230,69,17,113,25,205,93],[136,23,176,101,183,140,52],[221,34,32,71,253,97,67],[6,254,251,77,247,41,57],[114,228,84,111,88,41,68],[139,242,76,94,94,112,126]],\r\n\t[[211,225,29,80,208,31,120],[197,146,83,253,242,112,16],[19,84,204,11,184,68,247],[4,232,34,210,165,104,176],[25,94,173,136,17,132,62],[16,108,194,7,172,45,101],[207,7,169,63,231,130,64]],\r\n\t[[73,74,105,248,207,71,9],[211,111,128,87,224,8,133],[38,190,132,69,155,53,69],[28,49,144,239,4,39,115],[119,130,40,109,31,155,100],[216,26,137,85,26,251,72],[103,61,217,159,32,160,185]],\r\n\t[[44,19,219,5,162,107,165],[29,25,8,184,231,40,193],[209,68,209,73,206,43,249],[185,92,31,199,89,74,62],[220,226,106,122,136,40,66],[104,90,156,136,252,20,154],[164,82,217,140,10,101,215]],\r\n\t[[235,253,16,44,111,131,250],[40,16,101,91,156,116,94],[240,24,119,131,130,54,52],[65,44,15,184,220,171,0],[47,13,158,135,230,29,159],[237,127,230,49,56,75,42],[84,192,77,64,191,63,17]],\r\n\t[[172,46,71,212,41,97,235],[23,203,71,45,180,35,178],[165,134,52,160,28,93,157],[206,230,144,246,0,56,202],[227,81,60,112,230,176,72],[42,4,95,75,185,130,241],[150,184,211,146,204,121,152]],\r\n\t[[98,109,249,71,239,80,219],[83,156,234,162,184,189,1],[132,229,203,194,177,41,76],[35,24,25,145,7,8,254],[174,188,152,45,123,120,127],[51,43,90,193,8,192,183],[188,213,43,214,254,17,35]]\r\n\t\t], dtype=np.int)\r\nmur = 23\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 118;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 79 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 79 passed!\")\r\narray = np.array([\r\n\t[[210,41,211,56,127,90,203],[201,3,145,194,231,254,93],[50,169,76,62,9,148,229],[204,62,193,219,25,187,14],[48,120,131,113,206,25,35],[62,2,8,34,91,206,211],[19,186,83,37,133,140,48]],\r\n\t[[131,103,56,89,254,27,34],[140,206,29,236,21,91,29],[131,166,76,154,17,144,181],[106,178,49,172,135,247,249],[157,10,239,28,25,236,48],[166,105,234,190,205,18,63],[76,34,123,243,30,136,91]],\r\n\t[[6,23,10,101,158,184,109],[152,101,105,172,173,75,254],[10,176,48,179,229,5,112],[42,159,102,174,207,86,98],[166,4,235,231,63,54,242],[87,183,145,68,75,129,132],[218,0,41,23,254,39,95]],\r\n\t[[1,6,249,141,28,78,116],[102,169,108,25,144,38,71],[12,63,159,187,152,138,211],[183,55,93,89,236,15,235],[191,4,51,184,16,234,163],[100,39,205,136,238,92,76],[121,226,84,100,159,221,2]],\r\n\t[[171,57,64,60,158,45,116],[127,104,137,44,17,89,230],[56,7,187,75,188,68,227],[33,206,187,114,77,73,129],[15,17,189,19,208,62,104],[14,244,103,121,102,175,226],[24,193,75,179,73,17,81]],\r\n\t[[97,203,241,161,116,237,22],[159,146,172,132,73,52,8],[206,24,208,23,24,142,176],[144,196,68,73,96,141,127],[182,113,140,133,151,12,199],[56,60,82,50,21,36,58],[202,4,149,71,217,110,211]],\r\n\t[[235,227,226,217,176,16,11],[16,150,51,79,246,148,208],[88,72,235,68,3,27,124],[89,16,72,188,209,70,133],[13,143,68,34,21,26,148],[209,195,98,250,36,4,128],[107,212,76,233,154,23,154]]\r\n\t\t], dtype=np.int)\r\nmur = 16\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 80 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 80 passed!\")\r\narray = np.array([\r\n\t[[67,102,250,77,1,87,176],[206,204,42,202,228,29,118],[219,14,115,239,173,89,24],[145,253,155,151,96,54,183],[79,234,65,29,103,44,162],[53,2,145,144,3,113,165],[161,236,119,186,4,238,71]],\r\n\t[[53,225,59,20,39,195,35],[33,192,189,243,53,167,18],[231,186,154,238,249,216,239],[0,120,76,136,61,75,113],[91,144,28,252,15,191,155],[54,87,71,9,44,81,123],[48,225,63,118,221,119,9]],\r\n\t[[165,252,183,80,75,250,211],[89,176,230,103,185,35,239],[61,140,150,90,225,33,103],[49,25,148,78,118,136,149],[121,108,26,87,168,146,189],[32,121,107,69,58,33,169],[1,128,163,48,87,215,65]],\r\n\t[[205,175,106,77,195,134,92],[152,60,31,111,242,115,242],[19,129,9,17,169,159,193],[17,27,170,160,206,231,13],[125,49,12,93,61,21,148],[120,206,104,162,99,232,209],[204,9,104,155,118,114,52]],\r\n\t[[19,208,203,243,94,9,12],[76,155,204,10,142,40,77],[4,243,135,240,231,135,137],[52,130,38,105,87,216,20],[250,94,72,233,22,221,154],[112,224,146,136,172,151,136],[190,183,215,51,222,235,232]],\r\n\t[[121,196,90,5,208,188,145],[13,144,99,196,241,181,4],[140,163,26,123,39,248,135],[182,123,95,129,251,173,181],[231,203,250,184,12,251,157],[95,208,61,15,55,214,104],[228,95,26,30,20,140,186]],\r\n\t[[8,228,169,144,87,58,248],[14,171,212,111,193,9,132],[254,252,91,95,179,162,195],[94,94,53,88,146,79,15],[48,21,251,126,102,200,107],[75,77,109,246,66,107,16],[83,42,106,209,194,28,205]]\r\n\t\t], dtype=np.int)\r\nmur = 100\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 81 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 81 passed!\")\r\narray = np.array([\r\n\t[[43,198,55,136,27,39,242],[112,145,167,110,211,10,6],[103,9,176,68,24,214,81],[200,99,173,238,244,158,11],[115,252,23,36,205,173,101],[156,197,153,71,64,244,120],[46,180,134,32,2,196,107]],\r\n\t[[197,13,183,88,64,18,19],[128,39,189,159,251,140,192],[164,10,83,63,19,73,153],[104,109,209,21,132,149,220],[8,134,21,84,245,139,202],[251,140,211,138,85,38,43],[110,145,126,170,121,180,3]],\r\n\t[[1,45,147,23,184,112,109],[237,31,189,182,197,245,165],[92,175,52,197,201,96,71],[75,123,10,41,218,247,54],[197,152,124,107,95,233,172],[154,15,76,66,52,222,202],[14,140,169,173,251,6,254]],\r\n\t[[136,28,65,225,193,55,150],[156,149,80,6,211,38,180],[230,42,128,20,3,212,26],[35,94,242,147,31,118,105],[129,147,5,1,243,27,56],[81,44,201,88,203,211,113],[72,205,62,205,60,90,39]],\r\n\t[[33,83,94,134,116,2,194],[163,165,173,181,246,203,198],[151,103,248,140,248,23,177],[203,136,54,189,30,85,159],[57,61,189,88,199,51,92],[124,57,125,214,20,99,78],[94,77,240,77,52,150,15]],\r\n\t[[206,1,225,48,29,219,173],[6,86,165,127,140,250,112],[97,67,27,200,88,15,105],[195,79,141,33,80,245,92],[135,96,153,10,197,241,170],[240,230,37,229,67,100,128],[13,142,84,237,229,133,156]],\r\n\t[[146,29,180,67,212,224,23],[110,70,31,248,12,175,175],[75,187,47,30,226,247,235],[66,246,171,189,88,88,182],[42,75,65,73,152,124,78],[107,47,97,230,39,29,237],[173,7,129,164,157,87,131]]\r\n\t\t], dtype=np.int)\r\nmur = 98\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 82 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 82 passed!\")\r\narray = np.array([\r\n\t[[0,113,101,100,204,125,151],[67,199,187,8,211,102,241],[115,38,37,176,210,28,146],[54,209,85,134,141,151,87],[15,193,136,43,77,221,46],[95,157,183,247,163,168,116],[49,29,105,121,223,226,27]],\r\n\t[[206,152,12,61,203,85,26],[243,170,123,162,117,42,209],[52,55,245,163,13,42,252],[7,163,166,69,82,124,197],[207,116,186,94,68,44,42],[229,216,205,197,170,55,245],[53,10,159,19,223,158,79]],\r\n\t[[181,102,49,14,149,37,251],[234,157,147,129,145,172,99],[211,27,173,28,239,188,148],[3,9,127,162,12,199,42],[171,232,74,208,177,184,13],[209,71,97,90,181,58,65],[50,155,55,33,71,28,163]],\r\n\t[[58,35,222,147,15,47,100],[26,235,228,209,54,83,177],[220,33,122,212,78,29,134],[195,66,58,196,71,57,144],[218,122,109,58,108,134,17],[229,55,6,18,96,141,226],[64,164,66,141,141,24,35]],\r\n\t[[24,113,218,101,196,181,229],[100,53,152,254,67,145,90],[1,77,138,80,249,170,214],[185,105,240,59,129,88,159],[101,149,141,212,119,94,0],[1,54,68,64,90,143,108],[253,214,11,160,179,45,2]],\r\n\t[[68,116,214,217,204,81,161],[237,22,6,44,4,40,173],[211,226,245,45,224,39,9],[95,118,23,181,27,116,238],[106,175,130,132,12,3,188],[149,251,41,149,248,65,96],[133,89,232,245,125,94,70]],\r\n\t[[58,62,71,0,138,31,90],[96,167,67,227,176,222,148],[209,237,232,39,116,17,71],[173,110,154,133,70,242,249],[67,135,176,251,83,219,18],[182,244,125,8,29,0,251],[83,103,18,7,186,8,197]]\r\n\t\t], dtype=np.int)\r\nmur = 12\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 83 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 83 passed!\")\r\narray = np.array([\r\n\t[[205,9,151,46,241,120,29],[85,126,99,214,169,96,125],[30,1,234,216,95,218,119],[33,207,230,245,67,110,100],[21,205,97,162,233,97,155],[130,138,57,246,222,58,122],[243,69,204,177,79,158,82]],\r\n\t[[192,133,183,169,89,185,152],[18,29,57,93,144,235,0],[0,196,70,187,66,211,79],[207,111,189,164,114,223,1],[165,240,3,77,180,220,223],[217,249,125,181,168,122,10],[208,201,97,186,245,22,13]],\r\n\t[[221,64,134,68,109,94,126],[144,126,1,11,159,54,125],[173,46,52,147,242,139,47],[144,125,140,17,161,76,180],[207,22,15,175,37,193,25],[238,73,5,153,223,194,225],[52,163,224,129,241,100,41]],\r\n\t[[100,243,12,199,98,254,229],[59,60,179,16,247,204,143],[223,86,137,138,164,158,203],[177,45,73,161,167,16,147],[128,140,78,183,11,2,5],[137,108,67,215,0,6,177],[148,212,32,145,52,68,79]],\r\n\t[[31,150,210,107,34,152,63],[120,105,160,223,197,88,117],[247,127,76,124,178,195,252],[87,84,12,70,239,150,198],[157,143,5,22,245,31,249],[207,223,163,31,199,73,184],[208,247,27,49,85,198,67]],\r\n\t[[87,26,209,124,124,57,81],[125,95,131,173,55,236,77],[205,190,103,97,27,113,211],[247,96,209,177,94,1,122],[45,178,45,138,116,167,147],[163,87,97,177,164,247,241],[6,155,48,49,243,131,131]],\r\n\t[[220,180,74,44,175,23,177],[201,33,97,107,31,51,163],[9,176,190,69,175,15,41],[254,33,187,213,225,11,213],[27,48,50,89,127,51,42],[155,116,188,75,5,125,100],[32,161,225,17,229,165,245]]\r\n\t\t], dtype=np.int)\r\nmur = 62\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 84 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 84 passed!\")\r\narray = np.array([\r\n\t[[103,107,9,113,99,24,140],[106,110,102,204,153,47,141],[173,229,130,120,217,88,36],[199,236,31,98,120,187,91],[149,43,233,81,43,97,97],[83,16,4,25,47,230,246],[22,56,71,146,15,8,236]],\r\n\t[[105,178,96,160,193,178,103],[191,146,45,7,139,252,139],[193,32,141,96,3,188,108],[121,108,80,154,59,193,159],[227,13,51,246,234,55,140],[183,84,179,79,172,199,157],[202,162,26,102,200,239,189]],\r\n\t[[160,102,79,164,51,127,76],[91,154,63,111,147,191,187],[219,119,252,204,4,149,252],[75,223,180,95,114,198,130],[7,97,239,51,49,245,112],[246,120,210,181,136,92,61],[117,224,144,110,57,139,141]],\r\n\t[[228,232,108,111,224,134,194],[190,133,195,160,153,193,231],[30,51,190,193,135,239,238],[37,178,165,90,116,21,194],[213,37,117,73,170,13,27],[108,194,231,88,203,232,3],[63,189,19,208,167,124,29]],\r\n\t[[206,198,199,135,233,76,143],[171,228,226,54,60,66,137],[18,251,126,108,143,173,173],[39,176,173,254,246,244,87],[217,53,28,253,47,239,12],[186,140,95,129,35,65,186],[150,73,67,211,248,55,151]],\r\n\t[[130,146,140,36,70,168,2],[196,42,66,225,88,17,35],[236,214,58,210,215,93,75],[195,120,36,90,115,246,119],[31,217,111,46,201,45,54],[109,141,70,75,46,223,154],[58,88,106,163,105,137,37]],\r\n\t[[192,15,59,45,39,148,139],[109,190,247,203,163,15,204],[58,23,242,34,19,223,212],[251,133,186,100,176,163,103],[93,210,80,86,205,95,148],[35,113,117,38,61,91,89],[213,43,118,39,23,86,249]]\r\n\t\t], dtype=np.int)\r\nmur = 174\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 85 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 85 passed!\")\r\narray = np.array([\r\n\t[[223,84,139,76,242,218,187],[55,118,59,90,91,166,196],[244,12,246,211,65,173,187],[200,103,183,46,19,116,31],[124,107,218,145,205,131,189],[15,15,190,177,233,53,108],[131,226,53,97,21,232,175]],\r\n\t[[47,63,127,194,211,158,204],[31,151,3,95,180,47,156],[92,43,165,68,209,238,176],[237,136,251,157,247,192,211],[9,43,216,219,64,65,205],[188,211,32,96,81,95,9],[143,9,0,191,162,26,215]],\r\n\t[[79,37,10,142,152,138,1],[137,28,86,76,202,174,23],[45,186,192,13,135,116,96],[68,58,203,171,29,34,248],[209,144,190,230,146,62,45],[192,161,229,170,187,210,31],[160,132,53,212,149,4,172]],\r\n\t[[8,145,188,141,4,248,134],[45,159,224,149,109,179,254],[249,8,215,34,116,125,54],[201,166,22,61,250,69,148],[144,224,157,200,247,220,106],[6,6,109,154,18,166,164],[223,189,171,242,114,61,136]],\r\n\t[[238,105,190,250,98,114,74],[43,3,49,99,34,37,32],[104,108,99,90,128,192,74],[37,0,197,49,37,10,44],[92,117,30,124,234,138,32],[142,242,98,137,3,52,194],[251,220,253,176,105,131,215]],\r\n\t[[112,17,62,87,188,70,17],[129,143,36,151,86,73,151],[109,91,111,155,31,227,101],[172,126,227,215,56,158,198],[229,229,85,68,36,81,219],[34,179,152,164,2,150,57],[67,54,207,21,55,246,178]],\r\n\t[[124,64,191,118,193,173,36],[1,210,107,238,94,19,92],[236,174,239,194,86,138,34],[72,206,239,83,249,9,128],[118,193,168,1,250,75,60],[46,40,17,168,215,199,219],[238,70,243,202,246,108,100]]\r\n\t\t], dtype=np.int)\r\nmur = 27\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 86 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 86 passed!\")\r\narray = np.array([\r\n\t[[135,102,35,104,223,148,95],[188,208,242,211,8,229,219],[68,83,99,48,104,171,239],[171,148,93,49,38,42,190],[34,197,40,158,102,25,156],[113,222,210,95,129,83,243],[5,94,206,201,52,8,119]],\r\n\t[[123,248,98,141,67,150,199],[108,213,10,229,19,86,90],[16,99,1,244,142,129,90],[4,43,112,63,234,214,75],[173,174,129,178,231,242,130],[35,227,162,173,9,120,151],[22,161,123,247,246,146,178]],\r\n\t[[107,133,244,167,112,67,125],[2,108,117,213,241,81,231],[14,48,80,48,17,77,217],[232,37,209,156,179,245,2],[169,55,124,85,203,16,89],[210,19,136,129,241,162,192],[134,116,223,44,245,186,66]],\r\n\t[[30,205,18,205,84,235,83],[240,125,167,114,191,76,183],[182,137,138,17,7,163,52],[97,211,222,33,227,230,192],[57,129,225,54,100,209,108],[24,145,165,152,202,189,179],[193,246,137,118,56,215,207]],\r\n\t[[26,252,69,186,155,89,203],[207,31,171,231,22,33,164],[104,242,146,191,89,189,130],[119,18,70,127,214,102,126],[136,23,230,16,138,209,36],[161,106,64,110,127,173,204],[67,67,68,222,39,147,78]],\r\n\t[[41,73,225,77,41,33,120],[33,133,223,206,23,211,201],[52,165,58,220,149,155,153],[154,152,184,158,44,90,238],[51,15,47,107,70,55,125],[204,235,212,75,85,229,211],[166,166,60,41,14,235,200]],\r\n\t[[114,95,146,47,252,140,101],[54,73,35,221,241,17,11],[155,140,246,135,106,240,237],[113,245,198,178,83,143,236],[31,5,156,114,163,31,190],[185,163,63,4,161,62,25],[233,163,145,237,132,32,63]]\r\n\t\t], dtype=np.int)\r\nmur = 238\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 87 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 87 passed!\")\r\narray = np.array([\r\n\t[[219,110,5,61,89,40,125],[156,206,177,101,245,39,66],[224,212,11,5,148,74,46],[160,41,67,120,23,8,114],[236,9,157,128,141,238,203],[185,231,0,23,248,102,228],[95,229,167,182,52,217,31]],\r\n\t[[180,93,136,185,126,179,95],[163,245,118,183,107,100,89],[155,145,221,86,173,151,240],[193,38,15,198,122,246,100],[124,69,141,137,248,99,199],[219,158,193,12,75,18,128],[119,139,243,145,109,223,48]],\r\n\t[[159,48,37,247,236,228,2],[119,179,107,250,146,21,47],[239,125,132,149,176,95,146],[37,165,12,5,234,152,146],[147,93,12,187,245,199,207],[76,7,198,28,125,153,91],[15,167,183,8,17,161,119]],\r\n\t[[211,77,197,84,26,6,30],[102,212,248,47,74,108,144],[175,212,133,63,64,100,159],[133,4,82,21,69,52,120],[92,7,20,24,218,68,129],[1,241,129,191,135,193,30],[131,199,216,217,60,8,70]],\r\n\t[[16,62,62,22,14,68,148],[41,14,150,133,162,156,73],[97,82,208,131,178,74,194],[84,164,201,129,0,155,122],[86,22,74,62,170,47,40],[38,11,121,189,155,49,114],[242,188,186,136,41,7,55]],\r\n\t[[230,86,28,107,245,54,32],[169,81,137,218,25,0,251],[251,208,214,121,237,197,225],[92,82,2,145,67,43,123],[58,27,178,35,42,143,207],[21,98,148,132,105,143,20],[107,47,79,97,250,61,99]],\r\n\t[[179,139,56,169,207,61,155],[220,105,37,53,187,107,46],[79,61,213,227,15,82,198],[224,186,136,13,72,106,5],[6,128,157,118,119,202,36],[45,230,144,189,9,204,190],[143,197,122,70,41,153,138]]\r\n\t\t], dtype=np.int)\r\nmur = 250\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 88 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 88 passed!\")\r\narray = np.array([\r\n\t[[227,157,246,206,221,64,189],[54,240,81,16,52,156,199],[146,28,51,4,240,193,148],[108,89,44,0,137,48,230],[69,147,193,23,109,91,169],[221,13,149,161,174,99,189],[121,232,180,34,24,57,66]],\r\n\t[[73,171,43,17,118,67,98],[42,204,245,150,38,129,250],[134,232,164,210,69,235,127],[106,98,68,91,10,56,192],[192,19,182,93,66,163,43],[132,138,204,48,16,78,126],[168,205,124,148,218,147,232]],\r\n\t[[65,29,113,165,29,130,8],[115,17,109,134,54,224,211],[229,135,218,154,67,94,156],[115,199,138,153,62,192,73],[246,55,162,142,227,109,16],[246,233,4,32,124,214,131],[218,3,201,143,10,228,103]],\r\n\t[[58,175,67,128,199,239,246],[177,101,192,124,249,207,203],[210,32,240,71,207,152,1],[57,231,176,149,21,133,248],[57,91,242,178,206,188,234],[156,102,239,44,43,126,166],[209,165,51,144,232,192,107]],\r\n\t[[42,60,188,194,86,74,138],[89,141,18,58,169,5,153],[44,155,124,252,169,110,231],[12,73,46,250,233,76,193],[243,26,24,6,106,222,209],[51,252,119,121,137,102,32],[146,167,149,112,81,220,166]],\r\n\t[[62,117,7,48,57,71,150],[15,57,62,194,242,239,93],[177,235,128,239,82,179,139],[108,108,57,89,79,174,85],[168,186,65,95,94,180,14],[144,179,137,173,155,210,117],[217,59,89,153,47,10,195]],\r\n\t[[171,56,153,210,202,131,56],[97,95,7,76,174,128,128],[120,167,181,118,212,86,138],[87,94,213,19,141,251,207],[178,62,154,112,233,245,102],[66,228,88,61,78,60,130],[176,91,183,241,212,39,126]]\r\n\t\t], dtype=np.int)\r\nmur = 206\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 89 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 89 passed!\")\r\narray = np.array([\r\n\t[[39,203,156,166,109,230,49],[221,44,12,156,78,225,202],[212,131,33,143,23,195,38],[168,4,15,53,40,76,93],[84,175,51,33,184,188,115],[200,27,252,4,145,180,18],[73,43,192,93,150,205,156]],\r\n\t[[183,53,134,98,231,63,74],[221,113,13,134,117,82,124],[30,192,96,154,61,229,110],[81,193,231,74,205,155,105],[51,62,84,67,234,43,15],[174,217,13,203,194,14,158],[123,45,71,200,140,175,134]],\r\n\t[[125,162,128,46,68,171,151],[116,135,92,35,164,214,155],[170,99,65,169,58,99,31],[17,244,115,8,20,236,137],[212,24,234,100,126,50,70],[39,43,215,97,209,52,95],[141,17,155,217,127,244,71]],\r\n\t[[107,47,175,28,23,208,46],[59,45,171,152,213,219,89],[44,166,240,26,36,134,232],[235,205,160,243,177,209,57],[133,101,163,58,230,98,174],[204,239,242,225,189,158,249],[51,130,167,28,206,217,21]],\r\n\t[[177,166,221,236,5,197,171],[145,165,44,95,48,211,132],[55,57,219,233,11,164,173],[138,81,168,71,30,91,30],[177,6,126,247,193,147,109],[10,223,67,12,183,31,162],[204,15,191,41,1,154,68]],\r\n\t[[6,59,21,156,244,97,78],[247,5,51,211,64,166,251],[220,5,64,130,236,24,170],[34,13,166,36,121,45,240],[155,52,111,40,9,236,136],[129,192,162,186,1,254,138],[209,180,78,1,54,90,37]],\r\n\t[[135,233,166,32,85,226,9],[189,131,100,96,68,119,160],[92,35,147,241,99,170,121],[157,51,33,236,136,59,252],[108,181,99,210,209,56,169],[245,96,35,112,201,100,44],[124,78,159,59,146,208,168]]\r\n\t\t], dtype=np.int)\r\nmur = 227\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 90 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 90 passed!\")\r\narray = np.array([\r\n\t[[125,197,99,246,97,197,181],[118,161,240,1,99,242,251],[209,38,151,232,243,36,146],[59,183,218,228,215,204,68],[187,109,239,111,153,88,14],[145,194,180,230,21,190,57],[185,198,162,155,35,223,120]],\r\n\t[[156,151,174,75,135,230,138],[42,224,30,177,89,117,199],[188,33,93,80,118,242,237],[20,100,185,170,131,220,68],[141,106,236,195,23,80,115],[119,49,135,224,53,55,32],[80,170,151,16,39,226,56]],\r\n\t[[150,157,213,96,176,253,22],[206,165,113,176,68,53,126],[213,223,80,40,22,151,107],[90,211,154,12,41,8,30],[187,176,126,140,106,133,168],[140,23,75,242,49,65,161],[87,190,39,41,147,225,57]],\r\n\t[[176,115,35,73,17,213,72],[177,128,14,124,249,254,19],[132,146,185,87,118,205,174],[238,138,211,154,103,247,121],[81,97,222,118,4,115,47],[221,95,153,125,142,180,154],[252,75,118,149,224,198,17]],\r\n\t[[17,157,74,186,182,140,57],[95,218,118,252,68,57,119],[151,246,247,231,176,196,130],[59,81,122,64,126,176,251],[100,43,229,185,206,56,4],[24,118,117,140,129,116,226],[63,179,238,124,106,151,211]],\r\n\t[[187,81,95,188,213,226,184],[182,89,115,250,13,17,85],[233,184,182,133,42,13,206],[238,237,41,29,205,50,17],[62,35,244,37,22,254,104],[99,125,174,187,106,19,126],[139,133,22,102,137,124,221]],\r\n\t[[210,110,217,158,167,11,84],[23,197,2,29,71,164,8],[221,65,233,120,101,222,173],[52,79,241,238,254,8,85],[158,56,236,177,71,218,213],[109,100,152,208,220,23,222],[8,223,101,153,182,14,63]]\r\n\t\t], dtype=np.int)\r\nmur = 251\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 91 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 91 passed!\")\r\narray = np.array([\r\n\t[[217,237,187,206,136,224,91],[79,15,115,126,188,79,98],[18,56,107,157,28,130,250],[178,252,120,124,254,105,57],[42,10,217,240,145,120,71],[225,88,36,254,29,230,87],[20,42,163,76,93,192,166]],\r\n\t[[228,130,94,86,26,79,43],[162,143,24,179,162,89,88],[116,96,178,199,223,156,89],[17,39,219,247,114,229,92],[223,20,121,109,36,94,21],[50,18,43,133,131,96,54],[226,70,144,70,163,27,230]],\r\n\t[[165,36,183,232,222,76,37],[73,140,142,94,227,204,33],[156,6,21,247,154,193,73],[93,94,33,237,150,139,77],[61,226,179,123,173,238,163],[154,19,24,249,76,213,95],[80,173,151,206,39,205,254]],\r\n\t[[70,12,243,58,133,59,162],[3,19,236,57,235,95,241],[86,85,243,178,126,29,17],[41,228,163,89,187,178,152],[237,232,22,249,191,185,180],[50,246,51,224,87,7,211],[93,161,160,25,94,11,196]],\r\n\t[[249,202,244,138,190,145,150],[157,204,21,190,36,58,226],[68,202,187,132,36,19,180],[215,43,211,86,138,143,197],[192,13,10,78,173,211,249],[97,183,241,146,201,252,56],[43,64,194,124,158,226,62]],\r\n\t[[23,73,253,90,97,62,128],[94,165,192,53,178,215,94],[117,129,96,198,26,205,212],[63,213,16,160,211,241,77],[88,69,21,2,248,73,13],[166,43,174,168,161,18,197],[84,194,160,127,241,129,199]],\r\n\t[[111,184,107,229,222,188,21],[213,72,221,145,223,196,112],[75,31,205,154,151,228,248],[60,7,47,239,24,81,108],[100,240,86,121,90,12,100],[56,191,93,83,102,43,53],[166,33,97,14,92,229,163]]\r\n\t\t], dtype=np.int)\r\nmur = 239\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 92 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 92 passed!\")\r\narray = np.array([\r\n\t[[38,252,136,144,244,32,204],[73,223,141,30,244,217,7],[127,238,127,85,229,19,113],[30,225,204,217,183,15,195],[11,224,247,131,233,184,240],[252,226,216,104,14,196,162],[17,191,77,21,204,22,14]],\r\n\t[[218,252,151,146,203,27,200],[8,19,75,88,124,188,205],[251,8,217,100,124,33,20],[81,118,75,188,116,208,225],[4,231,92,220,189,68,52],[37,137,169,179,148,58,157],[94,136,220,171,191,101,184]],\r\n\t[[31,151,205,155,238,42,6],[40,29,215,236,204,24,194],[85,157,172,91,128,32,252],[84,92,228,113,129,136,211],[249,149,134,71,127,90,132],[96,176,60,70,123,229,200],[169,197,77,190,67,203,110]],\r\n\t[[207,228,94,44,214,48,210],[154,0,61,121,100,224,68],[93,70,239,31,201,184,39],[21,158,216,173,206,90,210],[208,4,165,104,41,224,62],[8,240,154,168,65,173,22],[136,6,30,69,212,73,210]],\r\n\t[[225,75,246,125,5,29,99],[160,7,58,152,145,186,73],[86,109,71,160,6,82,198],[176,189,66,133,203,162,68],[146,177,213,151,121,221,82],[77,9,171,13,134,243,64],[15,22,151,106,44,125,193]],\r\n\t[[128,74,12,251,142,114,235],[212,102,96,64,42,135,90],[2,35,129,106,247,64,73],[183,216,254,123,76,217,120],[176,241,148,37,169,40,105],[215,76,162,37,80,67,188],[185,244,154,159,176,107,110]],\r\n\t[[196,33,178,229,159,101,205],[153,82,168,18,91,86,101],[145,183,153,95,86,165,209],[125,203,67,233,119,218,120],[164,190,178,15,202,232,166],[115,160,152,34,7,173,1],[239,96,135,121,22,126,52]]\r\n\t\t], dtype=np.int)\r\nmur = 157\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 93 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 93 passed!\")\r\narray = np.array([\r\n\t[[244,99,99,207,162,99,192],[244,15,62,99,98,204,6],[118,190,22,186,133,223,96],[1,165,47,17,70,111,196],[38,190,87,139,254,152,174],[241,229,136,77,157,215,228],[42,49,235,74,233,253,144]],\r\n\t[[165,97,204,97,159,8,17],[220,34,70,147,241,88,222],[173,84,21,88,24,100,187],[32,122,235,82,228,28,113],[41,165,94,105,203,41,19],[108,248,91,204,177,7,41],[94,216,201,22,32,110,202]],\r\n\t[[127,78,127,141,62,132,182],[2,220,244,101,96,64,187],[100,29,251,155,192,181,86],[181,206,216,146,225,116,157],[217,72,99,66,56,193,14],[248,15,27,237,70,70,27],[168,200,210,193,28,253,4]],\r\n\t[[78,139,229,168,134,207,115],[133,5,158,137,70,36,176],[137,123,168,51,167,253,235],[239,186,221,185,7,193,76],[176,112,31,31,176,55,176],[232,46,25,93,120,80,69],[27,88,10,185,212,35,136]],\r\n\t[[219,13,37,132,26,124,203],[136,81,84,5,148,165,125],[48,147,108,108,209,34,234],[82,39,13,196,150,104,59],[42,7,168,61,148,55,136],[154,8,174,139,219,54,119],[130,58,12,248,212,119,106]],\r\n\t[[127,115,66,237,195,76,104],[251,107,43,160,208,113,5],[247,91,189,19,50,20,85],[197,142,244,120,67,179,44],[177,60,185,171,228,97,222],[160,238,41,150,103,92,9],[57,181,87,161,158,167,225]],\r\n\t[[97,86,64,184,35,235,39],[133,186,59,217,191,235,75],[163,21,168,241,205,33,199],[143,161,144,16,196,6,52],[206,61,35,130,7,185,25],[89,126,188,220,114,88,227],[224,108,68,223,132,113,105]]\r\n\t\t], dtype=np.int)\r\nmur = 10\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 94 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 94 passed!\")\r\narray = np.array([\r\n\t[[60,193,82,68,237,175,48],[78,13,53,11,64,7,239],[135,216,207,146,144,118,248],[215,208,252,104,12,74,32],[191,217,141,9,190,126,73],[86,36,139,39,151,61,70],[56,102,226,233,149,39,111]],\r\n\t[[198,226,46,60,245,218,106],[141,244,208,112,218,69,87],[175,15,252,18,126,28,150],[214,250,224,75,210,1,206],[7,136,177,207,87,87,127],[75,108,46,3,107,244,75],[221,59,152,5,112,162,110]],\r\n\t[[238,236,124,219,8,48,111],[105,127,204,245,209,236,167],[69,65,145,116,139,158,161],[22,195,242,125,102,210,4],[46,91,192,95,106,57,79],[50,169,36,64,249,35,104],[240,92,86,237,17,220,59]],\r\n\t[[24,33,169,251,138,132,229],[239,156,36,206,214,43,229],[14,150,113,201,128,186,113],[9,16,19,97,122,254,119],[245,86,25,202,137,200,96],[35,171,209,40,25,52,207],[155,135,20,241,105,244,103]],\r\n\t[[177,60,62,107,251,99,115],[187,3,136,165,11,77,143],[235,5,48,99,122,251,223],[161,57,229,231,35,230,126],[164,108,68,2,237,13,32],[170,245,141,13,222,26,7],[189,44,84,142,113,147,172]],\r\n\t[[223,194,40,253,90,242,219],[105,170,57,138,111,61,45],[171,93,110,91,15,113,11],[144,119,31,119,161,218,236],[57,207,77,198,33,148,13],[200,245,169,181,22,165,43],[38,123,122,245,149,55,247]],\r\n\t[[162,230,36,38,187,99,68],[150,68,53,6,185,115,251],[57,138,121,45,246,154,212],[59,42,139,44,86,159,43],[238,178,202,160,20,217,222],[63,226,16,86,94,10,105],[214,22,138,139,114,183,138]]\r\n\t\t], dtype=np.int)\r\nmur = 221\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 95 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 95 passed!\")\r\narray = np.array([\r\n\t[[162,166,111,34,120,207,97],[114,101,38,177,65,16,218],[51,200,160,117,112,90,77],[211,100,242,238,199,203,31],[186,103,20,181,142,73,104],[253,194,163,89,116,102,229],[117,13,155,213,175,148,229]],\r\n\t[[183,144,73,230,169,20,12],[100,64,244,171,231,168,70],[91,105,24,102,17,144,114],[5,193,70,27,114,199,210],[22,146,251,126,212,216,206],[52,222,125,116,145,252,82],[221,191,44,199,47,39,171]],\r\n\t[[164,253,172,48,176,124,11],[232,143,174,146,26,176,192],[186,20,52,2,13,21,164],[71,38,67,86,199,198,245],[84,60,13,230,204,26,227],[191,9,117,61,169,245,43],[119,90,45,73,112,239,146]],\r\n\t[[49,7,146,86,150,179,56],[149,132,24,29,233,33,3],[182,146,144,106,249,9,244],[218,207,8,126,197,18,45],[251,126,144,239,21,93,220],[136,65,180,243,208,225,138],[123,71,193,90,52,207,141]],\r\n\t[[222,40,198,192,145,128,241],[171,74,85,207,159,225,169],[204,1,206,159,212,206,113],[53,188,36,152,30,204,38],[113,168,159,93,192,49,76],[99,137,121,127,230,113,153],[87,167,5,19,94,165,184]],\r\n\t[[9,71,36,199,6,211,38],[240,184,48,17,230,65,226],[32,43,101,140,91,63,146],[150,108,90,119,134,57,161],[127,125,128,25,79,167,157],[112,137,92,173,130,32,153],[142,54,10,136,189,188,197]],\r\n\t[[130,40,19,167,248,16,136],[45,163,102,133,142,95,176],[112,108,147,174,152,211,67],[11,3,153,148,87,96,211],[224,154,195,109,82,226,132],[39,214,132,75,29,47,166],[233,118,50,122,238,193,141]]\r\n\t\t], dtype=np.int)\r\nmur = 140\r\nV = 4\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 96 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 96 passed!\")\r\narray = np.array([\r\n\t[[40,187,156,107,211,173,113],[187,152,67,24,94,102,24],[141,207,221,25,157,14,9],[77,128,2,63,150,152,57],[124,165,48,226,79,109,65],[153,92,92,99,100,102,211],[101,103,219,151,48,4,251]],\r\n\t[[212,22,216,51,66,74,119],[149,107,107,187,42,246,77],[100,82,73,90,164,112,147],[184,49,72,151,214,250,182],[201,228,137,51,59,168,82],[120,5,95,137,57,31,53],[48,169,250,72,166,11,47]],\r\n\t[[213,141,181,87,42,217,189],[69,15,65,247,63,151,220],[16,27,182,128,25,89,3],[43,21,121,225,88,230,45],[131,212,40,82,74,94,7],[123,5,147,85,176,39,239],[162,175,52,34,164,93,195]],\r\n\t[[207,157,0,223,87,220,115],[240,195,195,147,146,17,210],[70,4,32,204,42,182,24],[10,218,101,127,245,15,39],[16,67,69,121,111,185,73],[8,220,73,88,150,119,140],[137,121,112,161,173,223,113]],\r\n\t[[252,236,145,113,144,208,126],[195,206,78,0,181,219,43],[50,193,73,130,231,142,126],[72,171,248,153,48,48,182],[199,44,42,9,127,0,85],[8,246,64,118,128,151,207],[57,143,186,139,182,123,110]],\r\n\t[[37,0,241,36,32,74,222],[68,144,220,128,134,60,158],[240,57,234,232,92,151,29],[14,86,93,163,112,154,70],[113,124,119,242,80,6,97],[28,86,201,211,34,230,89],[109,243,253,5,100,170,37]],\r\n\t[[30,202,106,42,202,30,192],[83,144,196,55,65,47,209],[89,90,92,75,161,236,195],[250,195,142,155,30,134,42],[77,36,68,193,250,119,65],[226,173,176,13,64,5,74],[6,11,109,87,253,29,246]]\r\n\t\t], dtype=np.int)\r\nmur = 64\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 97 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 97 passed!\")\r\narray = np.array([\r\n\t[[231,172,93,139,121,115,229],[209,228,17,33,151,37,93],[118,163,66,204,96,23,254],[46,207,175,205,239,248,186],[15,182,52,85,232,168,191],[207,120,22,165,241,23,54],[203,63,77,75,228,211,10]],\r\n\t[[94,190,250,193,177,174,200],[121,250,112,246,91,70,19],[187,9,25,152,137,71,155],[55,134,47,223,138,153,37],[32,131,105,253,3,137,243],[99,63,234,43,46,16,61],[84,204,119,8,149,102,209]],\r\n\t[[177,229,99,103,27,160,98],[0,126,17,28,171,216,169],[247,9,67,44,95,145,143],[149,78,201,177,201,201,97],[111,200,169,18,164,181,109],[33,187,190,241,220,34,246],[140,155,131,129,51,139,220]],\r\n\t[[82,92,149,222,139,137,140],[121,183,1,40,118,217,75],[53,54,126,53,106,144,39],[156,99,182,144,193,71,194],[20,248,230,91,222,154,37],[70,174,190,167,107,167,188],[204,112,152,220,251,96,113]],\r\n\t[[19,191,204,34,105,186,113],[67,42,175,129,204,91,191],[74,216,242,57,8,147,50],[183,164,13,230,173,224,77],[210,98,62,224,239,37,86],[110,0,45,85,114,247,37],[48,125,233,69,75,236,171]],\r\n\t[[88,198,99,1,135,212,154],[60,226,9,110,60,48,193],[246,24,205,119,169,47,169],[10,120,127,119,107,252,65],[193,172,6,144,86,12,120],[36,39,27,21,28,211,2],[234,119,189,189,219,64,235]],\r\n\t[[48,110,200,221,160,165,143],[202,88,147,22,109,101,35],[219,67,249,77,23,138,187],[237,207,243,166,74,32,186],[244,13,156,35,88,206,3],[35,113,26,36,53,51,237],[222,86,76,251,253,67,195]]\r\n\t\t], dtype=np.int)\r\nmur = 197\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 98 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 98 passed!\")\r\narray = np.array([\r\n\t[[172,99,190,150,81,146,187],[99,28,155,86,192,39,6],[170,220,64,83,162,17,82],[90,193,165,191,64,53,182],[117,251,109,119,205,156,57],[64,195,78,61,99,131,131],[219,86,120,232,8,176,61]],\r\n\t[[29,121,97,88,13,127,165],[124,43,209,235,167,138,58],[133,83,151,87,22,69,3],[250,129,156,221,184,14,130],[182,150,251,120,237,187,47],[236,245,64,92,245,233,253],[174,16,161,250,46,70,79]],\r\n\t[[174,236,106,53,85,245,87],[1,181,131,60,180,46,182],[173,215,128,81,245,103,47],[2,187,108,187,85,232,60],[119,2,199,80,183,10,212],[207,165,104,33,67,109,9],[32,2,176,2,62,91,73]],\r\n\t[[176,245,28,42,208,145,13],[70,29,42,69,82,243,217],[117,146,6,6,154,229,164],[132,194,78,223,78,112,43],[171,197,51,66,61,232,235],[247,32,242,174,168,214,42],[246,72,103,161,202,22,156]],\r\n\t[[139,186,111,22,219,102,94],[174,44,179,223,143,13,171],[243,222,76,31,148,176,127],[34,204,113,159,34,214,170],[99,149,41,28,30,171,22],[231,147,198,44,147,121,3],[7,167,1,241,122,191,236]],\r\n\t[[59,28,32,117,98,121,139],[27,247,61,11,229,56,205],[250,190,240,29,181,237,17],[57,220,193,50,40,131,246],[239,2,161,37,36,124,27],[253,237,114,192,227,197,200],[134,140,164,253,129,110,247]],\r\n\t[[229,190,33,132,41,173,152],[191,159,129,226,43,83,0],[98,60,135,177,226,2,120],[217,73,32,39,132,233,165],[166,22,27,141,48,66,168],[157,240,253,27,145,190,131],[157,48,66,131,97,67,7]]\r\n\t\t], dtype=np.int)\r\nmur = 38\r\nV = 3\r\nlbp = ext3DLBPpy.RD_LBP_P252g_R3(mur, V)\r\nLBPcode = lbp.convert(array)\r\ntruth = 253;\r\nassert LBPcode==truth, \"RD_LBP_P252g_R3: test 99 failed!\"\r\nprint(\"RD_LBP_P252g_R3: test 99 passed!\")\r\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rfcx/audio-feature-visuals
|
[
"b2a0ce2e38b477647142c63e008eca3e4e08af7b"
] |
[
"datavis/audio_io.py"
] |
[
"import os\nimport re\nimport glob\nimport logging\nimport pandas as pd\nfrom io import StringIO\nfrom typing import Generator, Tuple\nfrom joblib import Parallel, delayed\nfrom datetime import datetime\nfrom pathlib import Path, PosixPath\n\n\nclass AudioIOException(Exception):\n pass\n\n\ndef get_all_waves_generator(directory: str, resume: bool = False):\n gen = Path(directory).rglob('*.wav')\n if resume:\n logging.info('Resuming processing')\n wav_paths = list(gen)\n all_paths = [os.path.splitext(path)[0] for path in wav_paths]\n all_paths = set(all_paths)\n csvs = list(Path(directory).rglob('*.csv'))\n csvs = [os.path.splitext(path)[0] for path in csvs]\n csvs = set(csvs)\n paths = all_paths - csvs\n paths = [path + '.wav' for path in paths]\n total = len(paths)\n logging.info('%d / %d completed. Remaining: %d', len(csvs), len(all_paths), total)\n else:\n total = sum(1 for _ in gen)\n paths = Path(directory).rglob('*.wav')\n return paths, total\n\n\ndef get_all_waves(directory: str) -> list:\n \"\"\"\n Return all wave files (recursively) from the provided directory in sorted order\n :param directory: path to the directory\n :return: list of files (possibly empty)\n \"\"\"\n files = glob.glob(directory + '/**/*.wav')\n if not files:\n logging.warning('No WAVE files found in ', directory)\n else:\n files.sort()\n return files\n\n\ndef extract_datetime_from_filename(filename: str) -> datetime:\n match = re.search(r'\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}', filename)\n if not match:\n raise AudioIOException(f'Infering datetime from filename {filename} failed. '\n f'Following regular expression was expected '\n f'\"\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}\"')\n else:\n time_str = match.group(0)\n dt = datetime.strptime(time_str, \"%Y-%m-%dT%H-%M-%S\")\n return dt\n\n\ndef get_date_range_from_directory(directory: str, periods: int) -> pd.DatetimeIndex:\n waves = get_all_waves(directory=directory)\n first_file = os.path.basename(waves[0])\n last_file = os.path.basename(waves[-1])\n start = extract_datetime_from_filename(first_file)\n end = extract_datetime_from_filename(last_file)\n daterange = pd.date_range(start=start, end=end, periods=periods)\n return daterange\n\n\ndef read_result_csv(path):\n \"\"\"\n Assumes the result file has a header and a single line with results\n :param path:\n :return:\n \"\"\"\n with open(path) as fo:\n data = fo.readlines()[1]\n filename = os.path.basename(path)\n time = extract_datetime_from_filename(filename)\n data = str(time) + ',' + data\n return data\n\n\ndef get_result_header(path):\n with open(path) as fo:\n return fo.readline()\n\n\ndef read_results(directory: str) -> pd.DataFrame:\n \"\"\"\n If reading this section makes you think \"why not use pandas or dask read_csv?\", answer is simple: processing\n with these takes prohibitively long time, especially concat of results. By using StringIO we reduce the load time\n over 100x for large datasets\n :param directory:\n :return:\n \"\"\"\n csv_paths = list(Path(directory).rglob('*.csv'))\n header = get_result_header(csv_paths[0])\n data = Parallel(n_jobs=15, backend='loky')(delayed(read_result_csv)(path=path) for path in csv_paths)\n data = header + ''.join(data)\n data = StringIO(data)\n data = pd.read_csv(data)\n data.index = pd.to_datetime(data.index)\n return data.sort_index()\n"
] |
[
[
"pandas.read_csv",
"pandas.to_datetime",
"pandas.date_range"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
marx1992620/cnn_keras_filtercars
|
[
"415eb629069d13f7e2c661bf6f6d7fb5a96e16de"
] |
[
"CnnModel_identifyCar_pred.py"
] |
[
"# --coding:utf-8--\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing import image\nfrom keras.models import load_model\nimport numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\ntrain_dir = r'E:\\car_pic\\training_in_out'\nvalidation_dir = r'E:\\car_pic\\validation_in_out'\ntest_dir = r'E:\\car_pic\\test_in_out'\n\ntrain_datagen = ImageDataGenerator(rescale=1./255)\ntrain_generator = train_datagen.flow_from_directory(train_dir)\n\nprint('='*30)\nprint('訓練的分類:',train_generator.class_indices)\nprint('='*30)\n\nlabels = train_generator.class_indices\n\n#將分類做成字典方便查詢\nlabels = dict((v,k) for k,v in labels.items())\nprint(labels)\n\n# 載入模型\nmodel = load_model('carmodel_CnnModelTrainKaggle.2')\n\n# 將圖片轉為待測數據\ndef read_image(img_path):\n try:\n img = image.load_img(img_path, target_size=(150, 150))\n except Exception as e:\n print(img_path,e)\n\n img = image.img_to_array(img)\n img = np.expand_dims(img, axis=0)\n return img\n\n\n# 隨機輸入一個待測圖片\nfilename = \"E:\\car_pic\\\\train_classify\\Honda_Civic\\*\"\n\nplt.figure()\nim = Image.open(filename)\nim_list = np.asarray(im)\nplt.title(\"predict\")\nplt.axis(\"off\")\nplt.imshow(im_list)\nplt.show()\n\nimg = read_image(filename)\npred = model.predict(img)[0]\nprint('辨識結果:',labels[pred[0]])\n"
] |
[
[
"matplotlib.pyplot.imshow",
"numpy.expand_dims",
"matplotlib.pyplot.title",
"numpy.asarray",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tzmhuang/chess-nn
|
[
"ecd2188063155544dc7759e72602df9a8bcf76c1",
"ecd2188063155544dc7759e72602df9a8bcf76c1"
] |
[
"preprocess/combine_data.py",
"models/evl_NN_Adam.py"
] |
[
"import numpy as np\nimport pandas as pd\n\n\ndef file_combine(start,finish):\n combine_df = pd.DataFrame()\n for i in range(start,finish,500):\n temp = pd.read_csv(\"~/Desktop/Chess/data/train_data{}\".format(i), index_col = 0)\n combine_df = combine_df.append(temp, ignore_index=True)\n print (i)\n return combine_df\n\ntrain_data_2013 = file_combine(499,41500)\n\ntemp = pd.read_csv(\"~/Desktop/Chess/data/train_data41737\", index_col = 0)\ntrain_data_2013 = train_data_2013.append(temp, ignore_index = True)\n\n\n\n\ndef file_combine(start,finish):\n combine_df = pd.DataFrame()\n for i in range(start,finish,10000):\n temp = pd.read_csv(\"~/Chess/piece_pos_data{}\".format(i), index_col = 0)\n combine_df = combine_df.append(temp, ignore_index=True)\n print (i)\n #if (i+1) % 100000 == 0:\n #combine_df.to_csv(\"~/Desktop/Chess/data/piece_pos_checkpt\")\n #print(\"check point done\")\n return combine_df\n\npiece_pos_data_2013 = file_combine(9999,3399999)\n\ntemp = pd.read_csv(\"~/Chess/data/piece_pos_data3406525\", index_col = 0)\npiece_pos_data_2013 = piece_pos_data_2013.append(temp, ignore_index = True)\n\n\ndef file_combine():\n combine_df = pd.DataFrame()\n for i in range(1,10):\n temp = pd.read_csv(\"./Chess/atk_map_{}\".format(i), index_col = 0)\n combine_df = combine_df.append(temp, ignore_index=True)\n print (i)\n #if (i+1) % 100000 == 0:\n #combine_df.to_csv(\"~/Desktop/Chess/data/piece_pos_checkpt\")\n #print(\"check point done\")\n return combine_df\n\ndef file_combine():\n combine_np = np.empty([0,768])\n for i in range(1,10):\n temp = np.load(\"./Chess/atk_map_{}\".format(i))\n combine_df = np.concatenate((combine_np,temp), axis = 0)\n print (i)\n #if (i+1) % 100000 == 0:\n #combine_df.to_csv(\"~/Desktop/Chess/data/piece_pos_checkpt\")\n #print(\"check point done\")\n return combine_df\n",
"'''\nName: evl_NN_Adam\nDate: 15,Apr,2018\nTrain on: Google VM\nPurpose:\n - Adamoptimizer\n - using batch size: 512\n - using more random sample, shuffle -> iter from start\n - failed due to memory error\n - retry with another implementation\n - Using one_hot representation\n - Adding move_num as training input, hopefully help machine distinguish stages of game\n - using Xaviar initizlization\n - *var(W) = 2/[num_in]\nConfig:\n - Structure: 3(4) hidden layer including all extracted data columns\n - Epoch: 5\n - batch_size: 512\n - Initialization: rand_normal [mean = 0, std = Xaviar]\n - Training: Adamoptimizer\n - learning rate: 0.0001\n - beta1 = 0.9\n - beta2 = 0.999\n'''\n\n'''\nFrom bucket to terminal:\n gsutil cp gs://chess-nn/test_data.h5 ~/DNN\n gsutil cp gs://chess-nn/train_data.h5 ~/DNN\n\nGet graph/model:\n gcloud compute copy-files nn-instance1:/home/huangtom2/DNN/evl_NN_Adam/ ./\nGet model:\n gcloud compute copy-files nn-instance1:/home/huangtom2/DNN/model/... ./\nReset:\n rm ./DNN/graph/evl_NN_Adam/*\n'''\n\nimport tensorflow as tf\nimport numpy as np\nimport random\nimport h5py\n\n\ntf.reset_default_graph()\n\n#config\n# logs_path = \"./chess_nn/evl_NN_2_4/graph\"\n# saver_dir = \"./chess_nn/evl_NN_2_4/model/evl_NN_2_4\"\nlogs_path = \"./DNN/evl_NN_Adam/graph\"\nsaver_dir = \"./DNN/evl_NN_Adam/model/evl_NN_Adam\"\n\n\n\nbatch_size = 512\ntraining_epochs = 5\n\n# h = h5py.File(\"//Volumes/DiskA/chess_data.h5\")\n# train_h = h5py.File(\"//Volumes/DiskA/train_data.h5\")\n# test_h = h5py.File(\"//Volumes/DiskA/test_data.h5\")\n\ntrain_h = h5py.File(\"./DNN/train_data.h5\")\ntest_h = h5py.File(\"./DNN/test_data.h5\")\n\ndata_size = train_h['flag'].shape[0] + test_h['flag'].shape[0]\npartition_train = int(0.7*data_size)\npartition_test = data_size - partition_train\n\n\ndef weight_variable(r_num, c_num, name):\n initial = tf.truncated_normal([r_num,c_num], stddev = tf.sqrt(2/r_num))\n return tf.Variable(initial, name = name)\n\ndef full_layer(input, W,b):\n return tf.matmul(input, W) + b\n\n\n'''removed board_set from random batch'''\ndef rand_batch(h5_ptr,batch_size, data_size):\n pos = random.randint(0, int(data_size/batch_size)-1) * batch_size\n #move_num = h5_ptr['move_num'][pos:pos+batch_size] #1\n game_phase = h5_ptr['game_phase'][pos:pos+batch_size] #3\n turn_move = h5_ptr['turn_move'][pos:pos+batch_size] #1\n castling = h5_ptr['castling'][pos:pos+batch_size] #4\n #board_set = h5_ptr['board_set'][pos:pos+batch_size] #64\n piece_pos = h5_ptr['piece_pos'][pos:pos+batch_size] #768\n atk_map = h5_ptr['atk_map'][pos:pos+batch_size] #768\n flag = h5_ptr['flag'][pos:pos+batch_size] #3\n current_data = np.concatenate((game_phase,turn_move,castling,piece_pos,atk_map,flag), axis = 1)\n return current_data\n\ndef rand_fetch(h5_ptr, ind_list, batch_size):\n ind = np.random.choice(ind_list,batch_size,replace = False)\n ind.sort()\n ind = list(ind)\n #move_num = h5_ptr['move_num'][pos:pos+batch_size] #1\n game_phase = h5_ptr['game_phase'][ind] #3\n turn_move = h5_ptr['turn_move'][ind] #1\n castling = h5_ptr['castling'][ind] #4\n #board_set = h5_ptr['board_set'][pos:pos+batch_size] #64\n piece_pos = h5_ptr['piece_pos'][ind] #768\n atk_map = h5_ptr['atk_map'][ind] #768\n flag = h5_ptr['flag'][ind] #3\n current_data = np.concatenate((game_phase,turn_move,castling,piece_pos,atk_map,flag), axis = 1)\n return current_data\n\ndef fetch(h5_ptr,ind):\n ind = list(ind)\n #move_num = h5_ptr['move_num'][pos:pos+batch_size] #1\n game_phase = h5_ptr['game_phase'][ind] #3\n turn_move = h5_ptr['turn_move'][ind] #1\n castling = h5_ptr['castling'][ind] #4\n #board_set = h5_ptr['board_set'][pos:pos+batch_size] #64\n piece_pos = h5_ptr['piece_pos'][ind] #768\n atk_map = h5_ptr['atk_map'][ind] #768\n flag = h5_ptr['flag'][ind] #3\n current_data = np.concatenate((game_phase,turn_move,castling,piece_pos,atk_map,flag), axis = 1)\n return current_data\n\n\ndef partition(h5_ptr, data_size,partition_train):\n train = h5py.File('train_data.h5') #./Chess/train_data.h5\n test = h5py.File('test_data.h5') #./Chess/test_data.h5\n #train\n train_turn_move = h5_ptr['turn_move'][0:partition_train]\n train['turn_move'] = train_turn_move\n train_castling = h5_ptr['castling'][0:partition_train]\n train['castling'] = train_castling\n train_board_set = h5_ptr['board_set'][0:partition_train]\n train['board_set'] = train_board_set #\n train_piece_pos = h5_ptr['piece_pos'][0:partition_train]\n train['piece_pos'] = train_piece_pos\n train_atk_map = h5_ptr['atk_map'][0:partition_train]\n train['atk_map'] = train_atk_map\n train_flag = h5_ptr['flag'][0:partition_train]\n train['flag'] = train_flag\n #test\n test_turn_move = h5_ptr['turn_move'][partition_train:data_size]\n test['turn_move'] = test_turn_move\n test_castling = h5_ptr['castling'][partition_train:data_size]\n test['castling'] = test_castling\n test_board_set = h5_ptr['board_set'][partition_train:data_size]\n test['board_set'] = test_board_set\n test_piece_pos = h5_ptr['piece_pos'][partition_train:data_size]\n test['piece_pos'] = test_piece_pos\n test_atk_map = h5_ptr['atk_map'][partition_train:data_size]\n test['atk_map'] = test_atk_map\n test_flag = h5_ptr['flag'][partition_train:data_size]\n test['flag'] = test_flag\n train.close()\n test.close()\n return\n\ndef variable_summaries(var):\n with tf.name_scope('summaries'):\n mean = tf.reduce_mean(var)\n tf.summary.scalar('mean', mean)\n with tf.name_scope('stddev'):\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('stddev', stddev)\n tf.summary.scalar('max', tf.reduce_max(var))\n tf.summary.scalar('min', tf.reduce_min(var))\n tf.summary.histogram('histogram', var)\n\n\n\nglobal_step = tf.Variable(0, name='global_step',trainable=False)\n\n# with tf.name_scope(\"Data\"):\n# data = tf.placeholder(tf.float32, name = \"data\" ,shape = [None,1544])\n# shuffle = tf.random_shuffle(data, name = \"shuffle\")\n\n\nwith tf.name_scope(\"input\"):\n x = tf.placeholder(tf.float32, name = \"input\", shape = [None,1544])\n y_ = tf.placeholder(tf.float32, name = \"flag\",shape = [None,3])\n\ntf.summary.histogram('input_x',x)\n\n\n\nwith tf.name_scope(\"layer_0\"):\n with tf.name_scope(\"weights_0\"):\n W_0 = weight_variable(1544,1544,\"W_0\")\n variable_summaries(W_0)\n with tf.name_scope(\"bias_0\"):\n b_0 = tf.Variable(initial_value =0.0,name = \"b_0\")\n variable_summaries(b_0)\n with tf.name_scope(\"pre_activate_0\"):\n a_0 = full_layer(x, W_0, b_0)\n tf.summary.histogram(\"a_0\",a_0)\n\nwith tf.name_scope(\"relu_0\"):\n relu_0 = tf.nn.relu(a_0)\n\ntf.summary.histogram(\"relu_0s\",relu_0)\n\n\nwith tf.name_scope(\"layer_1\"):\n with tf.name_scope(\"weights_1\"):\n W_1 = weight_variable(1544,1544,\"W_1\")\n variable_summaries(W_1)\n with tf.name_scope(\"bias_1\"):\n b_1 = tf.Variable(initial_value =0.0,name = \"b_1\")\n variable_summaries(b_1)\n with tf.name_scope(\"pre_activate_1\"):\n a_1 = full_layer(relu_0, W_1, b_1)\n tf.summary.histogram(\"a_1\",a_1)\n\nwith tf.name_scope(\"relu_1\"):\n relu_1 = tf.nn.relu(a_1)\n\ntf.summary.histogram(\"relu_1s\",relu_1)\n\n\nwith tf.name_scope(\"layer_2\"):\n with tf.name_scope(\"weights_2\"):\n W_2 = weight_variable(1544,1544,\"W_2\")\n variable_summaries(W_2)\n with tf.name_scope(\"bias_2\"):\n b_2 = tf.Variable(initial_value =0.0,name = \"b_2\")\n variable_summaries(b_2)\n with tf.name_scope(\"pre_activate_2\"):\n a_2 = full_layer(relu_1, W_2, b_2)\n tf.summary.histogram(\"a_2\",a_2)\n\nwith tf.name_scope(\"relu_2\"):\n relu_2 = tf.nn.relu(a_2)\n\ntf.summary.histogram(\"relu_2s\",relu_2)\n\n\nwith tf.name_scope(\"layer_3\"):\n with tf.name_scope(\"weights_3\"):\n W_3 = weight_variable(1544,3,\"W_3\")\n variable_summaries(W_3)\n with tf.name_scope(\"bias_3\"):\n b_3 = tf.Variable(initial_value =0.0,name = \"b_3\")\n variable_summaries(b_3)\n with tf.name_scope(\"pre_activate_3\"):\n a_3 = full_layer(relu_2, W_3, b_3)\n tf.summary.histogram(\"a_3\",a_3)\n\nwith tf.name_scope(\"relu_3\"):\n relu_3 = tf.nn.relu(a_3)\n\ntf.summary.histogram(\"relu_3s\",relu_3)\n\n\n\nwith tf.name_scope(\"prob\"):\n Y = tf.nn.softmax( relu_3 )\n\ntf.summary.histogram(\"softmax\", Y)\n\nwith tf.name_scope(\"prediction\"):\n pred = tf.argmax(Y, axis = 1)\n\n\nwith tf.name_scope(\"cross_entropy\"):\n #cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(Y+10e-5), reduction_indices=[1]))\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits( labels = tf.argmax(y_,1) ,logits = relu_3)\n loss = tf.reduce_mean(cross_entropy)\n\ntf.summary.scalar(\"loss\", loss)\n\n\nwith tf.name_scope(\"train\"):\n #train_step = tf.train.GradientDescentOptimizer(0.0001).minimize(loss, global_step = global_step)\n #train_step = tf.train.MomentumOptimizer(1/global_step,0.5).minimize(loss,global_step = global_step)\n train_step = tf.train.AdamOptimizer(learning_rate = 0.0001).minimize(loss, global_step = global_step)\n\nwith tf.name_scope(\"accuracy\"):\n accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y_, axis = 1), pred),dtype = tf.float32))\n\ntf.summary.scalar(\"accuracy\", accuracy)\n\n\n\n#summary output to tensorboard\nmerged = tf.summary.merge_all()\n\n#model saver\nsaver = tf.train.Saver()\n\n\nwith tf.Session() as sess:\n train_writer = tf.summary.FileWriter(logs_path + '/train',sess.graph)\n test_writer = tf.summary.FileWriter(logs_path + '/test')\n sess.run(tf.global_variables_initializer())\n #train_np = fetch(train_h)\n test_np = rand_batch(test_h,50000,partition_test)\n test_x = test_np[:,0:1544] #testing data\n test_y = test_np[:,1544:1547] #testing data\n #writer = tf.summary.FileWriter ( logs_path , sess.graph)\n saver.save(sess, saver_dir, global_step=global_step ,write_meta_graph=True)\n for epochs in range(training_epochs):\n batch_count = int(partition_train / batch_size)\n data_index = np.array(range(partition_train))\n np.random.shuffle(data_index)\n #data = sess.run(shuffle, feed_dict = train_np )\n for i in range(batch_count):\n #batch = data[i*batch_size:i*batch_size+batch_size]\n ind = data_index[i*batch_size:i*batch_size+batch_size]\n ind.sort()\n batch = fetch(train_h,ind)\n #batch = rand_batch(train_h, batch_size, partition_train)\n train_x = batch[:,0:1544] #training data\n train_y = batch[:,1544:1547] #training flag\n plt_train,cost,train_ac,_ = sess.run([merged,loss,accuracy,train_step], feed_dict={x: train_x,y_: train_y})\n train_writer.add_summary(plt_train,epochs*batch_count+i) #write log\n if (i)%500 == 0:\n test_ac,plt_test= sess.run([accuracy,merged], feed_dict={x:test_x, y_: test_y})\n test_writer.add_summary(plt_test,global_step = epochs*batch_count+i)\n print (\"epoch: \",epochs,\"iterations: \",i,\"cost: \",cost, \"train accuracy: \",train_ac, \"test accuracy: \",test_ac)\n saver.save(sess, saver_dir, global_step=global_step ,write_meta_graph=True)\n\n\n\nwriter.close()\n"
] |
[
[
"numpy.concatenate",
"numpy.empty",
"pandas.read_csv",
"pandas.DataFrame"
],
[
"numpy.concatenate",
"tensorflow.train.AdamOptimizer",
"tensorflow.summary.scalar",
"tensorflow.Variable",
"tensorflow.reset_default_graph",
"tensorflow.name_scope",
"tensorflow.Session",
"tensorflow.square",
"tensorflow.train.Saver",
"tensorflow.argmax",
"tensorflow.matmul",
"numpy.random.choice",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.summary.merge_all",
"tensorflow.summary.histogram",
"tensorflow.nn.relu",
"tensorflow.reduce_max",
"tensorflow.nn.softmax",
"tensorflow.summary.FileWriter",
"tensorflow.reduce_mean",
"numpy.random.shuffle",
"tensorflow.reduce_min",
"tensorflow.sqrt"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
Sivatejareddyseelam/spark_cnn
|
[
"f25a79a4d00bf03c7e94e29e78e669271e024120"
] |
[
"naive_test.py"
] |
[
"# test the performance of learnt CNN on its corresponding training data\nimport sys\nimport numpy as np\nfrom spark.utils import *\nfrom spark.cnn import CNN\nfrom time import time\n\ndef test(size):\n print('Testing naive CNN for %d testing images' % (size))\n start = time()\n cnn = CNN(0)\n X, Y = load_testing_data(0, size)\n P = cnn.predict(X)\n P = np.argmax(P, 1)\n print('Predicted Classifications:')\n print(P)\n print('Correct Classifications:')\n print(Y)\n\n C = np.concatenate([P, Y]).reshape(2, -1).T\n C = [x for x in C if x[0] == x[1]]\n print('Correct:')\n print('%d/%d' % (len(C), size))\n end = time()\n print('Total time consumption: %.3f' % (end - start))\n\nif __name__ == '__main__':\n size = int(sys.argv[1]) if len(sys.argv) > 1 else 10000\n test(size)\n"
] |
[
[
"numpy.concatenate",
"numpy.argmax"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
krzysztoffiok/twitter_sentiment_to_usnavy
|
[
"673e01336242348d9aa79e6e9b3385222bcd62d7",
"673e01336242348d9aa79e6e9b3385222bcd62d7"
] |
[
"roberta_mbs_optim/usnavy_tweet_sentiment_sh.py",
"semeval_data_splitter.py"
] |
[
"import pandas as pd\nimport numpy as np\nfrom sklearn.metrics import classification_report\nfrom sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier\nfrom sklearn.naive_bayes import BernoulliNB, GaussianNB\nimport sklearn\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\nimport xgboost as xgb\nimport random\nimport shap\nimport datatable as dt\nimport argparse\nimport _utils\nimport matplotlib.pyplot as plt\n\nparser = argparse.ArgumentParser(description='Classify data')\nparser.add_argument('--fold', required=False, type=int, default=0)\nparser.add_argument('--shap', required=False, default=None, help='If argument is passed, SHAP explanations for'\n ' a selected LM will be computed. Possible values'\n 'include e.g. SEANCE, LIWC, Term Frequency')\nparser.add_argument('--samples', required=False, type=int, default=200,\n help=\"number of samples of data to explain by SHAP\")\nparser.add_argument('--estimators', required=False, type=int, default=250,\n help=\"number of estimators in machine learning classification models\")\n\nargs = parser.parse_args()\n_fold = args.fold\n_shap = args.shap\n_estimators = args.estimators\n_shap_samples = args.samples\n\n# choose the dataset\ndataset = \"usnavy\"\n\n# <H1> Preparing data split: 5 fold cross validation </H1>\n# <h3> The procedure is identical as when splitting data for the purpose of training selected Language Models\ndf = pd.read_excel(f\"./{dataset}_data/source_data/tweet_sentiment_input_file.xlsx\", converters={'dummy_id': str})\n\n# drop not needed columns\ndf = df.drop([\"row\", \"dummy_id\"], axis=1)\n\n# 5 fold CV\n# setup random state\nnp.random.seed(13)\n\n# define number of folds\nfold_number = 5\nkf = KFold(n_splits=fold_number, random_state=13, shuffle=True)\n\n# create data splits for Deep Learning Language Models trained with Flair framework\ntrain_indexes = {}\ntest_indexes = {}\n\n# train sets for Machine Learning\ntrain_ml = {}\ni = 0\n\n# this split (with fold_number=5) results in: 20% test, 10% val, 70% train for Flair framework\n# and the same 20% test and 80 % train for Machine Learning\nindexes = list(range(0, len(df)))\nfor train_index, test_index in kf.split(indexes):\n test_indexes[i] = test_index\n train_ml[i] = train_index\n i += 1\n\n# test sets for Machine Learning are equal to those for Flair framework\ntest_ml = test_indexes\n\n# <h1>Reading data: tweets encoded by various Language Models\n# <h3> Linguistic Inquiry and Word Count (LIWC) feature file\ndfliwc = pd.read_excel(f\"./{dataset}_data/embeddings/LIWC2015_5k.xlsx\", converters={'dummy_id': str})\n\n# rename columns to get unique names\ndfliwc.rename(columns={'text': 'text_liwc', \"sentiment\": 'liwc_sent'}, inplace=True)\n\n# define LIWC features names\nliwcfeatures = ['WC', 'Analytic', 'Clout', 'Authentic','Tone', 'WPS', 'Sixltr', 'Dic', 'function', 'pronoun', 'ppron',\n 'i', 'we', 'you', 'shehe', 'they', 'ipron', 'article', 'prep', 'auxverb', 'adverb', 'conj', 'negate',\n 'verb', 'adj', 'compare', 'interrog', 'number', 'quant', 'affect', 'posemo', 'negemo', 'anx', 'anger',\n 'sad', 'social', 'family', 'friend', 'female', 'male', 'cogproc', 'insight', 'cause', 'discrep',\n 'tentat', 'certain', 'differ', 'percept', 'see', 'hear', 'feel', 'bio', 'body', 'health', 'sexual',\n 'ingest', 'drives', 'affiliation', 'achieve', 'power', 'reward', 'risk', 'focuspast', 'focuspresent',\n 'focusfuture', 'relativ', 'motion', 'space', 'time', 'work', 'leisure', 'home', 'money', 'relig',\n 'death', 'informal', 'swear', 'netspeak', 'assent', 'nonflu', 'filler', 'AllPunc', 'Period', 'Comma',\n 'Colon', 'SemiC', 'QMark', 'Exclam', 'Dash', 'Quote', 'Apostro', 'Parenth', 'OtherP']\n\n# read SEANCE features\ndfseance = dt.fread(f\"./{dataset}_data/embeddings/seance_5k.csv\").to_pandas()\ndfseance = dfseance.sort_values([\"filename\"])\ndfseance.drop([\"filename\"], axis=1, inplace=True)\n# create a list of seance features\nseancefeatures = dfseance.columns.to_list()\n# make seance feature names unique\nseancefeatures = [f\"S_{x}\" for x in seancefeatures]\ndfseance.columns = seancefeatures\ndfseance.index = [x for x in range(len(dfseance))]\n\n# rename columns to get unique names\ndfliwc.rename(columns={'text': 'text_liwc', \"sentiment\": 'liwc_sent'}, inplace=True)\n\n# <h3> Vector representations (embeddings) created by selected Deep Learning Language Models\n# trained previously on here addressed task\n# define which embedding files to read\nembeddings = [(\"FastText_lstm\", \"fasttext\"), (\"Roberta_lstm\", \"roberta_lstm\"),\n (\"Roberta_CLS\", \"roberta_ft\")]\nembeddings = []\n# instantiate list of data frames with features and a list of feature names for each df\ndfemblist = []\n\n# Initialize a dictionary with all features used later on in Machine Learning\nallFeatures = {}\n\n# read embedding files and define corresponding feature names (lists of names)\nfor emname, embedding in embeddings:\n embfeaturedict = {}\n for fold in range(fold_number):\n # read encoded sentences by the selected language model\n dfemb = dt.fread(f\"./{dataset}_data/embeddings/{embedding}_encoded_sentences_{fold}.csv\").to_pandas()\n embfeatures = [f\"{emname}{fold}row\"]\n \n # define number of feature columns (columns - 3)\n number_of_feature_columns = len(dfemb.columns) - 3\n \n # create unique feature (column) names\n embfeatures.extend([f\"{emname}{fold}{x}\" for x in range(number_of_feature_columns)])\n embfeatures.extend([f\"{emname}{fold}_sentiment_\", f\"{emname}{fold}_dummy_id_\"])\n dfemb.columns = embfeatures\n \n # append features from each language model in tuple ((model_name,fold), [features])\n embfeaturedict[fold] = [f\"{emname}{fold}{x}\" for x in range(number_of_feature_columns)]\n \n # append encoded sentences by the selected language model to a list of data frames\n dfemblist.append(dfemb)\n \n # create entry in dictionary with all features for each trained language model \n allFeatures[emname] = embfeaturedict\n\n\n# <h3> Vector representations (embeddings) created by selected pre-trained Deep Learning Language Models.\n# No special training was carried out for here addressed task\n# read pooled embeddings and Universal Sentence Encoder (USE) embeddings\npooled_embeddings = [[\"Pooled FastText\", \"fasttext\"], [\"Pooled RoBERTa\", \"roberta\"],\n [\"Universal Sentence Encoder\", \"USE\"]]\npooled_embeddings = [[\"Universal Sentence Encoder\", \"USE\"]]\nfor emname, embedding in pooled_embeddings:\n # two options due to naming convention\n if emname != \"Universal Sentence Encoder\":\n dfemb = dt.fread(f\"./{dataset}_data/embeddings/_deprecated/{embedding}_encoded_sentences_pooled.csv\").to_pandas()\n else:\n dfemb = dt.fread(f\"./{dataset}_data/embeddings/USE_encoded_sentences.csv\").to_pandas()\n \n embfeatures = [f\"{emname}row\"]\n \n # define number of feature columns (columns - 3)\n number_of_feature_columns = len(dfemb.columns) - 3\n \n # create unique feature (column) names\n embfeatures.extend([f\"{emname}{x}\" for x in range(number_of_feature_columns)])\n embfeatures.extend([f\"{emname}_sentiment_\", f\"{emname}_dummy_id_\"])\n dfemb.columns = embfeatures\n \n # add features from each fold to a local dictionary\n embfeaturedict = {}\n for fold in range(fold_number): \n embfeaturedict[fold] = [f\"{emname}{x}\" for x in range(number_of_feature_columns)]\n \n # append encoded sentences by the selected language model to a list of data frames\n dfemblist.append(dfemb)\n \n # create entry in dictionary with all features for each language model \n allFeatures[emname] = embfeaturedict\n\n\n# <h3> Vector representations (embeddings) created by Term Frequency Language Model\n# Create a per-fold feature dictionary for Term Frequency model\ndftf, allFeatures = _utils.term_frequency(train_ml=train_ml, dfliwc=dfliwc, df=df, allFeatures=allFeatures)\n\n# Create per-fold feature dictionary for LIWC model.\nfoldLIWCfeatures = {}\nfor fold, rows in train_ml.items():\n foldLIWCfeatures[fold] = liwcfeatures.copy()\n\n# add the LIWC language model key to dictionary with allFeatures from various language models\nallFeatures[\"LIWC\"] = foldLIWCfeatures\n\n# Create per-fold feature dictionary for SEANCE model.\nfoldSEANCEfeatures = {}\nfor fold, rows in train_ml.items():\n foldSEANCEfeatures[fold] = seancefeatures.copy()\n\n# add the SEANCE language model key to dictionary with allFeatures from various language models\nallFeatures[\"SEANCE\"] = foldSEANCEfeatures\n\n# concat all Data Frames: liwc, TF, DL embedding into one df_ml that will be used in Machine Learning\ndftemp = pd.concat([dfliwc, dftf, dfseance], axis=1)\nfor dfemb in dfemblist:\n dftemp = pd.concat([dftemp, dfemb], axis=1)\ndf_ml = dftemp\n\n# define the target variable in the final df_ml data frame\ndf_ml[\"target_ml\"] = df[\"sentiment\"]\n\n# <h1> Machine Learning part\n# Define list of names of language models that can be tested\nall_language_models = [\"Term Frequency\", \"LIWC\", \"SEANCE\", \"Pooled FastText\", \"Pooled RoBERTa\",\n \"Universal Sentence Encoder\", \"FastText_lstm\", \"Roberta_lstm\", \"Roberta_CLS\"]\n\nif _shap is None:\n\n # instantiate dictionary for data frames with results\n allPreds = {}\n allTrues = {}\n\n # define which classification models to use\n models = [RandomForestClassifier(n_estimators=_estimators, max_depth=7, min_samples_split=2,\n min_samples_leaf=1, max_features='auto', n_jobs=-1, random_state=2020),\n xgb.XGBClassifier(objective='multi:softprob', n_jobs=24, learning_rate=0.03,\n max_depth=10, subsample=0.7, colsample_bytree=0.6,\n random_state=2020, n_estimators=_estimators, tree_method='gpu_hist')]\n\n # use features from selected language models\n for language_model in all_language_models:\n # for training of selected classification models\n for classification_model in models:\n preds, trues = _utils.ML_classification(allFeatures=allFeatures, train_ml=train_ml, test_ml=test_ml,\n df_ml=df_ml, classification_model=classification_model,\n language_model=language_model, fold_number=fold_number)\n\n # save model predictions\n allPreds[f\"{language_model}_{type(classification_model).__name__}\"] = preds.copy()\n allTrues[f\"{language_model}_{type(classification_model).__name__}\"] = trues.copy()\n\n # save model predictions together with true sentiment labels\n pd.DataFrame(allPreds).to_csv(f\"./{dataset}_data/predictions.csv\")\n pd.DataFrame(allTrues).to_csv(f\"./{dataset}_data/trues.csv\")\n\n _utils.compute_metrics(dataset=dataset)\n\nelse:\n\n # prepare model for SHAP explanations\n shap_model, train_data, test_data = _utils.train_model_for_shap(allFeatures=allFeatures, train_ml=train_ml,\n test_ml=test_ml, df_ml=df_ml, classification_model=\n xgb.XGBClassifier(objective='multi:softprob', n_jobs=24, learning_rate=0.03, max_depth=10, subsample=0.7,\n colsample_bytree=0.6, random_state=2020, n_estimators=_estimators, tree_method='gpu_hist')\n ,language_model=_shap, fold=_fold)\n\n fig = _utils.explain_model(model=shap_model, train_data=train_data, test_data=test_data, samples=_shap_samples)\n plt.savefig(f'./results/{dataset}_{_shap}_{_fold}_{_estimators}_summary_plot.png')\n",
"import pandas as pd\nimport numpy as np\nimport os\nimport datatable as dt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\n\n\"\"\"\nPrepares the 5 data splits for Flair models to train on SemEval2017 data\n\"\"\"\n\ndf_semtest = dt.fread(\"./semeval_data/source_data/semtest_filtered.csv\").to_pandas()\ndf_semtrain = dt.fread(\"./semeval_data/source_data/semtrain_filtered.csv\").to_pandas()\ndf_semtest.drop(\"C0\", axis=1, inplace=True)\ndf_semtrain.drop(\"C0\", axis=1, inplace=True)\n\n# 5 fold CV\n# setup random state\nnp.random.seed(13)\nfold_number = 5\nkf = KFold(n_splits=fold_number, random_state=13, shuffle=True)\n\n# create data splits for Deep Learning Language Models trained with Flair framework\ntrain_indexes = {}\nval_indexes = {}\n\n# train sets for Machine Learning\ntrain_ml = {}\ni = 0\n\n# this split (with fold_number=5) results in: 20% val, 80% train for Flair framework\nindexes = list(range(0, len(df_semtrain)))\nfor train_index, val_index in kf.split(indexes):\n val_indexes[i] = val_index\n train_indexes[i] = train_index\n i += 1\n\n# add string required by Flair framework\ndf_semtrain['sentiment'] = '__label__' + df_semtrain['sentiment'].astype(str)\ndf_semtest['sentiment'] = '__label__' + df_semtest['sentiment'].astype(str)\n\n# create folders for FLAIR data splits and .tsv files for training\nfolds_path1 = []\nfor fold in range(fold_number):\n folds_path1.append('./semeval_data/model_sentiment_{}/'.format(str(fold)))\n try:\n os.mkdir('./semeval_data/model_sentiment_{}'.format(str(fold)))\n except FileExistsError:\n None # continue\n df_semtest.to_csv(os.path.join(folds_path1[fold], \"test_.tsv\"), index=False, header=False, encoding='utf-8',\n sep='\\t')\n df_semtrain.iloc[train_indexes[fold]].to_csv(os.path.join(folds_path1[fold], \"train.tsv\"), index=False,\n header=False, encoding='utf-8', sep='\\t')\n df_semtrain.iloc[val_indexes[fold]].to_csv(os.path.join(folds_path1[fold], \"dev.tsv\"), index=False, header=False,\n encoding='utf-8', sep='\\t')\n"
] |
[
[
"pandas.concat",
"pandas.read_excel",
"numpy.random.seed",
"sklearn.ensemble.RandomForestClassifier",
"matplotlib.pyplot.savefig",
"sklearn.model_selection.KFold",
"pandas.DataFrame"
],
[
"numpy.random.seed",
"sklearn.model_selection.KFold"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kflu/benchmark
|
[
"4bf35cf7034a5319d402fa046558cb1a8c6d1a11",
"4bf35cf7034a5319d402fa046558cb1a8c6d1a11"
] |
[
"run.py",
"torchbenchmark/models/detectron2_maskrcnn/__init__.py"
] |
[
"\"\"\"\nA lightweight runner that just sets up a model and runs one of its functions in a particular configuration.\n\nIntended for debugging/exploration/profiling use cases, where the test/measurement harness is overhead.\n\nDANGER: make sure to `python install.py` first or otherwise make sure the benchmark you are going to run\n has been installed. This script intentionally does not automate or enforce setup steps.\n\nWall time provided for sanity but is not a sane benchmark measurement.\n\"\"\"\nimport argparse\nimport time\nimport numpy as np\nimport torch.profiler as profiler\n\nfrom torchbenchmark import load_model_by_name\nimport torch\n\nWARMUP_ROUNDS = 3\n\ndef run_one_step_with_cudastreams(func, streamcount):\n\n print(\"Running Utilization Scaling Using Cuda Streams\")\n\n streamlist = []\n for i in range(1, streamcount + 1, 1):\n\n # create additional streams and prime with load\n while len(streamlist) < i :\n s = torch.cuda.Stream()\n streamlist.append(s)\n\n for s in streamlist:\n with torch.cuda.stream(s):\n func()\n\n torch.cuda.synchronize() # Wait for the events to be recorded!\n\n # now run benchmark using streams\n start_event = torch.cuda.Event(enable_timing=True)\n end_event = torch.cuda.Event(enable_timing=True)\n start_event.record()\n\n for s in streamlist:\n with torch.cuda.stream(s):\n func()\n\n end_event.record()\n torch.cuda.synchronize()\n\n print(f\"Cuda StreamCount:{len(streamlist)}\")\n print('{:<20} {:>20}'.format(\"GPU Time:\", \"%.3f milliseconds\" % start_event.elapsed_time(end_event)), sep='')\n\n\ndef run_one_step(func, nwarmup=WARMUP_ROUNDS, model_flops=None, num_iter=10):\n # Warm-up `nwarmup` rounds\n for _i in range(nwarmup):\n func()\n\n result_summary = []\n for _i in range(num_iter):\n if args.device == \"cuda\":\n torch.cuda.synchronize()\n start_event = torch.cuda.Event(enable_timing=True)\n end_event = torch.cuda.Event(enable_timing=True)\n\n # Collect time_ns() instead of time() which does not provide better precision than 1\n # second according to https://docs.python.org/3/library/time.html#time.time.\n t0 = time.time_ns()\n start_event.record()\n func()\n t1 = time.time_ns()\n\n end_event.record()\n torch.cuda.synchronize()\n t2 = time.time_ns()\n\n # CPU Dispatch time include only the time it took to dispatch all the work to the GPU.\n # CPU Total Wall Time will include the CPU Dispatch, GPU time and device latencies.\n result_summary.append((start_event.elapsed_time(end_event), (t1 - t0) / 1_000_000, (t2 - t0) / 1_000_000))\n else:\n t0 = time.time_ns()\n func()\n t1 = time.time_ns()\n result_summary.append([(t1 - t0) / 1_000_000])\n\n if args.device == \"cuda\":\n gpu_time = np.median(list(map(lambda x: x[0], result_summary)))\n cpu_dispatch_time = np.median(list(map(lambda x: x[1], result_summary)))\n cpu_walltime = np.median(list(map(lambda x: x[2], result_summary)))\n print('{:<20} {:>20}'.format(\"GPU Time:\", \"%.3f milliseconds\" % gpu_time, sep=''))\n print('{:<20} {:>20}'.format(\"CPU Dispatch Time:\", \"%.3f milliseconds\" % cpu_dispatch_time, sep=''))\n print('{:<20} {:>20}'.format(\"CPU Total Wall Time:\", \"%.3f milliseconds\" % cpu_walltime, sep=''))\n else:\n cpu_walltime = np.median(list(map(lambda x: x[0], result_summary)))\n print('{:<20} {:>20}'.format(\"CPU Total Wall Time:\", \"%.3f milliseconds\" % cpu_walltime, sep=''))\n\n # if model_flops is not None, output the TFLOPs per sec\n if model_flops:\n flops, batch_size = model_flops\n tflops = flops * batch_size / (cpu_walltime / 1.0e9) / 1.0e12\n print('{:<20} {:>20}'.format(\"FLOPS:\", \"%.4f TFLOPs per second\" % tflops, sep=''))\n\ndef profile_one_step(func, nwarmup=WARMUP_ROUNDS):\n activity_groups = []\n if ((not args.profile_devices and args.device == 'cuda') or\n (args.profile_devices and 'cuda' in args.profile_devices)):\n print(\"Collecting CUDA activity.\")\n activity_groups.append(profiler.ProfilerActivity.CUDA)\n\n if ((not args.profile_devices and args.device == 'cpu') or\n (args.profile_devices and 'cpu' in args.profile_devices)):\n print(\"Collecting CPU activity.\")\n activity_groups.append(profiler.ProfilerActivity.CPU)\n\n with profiler.profile(\n schedule=profiler.schedule(wait=0, warmup=nwarmup, active=1),\n activities=activity_groups,\n record_shapes=args.profile_detailed,\n profile_memory=args.profile_detailed,\n with_stack=args.profile_detailed,\n with_flops=args.profile_detailed,\n on_trace_ready=profiler.tensorboard_trace_handler(args.profile_folder)\n ) as prof:\n for _i in range(nwarmup + 1):\n func()\n torch.cuda.synchronize() # Need to sync here to match run_one_step()'s timed run.\n prof.step()\n\n print(prof.key_averages(group_by_input_shape=True).table(sort_by=\"cpu_time_total\", row_limit=30))\n print(f\"Saved TensorBoard Profiler traces to {args.profile_folder}.\")\n\n\ndef _validate_devices(devices: str):\n devices_list = devices.split(\",\")\n valid_devices = ['cpu', 'cuda']\n for d in devices_list:\n if d not in valid_devices:\n raise ValueError(f'Invalid device {d} passed into --profile-devices. Expected devices: {valid_devices}.')\n return devices_list\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(__doc__)\n SUPPORT_DEVICE_LIST = [\"cpu\", \"cuda\"]\n parser.add_argument(\"model\", help=\"Full or partial name of a model to run. If partial, picks the first match.\")\n parser.add_argument(\"-d\", \"--device\", choices=SUPPORT_DEVICE_LIST, default=\"cpu\", help=\"Which device to use.\")\n parser.add_argument(\"-m\", \"--mode\", choices=[\"eager\", \"jit\"], default=\"eager\", help=\"Which mode to run.\")\n parser.add_argument(\"-t\", \"--test\", choices=[\"eval\", \"train\"], default=\"eval\", help=\"Which test to run.\")\n parser.add_argument(\"--profile\", action=\"store_true\", help=\"Run the profiler around the function\")\n parser.add_argument(\"--profile-folder\", default=\"./logs\", help=\"Save profiling model traces to this directory.\")\n parser.add_argument(\"--profile-detailed\", action=\"store_true\",\n help=\"Profiling includes record_shapes, profile_memory, with_stack, and with_flops.\")\n parser.add_argument(\"--profile-devices\", type=_validate_devices,\n help=\"Profiling comma separated list of activities such as cpu,cuda.\")\n parser.add_argument(\"--cudastreams\", action=\"store_true\",\n help=\"Utilization test using increasing number of cuda streams.\")\n parser.add_argument(\"--bs\", type=int, help=\"Specify batch size to the test.\")\n parser.add_argument(\"--flops\", action=\"store_true\", help=\"Return the flops result\")\n args, extra_args = parser.parse_known_args()\n\n if args.cudastreams and not args.device == \"cuda\":\n print(\"cuda device required to use --cudastreams option!\")\n exit(-1)\n\n found = False\n Model = load_model_by_name(args.model)\n if not Model:\n print(f\"Unable to find model matching {args.model}.\")\n exit(-1)\n print(f\"Running {args.test} method from {Model.name} on {args.device} in {args.mode} mode.\")\n\n # build the model and get the chosen test method\n if args.flops:\n extra_args.append(\"--flops\")\n\n m = Model(device=args.device, test=args.test, jit=(args.mode == \"jit\"), batch_size=args.bs, extra_args=extra_args)\n\n test = getattr(m, args.test)\n model_flops = None\n if args.flops:\n assert hasattr(m, \"get_flops\"), f\"The model {args.model} does not support calculating flops.\"\n model_flops = m.get_flops(test=args.test)\n if args.profile:\n profile_one_step(test)\n elif args.cudastreams:\n run_one_step_with_cudastreams(test, 10)\n else:\n run_one_step(test, model_flops=model_flops)\n if hasattr(m, 'correctness'):\n print('{:<20} {:>20}'.format(\"Correctness:\", \"%.15f\" % m.correctness), sep='')\n",
"import torch\nimport os\nimport itertools\nimport random\nimport itertools\nfrom pathlib import Path\nfrom typing import Tuple\n\n# TorchBench imports\nfrom torchbenchmark.util.model import BenchmarkModel\nfrom torchbenchmark.tasks import COMPUTER_VISION\n\n# setup environment variable\nCURRENT_DIR = Path(os.path.dirname(os.path.realpath(__file__)))\nDATA_DIR = os.path.join(CURRENT_DIR.parent.parent, \"data\", \".data\", \"coco2017-minimal\")\nassert os.path.exists(DATA_DIR), \"Couldn't find coco2017 minimal data dir, please run install.py again.\"\nif not 'DETECTRON2_DATASETS' in os.environ:\n os.environ['DETECTRON2_DATASETS'] = DATA_DIR\n\nfrom detectron2.config import instantiate\nfrom detectron2 import model_zoo\nfrom detectron2.utils.collect_env import collect_env_info\nfrom detectron2.utils.logger import setup_logger\nfrom detectron2.utils.events import EventStorage\n\ntorch.backends.cudnn.deterministic = False\ntorch.backends.cudnn.benchmark = False\n\nclass Model(BenchmarkModel):\n task = COMPUTER_VISION.DETECTION\n DEFAULT_TRAIN_BSIZE = 1\n DEFAULT_EVAL_BSIZE = 2\n\n def __init__(self, test, device, jit=False, batch_size=None, extra_args=[]):\n if jit:\n raise NotImplementedError(\"Detection Maskrcnn does not support JIT.\")\n super().__init__(test=test, device=device, jit=jit, batch_size=batch_size, extra_args=extra_args)\n\n model_cfg = model_zoo.get_config(\"common/models/mask_rcnn_fpn.py\").model\n data_cfg = model_zoo.get_config(\"common/data/coco.py\").dataloader\n\n if test == \"train\":\n # use a mini dataset\n data_cfg.train.dataset.names = \"coco_2017_val_100\"\n data_cfg.train.total_batch_size = self.batch_size\n self.model = instantiate(model_cfg).to(self.device)\n train_loader = instantiate(data_cfg.train)\n self.example_inputs = itertools.cycle(itertools.islice(train_loader, 100))\n self.optimizer = torch.optim.SGD(self.model.parameters(), 0.)\n elif test == \"eval\":\n data_cfg.test.dataset.names = \"coco_2017_val_100\"\n data_cfg.test.batch_size = self.batch_size\n self.model = instantiate(model_cfg).to(self.device)\n self.model.eval()\n test_loader = instantiate(data_cfg.test)\n self.example_inputs = itertools.cycle(itertools.islice(test_loader, 100))\n\n def get_module(self):\n for data in self.example_inputs:\n return self.model, (data, )\n\n def train(self, niter=1):\n if not self.device == \"cuda\":\n raise NotImplementedError(\"Only CUDA is supported by this model\")\n if self.jit:\n raise NotImplementedError(\"JIT is not supported by this model\")\n self.model.train()\n with EventStorage():\n for idx, data in zip(range(niter), self.example_inputs):\n losses = self.model(data)\n loss = sum(losses.values())\n loss.backward()\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n def eval(self, niter=2) -> Tuple[torch.Tensor]:\n if not self.device == \"cuda\":\n raise NotImplementedError(\"Only CUDA is supported by this model\")\n if self.jit:\n raise NotImplementedError(\"JIT is not supported by this model\")\n self.model.eval()\n with torch.no_grad():\n for idx, data in zip(range(niter), self.example_inputs):\n out = self.model(data)\n # retrieve output tensors\n outputs = []\n for item in out:\n fields = list(map(lambda x: list(x.get_fields().values()), item.values()))\n for boxes in fields:\n tensor_box = list(filter(lambda x: isinstance(x, torch.Tensor), boxes))\n outputs.extend(tensor_box)\n return tuple(outputs)\n"
] |
[
[
"torch.cuda.synchronize",
"torch.profiler.tensorboard_trace_handler",
"torch.profiler.schedule",
"torch.cuda.Event",
"torch.cuda.stream",
"torch.cuda.Stream"
],
[
"torch.no_grad"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tommccoy1/tpdn
|
[
"a4ea54030056a49e5fd00a700eb71790157bc697"
] |
[
"binding_operations.py"
] |
[
"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch import optim\nimport torch.nn.functional as F\n\nimport numpy as np\nimport pickle\n\n# Defines various functions for binding fillers and roles\n\n# Defines the tensor product, used in tensor product representations\nclass SumFlattenedOuterProduct(nn.Module):\n def __init__(self):\n super(SumFlattenedOuterProduct, self).__init__()\n \n def forward(self, input1, input2):\n outer_product = torch.bmm(input1.transpose(1,2), input2)\n flattened_outer_product = outer_product.view(outer_product.size()[0],-1).unsqueeze(0)\n sum_flattened_outer_product = flattened_outer_product\n return sum_flattened_outer_product\n\n# The next several functions define circular convolution, used in \n# holographic reduced representations\ndef permutation_matrix(dim, offset):\n matrix = []\n \n for i in range(dim):\n row = [0 for j in range(dim)]\n row[(offset + 1 + i)%dim] = 1\n matrix.append(row)\n \n return matrix\n \ndef permutation_tensor(dim):\n tensor = []\n \n for offset in range(dim)[::-1]:\n tensor.append(permutation_matrix(dim, offset))\n \n return tensor\n\n\nclass CircularConvolutionHelper(nn.Module):\n def __init__(self, dim):\n super(CircularConvolutionHelper, self).__init__()\n self.permuter = Variable(torch.FloatTensor(permutation_tensor(dim))).cuda()\n \n \n def forward(self, input1, input2):\n outer_product = torch.bmm(input1.unsqueeze(2), input2.unsqueeze(1))\n permuted = torch.bmm(self.permuter, outer_product.transpose(0,2))\n circular_conv = torch.sum(permuted, dim = 0)\n sum_rep = torch.sum(circular_conv, dim = 1)\n \n return sum_rep.unsqueeze(0).unsqueeze(0)\n\n\nclass CircularConvolution(nn.Module):\n def __init__(self, dim):\n super(CircularConvolution, self).__init__()\n self.helper = CircularConvolutionHelper(dim) \n \n def forward(self, input1, input2):\n conv = None\n\n for i in range(len(input1)):\n this_conv = self.helper(input1[i], input2[i]) \n if conv is None:\n conv = this_conv\n else:\n conv = torch.cat((conv, this_conv), 1)\n\n \n return conv\n\n# Elementwise product\nclass EltWise(nn.Module):\n def __init__(self):\n super(EltWise, self).__init__()\n \n \n def forward(self, input1, input2):\n \n eltwise_product = input1 * input2\n \n sum_rep = torch.sum(eltwise_product, dim = 1)\n \n return sum_rep.unsqueeze(0)\n\n\n\n\n\n\n"
] |
[
[
"torch.sum",
"torch.cat"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
KCL-BMEIS/ExeTeraEval
|
[
"c6ef1485aff08fba17cd328a76fcc398c757255d"
] |
[
"exeteraeval/execute_hdf_pandas_t_to_p_join_scenario.py"
] |
[
"import resource\nimport sys\nimport time\nimport numpy as np\nimport pandas as pd\n\n\ndef go(l_filename, r_filename):\n\n t0 = time.time()\n l_df = pd.read_hdf(l_filename)\n left_read = time.time() - t0\n print(\"left dataframe read in {}\".format(left_read))\n\n t0 = time.time()\n r_df = pd.read_hdf(r_filename)\n right_read = time.time() - t0\n print(\"left dataframe read in {}\".format(right_read))\n\n t0 = time.time()\n l_df = l_df.sort_values('id')\n r_df = r_df.sort_values(['patient_id', 'created_at'])\n print(\"sorted in {}\".format(time.time() - t0))\n\n t0 = time.time()\n m_df = pd.merge(l_df, r_df, left_on='id', right_on='patient_id', how='left')\n merged = time.time() - t0\n print(\"pandas: merged in {}\".format(merged))\n print(len(m_df))\n\n print(\"total:\", left_read + right_read + merged)\n\nif __name__ == '__main__':\n # c_soft, c_hard = resource.getrlimit(resource.RLIMIT_AS)\n # resource.setrlimit(resource.RLIMIT_AS, (32 * 1024 * 1024 * 1024, c_hard))\n if len(sys.argv) != 3:\n print(\"Usage: pandas_join_scenario.py <left_csv> <right_csv>\")\n exit(-1)\n\n go(sys.argv[1], sys.argv[2])\n"
] |
[
[
"pandas.read_hdf",
"pandas.merge"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
VITA-Group/CV_A-FAN
|
[
"d5cc54bfea4636868b192ac2a628ac74446db88f",
"d5cc54bfea4636868b192ac2a628ac74446db88f",
"d5cc54bfea4636868b192ac2a628ac74446db88f",
"d5cc54bfea4636868b192ac2a628ac74446db88f",
"d5cc54bfea4636868b192ac2a628ac74446db88f"
] |
[
"Classification/attack_algo.py",
"Detection/py/train_aug_final_muti_advtrain.py",
"Segmentation/main_advtrain.py",
"Detection/py/train_aug_sat_muti_advt_final.py",
"Detection/py/train_aug_sat_muti_final.py"
] |
[
"import torch\r\nimport torch.nn as nn\r\nfrom torch.autograd import Variable\r\nimport torch.nn.functional as F\r\n\r\nimport pdb\r\nimport numpy as np\r\n\r\ndef tensor_clamp(t, min, max, in_place=True):\r\n if not in_place:\r\n res = t.clone()\r\n else:\r\n res = t\r\n idx = res.data < min\r\n res.data[idx] = min[idx]\r\n idx = res.data > max\r\n res.data[idx] = max[idx]\r\n\r\n return res\r\n\r\ndef l2ball_proj(center, radius, t, in_place=True):\r\n if not in_place:\r\n res = t.clone()\r\n else:\r\n res = t\r\n\r\n direction = t - center\r\n dist = direction.view(direction.size(0), -1).norm(p=2, dim=1, keepdim=True)\r\n direction.view(direction.size(0), -1).div_(dist)\r\n dist[dist > radius] = radius\r\n direction.view(direction.size(0), -1).mul_(dist)\r\n res.data.copy_(center + direction)\r\n return res\r\n\r\ndef linfball_proj(center, radius, t, in_place=True):\r\n return tensor_clamp(t, min=center - radius, max=center + radius, in_place=in_place)\r\n\r\ndef PGD(x, loss_fn, y=None, model=None, steps=3, gamma=None, start_idx=1, layer_number=16, eps=(2/255), randinit=False, clip=False):\r\n \r\n # Compute loss\r\n x_adv = x.clone()\r\n if randinit:\r\n # adv noise (-eps, eps)\r\n x_adv += (2.0 * torch.rand(x_adv.shape).cuda() - 1.0) * eps\r\n x_adv = Variable(x_adv.cuda(), requires_grad=True)\r\n x = x.cuda()\r\n\r\n for t in range(steps):\r\n\r\n out = model(x_adv, end_point=layer_number, start_point=start_idx)\r\n loss_adv0 = loss_fn(out, y)\r\n grad0 = torch.autograd.grad(loss_adv0, x_adv, only_inputs=True)[0]\r\n x_adv.data.add_(gamma * torch.sign(grad0.data))\r\n\r\n if clip:\r\n linfball_proj(x, eps, x_adv, in_place=True)\r\n\r\n return x_adv\r\n",
"import argparse\nimport os\nimport time\nimport uuid\nfrom collections import deque\nfrom typing import Optional\n\nimport torch\nimport torch.nn as nn\nfrom tensorboardX import SummaryWriter\nfrom torch import optim\nfrom torch.utils.data import DataLoader\n\nfrom backbone.base import Base as BackboneBase\nfrom config.train_config import TrainConfig as Config\nfrom dataset.base import Base as DatasetBase\nfrom extension.lr_scheduler import WarmUpMultiStepLR\nfrom logger import Logger as Log\nfrom model import Model\n# from model_advlayer4 import Model\nfrom roi.pooler import Pooler\nimport attack_algo\nimport pdb\n\ndef _train(dataset_name: str, backbone_name: str, path_to_data_dir: str, path_to_checkpoints_dir: str, path_to_resuming_checkpoint: Optional[str], args):\n print(\"DATASET:[{}] DIR:[{}]\".format(dataset_name, path_to_data_dir))\n dataset = DatasetBase.from_name(dataset_name)(path_to_data_dir, DatasetBase.Mode.TRAIN, Config.IMAGE_MIN_SIDE, Config.IMAGE_MAX_SIDE)\n dataloader = DataLoader(dataset, batch_size=Config.BATCH_SIZE,\n sampler=DatasetBase.NearestRatioRandomSampler(dataset.image_ratios, num_neighbors=Config.BATCH_SIZE),\n num_workers=8, collate_fn=DatasetBase.padding_collate_fn, pin_memory=True)\n\n Log.i('Found {:d} samples'.format(len(dataset)))\n\n backbone = BackboneBase.from_name(backbone_name)(pretrained=True)\n model = nn.DataParallel(\n Model(\n backbone, dataset.num_classes(), pooler_mode=Config.POOLER_MODE,\n anchor_ratios=Config.ANCHOR_RATIOS, anchor_sizes=Config.ANCHOR_SIZES,\n rpn_pre_nms_top_n=Config.RPN_PRE_NMS_TOP_N, rpn_post_nms_top_n=Config.RPN_POST_NMS_TOP_N,\n anchor_smooth_l1_loss_beta=Config.ANCHOR_SMOOTH_L1_LOSS_BETA, proposal_smooth_l1_loss_beta=Config.PROPOSAL_SMOOTH_L1_LOSS_BETA\n ).cuda()\n )\n \n optimizer = optim.SGD(model.parameters(), lr=Config.LEARNING_RATE,\n momentum=Config.MOMENTUM, weight_decay=Config.WEIGHT_DECAY)\n scheduler = WarmUpMultiStepLR(optimizer, milestones=Config.STEP_LR_SIZES, gamma=Config.STEP_LR_GAMMA,\n factor=Config.WARM_UP_FACTOR, num_iters=Config.WARM_UP_NUM_ITERS)\n step = 0\n time_checkpoint = time.time()\n losses = deque(maxlen=100)\n summary_writer = SummaryWriter(os.path.join(path_to_checkpoints_dir, 'summaries'))\n should_stop = False\n\n num_steps_to_display = Config.NUM_STEPS_TO_DISPLAY\n num_steps_to_snapshot = Config.NUM_STEPS_TO_SNAPSHOT\n num_steps_to_finish = Config.NUM_STEPS_TO_FINISH\n\n if path_to_resuming_checkpoint is not None:\n step = model.module.load(path_to_resuming_checkpoint, optimizer, scheduler)\n Log.i(f'Model has been restored from file: {path_to_resuming_checkpoint}')\n\n device_count = torch.cuda.device_count()\n assert Config.BATCH_SIZE % device_count == 0, 'The batch size is not divisible by the device count'\n Log.i('Start training with {:d} GPUs ({:d} batches per GPU)'.format(torch.cuda.device_count(),\n Config.BATCH_SIZE // torch.cuda.device_count()))\n\n f1, f2, f3, f4 = args.mix_layer\n f1, f2, f3, f4 = int(f1), int(f2), int(f3),int(f4),\n\n while not should_stop:\n for _, (_, image_batch, _, bboxes_batch, labels_batch) in enumerate(dataloader):\n\n batch_size = image_batch.shape[0]\n image_batch = image_batch.cuda()\n bboxes_batch = bboxes_batch.cuda()\n labels_batch = labels_batch.cuda()\n\n inputs_all_se = {\"x\": image_batch, \"adv\": None, \"out_idx\": args.pertub_idx_se, \"flag\": 'head'}\n inputs_all_sd = {\"x\": image_batch, \"adv\": None, \"out_idx\": args.pertub_idx_sd + '_head', \"flag\": 'clean'}\n\n feature_map_se = model.train().forward(inputs_all_se, bboxes_batch, labels_batch)\n feature_map_se = feature_map_se.detach()\n \n rpn_roi_output_dict = model.train().forward(inputs_all_sd, bboxes_batch, labels_batch)\n clean_feature_map_sd = rpn_roi_output_dict['roi_output_dict']['roi_feature_map'].detach()\n\n adv_image_batch = attack_algo.adv_input(\n x = image_batch, \n y = {'bb':bboxes_batch, 'lb': labels_batch},\n model= model,\n steps = args.steps_advt,\n eps = (args.eps_advt / 255), \n gamma = (args.gamma_advt / 255),\n randinit = args.randinit_advt,\n clip = args.clip_advt)\n \n feature_adv_se = attack_algo.PGD(feature_map_se, image_batch, \n y = {'bb':bboxes_batch, 'lb': labels_batch},\n model= model,\n steps = 1,\n eps = (2.0 / 255), \n gamma = (args.gamma_se / 255),\n idx = args.pertub_idx_se,\n randinit = args.randinit,\n clip = args.clip)\n \n feature_adv_m1 = attack_algo.PGD(feature_map_se, image_batch, \n y = {'bb':bboxes_batch, 'lb': labels_batch},\n model= model,\n steps = 1,\n eps = (2.0 / 255), \n gamma = (args.gamma_se / 255),\n idx = args.pertub_idx_se,\n randinit = args.randinit,\n clip = args.clip)\n \n feature_adv_se = attack_algo.PGD(feature_map_se, image_batch, \n y = {'bb':bboxes_batch, 'lb': labels_batch},\n model= model,\n steps = 1,\n eps = (2.0 / 255), \n gamma = (args.gamma_se / 255),\n idx = args.pertub_idx_se,\n randinit = args.randinit,\n clip = args.clip)\n\n adv_rpn_roi_output_dict = attack_algo.rpn_roi_PGD(\n layer = args.pertub_idx_sd,\n rpn_roi_output_dict = rpn_roi_output_dict, \n y = {'bb':bboxes_batch, 'lb': labels_batch},\n model= model,\n steps = 1,\n eps = (2.0 / 255), \n gamma = (args.gamma_sd / 255),\n randinit = args.randinit,\n clip = args.clip,\n only_roi_loss=args.only_roi_sd)\n \n adv_feature_map_sd = adv_rpn_roi_output_dict['roi_output_dict']['roi_feature_map'].detach()\n \n if args.mix_sd:\n adv_feature_map_sd = attack_algo.mix_feature(clean_feature_map_sd, adv_feature_map_sd)\n \n adv_rpn_roi_output_dict['roi_output_dict']['roi_feature_map'] = adv_feature_map_sd\n\n adv_list_se = attack_algo.get_sample_points(feature_map_se, feature_adv_se, 5)\n\n if f1: adv_list_se[1] = attack_algo.mix_feature(feature_map_se, adv_list_se[1])\n if f2: adv_list_se[2] = attack_algo.mix_feature(feature_map_se, adv_list_se[2])\n if f3: adv_list_se[3] = attack_algo.mix_feature(feature_map_se, adv_list_se[3])\n if f4: adv_list_se[4] = attack_algo.mix_feature(feature_map_se, adv_list_se[4])\n\n clean_input_dict = {'x': image_batch, \"adv\": None, 'out_idx': 0, 'flag':'clean'}\n adv_input_dict = {'x': adv_image_batch, \"adv\": None, 'out_idx': 0, 'flag':'clean'}\n adv_input_dict_se1 = {'x': image_batch, 'adv': adv_list_se[1], 'out_idx': args.pertub_idx_se, 'flag':'tail' }\n adv_input_dict_se2 = {'x': image_batch, 'adv': adv_list_se[2], 'out_idx': args.pertub_idx_se, 'flag':'tail' }\n adv_input_dict_se3 = {'x': image_batch, 'adv': adv_list_se[3], 'out_idx': args.pertub_idx_se, 'flag':'tail' }\n adv_input_dict_se4 = {'x': image_batch, 'adv': adv_list_se[4], 'out_idx': args.pertub_idx_se, 'flag':'tail' }\n adv_input_dict_sd = {'adv': adv_rpn_roi_output_dict, 'out_idx': args.pertub_idx_sd + '_tail','flag':'clean'}\n\n anchor_objectness_losses0, anchor_transformer_losses0, proposal_class_losses0, proposal_transformer_losses0 = \\\n model.train().forward(clean_input_dict, bboxes_batch, labels_batch)\n anchor_objectness_losses1, anchor_transformer_losses1, proposal_class_losses1, proposal_transformer_losses1 = \\\n model.train().forward(adv_input_dict_se1, bboxes_batch, labels_batch)\n anchor_objectness_losses2, anchor_transformer_losses2, proposal_class_losses2, proposal_transformer_losses2 = \\\n model.train().forward(adv_input_dict_se2, bboxes_batch, labels_batch)\n anchor_objectness_losses3, anchor_transformer_losses3, proposal_class_losses3, proposal_transformer_losses3 = \\\n model.train().forward(adv_input_dict_se3, bboxes_batch, labels_batch)\n anchor_objectness_losses4, anchor_transformer_losses4, proposal_class_losses4, proposal_transformer_losses4 = \\\n model.train().forward(adv_input_dict_se4, bboxes_batch, labels_batch)\n anchor_objectness_losses5, anchor_transformer_losses5, proposal_class_losses5, proposal_transformer_losses5 = \\\n model.train().forward(adv_input_dict_sd, bboxes_batch, labels_batch)\n anchor_objectness_losses6, anchor_transformer_losses6, proposal_class_losses6, proposal_transformer_losses6 = \\\n model.train().forward(adv_input_dict, bboxes_batch, labels_batch)\n\n loss0 = attack_algo.compute_loss(anchor_objectness_losses0, anchor_transformer_losses0, proposal_class_losses0, proposal_transformer_losses0)\n loss1 = attack_algo.compute_loss(anchor_objectness_losses1, anchor_transformer_losses1, proposal_class_losses1, proposal_transformer_losses1)\n loss2 = attack_algo.compute_loss(anchor_objectness_losses2, anchor_transformer_losses2, proposal_class_losses2, proposal_transformer_losses2)\n loss3 = attack_algo.compute_loss(anchor_objectness_losses3, anchor_transformer_losses3, proposal_class_losses3, proposal_transformer_losses3)\n loss4 = attack_algo.compute_loss(anchor_objectness_losses4, anchor_transformer_losses4, proposal_class_losses4, proposal_transformer_losses4)\n loss5 = attack_algo.compute_loss(anchor_objectness_losses5, anchor_transformer_losses5, proposal_class_losses5, proposal_transformer_losses5)\n loss6 = attack_algo.compute_loss(anchor_objectness_losses6, anchor_transformer_losses6, proposal_class_losses6, proposal_transformer_losses6)\n \n # loss = ((loss0 + loss1 + loss2 + loss3 + loss4 ) / 6.0) * (1 - args.sd_adv_loss_weight) + (loss5 / 6.0) * args.sd_adv_loss_weight\n ''' 59.03\n clean_loss = ((loss0 + loss1 + loss2 + loss3 + loss4 ) / 3.0) * (1 - args.sd_adv_loss_weight) + (loss5 / 3.0) * args.sd_adv_loss_weight\n loss = 0.5 * clean_loss + 0.5 * loss6\n '''\n clean_loss = ((loss0 + loss1 + loss2 + loss3 + loss4 ) / 3.0) * (1 - args.sd_adv_loss_weight) + (loss5 / 3.0) * args.sd_adv_loss_weight\n loss = 0.5 * clean_loss + 0.5 * loss6\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n scheduler.step()\n losses.append(loss.item())\n summary_writer.add_scalar('train/loss', loss.item(), step)\n step += 1\n\n if step == num_steps_to_finish:\n should_stop = True\n\n if step % num_steps_to_display == 0:\n elapsed_time = time.time() - time_checkpoint\n time_checkpoint = time.time()\n steps_per_sec = num_steps_to_display / elapsed_time\n samples_per_sec = batch_size * steps_per_sec\n eta = (num_steps_to_finish - step) / steps_per_sec / 3600\n avg_loss = sum(losses) / len(losses)\n lr = scheduler.get_lr()[0]\n Log.i(f'[Step {step}] Avg. Loss = {avg_loss:.6f}, LR = {lr:.8f} ({samples_per_sec:.2f} samples/sec; ETA {eta:.1f} hrs)')\n\n if step % num_steps_to_snapshot == 0 or should_stop:\n path_to_checkpoint = model.module.save(path_to_checkpoints_dir, step, optimizer, scheduler)\n Log.i(f'Model has been saved to {path_to_checkpoint}')\n\n if should_stop:\n break\n\n Log.i('Done')\n print(\"=\" * 100)\n print(\"FINISL!\")\n print(\"=\" * 100)\n\n\nif __name__ == '__main__':\n def main():\n parser = argparse.ArgumentParser()\n # se settings\n parser.add_argument('--steps', default=1, type=int, help='PGD-steps')\n parser.add_argument('--steps_advt', default=1, type=int, help='PGD-steps')\n parser.add_argument('--pertub_idx_se', help='index of perturb layers', default=None, type=int)\n parser.add_argument('--pertub_idx_sd', help='index of perturb layers', default='roi', type=str)\n\n parser.add_argument('--gamma_se', help='index of PGD gamma', default=0.5, type=float)\n parser.add_argument('--gamma_sd', help='index of PGD gamma', default=0.1, type=float)\n parser.add_argument('--gamma_advt', help='index of PGD gamma', default=0.1, type=float)\n parser.add_argument('--eps', default=2, type=float)\n parser.add_argument('--eps_advt', default=2, type=float)\n\n parser.add_argument('--randinit', action=\"store_true\", help=\"whether using apex\")\n parser.add_argument('--clip', action=\"store_true\", help=\"whether using apex\")\n parser.add_argument('--randinit_advt', action=\"store_true\", help=\"whether using apex\")\n parser.add_argument('--clip_advt', action=\"store_true\", help=\"whether using apex\")\n\n parser.add_argument('--mix_layer', type=str, help=\"\")\n # sd settings\n parser.add_argument('--noise_sd', help='if use noise', default=0, type=float)\n parser.add_argument('--only_roi_sd', action=\"store_true\", help=\"whether only using roi loss\")\n parser.add_argument('--mix_sd', action=\"store_true\", help=\"whether using mix\")\n parser.add_argument('--sd_adv_loss_weight', help='loss', default=0.5, type=float)\n\n parser.add_argument('-s', '--dataset', type=str, choices=DatasetBase.OPTIONS, required=True, help='name of dataset')\n parser.add_argument('-b', '--backbone', type=str, choices=BackboneBase.OPTIONS, required=True, help='name of backbone model')\n parser.add_argument('-d', '--data_dir', type=str, default='./data', help='path to data directory')\n parser.add_argument('-o', '--outputs_dir', type=str, default='./outputs', help='path to outputs directory')\n parser.add_argument('-r', '--resume_checkpoint', type=str, help='path to resuming checkpoint')\n\n parser.add_argument('--image_min_side', type=float, help='default: {:g}'.format(Config.IMAGE_MIN_SIDE))\n parser.add_argument('--image_max_side', type=float, help='default: {:g}'.format(Config.IMAGE_MAX_SIDE))\n parser.add_argument('--anchor_ratios', type=str, help='default: \"{!s}\"'.format(Config.ANCHOR_RATIOS))\n parser.add_argument('--anchor_sizes', type=str, help='default: \"{!s}\"'.format(Config.ANCHOR_SIZES))\n parser.add_argument('--pooler_mode', type=str, choices=Pooler.OPTIONS, help='default: {.value:s}'.format(Config.POOLER_MODE))\n parser.add_argument('--rpn_pre_nms_top_n', type=int, help='default: {:d}'.format(Config.RPN_PRE_NMS_TOP_N))\n parser.add_argument('--rpn_post_nms_top_n', type=int, help='default: {:d}'.format(Config.RPN_POST_NMS_TOP_N))\n parser.add_argument('--anchor_smooth_l1_loss_beta', type=float, help='default: {:g}'.format(Config.ANCHOR_SMOOTH_L1_LOSS_BETA))\n parser.add_argument('--proposal_smooth_l1_loss_beta', type=float, help='default: {:g}'.format(Config.PROPOSAL_SMOOTH_L1_LOSS_BETA))\n parser.add_argument('--batch_size', type=int, help='default: {:g}'.format(Config.BATCH_SIZE))\n parser.add_argument('--learning_rate', type=float, help='default: {:g}'.format(Config.LEARNING_RATE))\n parser.add_argument('--momentum', type=float, help='default: {:g}'.format(Config.MOMENTUM))\n parser.add_argument('--weight_decay', type=float, help='default: {:g}'.format(Config.WEIGHT_DECAY))\n parser.add_argument('--step_lr_sizes', type=str, help='default: {!s}'.format(Config.STEP_LR_SIZES))\n parser.add_argument('--step_lr_gamma', type=float, help='default: {:g}'.format(Config.STEP_LR_GAMMA))\n parser.add_argument('--warm_up_factor', type=float, help='default: {:g}'.format(Config.WARM_UP_FACTOR))\n parser.add_argument('--warm_up_num_iters', type=int, help='default: {:d}'.format(Config.WARM_UP_NUM_ITERS))\n parser.add_argument('--num_steps_to_display', type=int, help='default: {:d}'.format(Config.NUM_STEPS_TO_DISPLAY))\n parser.add_argument('--num_steps_to_snapshot', type=int, help='default: {:d}'.format(Config.NUM_STEPS_TO_SNAPSHOT))\n parser.add_argument('--num_steps_to_finish', type=int, help='default: {:d}'.format(Config.NUM_STEPS_TO_FINISH))\n args = parser.parse_args()\n attack_algo.print_args(args, 100)\n \n dataset_name = args.dataset\n backbone_name = args.backbone\n\n exp_name = \"s\" + str(args.steps) + \"se_\" + str(args.pertub_idx_se) + \"_sd_\" + str(args.pertub_idx_sd) + \"_g\" + str(args.gamma_se) + \"e\" + str(args.eps) + \"_MIX\" + args.mix_layer\n if args.randinit: exp_name += \"_rand\"\n if args.clip: exp_name += \"_clip\"\n \n path_to_data_dir = args.data_dir\n path_to_outputs_dir = args.outputs_dir\n path_to_resuming_checkpoint = args.resume_checkpoint\n\n path_to_checkpoints_dir = os.path.join(path_to_outputs_dir, 'ckpt-{:s}-{:s}-{:s}'\n .format(exp_name, dataset_name, backbone_name))\n if not os.path.exists(path_to_checkpoints_dir):\n print(\"create dir:[{}]\".format(path_to_checkpoints_dir))\n os.makedirs(path_to_checkpoints_dir)\n\n Config.setup(image_min_side=args.image_min_side, image_max_side=args.image_max_side,\n anchor_ratios=args.anchor_ratios, anchor_sizes=args.anchor_sizes, pooler_mode=args.pooler_mode,\n rpn_pre_nms_top_n=args.rpn_pre_nms_top_n, rpn_post_nms_top_n=args.rpn_post_nms_top_n,\n anchor_smooth_l1_loss_beta=args.anchor_smooth_l1_loss_beta, proposal_smooth_l1_loss_beta=args.proposal_smooth_l1_loss_beta,\n batch_size=args.batch_size, learning_rate=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay,\n step_lr_sizes=args.step_lr_sizes, step_lr_gamma=args.step_lr_gamma,\n warm_up_factor=args.warm_up_factor, warm_up_num_iters=args.warm_up_num_iters,\n num_steps_to_display=args.num_steps_to_display, num_steps_to_snapshot=args.num_steps_to_snapshot, num_steps_to_finish=args.num_steps_to_finish)\n\n Log.initialize(os.path.join(path_to_checkpoints_dir, 'train.log'))\n Log.i('Arguments:')\n for k, v in vars(args).items():\n Log.i(f'\\t{k} = {v}')\n Log.i(Config.describe())\n print(\"-\" * 100)\n print(\"INFO: PID : [{}]\".format(os.getpid()))\n\n print(\"EXP: [SE + SAT + MIX + SD] Dataset: [{}]\".format(args.dataset))\n print(\"SE : Layer:[{}] MIX:[{}] Gamma:[{}] Eps:[{}] Randinit:[{}] Clip:[{}]\"\n .format( args.pertub_idx_se, args.mix_layer, args.gamma_se, args.eps, args.randinit, args.clip))\n print(\"SD : Layer:[{}] MIX:[{}] Gamma:[{}] AdvWeight:[{}] Noise:[{}] ROI:[{}]\"\n .format(args.pertub_idx_sd, args.mix_sd, args.gamma_sd, args.sd_adv_loss_weight, args.noise_sd, args.only_roi_sd))\n\n print(\"DIR:[{}]\".format(path_to_checkpoints_dir))\n print(\"-\" * 100)\n _train(dataset_name, backbone_name, path_to_data_dir, path_to_checkpoints_dir, path_to_resuming_checkpoint, args)\n\n main()\n",
"import network\nimport utils\nimport os\nimport random\nimport args\nimport numpy as np\nimport time\nfrom torch.utils import data\nfrom metrics import StreamSegMetrics\n\nimport torch\nimport torch.nn as nn\nfrom utils.visualizer import Visualizer\nfrom torch.utils.tensorboard import SummaryWriter\nfrom PIL import Image\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport attack_algo\nimport pdb\n\ndef main():\n\n opts = args.get_argparser().parse_args()\n args.print_args(opts)\n\n if opts.dataset.lower() == 'voc':\n opts.num_classes = 21\n elif opts.dataset.lower() == 'cityscapes':\n opts.num_classes = 19\n\n # Setup visualization\n vis = Visualizer(port=opts.vis_port,\n env=opts.vis_env) if opts.enable_vis else None\n if vis is not None: # display options\n vis.vis_table(\"Options\", vars(opts))\n\n os.environ['CUDA_VISIBLE_DEVICES'] = opts.gpu_id\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n print(\"Device: %s\" % device)\n\n # Setup random seed\n torch.manual_seed(opts.random_seed)\n np.random.seed(opts.random_seed)\n random.seed(opts.random_seed)\n\n # Setup dataloader\n if opts.dataset=='voc' and not opts.crop_val:\n opts.val_batch_size = 1\n \n train_dst, val_dst = args.get_dataset(opts)\n \n train_loader = data.DataLoader(\n train_dst, batch_size=opts.batch_size, shuffle=True, num_workers=2)\n val_loader = data.DataLoader(\n val_dst, batch_size=opts.val_batch_size, shuffle=True, num_workers=2)\n print(\"Dataset: %s, Train set: %d, Val set: %d\" %\n (opts.dataset, len(train_dst), len(val_dst)))\n\n # Set up model\n model_map = {\n 'deeplabv3_resnet50': network.deeplabv3_resnet50,\n 'deeplabv3plus_resnet50': network.deeplabv3plus_resnet50,\n 'deeplabv3_resnet101': network.deeplabv3_resnet101,\n 'deeplabv3plus_resnet101': network.deeplabv3plus_resnet101,\n 'deeplabv3_mobilenet': network.deeplabv3_mobilenet,\n 'deeplabv3plus_mobilenet': network.deeplabv3plus_mobilenet\n }\n\n model = model_map[opts.model](num_classes=opts.num_classes, output_stride=opts.output_stride)\n if opts.separable_conv and 'plus' in opts.model:\n network.convert_to_separable_conv(model.classifier)\n utils.set_bn_momentum(model.backbone, momentum=0.01)\n # Set up metrics\n metrics = StreamSegMetrics(opts.num_classes)\n # Set up optimizer\n optimizer = torch.optim.SGD(params=[\n {'params': model.backbone.parameters(), 'lr': 0.1*opts.lr},\n {'params': model.classifier.parameters(), 'lr': opts.lr},\n ], lr=opts.lr, momentum=0.9, weight_decay=opts.weight_decay)\n #optimizer = torch.optim.SGD(params=model.parameters(), lr=opts.lr, momentum=0.9, weight_decay=opts.weight_decay)\n #torch.optim.lr_scheduler.StepLR(optimizer, step_size=opts.lr_decay_step, gamma=opts.lr_decay_factor)\n if opts.lr_policy=='poly':\n scheduler = utils.PolyLR(optimizer, opts.total_itrs, power=0.9)\n elif opts.lr_policy=='step':\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=opts.step_size, gamma=0.1)\n\n # Set up criterion\n #criterion = utils.get_loss(opts.loss_type)\n if opts.loss_type == 'focal_loss':\n criterion = utils.FocalLoss(ignore_index=255, size_average=True)\n elif opts.loss_type == 'cross_entropy':\n criterion = nn.CrossEntropyLoss(ignore_index=255, reduction='mean')\n \n def save_ckpt(path):\n \"\"\" save current model\n \"\"\"\n torch.save({\n \"cur_itrs\": cur_itrs,\n \"model_state\": model.module.state_dict(),\n \"optimizer_state\": optimizer.state_dict(),\n \"scheduler_state\": scheduler.state_dict(),\n \"best_score\": best_score,\n }, path)\n print(\"Model saved as %s\" % path)\n\n writer = SummaryWriter(log_dir='runs/' + opts.exp)\n utils.mkdir('adv_training/' + opts.exp)\n # Restore\n best_score = 0.0\n cur_itrs = 0\n cur_epochs = 0\n if opts.ckpt is not None and os.path.isfile(opts.ckpt):\n # https://github.com/VainF/DeepLabV3Plus-Pytorch/issues/8#issuecomment-605601402, @PytaichukBohdan\n checkpoint = torch.load(opts.ckpt, map_location=torch.device('cpu'))\n model.load_state_dict(checkpoint[\"model_state\"])\n model = nn.DataParallel(model)\n model.to(device)\n if opts.continue_training:\n optimizer.load_state_dict(checkpoint[\"optimizer_state\"])\n scheduler.load_state_dict(checkpoint[\"scheduler_state\"])\n cur_itrs = checkpoint[\"cur_itrs\"]\n best_score = checkpoint['best_score']\n print(\"Training state restored from %s\" % opts.ckpt)\n print(\"Model restored from %s\" % opts.ckpt)\n del checkpoint # free memory\n else:\n print(\"[!] Retrain\")\n model = nn.DataParallel(model)\n model.to(device)\n\n #========== Train Loop ==========#\n vis_sample_id = np.random.randint(0, len(val_loader), opts.vis_num_samples,\n np.int32) if opts.enable_vis else None # sample idxs for visualization\n denorm = utils.Denormalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # denormalization for ori images\n\n if opts.test_only != \"\":\n \n print(\"Test Clean baseline:[{}]\".format(opts.test_only))\n checkpoint = torch.load(opts.test_only, map_location=torch.device('cpu'))[\"model_state\"]\n model_state_dict = model.module.state_dict()\n overlap_dict = {k : v for k, v in checkpoint.items() if k in model_state_dict.keys()}\n model_state_dict.update(overlap_dict)\n model.module.load_state_dict(model_state_dict)\n print(\"Overlap:[{}/{}]\".format(len(overlap_dict.keys()), len(model_state_dict.keys())))\n model.eval()\n val_score, ret_samples = args.validate(\n opts=opts, model=model, loader=val_loader, device=device, metrics=metrics, ret_samples_ids=vis_sample_id)\n print(metrics.to_str(val_score))\n return\n\n if opts.eval_pgd != \"\":\n\n print(\"Test Attack :[{}]\".format(opts.eval_pgd))\n print(\"Attack Settings: Step[{}] Gamma[{}] Eps[{}] Randinit[{}] Clip[{}]\"\n .format(opts.steps_pgd, opts.gamma_pgd, opts.eps_pgd, opts.randinit_pgd, opts.clip_pgd))\n checkpoint = torch.load(opts.eval_pgd, map_location=torch.device('cpu'))[\"model_state\"]\n model_state_dict = model.module.state_dict()\n overlap_dict = {k : v for k, v in checkpoint.items() if k in model_state_dict.keys()}\n model_state_dict.update(overlap_dict)\n model.module.load_state_dict(model_state_dict)\n print(\"Overlap:[{}/{}]\".format(len(overlap_dict.keys()), len(model_state_dict.keys())))\n model.eval()\n val_score, ret_samples = args.pgd_validate(\n opts=opts, model=model, loader=val_loader, device=device, metrics=metrics, criterion=criterion, ret_samples_ids=vis_sample_id)\n print(\"Attack Settings: Step[{}] Gamma[{}] Eps[{}] Randinit[{}] Clip[{}]\"\n .format(opts.steps_pgd, opts.gamma_pgd, opts.eps_pgd, opts.randinit_pgd, opts.clip_pgd))\n print(metrics.to_str(val_score))\n return\n\n interval_loss = 0\n total_time = 0\n while True: #cur_itrs < opts.total_itrs:\n # ===== Train =====\n model.train()\n cur_epochs += 1\n for (images, labels) in train_loader:\n \n t0 = time.time()\n cur_itrs += 1\n \n images = images.to(device, dtype=torch.float32)\n labels = labels.to(device, dtype=torch.long)\n \n if images.shape[0] != 4: continue\n adv_images = attack_algo.adv_input(\n x = images, \n criterion = criterion,\n y = labels,\n model= model,\n steps = opts.steps_pgd,\n eps = (opts.eps_pgd / 255), \n gamma = (opts.gamma_pgd / 255),\n randinit = opts.randinit_pgd,\n clip = opts.clip_pgd)\n \n adv_input_dict = {'x': adv_images, \"adv\": None, 'out_idx': 0, 'flag':'clean'}\n\n optimizer.zero_grad()\n output = model(adv_input_dict)\n loss = criterion(output, labels)\n loss.backward()\n optimizer.step()\n\n np_loss = loss.detach().cpu().numpy()\n interval_loss += np_loss\n if vis is not None:\n vis.vis_scalar('Loss', cur_itrs, np_loss)\n\n if (cur_itrs) % 10 == 0:\n interval_loss = interval_loss / 10\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' | ' + \n \"Epoch:[{}], Itrs:[{}/{}], Loss:[{:.4f}], Time:[{:.4f} min], Best IOU:[{:.4f}]\"\n .format(cur_epochs, cur_itrs, int(opts.total_itrs), interval_loss, total_time / 60, best_score))\n writer.add_scalar('Loss/train', interval_loss, cur_itrs)\n interval_loss = 0.0\n total_time = 0.0\n\n if (cur_itrs) % opts.val_interval == 0 and cur_itrs >= opts.total_itrs / 2:\n save_ckpt('adv_training/' + opts.exp + '/latest_%s_%s_os%d.pth' %\n (opts.model, opts.dataset, opts.output_stride))\n print(\"validation...\")\n model.eval()\n val_score, ret_samples = args.validate(\n opts=opts, model=model, loader=val_loader, device=device, metrics=metrics, ret_samples_ids=vis_sample_id)\n print(metrics.to_str(val_score))\n\n writer.add_scalar('mIOU/test', val_score['Mean IoU'], cur_itrs)\n\n if val_score['Mean IoU'] > best_score: # save best model\n best_score = val_score['Mean IoU']\n save_ckpt('adv_training/' + opts.exp +'/best_%s_%s_os%d.pth' %\n (opts.model, opts.dataset, opts.output_stride))\n\n if vis is not None: # visualize validation score and samples\n vis.vis_scalar(\"[Val] Overall Acc\", cur_itrs, val_score['Overall Acc'])\n vis.vis_scalar(\"[Val] Mean IoU\", cur_itrs, val_score['Mean IoU'])\n vis.vis_table(\"[Val] Class IoU\", val_score['Class IoU'])\n\n for k, (img, target, lbl) in enumerate(ret_samples):\n img = (denorm(img) * 255).astype(np.uint8)\n target = train_dst.decode_target(target).transpose(2, 0, 1).astype(np.uint8)\n lbl = train_dst.decode_target(lbl).transpose(2, 0, 1).astype(np.uint8)\n concat_img = np.concatenate((img, target, lbl), axis=2) # concat along width\n vis.vis_image('Sample %d' % k, concat_img)\n model.train()\n\n scheduler.step() \n t1 = time.time() \n total_time += t1 - t0\n\n if cur_itrs >= opts.total_itrs:\n print(\"Final Best mIOU:[{:.4f}]\".format(best_score))\n writer.close()\n return\n\n \nif __name__ == '__main__':\n main()\n",
"import argparse\nimport os\nimport time\nimport uuid\nfrom collections import deque\nfrom typing import Optional\n\nimport torch\nimport torch.nn as nn\nfrom tensorboardX import SummaryWriter\nfrom torch import optim\nfrom torch.utils.data import DataLoader\n\nfrom backbone.base import Base as BackboneBase\nfrom config.train_config import TrainConfig as Config\nfrom dataset.base import Base as DatasetBase\nfrom extension.lr_scheduler import WarmUpMultiStepLR\nfrom logger import Logger as Log\nfrom model import Model\n# from model_advlayer4 import Model\nfrom roi.pooler import Pooler\nfrom attack_algo import *\nimport attack_algo\nimport pdb\n\ndef _train(dataset_name: str, backbone_name: str, path_to_data_dir: str, path_to_checkpoints_dir: str, path_to_resuming_checkpoint: Optional[str], args):\n print(\"DATASET:[{}] DIR:[{}]\".format(dataset_name, path_to_data_dir))\n dataset = DatasetBase.from_name(dataset_name)(path_to_data_dir, DatasetBase.Mode.TRAIN, Config.IMAGE_MIN_SIDE, Config.IMAGE_MAX_SIDE)\n dataloader = DataLoader(dataset, batch_size=Config.BATCH_SIZE,\n sampler=DatasetBase.NearestRatioRandomSampler(dataset.image_ratios, num_neighbors=Config.BATCH_SIZE),\n num_workers=8, collate_fn=DatasetBase.padding_collate_fn, pin_memory=True)\n\n Log.i('Found {:d} samples'.format(len(dataset)))\n\n backbone = BackboneBase.from_name(backbone_name)(pretrained=True)\n model = nn.DataParallel(\n Model(\n backbone, dataset.num_classes(), pooler_mode=Config.POOLER_MODE,\n anchor_ratios=Config.ANCHOR_RATIOS, anchor_sizes=Config.ANCHOR_SIZES,\n rpn_pre_nms_top_n=Config.RPN_PRE_NMS_TOP_N, rpn_post_nms_top_n=Config.RPN_POST_NMS_TOP_N,\n anchor_smooth_l1_loss_beta=Config.ANCHOR_SMOOTH_L1_LOSS_BETA, proposal_smooth_l1_loss_beta=Config.PROPOSAL_SMOOTH_L1_LOSS_BETA\n ).cuda()\n )\n \n optimizer = optim.SGD(model.parameters(), lr=Config.LEARNING_RATE,\n momentum=Config.MOMENTUM, weight_decay=Config.WEIGHT_DECAY)\n scheduler = WarmUpMultiStepLR(optimizer, milestones=Config.STEP_LR_SIZES, gamma=Config.STEP_LR_GAMMA,\n factor=Config.WARM_UP_FACTOR, num_iters=Config.WARM_UP_NUM_ITERS)\n step = 0\n time_checkpoint = time.time()\n losses = deque(maxlen=100)\n summary_writer = SummaryWriter(os.path.join(path_to_checkpoints_dir, 'summaries'))\n should_stop = False\n\n num_steps_to_display = Config.NUM_STEPS_TO_DISPLAY\n num_steps_to_snapshot = Config.NUM_STEPS_TO_SNAPSHOT\n num_steps_to_finish = Config.NUM_STEPS_TO_FINISH\n\n if path_to_resuming_checkpoint is not None:\n step = model.module.load(path_to_resuming_checkpoint, optimizer, scheduler)\n Log.i(f'Model has been restored from file: {path_to_resuming_checkpoint}')\n\n device_count = torch.cuda.device_count()\n assert Config.BATCH_SIZE % device_count == 0, 'The batch size is not divisible by the device count'\n Log.i('Start training with {:d} GPUs ({:d} batches per GPU)'.format(torch.cuda.device_count(),\n Config.BATCH_SIZE // torch.cuda.device_count()))\n\n while not should_stop:\n for _, (_, image_batch, _, bboxes_batch, labels_batch) in enumerate(dataloader):\n\n batch_size = image_batch.shape[0]\n image_batch = image_batch.cuda()\n bboxes_batch = bboxes_batch.cuda()\n labels_batch = labels_batch.cuda()\n y = {'bb':bboxes_batch, 'lb': labels_batch}\n \n # adv input\n adv_image_batch = attack_algo.adv_input(x=image_batch, y=y, model=model, steps=5, eps=(2.0 / 255), gamma=(0.3 / 255), randinit=True, clip=True)\n \n inputs_all1 = {\"x\": image_batch, \"adv\": None, \"out_idx\": 1, \"flag\": 'head'}\n inputs_all2 = {\"x\": image_batch, \"adv\": None, \"out_idx\": 2, \"flag\": 'head'}\n inputs_all3 = {\"x\": image_batch, \"adv\": None, \"out_idx\": 3, \"flag\": 'head'}\n inputs_all_sd = {\"x\": image_batch, \"adv\": None, \"out_idx\": 'roi_head', \"flag\": 'clean'}\n \n feature_map1 = model.train().forward(inputs_all1, bboxes_batch, labels_batch).detach()\n feature_map2 = model.train().forward(inputs_all2, bboxes_batch, labels_batch).detach()\n feature_map3 = model.train().forward(inputs_all3, bboxes_batch, labels_batch).detach()\n rpn_roi_output_dict = model.train().forward(inputs_all_sd, bboxes_batch, labels_batch)\n clean_feature_map_sd = rpn_roi_output_dict['roi_output_dict']['roi_feature_map'].detach()\n\n feature_adv1 = attack_algo.PGD(feature_map1, image_batch, y=y, model=model, steps=1, eps=(0.1 / 255), gamma=(0.001 / 255), idx=1)\n feature_adv2 = attack_algo.PGD(feature_map2, image_batch, y=y, model=model, steps=1, eps=(0.1 / 255), gamma=(0.001 / 255), idx=2)\n feature_adv3 = attack_algo.PGD(feature_map3, image_batch, y=y, model=model, steps=1, eps=(2.0 / 255), gamma=(1.0 / 255), idx=3)\n \n adv_list = attack_algo.get_sample_points(feature_map3, feature_adv3, 5)\n adv_list[1] = attack_algo.mix_feature(feature_map3, adv_list[1])\n adv_list[2] = attack_algo.mix_feature(feature_map3, adv_list[2])\n\n adv_rpn_roi_output_dict = attack_algo.rpn_roi_PGD(rpn_roi_output_dict=rpn_roi_output_dict, y=y,\n model= model, steps = 1, eps = (2.0 / 255), gamma = (0.2 / 255), only_roi_loss=False)\n \n adv_feature_map_sd = adv_rpn_roi_output_dict['roi_output_dict']['roi_feature_map'].detach()\n adv_feature_map_sd = attack_algo.mix_feature(clean_feature_map_sd, adv_feature_map_sd)\n adv_rpn_roi_output_dict['roi_output_dict']['roi_feature_map'] = adv_feature_map_sd\n\n advt_input_dict = {'x': adv_image_batch, \"adv\": None, 'out_idx': 0, 'flag':'clean'}\n adv_input_dict1 = {'x': image_batch, 'adv': feature_adv1, 'out_idx': 1, 'flag':'tail' }\n adv_input_dict2 = {'x': image_batch, 'adv': feature_adv2, 'out_idx': 2, 'flag':'tail' }\n adv_input_dict31 = {'x': image_batch, 'adv': adv_list[1], 'out_idx': 3, 'flag':'tail' }\n adv_input_dict32 = {'x': image_batch, 'adv': adv_list[2], 'out_idx': 3, 'flag':'tail' }\n adv_input_dict33 = {'x': image_batch, 'adv': adv_list[3], 'out_idx': 3, 'flag':'tail' }\n adv_input_dict34 = {'x': image_batch, 'adv': adv_list[4], 'out_idx': 3, 'flag':'tail' }\n adv_input_dict_sd = {'adv': adv_rpn_roi_output_dict,'out_idx': 'roi_tail','flag':'clean'}\n \n # advt\n anchor_objectness_losses0, anchor_transformer_losses0, proposal_class_losses0, proposal_transformer_losses0 = \\\n model.train().forward(advt_input_dict, bboxes_batch, labels_batch)\n # muti\n anchor_objectness_losses1, anchor_transformer_losses1, proposal_class_losses1, proposal_transformer_losses1 = \\\n model.train().forward(adv_input_dict1, bboxes_batch, labels_batch)\n anchor_objectness_losses2, anchor_transformer_losses2, proposal_class_losses2, proposal_transformer_losses2 = \\\n model.train().forward(adv_input_dict2, bboxes_batch, labels_batch)\n # sat\n anchor_objectness_losses3, anchor_transformer_losses3, proposal_class_losses3, proposal_transformer_losses3 = \\\n model.train().forward(adv_input_dict31, bboxes_batch, labels_batch)\n anchor_objectness_losses4, anchor_transformer_losses4, proposal_class_losses4, proposal_transformer_losses4 = \\\n model.train().forward(adv_input_dict32, bboxes_batch, labels_batch)\n anchor_objectness_losses5, anchor_transformer_losses5, proposal_class_losses5, proposal_transformer_losses5 = \\\n model.train().forward(adv_input_dict33, bboxes_batch, labels_batch)\n anchor_objectness_losses6, anchor_transformer_losses6, proposal_class_losses6, proposal_transformer_losses6 = \\\n model.train().forward(adv_input_dict34, bboxes_batch, labels_batch)\n # sd\n anchor_objectness_losses7, anchor_transformer_losses7, proposal_class_losses7, proposal_transformer_losses7 = \\\n model.train().forward(adv_input_dict_sd, bboxes_batch, labels_batch)\n \n # advt\n loss0 = attack_algo.compute_loss(anchor_objectness_losses0, anchor_transformer_losses0, proposal_class_losses0, proposal_transformer_losses0)\n # muti\n loss1 = attack_algo.compute_loss(anchor_objectness_losses1, anchor_transformer_losses1, proposal_class_losses1, proposal_transformer_losses1)\n loss2 = attack_algo.compute_loss(anchor_objectness_losses2, anchor_transformer_losses2, proposal_class_losses2, proposal_transformer_losses2)\n # sat\n loss3 = attack_algo.compute_loss(anchor_objectness_losses3, anchor_transformer_losses3, proposal_class_losses3, proposal_transformer_losses3)\n loss4 = attack_algo.compute_loss(anchor_objectness_losses4, anchor_transformer_losses4, proposal_class_losses4, proposal_transformer_losses4)\n loss5 = attack_algo.compute_loss(anchor_objectness_losses5, anchor_transformer_losses5, proposal_class_losses5, proposal_transformer_losses5)\n loss6 = attack_algo.compute_loss(anchor_objectness_losses6, anchor_transformer_losses6, proposal_class_losses6, proposal_transformer_losses6)\n # sd\n loss7 = attack_algo.compute_loss(anchor_objectness_losses7, anchor_transformer_losses7, proposal_class_losses7, proposal_transformer_losses7)\n loss_clean_adv = 0.9 * (0.2333 * (loss0 + loss3 + loss4 + loss5 + loss6) + 0.1 * loss7) + 0.05 * (loss1 + loss2)\n\n if args.loss_settings == 1:\n # setting 1: total our adv loss\n loss = loss_clean_adv\n elif args.loss_settings == 2:\n # setting 2: 0.9 total our adv loss + 0.1 adv loss\n loss = 0.9 * loss_clean_adv + 0.1 * loss0\n elif args.loss_settings == 3:\n # setting 3: 0.8 total our adv loss + 0.2 adv loss\n loss = 0.7 * loss_clean_adv + 0.3 * loss0\n elif args.loss_settings == 4:\n # setting 3: 0.7 clean + 0.3 adv\n loss = 0.5 * loss_clean_adv + 0.5 * loss0\n else: assert False\n\n\n # if args.loss_settings == 1:\n # # setting 1: 0.5 clean + 0.5 adv\n # loss = 0.5 * loss_clean + 0.5 * loss_advt\n # elif args.loss_settings == 2:\n # # setting 2: 0.6 clean + 0.4 adv\n # loss = 0.6 * loss_clean + 0.4 * loss_advt\n # elif args.loss_settings == 3:\n # # setting 3: 0.4 clean + 0.6 adv\n # loss = 0.4 * loss_clean + 0.6 * loss_advt\n # elif args.loss_settings == 4:\n # # setting 3: 0.7 clean + 0.3 adv\n # loss = 0.7 * loss_clean + 0.3 * loss_advt\n # else: assert False\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n scheduler.step()\n losses.append(loss.item())\n\n summary_writer.add_scalar('train/loss', loss.item(), step)\n step += 1\n\n if step == num_steps_to_finish:\n should_stop = True\n\n if step % num_steps_to_display == 0:\n elapsed_time = time.time() - time_checkpoint\n time_checkpoint = time.time()\n steps_per_sec = num_steps_to_display / elapsed_time\n samples_per_sec = batch_size * steps_per_sec\n eta = (num_steps_to_finish - step) / steps_per_sec / 3600\n avg_loss = sum(losses) / len(losses)\n lr = scheduler.get_lr()[0]\n Log.i(f'[Step {step}] Avg. Loss = {avg_loss:.6f}, LR = {lr:.8f} ({samples_per_sec:.2f} samples/sec; ETA {eta:.1f} hrs)')\n\n if step % num_steps_to_snapshot == 0 or should_stop:\n path_to_checkpoint = model.module.save(path_to_checkpoints_dir, step, optimizer, scheduler)\n Log.i(f'Model has been saved to {path_to_checkpoint}')\n\n if should_stop:\n break\n\n Log.i('Done')\n print(\"=\" * 100)\n print(\"FINISL!\")\n print(\"=\" * 100)\n\n\n\nif __name__ == '__main__':\n def main():\n parser = argparse.ArgumentParser()\n #PGD Setting \n parser.add_argument('--steps', default=1, type=int, help='PGD-steps')\n parser.add_argument('--pertub_idx', help='index of perturb layers', default=3, type=int)\n parser.add_argument('--gamma', help='index of PGD gamma', default=0.5, type=float)\n \n parser.add_argument('--eps', default=2, type=float)\n parser.add_argument('--randinit', action=\"store_true\", help=\"whether using apex\")\n parser.add_argument('--clip', action=\"store_true\", help=\"whether using apex\")\n\n parser.add_argument('--loss_settings', default=0, type=int, help='loss setting')\n parser.add_argument('-s', '--dataset', type=str, choices=DatasetBase.OPTIONS, required=True, help='name of dataset')\n parser.add_argument('-b', '--backbone', type=str, choices=BackboneBase.OPTIONS, required=True, help='name of backbone model')\n parser.add_argument('-d', '--data_dir', type=str, default='./data', help='path to data directory')\n parser.add_argument('-o', '--outputs_dir', type=str, default='./outputs', help='path to outputs directory')\n parser.add_argument('-r', '--resume_checkpoint', type=str, help='path to resuming checkpoint')\n parser.add_argument('--image_min_side', type=float, help='default: {:g}'.format(Config.IMAGE_MIN_SIDE))\n parser.add_argument('--image_max_side', type=float, help='default: {:g}'.format(Config.IMAGE_MAX_SIDE))\n parser.add_argument('--anchor_ratios', type=str, help='default: \"{!s}\"'.format(Config.ANCHOR_RATIOS))\n parser.add_argument('--anchor_sizes', type=str, help='default: \"{!s}\"'.format(Config.ANCHOR_SIZES))\n parser.add_argument('--pooler_mode', type=str, choices=Pooler.OPTIONS, help='default: {.value:s}'.format(Config.POOLER_MODE))\n parser.add_argument('--rpn_pre_nms_top_n', type=int, help='default: {:d}'.format(Config.RPN_PRE_NMS_TOP_N))\n parser.add_argument('--rpn_post_nms_top_n', type=int, help='default: {:d}'.format(Config.RPN_POST_NMS_TOP_N))\n parser.add_argument('--anchor_smooth_l1_loss_beta', type=float, help='default: {:g}'.format(Config.ANCHOR_SMOOTH_L1_LOSS_BETA))\n parser.add_argument('--proposal_smooth_l1_loss_beta', type=float, help='default: {:g}'.format(Config.PROPOSAL_SMOOTH_L1_LOSS_BETA))\n parser.add_argument('--batch_size', type=int, help='default: {:g}'.format(Config.BATCH_SIZE))\n parser.add_argument('--learning_rate', type=float, help='default: {:g}'.format(Config.LEARNING_RATE))\n parser.add_argument('--momentum', type=float, help='default: {:g}'.format(Config.MOMENTUM))\n parser.add_argument('--weight_decay', type=float, help='default: {:g}'.format(Config.WEIGHT_DECAY))\n parser.add_argument('--step_lr_sizes', type=str, help='default: {!s}'.format(Config.STEP_LR_SIZES))\n parser.add_argument('--step_lr_gamma', type=float, help='default: {:g}'.format(Config.STEP_LR_GAMMA))\n parser.add_argument('--warm_up_factor', type=float, help='default: {:g}'.format(Config.WARM_UP_FACTOR))\n parser.add_argument('--warm_up_num_iters', type=int, help='default: {:d}'.format(Config.WARM_UP_NUM_ITERS))\n parser.add_argument('--num_steps_to_display', type=int, help='default: {:d}'.format(Config.NUM_STEPS_TO_DISPLAY))\n parser.add_argument('--num_steps_to_snapshot', type=int, help='default: {:d}'.format(Config.NUM_STEPS_TO_SNAPSHOT))\n parser.add_argument('--num_steps_to_finish', type=int, help='default: {:d}'.format(Config.NUM_STEPS_TO_FINISH))\n args = parser.parse_args()\n print_args(args, 100)\n \n dataset_name = args.dataset\n backbone_name = args.backbone\n\n exp_name = \"s\" + str(args.steps) + \"p\" + str(args.pertub_idx) + \"g\" + str(args.gamma) + \"e\" + str(args.eps)\n if args.randinit: exp_name += \"_rand\"\n if args.clip: exp_name += \"_clip\"\n \n path_to_data_dir = args.data_dir\n path_to_outputs_dir = args.outputs_dir\n path_to_resuming_checkpoint = args.resume_checkpoint\n\n path_to_checkpoints_dir = os.path.join(path_to_outputs_dir, 'ckpt-{:s}-{:s}-{:s}'\n .format(exp_name, dataset_name, backbone_name))\n if not os.path.exists(path_to_checkpoints_dir):\n print(\"create dir:[{}]\".format(path_to_checkpoints_dir))\n os.makedirs(path_to_checkpoints_dir)\n\n Config.setup(image_min_side=args.image_min_side, image_max_side=args.image_max_side,\n anchor_ratios=args.anchor_ratios, anchor_sizes=args.anchor_sizes, pooler_mode=args.pooler_mode,\n rpn_pre_nms_top_n=args.rpn_pre_nms_top_n, rpn_post_nms_top_n=args.rpn_post_nms_top_n,\n anchor_smooth_l1_loss_beta=args.anchor_smooth_l1_loss_beta, proposal_smooth_l1_loss_beta=args.proposal_smooth_l1_loss_beta,\n batch_size=args.batch_size, learning_rate=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay,\n step_lr_sizes=args.step_lr_sizes, step_lr_gamma=args.step_lr_gamma,\n warm_up_factor=args.warm_up_factor, warm_up_num_iters=args.warm_up_num_iters,\n num_steps_to_display=args.num_steps_to_display, num_steps_to_snapshot=args.num_steps_to_snapshot, num_steps_to_finish=args.num_steps_to_finish)\n\n Log.initialize(os.path.join(path_to_checkpoints_dir, 'train.log'))\n Log.i('Arguments:')\n for k, v in vars(args).items():\n Log.i(f'\\t{k} = {v}')\n Log.i(Config.describe())\n print(\"-\" * 100)\n print(\"INFO: PID : [{}]\".format(os.getpid()))\n print(\"-\" * 100)\n _train(dataset_name, backbone_name, path_to_data_dir, path_to_checkpoints_dir, path_to_resuming_checkpoint, args)\n\n main()\n",
"import argparse\nimport os\nimport time\nimport uuid\nfrom collections import deque\nfrom typing import Optional\n\nimport torch\nimport torch.nn as nn\nfrom tensorboardX import SummaryWriter\nfrom torch import optim\nfrom torch.utils.data import DataLoader\n\nfrom backbone.base import Base as BackboneBase\nfrom config.train_config import TrainConfig as Config\nfrom dataset.base import Base as DatasetBase\nfrom extension.lr_scheduler import WarmUpMultiStepLR\nfrom logger import Logger as Log\nfrom model import Model\n# from model_advlayer4 import Model\nfrom roi.pooler import Pooler\nfrom attack_algo import *\nimport attack_algo\nimport pdb\n\ndef _train(dataset_name: str, backbone_name: str, path_to_data_dir: str, path_to_checkpoints_dir: str, path_to_resuming_checkpoint: Optional[str], args):\n print(\"DATASET:[{}] DIR:[{}]\".format(dataset_name, path_to_data_dir))\n dataset = DatasetBase.from_name(dataset_name)(path_to_data_dir, DatasetBase.Mode.TRAIN, Config.IMAGE_MIN_SIDE, Config.IMAGE_MAX_SIDE)\n dataloader = DataLoader(dataset, batch_size=Config.BATCH_SIZE,\n sampler=DatasetBase.NearestRatioRandomSampler(dataset.image_ratios, num_neighbors=Config.BATCH_SIZE),\n num_workers=8, collate_fn=DatasetBase.padding_collate_fn, pin_memory=True)\n\n Log.i('Found {:d} samples'.format(len(dataset)))\n\n backbone = BackboneBase.from_name(backbone_name)(pretrained=True)\n model = nn.DataParallel(\n Model(\n backbone, dataset.num_classes(), pooler_mode=Config.POOLER_MODE,\n anchor_ratios=Config.ANCHOR_RATIOS, anchor_sizes=Config.ANCHOR_SIZES,\n rpn_pre_nms_top_n=Config.RPN_PRE_NMS_TOP_N, rpn_post_nms_top_n=Config.RPN_POST_NMS_TOP_N,\n anchor_smooth_l1_loss_beta=Config.ANCHOR_SMOOTH_L1_LOSS_BETA, proposal_smooth_l1_loss_beta=Config.PROPOSAL_SMOOTH_L1_LOSS_BETA\n ).cuda()\n )\n \n optimizer = optim.SGD(model.parameters(), lr=Config.LEARNING_RATE,\n momentum=Config.MOMENTUM, weight_decay=Config.WEIGHT_DECAY)\n scheduler = WarmUpMultiStepLR(optimizer, milestones=Config.STEP_LR_SIZES, gamma=Config.STEP_LR_GAMMA,\n factor=Config.WARM_UP_FACTOR, num_iters=Config.WARM_UP_NUM_ITERS)\n step = 0\n time_checkpoint = time.time()\n losses = deque(maxlen=100)\n summary_writer = SummaryWriter(os.path.join(path_to_checkpoints_dir, 'summaries'))\n should_stop = False\n\n num_steps_to_display = Config.NUM_STEPS_TO_DISPLAY\n num_steps_to_snapshot = Config.NUM_STEPS_TO_SNAPSHOT\n num_steps_to_finish = Config.NUM_STEPS_TO_FINISH\n\n if path_to_resuming_checkpoint is not None:\n step = model.module.load(path_to_resuming_checkpoint, optimizer, scheduler)\n Log.i(f'Model has been restored from file: {path_to_resuming_checkpoint}')\n\n device_count = torch.cuda.device_count()\n assert Config.BATCH_SIZE % device_count == 0, 'The batch size is not divisible by the device count'\n Log.i('Start training with {:d} GPUs ({:d} batches per GPU)'.format(torch.cuda.device_count(),\n Config.BATCH_SIZE // torch.cuda.device_count()))\n\n while not should_stop:\n for _, (_, image_batch, _, bboxes_batch, labels_batch) in enumerate(dataloader):\n\n batch_size = image_batch.shape[0]\n image_batch = image_batch.cuda()\n bboxes_batch = bboxes_batch.cuda()\n labels_batch = labels_batch.cuda()\n y = {'bb':bboxes_batch, 'lb': labels_batch}\n\n inputs_all1 = {\"x\": image_batch, \"adv\": None, \"out_idx\": 1, \"flag\": 'head'}\n inputs_all2 = {\"x\": image_batch, \"adv\": None, \"out_idx\": 2, \"flag\": 'head'}\n inputs_all3 = {\"x\": image_batch, \"adv\": None, \"out_idx\": 3, \"flag\": 'head'}\n inputs_all_sd = {\"x\": image_batch, \"adv\": None, \"out_idx\": 'roi_head', \"flag\": 'clean'}\n \n feature_map1 = model.train().forward(inputs_all1, bboxes_batch, labels_batch).detach()\n feature_map2 = model.train().forward(inputs_all2, bboxes_batch, labels_batch).detach()\n feature_map3 = model.train().forward(inputs_all3, bboxes_batch, labels_batch).detach()\n rpn_roi_output_dict = model.train().forward(inputs_all_sd, bboxes_batch, labels_batch)\n clean_feature_map_sd = rpn_roi_output_dict['roi_output_dict']['roi_feature_map'].detach()\n\n feature_adv1 = attack_algo.PGD(feature_map1, image_batch, y=y, model=model, steps=1, eps=(0.1 / 255), gamma=(0.001 / 255), idx=1)\n feature_adv2 = attack_algo.PGD(feature_map2, image_batch, y=y, model=model, steps=1, eps=(2.0 / 255), gamma=(1.000 / 255), idx=2)\n feature_adv3 = attack_algo.PGD(feature_map3, image_batch, y=y, model=model, steps=1, eps=(0.1 / 255), gamma=(0.001 / 255), idx=3)\n \n adv_list = attack_algo.get_sample_points(feature_map2, feature_adv2, 5)\n adv_list[3] = attack_algo.mix_feature(feature_map2, adv_list[3])\n adv_list[4] = attack_algo.mix_feature(feature_map2, adv_list[4])\n\n adv_rpn_roi_output_dict = attack_algo.rpn_roi_PGD(rpn_roi_output_dict=rpn_roi_output_dict, y=y,\n model= model, steps = 1, eps = (2.0 / 255), gamma = (0.2 / 255), only_roi_loss=False)\n \n adv_feature_map_sd = adv_rpn_roi_output_dict['roi_output_dict']['roi_feature_map'].detach()\n adv_feature_map_sd = attack_algo.mix_feature(clean_feature_map_sd, adv_feature_map_sd)\n adv_rpn_roi_output_dict['roi_output_dict']['roi_feature_map'] = adv_feature_map_sd\n\n clean_input_dict = {'x': image_batch, \"adv\": None, 'out_idx': 0, 'flag':'clean'}\n adv_input_dict1 = {'x': image_batch, 'adv': feature_adv1, 'out_idx': 1, 'flag':'tail'}\n adv_input_dict21 = {'x': image_batch, 'adv': adv_list[1], 'out_idx': 2, 'flag':'tail'}\n adv_input_dict22 = {'x': image_batch, 'adv': adv_list[2], 'out_idx': 2, 'flag':'tail'}\n adv_input_dict23 = {'x': image_batch, 'adv': adv_list[3], 'out_idx': 2, 'flag':'tail'}\n adv_input_dict24 = {'x': image_batch, 'adv': adv_list[4], 'out_idx': 2, 'flag':'tail'}\n adv_input_dict3 = {'x': image_batch, 'adv': feature_adv3, 'out_idx': 3, 'flag':'tail'}\n adv_input_dict_sd = {'adv': adv_rpn_roi_output_dict, 'out_idx': 'roi_tail','flag':'clean'}\n \n # clean\n anchor_objectness_losses0, anchor_transformer_losses0, proposal_class_losses0, proposal_transformer_losses0 = \\\n model.train().forward(clean_input_dict, bboxes_batch, labels_batch)\n # muti\n anchor_objectness_losses1, anchor_transformer_losses1, proposal_class_losses1, proposal_transformer_losses1 = \\\n model.train().forward(adv_input_dict1, bboxes_batch, labels_batch)\n anchor_objectness_losses2, anchor_transformer_losses2, proposal_class_losses2, proposal_transformer_losses2 = \\\n model.train().forward(adv_input_dict3, bboxes_batch, labels_batch)\n # sat\n anchor_objectness_losses3, anchor_transformer_losses3, proposal_class_losses3, proposal_transformer_losses3 = \\\n model.train().forward(adv_input_dict21, bboxes_batch, labels_batch)\n anchor_objectness_losses4, anchor_transformer_losses4, proposal_class_losses4, proposal_transformer_losses4 = \\\n model.train().forward(adv_input_dict22, bboxes_batch, labels_batch)\n anchor_objectness_losses5, anchor_transformer_losses5, proposal_class_losses5, proposal_transformer_losses5 = \\\n model.train().forward(adv_input_dict23, bboxes_batch, labels_batch)\n anchor_objectness_losses6, anchor_transformer_losses6, proposal_class_losses6, proposal_transformer_losses6 = \\\n model.train().forward(adv_input_dict24, bboxes_batch, labels_batch)\n # sd\n anchor_objectness_losses7, anchor_transformer_losses7, proposal_class_losses7, proposal_transformer_losses7 = \\\n model.train().forward(adv_input_dict_sd, bboxes_batch, labels_batch)\n\n # clean\n loss0 = attack_algo.compute_loss(anchor_objectness_losses0, anchor_transformer_losses0, proposal_class_losses0, proposal_transformer_losses0)\n # muti\n loss1 = attack_algo.compute_loss(anchor_objectness_losses1, anchor_transformer_losses1, proposal_class_losses1, proposal_transformer_losses1)\n loss2 = attack_algo.compute_loss(anchor_objectness_losses2, anchor_transformer_losses2, proposal_class_losses2, proposal_transformer_losses2)\n # sat\n loss3 = attack_algo.compute_loss(anchor_objectness_losses3, anchor_transformer_losses3, proposal_class_losses3, proposal_transformer_losses3)\n loss4 = attack_algo.compute_loss(anchor_objectness_losses4, anchor_transformer_losses4, proposal_class_losses4, proposal_transformer_losses4)\n loss5 = attack_algo.compute_loss(anchor_objectness_losses5, anchor_transformer_losses5, proposal_class_losses5, proposal_transformer_losses5)\n loss6 = attack_algo.compute_loss(anchor_objectness_losses6, anchor_transformer_losses6, proposal_class_losses6, proposal_transformer_losses6)\n # sd\n loss7 = attack_algo.compute_loss(anchor_objectness_losses7, anchor_transformer_losses7, proposal_class_losses7, proposal_transformer_losses7)\n \n # 1106\n if args.loss_settings == 1:\n # setting 1: 0.35 clean + 0.35 sat + 0.2 sd + 0.1 muti\n loss = 0.35 * (loss0 + 0.25 * (loss3 + loss4 + loss5 + loss6)) + 0.2 * loss7 + 0.05 * (loss1 + loss2)\n \n elif args.loss_settings == 2:\n # setting 2: 0.8 (clean + sat) * 0.1 loss7 + 0.1 muti\n loss = 0.16 * (loss0 + loss3 + loss4 + loss5 + loss6) + 0.1 * loss7 + 0.05 * (loss1 + loss2)\n \n elif args.loss_settings == 3:\n # setting 3: 0.7 (clean + sat) * 0.3 others\n loss = 0.35 * (loss0 + 0.25 * (loss3 + loss4 + loss5 + loss6)) + 0.1 * (loss1 + loss2 + loss7)\n\n elif args.loss_settings == 4:\n # setting 4: ori: 75.38 + 0.1 others\n loss = 0.9 * (0.2333 * (loss0 + loss3 + loss4 + loss5 + loss6) + 0.1 * loss7) + 0.05 * (loss1 + loss2)\n else: assert False\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n scheduler.step()\n losses.append(loss.item())\n\n summary_writer.add_scalar('train/loss', loss.item(), step)\n step += 1\n\n if step == num_steps_to_finish:\n should_stop = True\n\n if step % num_steps_to_display == 0:\n elapsed_time = time.time() - time_checkpoint\n time_checkpoint = time.time()\n steps_per_sec = num_steps_to_display / elapsed_time\n samples_per_sec = batch_size * steps_per_sec\n eta = (num_steps_to_finish - step) / steps_per_sec / 3600\n avg_loss = sum(losses) / len(losses)\n lr = scheduler.get_lr()[0]\n Log.i(f'[Step {step}] Avg. Loss = {avg_loss:.6f}, LR = {lr:.8f} ({samples_per_sec:.2f} samples/sec; ETA {eta:.1f} hrs)')\n\n if step % num_steps_to_snapshot == 0 or should_stop:\n path_to_checkpoint = model.module.save(path_to_checkpoints_dir, step, optimizer, scheduler)\n Log.i(f'Model has been saved to {path_to_checkpoint}')\n\n if should_stop:\n break\n\n Log.i('Done')\n print(\"=\" * 100)\n print(\"FINISL!\")\n print(\"=\" * 100)\n\n\n\nif __name__ == '__main__':\n def main():\n parser = argparse.ArgumentParser()\n #PGD Setting \n parser.add_argument('--steps', default=1, type=int, help='PGD-steps')\n parser.add_argument('--pertub_idx', help='index of perturb layers', default=3, type=int)\n parser.add_argument('--gamma', help='index of PGD gamma', default=0.5, type=float)\n \n parser.add_argument('--eps', default=2, type=float)\n parser.add_argument('--randinit', action=\"store_true\", help=\"whether using apex\")\n parser.add_argument('--clip', action=\"store_true\", help=\"whether using apex\")\n\n parser.add_argument('--loss_settings', default=0, type=int, help='loss setting')\n parser.add_argument('-s', '--dataset', type=str, choices=DatasetBase.OPTIONS, required=True, help='name of dataset')\n parser.add_argument('-b', '--backbone', type=str, choices=BackboneBase.OPTIONS, required=True, help='name of backbone model')\n parser.add_argument('-d', '--data_dir', type=str, default='./data', help='path to data directory')\n parser.add_argument('-o', '--outputs_dir', type=str, default='./outputs', help='path to outputs directory')\n parser.add_argument('-r', '--resume_checkpoint', type=str, help='path to resuming checkpoint')\n parser.add_argument('--image_min_side', type=float, help='default: {:g}'.format(Config.IMAGE_MIN_SIDE))\n parser.add_argument('--image_max_side', type=float, help='default: {:g}'.format(Config.IMAGE_MAX_SIDE))\n parser.add_argument('--anchor_ratios', type=str, help='default: \"{!s}\"'.format(Config.ANCHOR_RATIOS))\n parser.add_argument('--anchor_sizes', type=str, help='default: \"{!s}\"'.format(Config.ANCHOR_SIZES))\n parser.add_argument('--pooler_mode', type=str, choices=Pooler.OPTIONS, help='default: {.value:s}'.format(Config.POOLER_MODE))\n parser.add_argument('--rpn_pre_nms_top_n', type=int, help='default: {:d}'.format(Config.RPN_PRE_NMS_TOP_N))\n parser.add_argument('--rpn_post_nms_top_n', type=int, help='default: {:d}'.format(Config.RPN_POST_NMS_TOP_N))\n parser.add_argument('--anchor_smooth_l1_loss_beta', type=float, help='default: {:g}'.format(Config.ANCHOR_SMOOTH_L1_LOSS_BETA))\n parser.add_argument('--proposal_smooth_l1_loss_beta', type=float, help='default: {:g}'.format(Config.PROPOSAL_SMOOTH_L1_LOSS_BETA))\n parser.add_argument('--batch_size', type=int, help='default: {:g}'.format(Config.BATCH_SIZE))\n parser.add_argument('--learning_rate', type=float, help='default: {:g}'.format(Config.LEARNING_RATE))\n parser.add_argument('--momentum', type=float, help='default: {:g}'.format(Config.MOMENTUM))\n parser.add_argument('--weight_decay', type=float, help='default: {:g}'.format(Config.WEIGHT_DECAY))\n parser.add_argument('--step_lr_sizes', type=str, help='default: {!s}'.format(Config.STEP_LR_SIZES))\n parser.add_argument('--step_lr_gamma', type=float, help='default: {:g}'.format(Config.STEP_LR_GAMMA))\n parser.add_argument('--warm_up_factor', type=float, help='default: {:g}'.format(Config.WARM_UP_FACTOR))\n parser.add_argument('--warm_up_num_iters', type=int, help='default: {:d}'.format(Config.WARM_UP_NUM_ITERS))\n parser.add_argument('--num_steps_to_display', type=int, help='default: {:d}'.format(Config.NUM_STEPS_TO_DISPLAY))\n parser.add_argument('--num_steps_to_snapshot', type=int, help='default: {:d}'.format(Config.NUM_STEPS_TO_SNAPSHOT))\n parser.add_argument('--num_steps_to_finish', type=int, help='default: {:d}'.format(Config.NUM_STEPS_TO_FINISH))\n args = parser.parse_args()\n print_args(args, 100)\n \n dataset_name = args.dataset\n backbone_name = args.backbone\n\n exp_name = \"s\" + str(args.steps) + \"p\" + str(args.pertub_idx) + \"g\" + str(args.gamma) + \"e\" + str(args.eps)\n if args.randinit: exp_name += \"_rand\"\n if args.clip: exp_name += \"_clip\"\n \n path_to_data_dir = args.data_dir\n path_to_outputs_dir = args.outputs_dir\n path_to_resuming_checkpoint = args.resume_checkpoint\n\n path_to_checkpoints_dir = os.path.join(path_to_outputs_dir, 'ckpt-{:s}-{:s}-{:s}'\n .format(exp_name, dataset_name, backbone_name))\n if not os.path.exists(path_to_checkpoints_dir):\n print(\"create dir:[{}]\".format(path_to_checkpoints_dir))\n os.makedirs(path_to_checkpoints_dir)\n\n Config.setup(image_min_side=args.image_min_side, image_max_side=args.image_max_side,\n anchor_ratios=args.anchor_ratios, anchor_sizes=args.anchor_sizes, pooler_mode=args.pooler_mode,\n rpn_pre_nms_top_n=args.rpn_pre_nms_top_n, rpn_post_nms_top_n=args.rpn_post_nms_top_n,\n anchor_smooth_l1_loss_beta=args.anchor_smooth_l1_loss_beta, proposal_smooth_l1_loss_beta=args.proposal_smooth_l1_loss_beta,\n batch_size=args.batch_size, learning_rate=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay,\n step_lr_sizes=args.step_lr_sizes, step_lr_gamma=args.step_lr_gamma,\n warm_up_factor=args.warm_up_factor, warm_up_num_iters=args.warm_up_num_iters,\n num_steps_to_display=args.num_steps_to_display, num_steps_to_snapshot=args.num_steps_to_snapshot, num_steps_to_finish=args.num_steps_to_finish)\n\n Log.initialize(os.path.join(path_to_checkpoints_dir, 'train.log'))\n Log.i('Arguments:')\n for k, v in vars(args).items():\n Log.i(f'\\t{k} = {v}')\n Log.i(Config.describe())\n print(\"-\" * 100)\n print(\"INFO: PID : [{}]\".format(os.getpid()))\n print(\"DIR:[{}]\".format(path_to_checkpoints_dir))\n print(\"-\" * 100)\n _train(dataset_name, backbone_name, path_to_data_dir, path_to_checkpoints_dir, path_to_resuming_checkpoint, args)\n\n main()\n"
] |
[
[
"torch.autograd.grad",
"torch.rand",
"torch.sign"
],
[
"torch.cuda.device_count"
],
[
"torch.nn.CrossEntropyLoss",
"numpy.random.seed",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"numpy.concatenate",
"torch.utils.tensorboard.SummaryWriter",
"torch.cuda.is_available",
"torch.device",
"torch.nn.DataParallel",
"torch.optim.lr_scheduler.StepLR"
],
[
"torch.cuda.device_count"
],
[
"torch.cuda.device_count"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mcps5601/TimeGAN-tensorflow2
|
[
"6f68f9ae9d9eb6f7f9e0992a5dde75c697fc0655",
"6f68f9ae9d9eb6f7f9e0992a5dde75c697fc0655"
] |
[
"hider/timegan/modules/model_utils.py",
"data/data_preprocess.py"
] |
[
"import tensorflow as tf\nimport numpy as np\nfrom .layer_norm_module import LSTMLNCell, LSTMLN\nimport json\n\n\ndef train_test_divide(data_x, data_x_hat, data_t, data_t_hat, train_rate = 0.8):\n \"\"\"Divide train and test data for both original and synthetic data.\n Args:\n data_x: original_data\n data_x_hat: generated_data\n data_t: original time\n data_t_hat: generated time\n train_rate: ratio of training data from the original data\n \"\"\"\n # Divide train/test index (original data)\n total_num = len(data)\n idx = np.random.permutation(total_num)\n train_idx = idx[:int(total_num * train_rate)]\n test_idx = idx[int(total_num * train_rate):]\n\n train_x = [data_x[i] for i in train_idx]\n test_x = [data_x[i] for i in test_idx]\n train_t = [data_t[i] for i in train_idx]\n test_t = [data_t[i] for i in test_idx]\n\n # Divide train/test index (synthetic data)\n total_num = len(data_x_hat)\n idx = np.random.permutation(total_num)\n train_idx = idx[:int(total_num * train_rate)]\n test_idx = idx[int(total_num * train_rate):]\n \n train_x_hat = [data_x_hat[i] for i in train_idx]\n test_x_hat = [data_x_hat[i] for i in test_idx]\n train_t_hat = [data_t_hat[i] for i in train_idx]\n test_t_hat = [data_t_hat[i] for i in test_idx]\n\n return train_x, train_x_hat, test_x, test_x_hat, train_t, train_t_hat, test_t, test_t_hat\n\n\ndef extract_time (data):\n \"\"\"Returns Maximum sequence length and each sequence length.\n Args:\n data: original data\n \n Returns:\n time: extracted time information\n max_seq_len: maximum sequence length\n \"\"\"\n time = list()\n max_seq_len = 0\n for i in range(len(data)):\n max_seq_len = max(max_seq_len, len(data[i][:,0]))\n time.append(len(data[i][:,0]))\n \n return time, max_seq_len\n\n\ndef rnn_cell(module_name, hidden_dim):\n \"\"\"\n Args:\n module_name: desired rnn module\n hidden_dim: dimension of hidden states\n Return:\n rnn_cell\n \"\"\"\n if module_name == 'gru':\n rnn_cell = tf.keras.layers.GRUCell(\n units=hidden_dim,\n activation='tanh')\n if module_name == 'lstm':\n rnn_cell = tf.keras.layers.LSTMCell(\n units=hidden_dim,\n activation='tanh')\n if module_name == 'lstmln':\n rnn_cell = lstmLNCell(\n units=hidden_dim,\n activation='tanh')\n return rnn_cell\n\n\ndef rnn_choices(module_name, hidden_dim):\n \"\"\"\n Args:\n module_name: desired rnn module\n hidden_dim: dimension of hidden states\n Return:\n rnn_cell\n \"\"\"\n if module_name == 'gru':\n rnn_model = tf.keras.layers.GRU(\n units=hidden_dim,\n activation='tanh',\n return_sequences=True)\n if module_name == 'lstm':\n rnn_model = tf.keras.layers.LSTM(\n units=hidden_dim,\n activation='tanh',\n return_sequences=True)\n if module_name == 'lstmln': # TODO: there may be bugs\n rnn_model = LSTMLN(\n units=hidden_dim,\n activation='tanh',\n return_sequences=True)\n return rnn_model\n\n\ndef random_generator(batch_size, z_dim, T_mb, max_seq_len):\n \"\"\"Random vector generation.\n Args:\n batch_size: size of the random vector\n z_dim: dimension of random vector\n T_mb: time information for the random vector\n max_seq_len: maximum sequence length\n Return:\n Z_mb: generated random vector\n \"\"\"\n Z_mb = list()\n for i in range(batch_size):\n temp = np.zeros([max_seq_len, z_dim])\n temp_Z = np.random.uniform(0., 1, [T_mb[i], z_dim])\n temp[:T_mb[i],:] = temp_Z\n Z_mb.append(temp_Z)\n\n return Z_mb\n\n\ndef batch_generator(data, time, batch_size, use_tf_data=False):\n \"\"\"Mini-batch generator\n Args:\n data: time-series data\n time: time information\n batch_size: the number of samples in each batch\n Return:\n X_mb: time-series data in each batch\n T_mb: time information in each batch\n \"\"\"\n total_num = len(data)\n idx = np.random.permutation(total_num)\n train_idx = idx[:batch_size]\n X_mb = list(data[i] for i in train_idx)\n T_mb = list(time[i] for i in train_idx)\n \n if use_tf_data:\n X_mb = tf.convert_to_tensor(X_mb, dtype=tf.float32)\n T_mb = tf.convert_to_tensor(T_mb, dtype=tf.float32)\n X_mb = tf.data.Dataset.from_tensors(X_mb)\n T_mb = tf.data.Dataset.from_tensors(T_mb)\n\n return X_mb, T_mb\n\n\ndef MinMaxScaler(data):\n \"\"\"Min_Max Normalizer.\n Args:\n data: raw_data\n Return:\n norm_data: normalized_data\n min_val: minimum values (for renormalization)\n max_val: maximum values (for renormalization)\n \"\"\"\n min_val = np.min(np.min(data, axis=0), axis=0)\n data = data - min_val\n\n max_val = np.max(np.max(data, axis=0), axis=0)\n norm_data = data / (max_val + 1e-7)\n\n return norm_data, min_val, max_val\n\n\ndef save_dict_to_json(dict_of_params, json_path):\n \"\"\"Saves dict of floats in json file\n Args:\n d: (dict) of float-castable values (np.float, int, float, etc.)\n json_path: (string) path to json file\n Return:\n a saved json file containing hyperparameters\n \"\"\"\n\n with open(json_path, 'w') as f:\n # We need to convert the values to float for json (it doesn't accept np.array, np.float, )\n dict_of_params = {k: v for k, v in dict_of_params.items()}\n json.dump(dict_of_params, f, indent=4)\n",
"\"\"\"Hide-and-Seek Privacy Challenge Codebase.\n\nReference: James Jordon, Daniel Jarrett, Jinsung Yoon, Ari Ercole, Cheng Zhang, Danielle Belgrave, Mihaela van der Schaar, \n\"Hide-and-Seek Privacy Challenge: Synthetic Data Generation vs. Patient Re-identification with Clinical Time-series Data,\" \nNeural Information Processing Systems (NeurIPS) Competition, 2020.\n\nLink: https://www.vanderschaar-lab.com/announcing-the-neurips-2020-hide-and-seek-privacy-challenge/\n\nLast updated Date: June 21th 2020\nCode author: Jinsung Yoon\nModified by Ying-Jia Lin\n\n-----------------------------\n\n(1) data_preprocess: Load the data and preprocess for 3d numpy array\n(2) imputation: Impute missing data using bfill, ffill and median imputation\n\"\"\"\n\n## Necessary packages\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\nfrom tqdm import tqdm\nfrom sklearn.preprocessing import MinMaxScaler\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndef data_preprocess(file_name, max_seq_len, imp_method):\n \"\"\"Load the data and preprocess for 3d numpy array.\n\n Args:\n - file_name: CSV file name\n - max_seq_len: maximum sequence length\n\n Returns:\n - processed_data: preprocessed data\n \"\"\"\n\n # Load data \n ori_data = pd.read_csv(file_name)\n\n # Parameters\n uniq_id = np.unique(ori_data['admissionid'])\n no = len(uniq_id)\n dim = len(ori_data.columns) - 1\n\n if imp_method == 'mode':\n # Get mode of each columns\n keys = ori_data.columns[2:]\n vals = []\n for key in keys:\n val = ori_data[str(key)].dropna().to_numpy()\n vals.append(stats.mode(val).mode[0])\n\n elif imp_method == 'median':\n vals = ori_data.median()\n\n # Preprocessing\n scaler = MinMaxScaler()\n scaler.fit(ori_data)\n\n # Output initialization\n processed_data = -np.ones([no, max_seq_len, dim])\n time = []\n\n # For each uniq id\n for i in tqdm(range(no)):\n # Extract the time-series data with a certain admissionid\n idx = ori_data.index[ori_data['admissionid'] == uniq_id[i]]\n curr_data = ori_data.iloc[idx]\n\n # Preprocess time\n curr_data['time'] = curr_data['time'] - np.min(curr_data['time']) \n\n # Impute missing data\n curr_data = imputation(curr_data, vals)\n\n # MinMax Scaling \n curr_data = scaler.transform(curr_data)\n\n # Assign to the preprocessed data (Excluding ID) \n curr_no = len(curr_data)\n if curr_no >= max_seq_len:\n processed_data[i, :, :] = curr_data[:max_seq_len, 1:]\n time.append(max_seq_len)\n else:\n processed_data[i, -curr_no:, :] = (curr_data)[:, 1:]\n time.append(curr_no)\n\n return processed_data, time\n\n\ndef imputation(curr_data, vals):\n \"\"\"Impute missing data using bfill, ffill and median imputation.\n\n Args:\n - curr_data: current pandas dataframe\n - median_vals: median values for each column\n\n Returns:\n - imputed_data: imputed pandas dataframe\n \"\"\"\n imputed_data = curr_data.fillna(vals)\n\n return imputed_data\n"
] |
[
[
"tensorflow.convert_to_tensor",
"tensorflow.keras.layers.GRUCell",
"tensorflow.data.Dataset.from_tensors",
"numpy.min",
"tensorflow.keras.layers.GRU",
"numpy.max",
"tensorflow.keras.layers.LSTM",
"numpy.random.permutation",
"numpy.random.uniform",
"tensorflow.keras.layers.LSTMCell",
"numpy.zeros"
],
[
"pandas.read_csv",
"numpy.min",
"numpy.unique",
"numpy.ones",
"scipy.stats.mode",
"sklearn.preprocessing.MinMaxScaler"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
jbschroder/pymgrit
|
[
"5c866c633dea3ebccf812550e0303f47771c4faf"
] |
[
"src/pymgrit/heat/vector_heat_1d_2pts.py"
] |
[
"\"\"\"\nVector class for 1D heat problem\n\nNote: values at two consecutive time points are grouped as pairs\n\"\"\"\n\nimport numpy as np\n\nfrom pymgrit.core.vector import Vector\n\n\nclass VectorHeat1D2Pts(Vector):\n \"\"\"\n Vector class for grouping values at two consecutive time points\n \"\"\"\n\n def __init__(self, size, dtau):\n \"\"\"\n Constructor.\n One vector object contains values at two consecutive time points and spacing between these time points.\n\n :param size: number of spatial degrees of freedom\n :param dtau: time-step size within pair\n \"\"\"\n super().__init__()\n self.size = size\n self.dtau = dtau\n self.values_first_time_point = np.zeros(size)\n self.values_second_time_point = np.zeros(size)\n\n def __add__(self, other):\n \"\"\"\n Addition of two vector objects (self and other)\n\n :param other: vector object to be added to self\n :return: sum of vector object self and input object other\n \"\"\"\n tmp = VectorHeat1D2Pts(self.size, self.dtau)\n first_self, second_self, dtau_self = self.get_values()\n first_other, second_other, dtau_other = other.get_values()\n tmp.set_values(first_self + first_other, second_self + second_other, dtau_self)\n return tmp\n\n def __sub__(self, other):\n \"\"\"\n Subtraction of two vector objects (self and other)\n\n :param other: vector object to be subtracted from self\n :return: difference of vector object self and input object other\n \"\"\"\n tmp = VectorHeat1D2Pts(self.size, self.dtau)\n first_self, second_self, dtau_self = self.get_values()\n first_other, second_other, dtau_other = other.get_values()\n tmp.set_values(first_self - first_other, second_self - second_other, dtau_self)\n return tmp\n\n def norm(self):\n \"\"\"\n Norm of a vector object\n\n :return: 2-norm of vector object\n \"\"\"\n return np.linalg.norm(np.append(self.values_first_time_point, self.values_second_time_point))\n\n def clone(self):\n \"\"\"\n Clone vector object\n\n :return: vector object with zero values\n \"\"\"\n tmp = VectorHeat1D2Pts(self.size, self.dtau)\n tmp.set_values(self.values_first_time_point, self.values_second_time_point, self.dtau)\n return tmp\n\n def clone_zero(self):\n \"\"\"\n Initialize vector object with zeros\n\n :return: vector object with zero values\n \"\"\"\n return VectorHeat1D2Pts(self.size, self.dtau)\n\n def clone_rand(self):\n \"\"\"\n Initialize vector object with random values\n\n :return: vector object with random values\n \"\"\"\n tmp = VectorHeat1D2Pts(self.size, self.dtau)\n tmp.set_values(np.random.rand(self.size), np.random.rand(self.size), self.dtau)\n return tmp\n\n def get_values(self):\n \"\"\"\n Get vector data\n\n :return: tuple of values of member variables\n \"\"\"\n return self.values_first_time_point, self.values_second_time_point, self.dtau\n\n def set_values(self, first_time_point, second_time_point, dtau):\n \"\"\"\n Set vector data\n\n :param first_time_point: values for first time point\n :param second_time_point: values for second time point\n :param dtau: time-step size within pair\n \"\"\"\n self.values_first_time_point = first_time_point\n self.values_second_time_point = second_time_point\n self.dtau = dtau\n\n def pack(self):\n \"\"\"\n Pack data\n\n :return: values of vector object\n \"\"\"\n return np.array([self.values_first_time_point, self.values_second_time_point])\n\n def unpack(self, values):\n \"\"\"\n Unpack and set data\n\n :param values: values for vector object\n \"\"\"\n self.values_first_time_point = values[0]\n self.values_second_time_point = values[1]\n"
] |
[
[
"numpy.append",
"numpy.array",
"numpy.zeros",
"numpy.random.rand"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jasongwq/MTCNN
|
[
"168d346461fd7e7c59e4f911296cfa6133dc2ea5"
] |
[
"train/jfda/detector.py"
] |
[
"# pylint: disable=bad-indentation, no-member, invalid-name, line-too-long\nimport math\nimport cv2\nimport caffe\nimport numpy as np\nfrom utils import crop_face, Timer\n\n\nclass JfdaDetector:\n '''JfdaDetector\n '''\n\n def __init__(self, nets):\n assert len(nets) in [2, 4, 6, 8], 'wrong number of nets'\n self.pnet, self.rnet, self.onet, self.lnet = None, None, None, None\n if len(nets) >= 2:\n self.pnet = caffe.Net(nets[0], caffe.TEST, weights=nets[1])\n if len(nets) >= 4:\n self.rnet = caffe.Net(nets[2], caffe.TEST, weights=nets[3])\n if len(nets) >= 6:\n self.onet = caffe.Net(nets[4], caffe.TEST, weights=nets[5])\n if len(nets) >= 8:\n self.lnet = caffe.Net(nets[6], caffe.TEST, weights=nets[7])\n self.pnet_single_forward = False\n\n def set_pnet_single_forward(self, single_forward=True):\n '''convert image pyramid to a single image and forward once\n '''\n self.pnet_single_forward = single_forward\n\n def detect(self, img, ths, min_size, factor, debug=False):\n '''detect face, return bboxes, [bbox score offset landmark]\n if debug is on, return bboxes of every stage and time consumption\n '''\n timer = Timer()\n ts = [0, 0, 0, 0]\n bb = [[], [], [], []]\n # stage-1\n timer.tic()\n base = 12. / min_size\n height, width = img.shape[:-1]\n l = min(width, height)\n l *= base\n scales = []\n while l > 12:\n scales.append(base)\n base *= factor\n l *= factor\n if not self.pnet_single_forward or len(scales) <= 1:\n bboxes = np.zeros((0, 4 + 1 + 4 + 10), dtype=np.float32)\n for scale in scales:\n w, h = int(math.ceil(scale * width)), int(math.ceil(scale * height))\n data = cv2.resize(img, (w, h))\n data = data.transpose((2, 0, 1)).astype(np.float32)\n data = (data - 128) / 128\n data = data.reshape((1, 3, h, w))\n prob, bbox_pred, landmark_pred = self._forward(self.pnet, data, ['prob', 'bbox_pred', 'landmark_pred'])\n _bboxes = self._gen_bbox(prob[0][1], bbox_pred[0], landmark_pred[0], scale, ths[0])\n keep = nms(_bboxes, 0.5)\n _bboxes = _bboxes[keep]\n bboxes = np.vstack([bboxes, _bboxes])\n else:\n # convert to a single image\n data, pyramid_info = convert_image_pyramid(img, scales, interval=2)\n # forward pnet\n data = data.astype(np.float32)\n data = (data.transpose((2, 0, 1)) - 128) / 128\n data = data[np.newaxis, :, :, :]\n prob, bbox_pred, landmark_pred = self._forward(self.pnet, data, ['prob', 'bbox_pred', 'landmark_pred'])\n bboxes = self._gen_bbox(prob[0][1], bbox_pred[0], landmark_pred[0], 1, ths[0])\n # nms over every pyramid\n keep = nms(bboxes, 0.5)\n bboxes = bboxes[keep]\n # map to original image\n bboxes = get_original_bboxes(bboxes, pyramid_info)\n keep = nms(bboxes, 0.7)\n bboxes = bboxes[keep]\n bboxes = self._bbox_reg(bboxes)\n bboxes = self._make_square(bboxes)\n timer.toc()\n ts[0] = timer.elapsed()\n bb[0] = bboxes.copy()\n self._clear_network_buffer(self.pnet)\n # stage-2\n if self.rnet is None or len(bboxes) == 0:\n if debug is True:\n return bb, ts\n else:\n return bboxes\n timer.tic()\n n = len(bboxes)\n data = np.zeros((n, 3, 24, 24), dtype=np.float32)\n for i, bbox in enumerate(bboxes):\n face = crop_face(img, bbox[:4])\n data[i] = cv2.resize(face, (24, 24)).transpose((2, 0, 1))\n data = (data - 128) / 128\n prob, bbox_pred, landmark_pred = self._forward(self.rnet, data, ['prob', 'bbox_pred', 'landmark_pred'])\n prob = prob.reshape(n, 2)\n bbox_pred = bbox_pred.reshape(n, 4)\n landmark_pred = landmark_pred.reshape(n, 10)\n keep = prob[:, 1] > ths[1]\n bboxes = bboxes[keep]\n bboxes[:, 4] = prob[keep, 1]\n bboxes[:, 5:9] = bbox_pred[keep]\n bboxes[:, 9:] = landmark_pred[keep]\n keep = nms(bboxes, 0.7)\n bboxes = bboxes[keep]\n bboxes = self._bbox_reg(bboxes)\n bboxes = self._make_square(bboxes)\n timer.toc()\n ts[1] = timer.elapsed()\n bb[1] = bboxes.copy()\n self._clear_network_buffer(self.rnet)\n # stage-3\n if self.onet is None or len(bboxes) == 0:\n if debug is True:\n return bb, ts\n else:\n return bboxes\n timer.tic()\n n = len(bboxes)\n data = np.zeros((n, 3, 48, 48), dtype=np.float32)\n for i, bbox in enumerate(bboxes):\n face = crop_face(img, bbox[:4])\n data[i] = cv2.resize(face, (48, 48)).transpose((2, 0, 1))\n data = (data - 128) / 128\n prob, bbox_pred, landmark_pred = self._forward(self.onet, data, ['prob', 'bbox_pred', 'landmark_pred'])\n prob = prob.reshape(n, 2)\n bbox_pred = bbox_pred.reshape(n, 4)\n landmark_pred = landmark_pred.reshape(n, 10)\n keep = prob[:, 1] > ths[2]\n bboxes = bboxes[keep]\n bboxes[:, 4] = prob[keep, 1]\n bboxes[:, 5:9] = bbox_pred[keep]\n bboxes[:, 9:] = landmark_pred[keep]\n bboxes = self._locate_landmark(bboxes)\n bboxes = self._bbox_reg(bboxes)\n keep = nms(bboxes, 0.7, 'Min')\n bboxes = bboxes[keep]\n timer.toc()\n ts[2] = timer.elapsed()\n bb[2] = bboxes.copy()\n self._clear_network_buffer(self.onet)\n # stage-4\n if self.lnet is None or len(bboxes) == 0:\n if debug is True:\n return bb, ts\n else:\n return bboxes\n timer.tic()\n n = len(bboxes)\n data = np.zeros((n, 15, 24, 24), dtype=np.float32)\n w, h = bboxes[:, 2]-bboxes[:, 0], bboxes[:, 3]-bboxes[:, 1]\n l = np.maximum(w, h) * 0.25\n for i in range(len(bboxes)):\n x1, y1, x2, y2 = bboxes[i, :4]\n landmark = bboxes[i, 9:].reshape((5, 2))\n for j in range(5):\n x, y = landmark[j]\n patch_bbox = [x-l[i]/2, y-l[i]/2, x+l[i]/2, y+l[i]/2]\n patch = crop_face(img, patch_bbox)\n patch = cv2.resize(patch, (24, 24))\n patch = patch.transpose((2, 0, 1))\n data[i, (3*j):(3*j+3)] = patch\n data = (data - 128) / 128\n offset = self._forward(self.lnet, data, ['landmark_offset'])[0]\n offset = offset.reshape(n, 10)\n offset *= l.reshape((-1, 1))\n bboxes[:, 9:] += offset\n timer.toc()\n ts[3] = timer.elapsed()\n bb[3] = bboxes.copy()\n self._clear_network_buffer(self.lnet)\n if debug is True:\n return bb, ts\n else:\n return bboxes\n\n def _forward(self, net, data, outs):\n '''forward a net with given data, return blobs[out]\n '''\n net.blobs['data'].reshape(*data.shape)\n net.blobs['data'].data[...] = data\n net.forward()\n return [net.blobs[out].data for out in outs]\n\n def _clear_network_buffer(self, net):\n if net is self.pnet:\n fake = np.zeros((1, 3, 12, 12), dtype=np.float32)\n elif net is self.rnet:\n fake = np.zeros((1, 3, 24, 24), dtype=np.float32)\n elif net is self.onet:\n fake = np.zeros((1, 3, 48, 48), dtype=np.float32)\n else:\n fake = np.zeros((1, 15, 24, 24), dtype=np.float32)\n net.blobs['data'].reshape(*fake.shape)\n net.blobs['data'].data[...] = fake\n net.forward()\n\n def _gen_bbox(self, hotmap, offset, landmark, scale, th):\n '''[x1, y1, x2, y2, score, offset_x1, offset_y1, offset_x2, offset_y2]\n '''\n h, w = hotmap.shape\n stride = 2\n win_size = 12\n hotmap = hotmap.reshape((h, w))\n keep = hotmap > th\n pos = np.where(keep)\n score = hotmap[keep]\n offset = offset[:, keep]\n landmark = landmark[:, keep]\n x, y = pos[1], pos[0]\n x1 = stride * x\n y1 = stride * y\n x2 = x1 + win_size\n y2 = y1 + win_size\n x1 = x1 / scale\n y1 = y1 / scale\n x2 = x2 / scale\n y2 = y2 / scale\n bbox = np.vstack([x1, y1, x2, y2, score, offset, landmark]).transpose()\n return bbox.astype(np.float32)\n\n def _locate_landmark(self, bboxes):\n w = bboxes[:, 2] - bboxes[:, 0]\n h = bboxes[:, 3] - bboxes[:, 1]\n bboxes[:, 9::2] = bboxes[:, 9::2] * w.reshape((-1, 1)) + bboxes[:, 0].reshape((-1, 1))\n bboxes[:, 10::2] = bboxes[:, 10::2] * h.reshape((-1, 1)) + bboxes[:, 1].reshape((-1, 1))\n return bboxes\n\n def _bbox_reg(self, bboxes):\n w = bboxes[:, 2] - bboxes[:, 0]\n h = bboxes[:, 3] - bboxes[:, 1]\n bboxes[:, 0] += bboxes[:, 5] * w\n bboxes[:, 1] += bboxes[:, 6] * h\n bboxes[:, 2] += bboxes[:, 7] * w\n bboxes[:, 3] += bboxes[:, 8] * h\n return bboxes\n\n def _make_square(self, bboxes):\n '''make bboxes sqaure\n '''\n x_center = (bboxes[:, 0] + bboxes[:, 2]) / 2\n y_center = (bboxes[:, 1] + bboxes[:, 3]) / 2\n w = bboxes[:, 2] - bboxes[:, 0]\n h = bboxes[:, 3] - bboxes[:, 1]\n size = np.vstack([w, h]).max(axis=0).transpose()\n bboxes[:, 0] = x_center - size / 2\n bboxes[:, 2] = x_center + size / 2\n bboxes[:, 1] = y_center - size / 2\n bboxes[:, 3] = y_center + size / 2\n return bboxes\n\n\ndef nms(dets, thresh, meth='Union'):\n '''nms from py-faster-rcnn\n '''\n x1 = dets[:, 0]\n y1 = dets[:, 1]\n x2 = dets[:, 2]\n y2 = dets[:, 3]\n scores = dets[:, 4]\n\n areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n order = scores.argsort()[::-1]\n\n keep = []\n while order.size > 0:\n i = order[0]\n keep.append(i)\n xx1 = np.maximum(x1[i], x1[order[1:]])\n yy1 = np.maximum(y1[i], y1[order[1:]])\n xx2 = np.minimum(x2[i], x2[order[1:]])\n yy2 = np.minimum(y2[i], y2[order[1:]])\n\n w = np.maximum(0.0, xx2 - xx1 + 1)\n h = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w * h\n if meth == 'Union':\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\n else:\n ovr = inter / np.minimum(areas[i], areas[order[1:]])\n\n inds = np.where(ovr <= thresh)[0]\n order = order[inds + 1]\n\n return keep\n\n\ndef convert_image_pyramid(img, scales, interval=2):\n \"\"\"convert image pyramid to a single image\n\n Parameters\n ==========\n img: image\n scales: pyramid scales\n interval: interval pixels between pyramid images\n\n Returns\n =======\n result: image pyramid in a single image\n bboxes: every pyramid image in the result image with position and scale information,\n (x, y, w, h, scale)\n \"\"\"\n assert len(scales) >= 2\n height, width = img.shape[:2]\n pyramids = []\n for scale in scales:\n w, h = int(math.ceil(scale*width)), int(math.ceil(scale*height))\n img_pyramid = cv2.resize(img, (w, h))\n pyramids.append(img_pyramid)\n\n input_h, input_w = pyramids[0].shape[:2]\n # x, y, w, h\n bboxes = [[0, 0, img.shape[1], img.shape[0], scale] for img, scale in zip(pyramids, scales)]\n if input_h < input_w:\n output_h = input_h + interval + pyramids[1].shape[0]\n output_w = 0\n available = [[0, 0]]\n for bbox in bboxes:\n min_used_width = 3 * width\n choosed = -1\n for i, (x, y) in enumerate(available):\n if y + bbox[3] <= output_h and x + bbox[2] < min_used_width:\n min_used_width = x + bbox[2]\n bbox[0], bbox[1] = x, y\n choosed = i\n assert choosed != -1, \"No suitable position for this pyramid scale\"\n # extend available positions\n x, y = available[choosed]\n w, h = bbox[2:4]\n available[choosed][0] = x + interval + w\n available[choosed][1] = y\n available.append([x, y + interval + h])\n output_w = max(output_w, min_used_width)\n else:\n output_w = input_w + interval + pyramids[1].shape[1]\n output_h = 0\n available = [[0, 0]]\n for bbox in bboxes:\n min_used_height = 3 * height\n choosed = -1\n for i, (x, y) in enumerate(available):\n if x + bbox[2] <= output_w and y + bbox[3] < min_used_height:\n min_used_height = y + bbox[3]\n bbox[0], bbox[1] = x, y\n choosed = i\n assert choosed != -1, \"No suitable position for this pyramid scale\"\n # extend available positions\n x, y = available[choosed]\n w, h = bbox[2:4]\n available[choosed][0] = x + interval + w\n available[choosed][1] = y\n available.append([x, y + interval + h])\n output_h = max(output_h, min_used_height)\n # convert to a single image\n result = np.zeros((output_h, output_w, 3), dtype=np.uint8)\n for bbox, pyramid in zip(bboxes, pyramids):\n x, y, w, h, scale = bbox\n assert pyramid.shape[0] == h and pyramid.shape[1] == w\n result[y:y+h, x:x+w, :] = pyramid\n\n return result, bboxes\n\n\ndef get_original_bboxes(bboxes, pyramid_info):\n \"\"\"get original bboxes\n\n Parameters\n ==========\n bboxes: detected bboxes\n pyramid_info: information of pyramid from `convert_image_pyramid`\n\n Returns\n =======\n bboxes_ori: bboxes in original image\n \"\"\"\n count = 0\n bboxes_ori = np.zeros((0, bboxes.shape[1]), dtype=np.float32)\n for x, y, w, h, scale in pyramid_info:\n x1, y1, x2, y2 = x, y, x+w, y+h\n idx = np.logical_and(\n np.logical_and(bboxes[:, 0] >= x1, bboxes[:, 1] >= y1),\n np.logical_and(bboxes[:, 2] <= x2, bboxes[:, 3] <= y2))\n bboxes[idx, 0] = (bboxes[idx, 0] - x1) / scale\n bboxes[idx, 1] = (bboxes[idx, 1] - y1) / scale\n bboxes[idx, 2] = (bboxes[idx, 2] - x1) / scale\n bboxes[idx, 3] = (bboxes[idx, 3] - y1) / scale\n bboxes_ori = np.vstack([bboxes_ori, bboxes[idx]])\n count += idx.sum()\n #assert count == len(bboxes), \"generate bboxes gives wrong number\"\n return bboxes_ori\n"
] |
[
[
"numpy.maximum",
"numpy.minimum",
"numpy.logical_and",
"numpy.zeros",
"numpy.where",
"numpy.vstack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
leon1330/Tensorflow
|
[
"b9f548d041ba8d66102c6d195e645051f1bee52f"
] |
[
"tensorflow/python/framework/test_util.py"
] |
[
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n# pylint: disable=invalid-name\n\"\"\"Test utils for tensorflow.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport contextlib\nimport gc\nimport math\nimport random\nimport re\nimport tempfile\nimport threading\n\nimport numpy as np\nimport six\n\n_portpicker_import_error = None\ntry:\n import portpicker # pylint: disable=g-import-not-at-top\nexcept ImportError as _error:\n _portpicker_import_error = _error\n portpicker = None\n\n# pylint: disable=g-import-not-at-top\nfrom google.protobuf import descriptor_pool\nfrom google.protobuf import text_format\n\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.core.protobuf import rewriter_config_pb2\nfrom tensorflow.python import pywrap_tensorflow\nfrom tensorflow.python.client import device_lib\nfrom tensorflow.python.client import session\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import tape # pylint: disable=unused-import\nfrom tensorflow.python.framework import device as pydev\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import importer\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import random_seed\nfrom tensorflow.python.framework import versions\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training import server_lib\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util.protobuf import compare\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n@tf_export(\"test.gpu_device_name\")\ndef gpu_device_name():\n \"\"\"Returns the name of a GPU device if available or the empty string.\"\"\"\n for x in device_lib.list_local_devices():\n if x.device_type == \"GPU\" or x.device_type == \"SYCL\":\n return compat.as_str(x.name)\n return \"\"\n\n\ndef assert_ops_in_graph(expected_ops, graph):\n \"\"\"Assert all expected operations are found.\n\n Args:\n expected_ops: `dict<string, string>` of op name to op type.\n graph: Graph to check.\n Returns:\n `dict<string, node>` of node name to node.\n\n Raises:\n ValueError: If the expected ops are not present in the graph.\n \"\"\"\n actual_ops = {}\n gd = graph.as_graph_def()\n for node in gd.node:\n if node.name in expected_ops:\n if expected_ops[node.name] != node.op:\n raise ValueError(\"Expected op for node %s is different. %s vs %s\" %\n (node.name, expected_ops[node.name], node.op))\n actual_ops[node.name] = node\n if set(expected_ops.keys()) != set(actual_ops.keys()):\n raise ValueError(\"Not all expected ops are present. Expected %s, found %s\" %\n (expected_ops.keys(), actual_ops.keys()))\n return actual_ops\n\n\n@tf_export(\"test.assert_equal_graph_def\")\ndef assert_equal_graph_def(actual, expected, checkpoint_v2=False):\n \"\"\"Asserts that two `GraphDef`s are (mostly) the same.\n\n Compares two `GraphDef` protos for equality, ignoring versions and ordering of\n nodes, attrs, and control inputs. Node names are used to match up nodes\n between the graphs, so the naming of nodes must be consistent.\n\n Args:\n actual: The `GraphDef` we have.\n expected: The `GraphDef` we expected.\n checkpoint_v2: boolean determining whether to ignore randomized attribute\n values that appear in V2 checkpoints.\n\n Raises:\n AssertionError: If the `GraphDef`s do not match.\n TypeError: If either argument is not a `GraphDef`.\n \"\"\"\n if not isinstance(actual, graph_pb2.GraphDef):\n raise TypeError(\n \"Expected tf.GraphDef for actual, got %s\" % type(actual).__name__)\n if not isinstance(expected, graph_pb2.GraphDef):\n raise TypeError(\n \"Expected tf.GraphDef for expected, got %s\" % type(expected).__name__)\n\n if checkpoint_v2:\n _strip_checkpoint_v2_randomized(actual)\n _strip_checkpoint_v2_randomized(expected)\n\n diff = pywrap_tensorflow.EqualGraphDefWrapper(actual.SerializeToString(),\n expected.SerializeToString())\n if diff:\n raise AssertionError(compat.as_str(diff))\n\n\ndef assert_meta_graph_protos_equal(tester, a, b):\n \"\"\"Compares MetaGraphDefs `a` and `b` in unit test class `tester`.\"\"\"\n # Carefully check the collection_defs\n tester.assertEqual(set(a.collection_def), set(b.collection_def))\n collection_keys = a.collection_def.keys()\n for k in collection_keys:\n a_value = a.collection_def[k]\n b_value = b.collection_def[k]\n proto_type = ops.get_collection_proto_type(k)\n if proto_type:\n a_proto = proto_type()\n b_proto = proto_type()\n # Number of entries in the collections is the same\n tester.assertEqual(\n len(a_value.bytes_list.value), len(b_value.bytes_list.value))\n for (a_value_item, b_value_item) in zip(a_value.bytes_list.value,\n b_value.bytes_list.value):\n a_proto.ParseFromString(a_value_item)\n b_proto.ParseFromString(b_value_item)\n tester.assertProtoEquals(a_proto, b_proto)\n else:\n tester.assertEquals(a_value, b_value)\n # Compared the fields directly, remove their raw values from the\n # proto comparison below.\n a.ClearField(\"collection_def\")\n b.ClearField(\"collection_def\")\n\n # Check the graph_defs.\n assert_equal_graph_def(a.graph_def, b.graph_def, checkpoint_v2=True)\n # Check graph_def versions (ignored by assert_equal_graph_def).\n tester.assertProtoEquals(a.graph_def.versions, b.graph_def.versions)\n # Compared the fields directly, remove their raw values from the\n # proto comparison below.\n a.ClearField(\"graph_def\")\n b.ClearField(\"graph_def\")\n\n tester.assertProtoEquals(a, b)\n\n\n# Matches attributes named via _SHARDED_SUFFIX in\n# tensorflow/python/training/saver.py\n_SHARDED_SAVE_OP_PATTERN = \"_temp_[0-9a-z]{32}/part\"\n\n\ndef _strip_checkpoint_v2_randomized(graph_def):\n for node in graph_def.node:\n delete_keys = []\n for attr_key in node.attr:\n attr_tensor_value = node.attr[attr_key].tensor\n if attr_tensor_value and len(attr_tensor_value.string_val) == 1:\n attr_tensor_string_value = attr_tensor_value.string_val[0]\n if (attr_tensor_string_value and\n re.match(_SHARDED_SAVE_OP_PATTERN, str(attr_tensor_string_value))):\n delete_keys.append(attr_key)\n for attr_key in delete_keys:\n del node.attr[attr_key]\n\n\ndef IsGoogleCudaEnabled():\n return pywrap_tensorflow.IsGoogleCudaEnabled()\n\n\ndef CudaSupportsHalfMatMulAndConv():\n return pywrap_tensorflow.CudaSupportsHalfMatMulAndConv()\n\n\ndef InstallStackTraceHandler():\n pywrap_tensorflow.InstallStacktraceHandler()\n\n\ndef NHWCToNCHW(input_tensor):\n \"\"\"Converts the input from the NHWC format to NCHW.\n\n Args:\n input_tensor: a 4- or 5-D tensor, or an array representing shape\n\n Returns:\n converted tensor or shape array\n \"\"\"\n # tensor dim -> new axis order\n new_axes = {4: [0, 3, 1, 2], 5: [0, 4, 1, 2, 3]}\n if isinstance(input_tensor, ops.Tensor):\n ndims = input_tensor.shape.ndims\n return array_ops.transpose(input_tensor, new_axes[ndims])\n else:\n ndims = len(input_tensor)\n return [input_tensor[a] for a in new_axes[ndims]]\n\n\ndef NHWCToNCHW_VECT_C(input_shape_or_tensor):\n \"\"\"Transforms the input from the NHWC layout to NCHW_VECT_C layout.\n\n Note: Does not include quantization or type conversion steps, which should\n be applied afterwards.\n\n Args:\n input_shape_or_tensor: a 4- or 5-D tensor, or an array representing shape\n\n Returns:\n tensor or shape array transformed into NCHW_VECT_C\n\n Raises:\n ValueError: if last dimension of `input_shape_or_tensor` is not evenly\n divisible by 4.\n \"\"\"\n permutations = {5: [0, 3, 1, 2, 4], 6: [0, 4, 1, 2, 3, 5]}\n is_tensor = isinstance(input_shape_or_tensor, ops.Tensor)\n temp_shape = (\n input_shape_or_tensor.shape.as_list()\n if is_tensor else input_shape_or_tensor)\n if temp_shape[-1] % 4 != 0:\n raise ValueError(\n \"Last dimension of input must be evenly divisible by 4 to convert to \"\n \"NCHW_VECT_C.\")\n temp_shape[-1] //= 4\n temp_shape.append(4)\n permutation = permutations[len(temp_shape)]\n if is_tensor:\n t = array_ops.reshape(input_shape_or_tensor, temp_shape)\n return array_ops.transpose(t, permutation)\n else:\n return [temp_shape[a] for a in permutation]\n\n\ndef NCHW_VECT_CToNHWC(input_shape_or_tensor):\n \"\"\"Transforms the input from the NCHW_VECT_C layout to NHWC layout.\n\n Note: Does not include de-quantization or type conversion steps, which should\n be applied beforehand.\n\n Args:\n input_shape_or_tensor: a 5- or 6-D tensor, or an array representing shape\n\n Returns:\n tensor or shape array transformed into NHWC\n\n Raises:\n ValueError: if last dimension of `input_shape_or_tensor` is not 4.\n \"\"\"\n permutations = {5: [0, 2, 3, 1, 4], 6: [0, 2, 3, 4, 1, 5]}\n is_tensor = isinstance(input_shape_or_tensor, ops.Tensor)\n input_shape = (\n input_shape_or_tensor.shape.as_list()\n if is_tensor else input_shape_or_tensor)\n if input_shape[-1] != 4:\n raise ValueError(\"Last dimension of NCHW_VECT_C must be 4.\")\n permutation = permutations[len(input_shape)]\n nhwc_shape = [input_shape[a] for a in permutation[:-1]]\n nhwc_shape[-1] *= input_shape[-1]\n if is_tensor:\n t = array_ops.transpose(input_shape_or_tensor, permutation)\n return array_ops.reshape(t, nhwc_shape)\n else:\n return nhwc_shape\n\n\ndef NCHWToNHWC(input_tensor):\n \"\"\"Converts the input from the NCHW format to NHWC.\n\n Args:\n input_tensor: a 4- or 5-D tensor, or an array representing shape\n\n Returns:\n converted tensor or shape array\n \"\"\"\n # tensor dim -> new axis order\n new_axes = {4: [0, 2, 3, 1], 5: [0, 2, 3, 4, 1]}\n if isinstance(input_tensor, ops.Tensor):\n ndims = input_tensor.shape.ndims\n return array_ops.transpose(input_tensor, new_axes[ndims])\n else:\n ndims = len(input_tensor)\n return [input_tensor[a] for a in new_axes[ndims]]\n\n\n# TODO(skyewm): remove this eventually\n# pylint: disable=protected-access\ndef _use_c_api_wrapper(fn, use_c_api, *args, **kwargs):\n prev_value = ops._USE_C_API\n ops._USE_C_API = use_c_api\n try:\n # Reset the default graph so it has the C API enabled. We call\n # reset_default_graph() instead of creating a new default Graph context to\n # make this robust to tests that call reset_default_graph(), which requires\n # that the current default graph isn't nested.\n ops.reset_default_graph()\n fn(*args, **kwargs)\n finally:\n ops._USE_C_API = prev_value\n # Make sure default graph reflects prev_value in case next test doesn't call\n # reset_default_graph().\n ops.reset_default_graph()\n# pylint: disable=protected-access\n\n\ndef c_api_and_cuda_enabled():\n return ops._USE_C_API and IsGoogleCudaEnabled()\n\n\ndef skip_if(condition):\n \"\"\"Skips the decorated function if condition is or evaluates to True.\n\n Args:\n condition: Either an expression that can be used in \"if not condition\"\n statement, or a callable whose result should be a boolean.\n Returns:\n The wrapped function\n \"\"\"\n\n def real_skip_if(fn):\n\n def wrapper(*args, **kwargs):\n if callable(condition):\n skip = condition()\n else:\n skip = condition\n if not skip:\n fn(*args, **kwargs)\n\n return wrapper\n\n return real_skip_if\n\n\n# TODO(skyewm): remove this eventually\ndef disable_c_api(fn):\n \"\"\"Decorator for disabling the C API on a test.\n\n Note this disables the C API after running the test class's setup/teardown\n methods.\n\n Args:\n fn: the function to be wrapped\n\n Returns:\n The wrapped function\n \"\"\"\n\n def wrapper(*args, **kwargs):\n _use_c_api_wrapper(fn, False, *args, **kwargs)\n\n return wrapper\n\n\n# TODO(skyewm): remove this eventually\ndef enable_c_api(fn):\n \"\"\"Decorator for enabling the C API on a test.\n\n Note this enables the C API after running the test class's setup/teardown\n methods.\n\n Args:\n fn: the function to be wrapped\n\n Returns:\n The wrapped function\n \"\"\"\n\n def wrapper(*args, **kwargs):\n _use_c_api_wrapper(fn, True, *args, **kwargs)\n\n return wrapper\n\n\n# This decorator is a hacky way to run all the test methods in a decorated\n# class with and without C API enabled.\n# TODO(iga): Remove this and its uses once we switch to using C API by default.\ndef with_c_api(cls):\n \"\"\"Adds methods that call original methods but with C API enabled.\n\n Note this enables the C API in new methods after running the test class's\n setup method. This can be a problem if some objects are created in it\n before the C API is enabled.\n\n Args:\n cls: class to decorate\n\n Returns:\n cls with new test methods added\n \"\"\"\n for name, value in cls.__dict__.copy().items():\n if callable(value) and name.startswith(\"test\"):\n setattr(cls, name + \"WithCApi\", enable_c_api(value))\n return cls\n\n\ndef assert_no_new_tensors(f):\n \"\"\"Decorator for asserting that no new Tensors persist after a test.\n\n Mainly useful for checking that code using the Python C API has correctly\n manipulated reference counts.\n\n Clears the caches that it knows about, runs the garbage collector, then checks\n that there are no Tensor or Tensor-like objects still around. This includes\n Tensors to which something still has a reference (e.g. from missing\n Py_DECREFs) and uncollectable cycles (i.e. Python reference cycles where one\n of the objects has __del__ defined).\n\n Args:\n f: The test case to run.\n Returns:\n The decorated test case.\n \"\"\"\n\n def decorator(self, **kwargs):\n \"\"\"Finds existing Tensors, runs the test, checks for new Tensors.\"\"\"\n\n def _is_tensor(obj):\n try:\n return (isinstance(obj, ops.Tensor) or\n isinstance(obj, variables.Variable))\n except ReferenceError:\n # If the object no longer exists, we don't care about it.\n return False\n\n tensors_before = set(id(obj) for obj in gc.get_objects() if _is_tensor(obj))\n outside_graph_key = ops.get_default_graph()._graph_key\n with ops.Graph().as_default():\n # Run the test in a new graph so that collections get cleared when it's\n # done, but inherit the graph key so optimizers behave.\n ops.get_default_graph()._graph_key = outside_graph_key\n f(self, **kwargs)\n # Make an effort to clear caches, which would otherwise look like leaked\n # Tensors.\n backprop._last_zero = [None]\n backprop._shape_dtype = [None, None]\n context.get_default_context().scalar_cache().clear()\n gc.collect()\n tensors_after = [\n obj for obj in gc.get_objects()\n if _is_tensor(obj) and id(obj) not in tensors_before\n ]\n if tensors_after:\n raise AssertionError((\"%d Tensors not deallocated after test: %s\" % (\n len(tensors_after),\n str(tensors_after),\n )))\n\n return decorator\n\n\ndef assert_no_garbage_created(f):\n \"\"\"Test method decorator to assert that no garbage has been created.\n\n Note that this decorator sets DEBUG_SAVEALL, which in some Python interpreters\n cannot be un-set (i.e. will disable garbage collection for any other unit\n tests in the same file/shard).\n\n Args:\n f: The function to decorate.\n Returns:\n The decorated function.\n \"\"\"\n\n def decorator(self, **kwargs):\n \"\"\"Sets DEBUG_SAVEALL, runs the test, and checks for new garbage.\"\"\"\n gc.disable()\n previous_debug_flags = gc.get_debug()\n gc.set_debug(gc.DEBUG_SAVEALL)\n gc.collect()\n previous_garbage = len(gc.garbage)\n f(self, **kwargs)\n gc.collect()\n # This will fail if any garbage has been created, typically because of a\n # reference cycle.\n self.assertEqual(previous_garbage, len(gc.garbage))\n # TODO(allenl): Figure out why this debug flag reset doesn't work. It would\n # be nice to be able to decorate arbitrary tests in a large test suite and\n # not hold on to every object in other tests.\n gc.set_debug(previous_debug_flags)\n gc.enable()\n\n return decorator\n\n\ndef run_in_graph_and_eager_modes(__unused__=None,\n graph=None,\n config=None,\n use_gpu=False,\n force_gpu=False,\n reset_test=True,\n assert_no_eager_garbage=False):\n \"\"\"Runs the test in both graph and eager modes.\n\n Args:\n __unused__: Prevents sliently skipping tests.\n graph: Optional graph to use during the returned session.\n config: An optional config_pb2.ConfigProto to use to configure the\n session.\n use_gpu: If True, attempt to run as many ops as possible on GPU.\n force_gpu: If True, pin all ops to `/device:GPU:0`.\n reset_test: If True, tearDown and SetUp the test case again.\n assert_no_eager_garbage: If True, sets DEBUG_SAVEALL on the garbage\n collector and asserts that no extra garbage has been created when running\n the test in eager mode. This will fail if there are reference cycles\n (e.g. a = []; a.append(a)). Off by default because some tests may create\n garbage for legitimate reasons (e.g. they define a class which inherits\n from `object`), and because DEBUG_SAVEALL is sticky in some Python\n interpreters (meaning that tests which rely on objects being collected\n elsewhere in the unit test file will not work). Additionally, checks that\n nothing still has a reference to Tensors that the test allocated.\n Returns:\n Returns a decorator that will run the decorated test function\n using both a graph and using eager execution.\n \"\"\"\n\n assert not __unused__, \"Add () after run_in_graph_and_eager_modes.\"\n\n def decorator(f):\n \"\"\"Test method decorator.\"\"\"\n\n def decorated(self, **kwargs):\n \"\"\"Decorated the test method.\"\"\"\n with context.graph_mode():\n with self.test_session(graph, config, use_gpu, force_gpu):\n f(self, **kwargs)\n\n if reset_test:\n # This decorator runs the wrapped test twice.\n # Reset the test environment between runs.\n self.tearDown()\n self.setUp()\n\n def run_eager_mode(self, **kwargs):\n if force_gpu:\n gpu_name = gpu_device_name()\n if not gpu_name:\n gpu_name = \"/device:GPU:0\"\n with context.device(gpu_name):\n f(self)\n elif use_gpu:\n # TODO(xpan): Support softplacement and gpu by default when available.\n f(self, **kwargs)\n else:\n with context.device(\"/device:CPU:0\"):\n f(self, **kwargs)\n\n if assert_no_eager_garbage:\n run_eager_mode = assert_no_new_tensors(\n assert_no_garbage_created(run_eager_mode))\n\n with context.eager_mode():\n with ops.Graph().as_default():\n run_eager_mode(self, **kwargs)\n\n return decorated\n\n return decorator\n\n\n@tf_export(\"test.is_gpu_available\")\ndef is_gpu_available(cuda_only=False, min_cuda_compute_capability=None):\n \"\"\"Returns whether TensorFlow can access a GPU.\n\n Args:\n cuda_only: limit the search to CUDA gpus.\n min_cuda_compute_capability: a (major,minor) pair that indicates the minimum\n CUDA compute capability required, or None if no requirement.\n\n Returns:\n True iff a gpu device of the requested kind is available.\n \"\"\"\n\n def compute_capability_from_device_desc(device_desc):\n # TODO(jingyue): The device description generator has to be in sync with\n # this file. Another option is to put compute capability in\n # DeviceAttributes, but I avoided that to keep DeviceAttributes\n # target-independent. Reconsider this option when we have more things like\n # this to keep in sync.\n # LINT.IfChange\n match = re.search(r\"compute capability: (\\d+)\\.(\\d+)\", device_desc)\n # LINT.ThenChange(//tensorflow/core/\\\n # common_runtime/gpu/gpu_device.cc)\n if not match:\n return 0, 0\n return int(match.group(1)), int(match.group(2))\n\n for local_device in device_lib.list_local_devices():\n if local_device.device_type == \"GPU\":\n if (min_cuda_compute_capability is None or\n compute_capability_from_device_desc(local_device.physical_device_desc)\n >= min_cuda_compute_capability):\n return True\n if local_device.device_type == \"SYCL\" and not cuda_only:\n return True\n return False\n\n\[email protected]\ndef device(use_gpu):\n \"\"\"Uses gpu when requested and available.\"\"\"\n if use_gpu and is_gpu_available():\n dev = \"/device:GPU:0\"\n else:\n dev = \"/device:CPU:0\"\n with ops.device(dev):\n yield\n\n\n@tf_export(\"test.TestCase\")\nclass TensorFlowTestCase(googletest.TestCase):\n \"\"\"Base class for tests that need to test TensorFlow.\n \"\"\"\n\n def __init__(self, methodName=\"runTest\"): # pylint: disable=invalid-name\n super(TensorFlowTestCase, self).__init__(methodName)\n self._threads = []\n self._tempdir = None\n self._cached_session = None\n\n def setUp(self):\n self._ClearCachedSession()\n random.seed(random_seed.DEFAULT_GRAPH_SEED)\n np.random.seed(random_seed.DEFAULT_GRAPH_SEED)\n # Note: The following line is necessary because some test methods may error\n # out from within nested graph contexts (e.g., via assertRaises and\n # assertRaisesRegexp), which may leave ops._default_graph_stack non-empty\n # under certain versions of Python. That would cause\n # ops.reset_default_graph() to throw an exception if the stack were not\n # cleared first.\n ops._default_graph_stack.reset() # pylint: disable=protected-access\n ops.reset_default_graph()\n random_seed.set_random_seed(random_seed.DEFAULT_GRAPH_SEED)\n\n def tearDown(self):\n for thread in self._threads:\n thread.check_termination()\n\n self._ClearCachedSession()\n\n def _ClearCachedSession(self):\n if self._cached_session is not None:\n self._cached_session.close()\n self._cached_session = None\n\n def get_temp_dir(self):\n \"\"\"Returns a unique temporary directory for the test to use.\n\n If you call this method multiple times during in a test, it will return the\n same folder. However, across different runs the directories will be\n different. This will ensure that across different runs tests will not be\n able to pollute each others environment.\n If you need multiple unique directories within a single test, you should\n use tempfile.mkdtemp as follows:\n tempfile.mkdtemp(dir=self.get_temp_dir()):\n\n Returns:\n string, the path to the unique temporary directory created for this test.\n \"\"\"\n if not self._tempdir:\n self._tempdir = tempfile.mkdtemp(dir=googletest.GetTempDir())\n return self._tempdir\n\n def _AssertProtoEquals(self, a, b, msg=None):\n \"\"\"Asserts that a and b are the same proto.\n\n Uses ProtoEq() first, as it returns correct results\n for floating point attributes, and then use assertProtoEqual()\n in case of failure as it provides good error messages.\n\n Args:\n a: a proto.\n b: another proto.\n msg: Optional message to report on failure.\n \"\"\"\n if not compare.ProtoEq(a, b):\n compare.assertProtoEqual(self, a, b, normalize_numbers=True, msg=msg)\n\n def assertProtoEquals(self, expected_message_maybe_ascii, message, msg=None):\n \"\"\"Asserts that message is same as parsed expected_message_ascii.\n\n Creates another prototype of message, reads the ascii message into it and\n then compares them using self._AssertProtoEqual().\n\n Args:\n expected_message_maybe_ascii: proto message in original or ascii form.\n message: the message to validate.\n msg: Optional message to report on failure.\n \"\"\"\n msg = msg if msg else \"\"\n if isinstance(expected_message_maybe_ascii, type(message)):\n expected_message = expected_message_maybe_ascii\n self._AssertProtoEquals(expected_message, message)\n elif isinstance(expected_message_maybe_ascii, str):\n expected_message = type(message)()\n text_format.Merge(\n expected_message_maybe_ascii,\n expected_message,\n descriptor_pool=descriptor_pool.Default())\n self._AssertProtoEquals(expected_message, message, msg=msg)\n else:\n assert False, (\"Can't compare protos of type %s and %s. %s\" %\n (type(expected_message_maybe_ascii), type(message), msg))\n\n def assertProtoEqualsVersion(\n self,\n expected,\n actual,\n producer=versions.GRAPH_DEF_VERSION,\n min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER,\n msg=None):\n expected = \"versions { producer: %d min_consumer: %d };\\n%s\" % (\n producer, min_consumer, expected)\n self.assertProtoEquals(expected, actual, msg=msg)\n\n def assertStartsWith(self, actual, expected_start, msg=None):\n \"\"\"Assert that actual.startswith(expected_start) is True.\n\n Args:\n actual: str\n expected_start: str\n msg: Optional message to report on failure.\n \"\"\"\n if not actual.startswith(expected_start):\n fail_msg = \"%r does not start with %r\" % (actual, expected_start)\n fail_msg += \" : %r\" % (msg) if msg else \"\"\n self.fail(fail_msg)\n\n def _eval_tensor(self, tensor):\n if tensor is None:\n return None\n elif isinstance(tensor, ops.EagerTensor):\n return tensor.numpy()\n elif isinstance(tensor, resource_variable_ops.ResourceVariable):\n return tensor.read_value().numpy()\n elif callable(tensor):\n return self._eval_helper(tensor())\n else:\n raise ValueError(\"Unsupported type %s.\" % type(tensor))\n\n def _eval_helper(self, tensors):\n if tensors is None:\n return None\n return nest.map_structure(self._eval_tensor, tensors)\n\n def evaluate(self, tensors):\n \"\"\"Evaluates tensors and returns numpy values.\n\n Args:\n tensors: A Tensor or a nested list/tuple of Tensors.\n\n Returns:\n tensors numpy values.\n \"\"\"\n if context.in_eager_mode():\n return self._eval_helper(tensors)\n else:\n sess = ops.get_default_session()\n if sess is None:\n with self.test_session() as sess:\n return sess.run(tensors)\n else:\n return sess.run(tensors)\n\n # pylint: disable=g-doc-return-or-yield\n @contextlib.contextmanager\n def test_session(self,\n graph=None,\n config=None,\n use_gpu=False,\n force_gpu=False):\n \"\"\"Returns a TensorFlow Session for use in executing tests.\n\n This method should be used for all functional tests.\n\n This method behaves different than session.Session: for performance reasons\n `test_session` will by default (if `graph` is None) reuse the same session\n across tests. This means you may want to either call the function\n `reset_default_graph()` before tests, or if creating an explicit new graph,\n pass it here (simply setting it with `as_default()` won't do it), which will\n trigger the creation of a new session.\n\n Use the `use_gpu` and `force_gpu` options to control where ops are run. If\n `force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if\n `use_gpu`\n is True, TensorFlow tries to run as many ops on the GPU as possible. If both\n `force_gpu and `use_gpu` are False, all ops are pinned to the CPU.\n\n Example:\n ```python\n class MyOperatorTest(test_util.TensorFlowTestCase):\n def testMyOperator(self):\n with self.test_session(use_gpu=True):\n valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]\n result = MyOperator(valid_input).eval()\n self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]\n invalid_input = [-1.0, 2.0, 7.0]\n with self.assertRaisesOpError(\"negative input not supported\"):\n MyOperator(invalid_input).eval()\n ```\n\n Args:\n graph: Optional graph to use during the returned session.\n config: An optional config_pb2.ConfigProto to use to configure the\n session.\n use_gpu: If True, attempt to run as many ops as possible on GPU.\n force_gpu: If True, pin all ops to `/device:GPU:0`.\n\n Returns:\n A Session object that should be used as a context manager to surround\n the graph building and execution code in a test case.\n \"\"\"\n if self.id().endswith(\".test_session\"):\n self.skipTest(\"Not a test.\")\n\n def prepare_config(config):\n \"\"\"Returns a config for sessions.\n\n Args:\n config: An optional config_pb2.ConfigProto to use to configure the\n session.\n Returns:\n A config_pb2.ConfigProto object.\n \"\"\"\n if config is None:\n config = config_pb2.ConfigProto()\n config.allow_soft_placement = not force_gpu\n config.gpu_options.per_process_gpu_memory_fraction = 0.3\n elif force_gpu and config.allow_soft_placement:\n config = config_pb2.ConfigProto().CopyFrom(config)\n config.allow_soft_placement = False\n # Don't perform optimizations for tests so we don't inadvertently run\n # gpu ops on cpu\n config.graph_options.optimizer_options.opt_level = -1\n config.graph_options.rewrite_options.constant_folding = (\n rewriter_config_pb2.RewriterConfig.OFF)\n config.graph_options.rewrite_options.arithmetic_optimization = (\n rewriter_config_pb2.RewriterConfig.OFF)\n return config\n\n if graph is None:\n if self._cached_session is None:\n self._cached_session = session.Session(\n graph=None, config=prepare_config(config))\n sess = self._cached_session\n with sess.graph.as_default(), sess.as_default():\n if force_gpu:\n # Use the name of an actual device if one is detected, or '/device:GPU:0'\n # otherwise\n gpu_name = gpu_device_name()\n if not gpu_name:\n gpu_name = \"/device:GPU:0\"\n with sess.graph.device(gpu_name):\n yield sess\n elif use_gpu:\n yield sess\n else:\n with sess.graph.device(\"/cpu:0\"):\n yield sess\n else:\n with session.Session(graph=graph, config=prepare_config(config)) as sess:\n if force_gpu:\n # Use the name of an actual device if one is detected, or '/device:GPU:0'\n # otherwise\n gpu_name = gpu_device_name()\n if not gpu_name:\n gpu_name = \"/device:GPU:0\"\n with sess.graph.device(gpu_name):\n yield sess\n elif use_gpu:\n yield sess\n else:\n with sess.graph.device(\"/cpu:0\"):\n yield sess\n\n # pylint: enable=g-doc-return-or-yield\n\n class _CheckedThread(object):\n \"\"\"A wrapper class for Thread that asserts successful completion.\n\n This class should be created using the TensorFlowTestCase.checkedThread()\n method.\n \"\"\"\n\n def __init__(self, testcase, target, args=None, kwargs=None):\n \"\"\"Constructs a new instance of _CheckedThread.\n\n Args:\n testcase: The TensorFlowTestCase for which this thread is being created.\n target: A callable object representing the code to be executed in the\n thread.\n args: A tuple of positional arguments that will be passed to target.\n kwargs: A dictionary of keyword arguments that will be passed to target.\n \"\"\"\n self._testcase = testcase\n self._target = target\n self._args = () if args is None else args\n self._kwargs = {} if kwargs is None else kwargs\n self._thread = threading.Thread(target=self._protected_run)\n self._exception = None\n\n self._is_thread_joined = False\n\n def _protected_run(self):\n \"\"\"Target for the wrapper thread. Sets self._exception on failure.\"\"\"\n try:\n self._target(*self._args, **self._kwargs)\n except Exception as e: # pylint: disable=broad-except\n self._exception = e\n\n def start(self):\n \"\"\"Starts the thread's activity.\n\n This must be called at most once per _CheckedThread object. It arranges\n for the object's target to be invoked in a separate thread of control.\n \"\"\"\n self._thread.start()\n\n def join(self):\n \"\"\"Blocks until the thread terminates.\n\n Raises:\n self._testcase.failureException: If the thread terminates with due to\n an exception.\n \"\"\"\n self._is_thread_joined = True\n self._thread.join()\n if self._exception is not None:\n self._testcase.fail(\"Error in checkedThread: %s\" % str(self._exception))\n\n def is_alive(self):\n \"\"\"Returns whether the thread is alive.\n\n This method returns True just before the run() method starts\n until just after the run() method terminates.\n\n Returns:\n True if the thread is alive, otherwise False.\n \"\"\"\n return self._thread.is_alive()\n\n def check_termination(self):\n \"\"\"Returns whether the checked thread was properly used and did terminate.\n\n Every checked thread should be \"join\"ed after starting, and before the\n test tears down. If it is not joined, it is possible the thread will hang\n and cause flaky failures in tests.\n\n Raises:\n self._testcase.failureException: If check_termination was called before\n thread was joined.\n\n RuntimeError: If the thread is not terminated. This means thread was not\n joined with the main thread.\n \"\"\"\n if self._is_thread_joined:\n if self.is_alive():\n raise RuntimeError(\n \"Thread was not joined with main thread, and is still running \"\n \"when the test finished.\")\n else:\n self._testcase.fail(\"A checked thread was not joined.\")\n\n def checkedThread(self, target, args=None, kwargs=None):\n \"\"\"Returns a Thread wrapper that asserts 'target' completes successfully.\n\n This method should be used to create all threads in test cases, as\n otherwise there is a risk that a thread will silently fail, and/or\n assertions made in the thread will not be respected.\n\n Args:\n target: A callable object to be executed in the thread.\n args: The argument tuple for the target invocation. Defaults to ().\n kwargs: A dictionary of keyword arguments for the target invocation.\n Defaults to {}.\n\n Returns:\n A wrapper for threading.Thread that supports start() and join() methods.\n \"\"\"\n ret = TensorFlowTestCase._CheckedThread(self, target, args, kwargs)\n self._threads.append(ret)\n return ret\n\n\n# pylint: enable=invalid-name\n\n def assertNear(self, f1, f2, err, msg=None):\n \"\"\"Asserts that two floats are near each other.\n\n Checks that |f1 - f2| < err and asserts a test failure\n if not.\n\n Args:\n f1: A float value.\n f2: A float value.\n err: A float value.\n msg: An optional string message to append to the failure message.\n \"\"\"\n # f1 == f2 is needed here as we might have: f1, f2 = inf, inf\n self.assertTrue(f1 == f2 or math.fabs(f1 - f2) <= err,\n \"%f != %f +/- %f%s\" % (f1, f2, err, \" (%s)\" % msg\n if msg is not None else \"\"))\n\n def assertArrayNear(self, farray1, farray2, err, msg=None):\n \"\"\"Asserts that two float arrays are near each other.\n\n Checks that for all elements of farray1 and farray2\n |f1 - f2| < err. Asserts a test failure if not.\n\n Args:\n farray1: a list of float values.\n farray2: a list of float values.\n err: a float value.\n msg: Optional message to report on failure.\n \"\"\"\n self.assertEqual(len(farray1), len(farray2), msg=msg)\n for f1, f2 in zip(farray1, farray2):\n self.assertNear(float(f1), float(f2), err, msg=msg)\n\n def _NDArrayNear(self, ndarray1, ndarray2, err):\n return np.linalg.norm(ndarray1 - ndarray2) < err\n\n def assertNDArrayNear(self, ndarray1, ndarray2, err, msg=None):\n \"\"\"Asserts that two numpy arrays have near values.\n\n Args:\n ndarray1: a numpy ndarray.\n ndarray2: a numpy ndarray.\n err: a float. The maximum absolute difference allowed.\n msg: Optional message to report on failure.\n \"\"\"\n self.assertTrue(self._NDArrayNear(ndarray1, ndarray2, err), msg=msg)\n\n def _GetNdArray(self, a):\n if not isinstance(a, np.ndarray):\n a = np.array(a)\n return a\n\n def _assertArrayLikeAllClose(self, a, b, rtol=1e-6, atol=1e-6, msg=None):\n a = self._GetNdArray(a)\n b = self._GetNdArray(b)\n self.assertEqual(a.shape, b.shape, \"Shape mismatch: expected %s, got %s.\" %\n (a.shape, b.shape))\n if not np.allclose(a, b, rtol=rtol, atol=atol):\n # Prints more details than np.testing.assert_allclose.\n #\n # NOTE: numpy.allclose (and numpy.testing.assert_allclose)\n # checks whether two arrays are element-wise equal within a\n # tolerance. The relative difference (rtol * abs(b)) and the\n # absolute difference atol are added together to compare against\n # the absolute difference between a and b. Here, we want to\n # print out which elements violate such conditions.\n cond = np.logical_or(\n np.abs(a - b) > atol + rtol * np.abs(b),\n np.isnan(a) != np.isnan(b))\n if a.ndim:\n x = a[np.where(cond)]\n y = b[np.where(cond)]\n print(\"not close where = \", np.where(cond))\n else:\n # np.where is broken for scalars\n x, y = a, b\n print(\"not close lhs = \", x)\n print(\"not close rhs = \", y)\n print(\"not close dif = \", np.abs(x - y))\n print(\"not close tol = \", atol + rtol * np.abs(y))\n print(\"dtype = %s, shape = %s\" % (a.dtype, a.shape))\n # TODO(xpan): There seems to be a bug:\n # tensorflow/compiler/tests:binary_ops_test pass with float32\n # nan even though the equal_nan is False by default internally.\n np.testing.assert_allclose(\n a, b, rtol=rtol, atol=atol, err_msg=msg, equal_nan=True)\n\n def _assertAllCloseRecursive(self, a, b, rtol=1e-6, atol=1e-6, path=None,\n msg=None):\n path = path or []\n path_str = ((\"[\" + \"][\".join([str(p) for p in path]) + \"]\") if path else \"\")\n msg = msg if msg else \"\"\n\n # Check if a and/or b are namedtuples.\n if hasattr(a, \"_asdict\"):\n a = a._asdict()\n if hasattr(b, \"_asdict\"):\n b = b._asdict()\n a_is_dict = isinstance(a, dict)\n if a_is_dict != isinstance(b, dict):\n raise ValueError(\"Can't compare dict to non-dict, a%s vs b%s. %s\" %\n (path_str, path_str, msg))\n if a_is_dict:\n self.assertItemsEqual(\n a.keys(),\n b.keys(),\n msg=\"mismatched keys: a%s has keys %s, but b%s has keys %s. %s\" %\n (path_str, a.keys(), path_str, b.keys(), msg))\n for k in a:\n path.append(k)\n self._assertAllCloseRecursive(\n a[k], b[k], rtol=rtol, atol=atol, path=path, msg=msg)\n del path[-1]\n elif isinstance(a, (list, tuple)):\n # Try to directly compare a, b as ndarrays; if not work, then traverse\n # through the sequence, which is more expensive.\n try:\n a_as_ndarray = np.array(a)\n b_as_ndarray = np.array(b)\n self._assertArrayLikeAllClose(\n a_as_ndarray,\n b_as_ndarray,\n rtol=rtol,\n atol=atol,\n msg=\"Mismatched value: a%s is different from b%s. %s\" %\n (path_str, path_str, msg))\n except (ValueError, TypeError) as e:\n if len(a) != len(b):\n raise ValueError(\n \"Mismatched length: a%s has %d items, but b%s has %d items. %s\" %\n (path_str, len(a), path_str, len(b), msg))\n for idx, (a_ele, b_ele) in enumerate(zip(a, b)):\n path.append(str(idx))\n self._assertAllCloseRecursive(\n a_ele, b_ele, rtol=rtol, atol=atol, path=path, msg=msg)\n del path[-1]\n # a and b are ndarray like objects\n else:\n try:\n self._assertArrayLikeAllClose(\n a,\n b,\n rtol=rtol,\n atol=atol,\n msg=\"Mismatched value: a%s is different from b%s.\" % (path_str,\n path_str))\n except TypeError as e:\n msg = \"Error: a%s has %s, but b%s has %s\" % (\n path_str, type(a), path_str, type(b))\n e.args = ((e.args[0] + ' : ' + msg,) + e.args[1:])\n raise\n\n def assertAllClose(self, a, b, rtol=1e-6, atol=1e-6, msg=None):\n \"\"\"Asserts that two structures of numpy arrays, have near values.\n\n `a` and `b` can be arbitrarily nested structures. A layer of a nested\n structure can be a `dict`, `namedtuple`, `tuple` or `list`.\n\n Args:\n a: The expected numpy `ndarray`, or anything that can be converted into a\n numpy `ndarray`, or any arbitrarily nested of structure of these.\n b: The actual numpy `ndarray`, or anything that can be converted into a\n numpy `ndarray`, or any arbitrarily nested of structure of these.\n rtol: relative tolerance.\n atol: absolute tolerance.\n msg: Optional message to report on failure.\n\n Raises:\n ValueError: if only one of `a[p]` and `b[p]` is a dict or\n `a[p]` and `b[p]` have different length, where `[p]` denotes a path\n to the nested structure, e.g. given `a = [(1, 1), {'d': (6, 7)}]` and\n `[p] = [1]['d']`, then `a[p] = (6, 7)`.\n \"\"\"\n self._assertAllCloseRecursive(a, b, rtol=rtol, atol=atol, msg=msg)\n\n def assertAllCloseAccordingToType(self,\n a,\n b,\n rtol=1e-6,\n atol=1e-6,\n float_rtol=1e-6,\n float_atol=1e-6,\n half_rtol=1e-3,\n half_atol=1e-3,\n bfloat16_rtol=1e-2,\n bfloat16_atol=1e-2,\n msg=None):\n \"\"\"Like assertAllClose, but also suitable for comparing fp16 arrays.\n\n In particular, the tolerance is reduced to 1e-3 if at least\n one of the arguments is of type float16.\n\n Args:\n a: the expected numpy ndarray or anything can be converted to one.\n b: the actual numpy ndarray or anything can be converted to one.\n rtol: relative tolerance.\n atol: absolute tolerance.\n float_rtol: relative tolerance for float32.\n float_atol: absolute tolerance for float32.\n half_rtol: relative tolerance for float16.\n half_atol: absolute tolerance for float16.\n bfloat16_rtol: relative tolerance for bfloat16.\n bfloat16_atol: absolute tolerance for bfloat16.\n msg: Optional message to report on failure.\n \"\"\"\n a = self._GetNdArray(a)\n b = self._GetNdArray(b)\n # types with lower tol are put later to overwrite previous ones.\n if (a.dtype == np.float32 or b.dtype == np.float32 or\n a.dtype == np.complex64 or b.dtype == np.complex64):\n rtol = max(rtol, float_rtol)\n atol = max(atol, float_atol)\n if a.dtype == np.float16 or b.dtype == np.float16:\n rtol = max(rtol, half_rtol)\n atol = max(atol, half_atol)\n if (a.dtype == dtypes.bfloat16.as_numpy_dtype or\n b.dtype == dtypes.bfloat16.as_numpy_dtype):\n rtol = max(rtol, bfloat16_rtol)\n atol = max(atol, bfloat16_atol)\n\n self.assertAllClose(a, b, rtol=rtol, atol=atol, msg=msg)\n\n def assertAllEqual(self, a, b, msg=None):\n \"\"\"Asserts that two numpy arrays have the same values.\n\n Args:\n a: the expected numpy ndarray or anything can be converted to one.\n b: the actual numpy ndarray or anything can be converted to one.\n msg: Optional message to report on failure.\n \"\"\"\n msg = msg if msg else \"\"\n a = self._GetNdArray(a)\n b = self._GetNdArray(b)\n self.assertEqual(a.shape, b.shape, \"Shape mismatch: expected %s, got %s.\"\n \" %s\" % (a.shape, b.shape, msg))\n same = (a == b)\n\n if a.dtype == np.float32 or a.dtype == np.float64:\n same = np.logical_or(same, np.logical_and(np.isnan(a), np.isnan(b)))\n if not np.all(same):\n # Prints more details than np.testing.assert_array_equal.\n diff = np.logical_not(same)\n if a.ndim:\n x = a[np.where(diff)]\n y = b[np.where(diff)]\n print(\"not equal where = \", np.where(diff))\n else:\n # np.where is broken for scalars\n x, y = a, b\n print(\"not equal lhs = \", x)\n print(\"not equal rhs = \", y)\n np.testing.assert_array_equal(a, b, err_msg=msg)\n\n # pylint: disable=g-doc-return-or-yield\n @contextlib.contextmanager\n def assertRaisesWithPredicateMatch(self, exception_type,\n expected_err_re_or_predicate):\n \"\"\"Returns a context manager to enclose code expected to raise an exception.\n\n If the exception is an OpError, the op stack is also included in the message\n predicate search.\n\n Args:\n exception_type: The expected type of exception that should be raised.\n expected_err_re_or_predicate: If this is callable, it should be a function\n of one argument that inspects the passed-in exception and\n returns True (success) or False (please fail the test). Otherwise, the\n error message is expected to match this regular expression partially.\n\n Returns:\n A context manager to surround code that is expected to raise an\n exception.\n \"\"\"\n if callable(expected_err_re_or_predicate):\n predicate = expected_err_re_or_predicate\n else:\n\n def predicate(e):\n err_str = e.message if isinstance(e, errors.OpError) else str(e)\n op = e.op if isinstance(e, errors.OpError) else None\n while op is not None:\n err_str += \"\\nCaused by: \" + op.name\n op = op._original_op # pylint: disable=protected-access\n logging.info(\"Searching within error strings: '%s' within '%s'\",\n expected_err_re_or_predicate, err_str)\n return re.search(expected_err_re_or_predicate, err_str)\n\n try:\n yield\n self.fail(exception_type.__name__ + \" not raised\")\n except Exception as e: # pylint: disable=broad-except\n if not isinstance(e, exception_type) or not predicate(e):\n raise AssertionError(\"Exception of type %s: %s\" % (str(type(e)),\n str(e)))\n\n # pylint: enable=g-doc-return-or-yield\n\n def assertRaisesOpError(self, expected_err_re_or_predicate):\n return self.assertRaisesWithPredicateMatch(errors.OpError,\n expected_err_re_or_predicate)\n\n def assertShapeEqual(self, np_array, tf_tensor, msg=None):\n \"\"\"Asserts that a Numpy ndarray and a TensorFlow tensor have the same shape.\n\n Args:\n np_array: A Numpy ndarray or Numpy scalar.\n tf_tensor: A Tensor.\n msg: Optional message to report on failure.\n\n Raises:\n TypeError: If the arguments have the wrong type.\n \"\"\"\n if not isinstance(np_array, (np.ndarray, np.generic)):\n raise TypeError(\"np_array must be a Numpy ndarray or Numpy scalar\")\n if not isinstance(tf_tensor, ops.Tensor):\n raise TypeError(\"tf_tensor must be a Tensor\")\n self.assertAllEqual(np_array.shape, tf_tensor.get_shape().as_list(),\n msg=msg)\n\n def assertDeviceEqual(self, device1, device2, msg=None):\n \"\"\"Asserts that the two given devices are the same.\n\n Args:\n device1: A string device name or TensorFlow `DeviceSpec` object.\n device2: A string device name or TensorFlow `DeviceSpec` object.\n msg: Optional message to report on failure.\n \"\"\"\n device1 = pydev.canonical_name(device1)\n device2 = pydev.canonical_name(device2)\n self.assertEqual(device1, device2,\n \"Devices %s and %s are not equal. %s\" % \n (device1, device2, msg))\n\n # Fix Python 3 compatibility issues\n if six.PY3:\n # pylint: disable=invalid-name\n\n # Silence a deprecation warning\n assertRaisesRegexp = googletest.TestCase.assertRaisesRegex\n\n # assertItemsEqual is assertCountEqual as of 3.2.\n assertItemsEqual = googletest.TestCase.assertCountEqual\n\n # pylint: enable=invalid-name\n\n\n@tf_export(\"test.create_local_cluster\")\ndef create_local_cluster(num_workers,\n num_ps,\n protocol=\"grpc\",\n worker_config=None,\n ps_config=None):\n \"\"\"Create and start local servers and return the associated `Server` objects.\n\n Example:\n ```python\n workers, _ = tf.test.create_local_cluster(num_workers=2, num_ps=2)\n\n worker_sessions = [tf.Session(w.target) for w in workers]\n\n with tf.device(\"/job:ps/task:0\"):\n ...\n with tf.device(\"/job:ps/task:1\"):\n ...\n with tf.device(\"/job:worker/task:0\"):\n ...\n with tf.device(\"/job:worker/task:1\"):\n ...\n\n worker_sessions[0].run(...)\n ```\n\n Args:\n num_workers: Number of worker servers to start.\n num_ps: Number of PS servers to start.\n protocol: Communication protocol. Allowed values are documented in\n the documentation of `tf.train.Server`.\n worker_config: (optional) ConfigProto to initialize workers. Can be used\n to instantiate multiple devices etc.\n ps_config: (optional) ConfigProto to initialize PS servers.\n\n Returns:\n A tuple `(worker_servers, ps_servers)`. `worker_servers` is a list\n of `num_workers` objects of type `tf.train.Server` (all running locally);\n and `ps_servers` is a list of `num_ps` objects of similar type.\n\n Raises:\n ImportError: if portpicker module was not found at load time\n \"\"\"\n if _portpicker_import_error:\n raise _portpicker_import_error # pylint: disable=raising-bad-type\n worker_ports = [portpicker.pick_unused_port() for _ in range(num_workers)]\n ps_ports = [portpicker.pick_unused_port() for _ in range(num_ps)]\n cluster_dict = {\n \"worker\": [\"localhost:%s\" % port for port in worker_ports],\n \"ps\": [\"localhost:%s\" % port for port in ps_ports]\n }\n cs = server_lib.ClusterSpec(cluster_dict)\n\n workers = [\n server_lib.Server(\n cs,\n job_name=\"worker\",\n protocol=protocol,\n task_index=ix,\n config=worker_config,\n start=True) for ix in range(num_workers)\n ]\n ps_servers = [\n server_lib.Server(\n cs,\n job_name=\"ps\",\n protocol=protocol,\n task_index=ix,\n config=ps_config,\n start=True) for ix in range(num_ps)\n ]\n\n return workers, ps_servers\n\n\ndef get_node_def_from_graph(node_name, graph_def):\n \"\"\"Returns the `NodeDef` instance for given node name in the graph def.\n\n This method explores only the NodeDefs in `graph_def.node`.\n\n Args:\n node_name: Name of the NodeDef to search for.\n graph_def: An instance of `GraphDef` proto.\n\n Returns:\n the `NodeDef` instance whose name field matches the given node_name or None.\n \"\"\"\n for node_def in graph_def.node:\n if node_def.name == node_name:\n return node_def\n return None\n\n\ndef set_producer_version(graph, producer_version):\n \"\"\"Sets graph.graph_def_versions.producer to `producer_version`.\"\"\"\n # The C API doesn't expose altering GraphDefVersions. We can indirectly set\n # it via import_graph_def though.\n graph_def = graph_pb2.GraphDef()\n graph_def.versions.producer = producer_version\n with graph.as_default():\n importer.import_graph_def(graph_def)\n assert graph.graph_def_versions.producer, producer_version\n"
] |
[
[
"tensorflow.python.client.device_lib.list_local_devices",
"tensorflow.python.pywrap_tensorflow.IsGoogleCudaEnabled",
"tensorflow.python.eager.context.in_eager_mode",
"numpy.all",
"tensorflow.python.eager.context.get_default_context",
"tensorflow.python.framework.ops.device",
"numpy.where",
"tensorflow.python.ops.array_ops.transpose",
"numpy.allclose",
"tensorflow.python.eager.context.device",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.framework.ops.get_default_session",
"tensorflow.python.util.protobuf.compare.assertProtoEqual",
"tensorflow.python.util.compat.as_str",
"tensorflow.python.training.server_lib.Server",
"tensorflow.python.eager.context.graph_mode",
"tensorflow.python.util.nest.map_structure",
"tensorflow.python.pywrap_tensorflow.InstallStacktraceHandler",
"tensorflow.python.framework.ops.reset_default_graph",
"numpy.logical_not",
"tensorflow.python.eager.context.eager_mode",
"tensorflow.python.framework.importer.import_graph_def",
"tensorflow.python.pywrap_tensorflow.CudaSupportsHalfMatMulAndConv",
"numpy.isnan",
"tensorflow.python.training.server_lib.ClusterSpec",
"tensorflow.python.framework.device.canonical_name",
"tensorflow.core.protobuf.config_pb2.ConfigProto",
"numpy.testing.assert_allclose",
"numpy.array",
"tensorflow.python.framework.random_seed.set_random_seed",
"tensorflow.python.util.protobuf.compare.ProtoEq",
"tensorflow.python.platform.googletest.GetTempDir",
"numpy.abs",
"numpy.random.seed",
"tensorflow.python.framework.ops._default_graph_stack.reset",
"tensorflow.python.framework.ops.Graph",
"numpy.linalg.norm",
"tensorflow.python.platform.tf_logging.info",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.ops.array_ops.reshape",
"numpy.testing.assert_array_equal",
"tensorflow.core.framework.graph_pb2.GraphDef",
"tensorflow.python.framework.ops.get_collection_proto_type"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
}
] |
lkeegan/spikeinterface
|
[
"237cc6f6119a5365be1d9e1c235d8410ceb482d3"
] |
[
"spikeinterface/sortingcomponents/motion_correction.py"
] |
[
"import numpy as np\nimport scipy.interpolate\n\nfrom tqdm import tqdm\n\n\ndef correct_motion_on_peaks(peaks, peak_locations, times,\n motion, temporal_bins, spatial_bins,\n direction='y', progress_bar=False):\n \"\"\"\n Given the output of estimate_motion() apply inverse motion on peak location.\n\n Parameters\n ----------\n peaks: np.array\n peaks vector\n peak_locations: \n peaks location vector\n times: \n times vector of recording\n motion: np.array 2D\n motion.shape[0] equal temporal_bins.shape[0] -1\n motion.shape[1] equal 1 when \"rigid\" motion\n equal temporal_bins.shape[0] when \"none rigid\"\n temporal_bins: np.array\n Temporal bins in second.\n spatial_bins: None or np.array\n Bins for non-rigid motion. If None, rigid motion is used \n\n Returns\n -------\n corrected_peak_locations: np.array\n Motion-corrected peak locations\n \"\"\"\n corrected_peak_locations = peak_locations.copy()\n\n if spatial_bins is None:\n # rigid motion interpolation 1D\n center_temporal_bins = temporal_bins[:-1] + np.diff(temporal_bins) / 2.\n sample_bins = np.searchsorted(times, center_temporal_bins)\n f = scipy.interpolate.interp1d(sample_bins, motion[:, 0], bounds_error=False, fill_value=\"extrapolate\")\n shift = f(peaks['sample_ind'])\n corrected_peak_locations[direction] -= shift\n else:\n # non rigid motion = interpolation 2D\n center_temporal_bins = temporal_bins[:-1] + np.diff(temporal_bins) / 2.\n sample_bins = np.searchsorted(times, center_temporal_bins)\n f = scipy.interpolate.RegularGridInterpolator((sample_bins, spatial_bins), motion, \n method='linear', bounds_error=False, fill_value=None)\n shift = f(list(zip(peaks['sample_ind'], peak_locations[direction])))\n corrected_peak_locations[direction] -= shift\n\n return corrected_peak_locations\n\n\ndef correct_motion_on_traces(traces, channel_locations, motion, temporal_bins, spatial_bins):\n \"\"\"\n Apply inverse motion with spatial interpolation on traces.\n\n Traces can be full traces, but also waveforms snippets.\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n pass"
] |
[
[
"numpy.diff",
"numpy.searchsorted"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
overlordmax/PaddleRec
|
[
"b4d6ac77450d98a935c6a5d0eba6abbb21b9d06a"
] |
[
"core/metrics/precision_recall.py"
] |
[
"# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\n\nimport numpy as np\nimport paddle.fluid as fluid\n\nfrom paddlerec.core.metric import Metric\nfrom paddle.fluid.initializer import Constant\nfrom paddle.fluid.layer_helper import LayerHelper\nfrom paddle.fluid.layers.tensor import Variable\n\n\nclass PrecisionRecall(Metric):\n \"\"\"\n Metric For Fluid Model\n \"\"\"\n\n def __init__(self, input, label, class_num):\n \"\"\"R\n \"\"\"\n kwargs = locals()\n del kwargs['self']\n\n self.num_cls = class_num\n\n if not isinstance(input, Variable):\n raise ValueError(\"input must be Variable, but received %s\" %\n type(input))\n if not isinstance(label, Variable):\n raise ValueError(\"label must be Variable, but received %s\" %\n type(label))\n\n helper = LayerHelper(\"PaddleRec_PrecisionRecall\", **kwargs)\n label = fluid.layers.cast(label, dtype=\"int32\")\n label.stop_gradient = True\n max_probs, indices = fluid.layers.nn.topk(input, k=1)\n indices = fluid.layers.cast(indices, dtype=\"int32\")\n indices.stop_gradient = True\n\n states_info, _ = helper.create_or_get_global_variable(\n name=\"states_info\",\n persistable=True,\n dtype='float32',\n shape=[self.num_cls, 4])\n states_info.stop_gradient = True\n\n helper.set_variable_initializer(\n states_info, Constant(\n value=0.0, force_cpu=True))\n\n batch_metrics, _ = helper.create_or_get_global_variable(\n name=\"batch_metrics\",\n persistable=False,\n dtype='float32',\n shape=[6])\n accum_metrics, _ = helper.create_or_get_global_variable(\n name=\"global_metrics\",\n persistable=False,\n dtype='float32',\n shape=[6])\n\n batch_states = fluid.layers.fill_constant(\n shape=[self.num_cls, 4], value=0.0, dtype=\"float32\")\n batch_states.stop_gradient = True\n\n helper.append_op(\n type=\"precision_recall\",\n attrs={'class_number': self.num_cls},\n inputs={\n 'MaxProbs': [max_probs],\n 'Indices': [indices],\n 'Labels': [label],\n 'StatesInfo': [states_info]\n },\n outputs={\n 'BatchMetrics': [batch_metrics],\n 'AccumMetrics': [accum_metrics],\n 'AccumStatesInfo': [batch_states]\n })\n helper.append_op(\n type=\"assign\",\n inputs={'X': [batch_states]},\n outputs={'Out': [states_info]})\n\n batch_states.stop_gradient = True\n states_info.stop_gradient = True\n\n self._global_metric_state_vars = dict()\n self._global_metric_state_vars['states_info'] = (states_info.name,\n \"float32\")\n\n self.metrics = dict()\n self.metrics[\"precision_recall_f1\"] = accum_metrics\n self.metrics[\"[TP FP TN FN]\"] = states_info\n\n def _calculate(self, global_metrics):\n for key in self._global_metric_state_vars:\n if key not in global_metrics:\n raise ValueError(\"%s not existed\" % key)\n\n def calc_precision(tp_count, fp_count):\n if tp_count > 0.0 or fp_count > 0.0:\n return tp_count / (tp_count + fp_count)\n return 1.0\n\n def calc_recall(tp_count, fn_count):\n if tp_count > 0.0 or fn_count > 0.0:\n return tp_count / (tp_count + fn_count)\n return 1.0\n\n def calc_f1_score(precision, recall):\n if precision > 0.0 or recall > 0.0:\n return 2 * precision * recall / (precision + recall)\n return 0.0\n\n states = global_metrics[\"states_info\"]\n total_tp_count = 0.0\n total_fp_count = 0.0\n total_fn_count = 0.0\n macro_avg_precision = 0.0\n macro_avg_recall = 0.0\n for i in range(self.num_cls):\n total_tp_count += states[i][0]\n total_fp_count += states[i][1]\n total_fn_count += states[i][3]\n macro_avg_precision += calc_precision(states[i][0], states[i][1])\n macro_avg_recall += calc_recall(states[i][0], states[i][3])\n metrics = []\n macro_avg_precision /= self.num_cls\n macro_avg_recall /= self.num_cls\n metrics.append(macro_avg_precision)\n metrics.append(macro_avg_recall)\n metrics.append(calc_f1_score(macro_avg_precision, macro_avg_recall))\n micro_avg_precision = calc_precision(total_tp_count, total_fp_count)\n metrics.append(micro_avg_precision)\n micro_avg_recall = calc_recall(total_tp_count, total_fn_count)\n metrics.append(micro_avg_recall)\n metrics.append(calc_f1_score(micro_avg_precision, micro_avg_recall))\n return \"total metrics: [TP, FP, TN, FN]=%s; precision_recall_f1=%s\" % (\n str(states), str(np.array(metrics).astype('float32')))\n\n def get_result(self):\n return self.metrics\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Seifar/ChitAnalysis
|
[
"9444dce96954c546333d5aecc92a06c3bfd19aa5"
] |
[
"venv/lib/python3.6/site-packages/numpy/core/numerictypes.py"
] |
[
"\"\"\"\nnumerictypes: Define the numeric type objects\n\nThis module is designed so \"from numerictypes import \\\\*\" is safe.\nExported symbols include:\n\n Dictionary with all registered number types (including aliases):\n typeDict\n\n Type objects (not all will be available, depends on platform):\n see variable sctypes for which ones you have\n\n Bit-width names\n\n int8 int16 int32 int64 int128\n uint8 uint16 uint32 uint64 uint128\n float16 float32 float64 float96 float128 float256\n complex32 complex64 complex128 complex192 complex256 complex512\n datetime64 timedelta64\n\n c-based names\n\n bool_\n\n object_\n\n void, str_, unicode_\n\n byte, ubyte,\n short, ushort\n intc, uintc,\n intp, uintp,\n int_, uint,\n longlong, ulonglong,\n\n single, csingle,\n float_, complex_,\n longfloat, clongfloat,\n\n As part of the type-hierarchy: xx -- is bit-width\n\n generic\n +-> bool_ (kind=b)\n +-> number\n | +-> integer\n | | +-> signedinteger (intxx) (kind=i)\n | | | byte\n | | | short\n | | | intc\n | | | intp int0\n | | | int_\n | | | longlong\n | | \\\\-> unsignedinteger (uintxx) (kind=u)\n | | ubyte\n | | ushort\n | | uintc\n | | uintp uint0\n | | uint_\n | | ulonglong\n | +-> inexact\n | +-> floating (floatxx) (kind=f)\n | | half\n | | single\n | | float_ (double)\n | | longfloat\n | \\\\-> complexfloating (complexxx) (kind=c)\n | csingle (singlecomplex)\n | complex_ (cfloat, cdouble)\n | clongfloat (longcomplex)\n +-> flexible\n | +-> character\n | | str_ (string_, bytes_) (kind=S) [Python 2]\n | | unicode_ (kind=U) [Python 2]\n | |\n | | bytes_ (string_) (kind=S) [Python 3]\n | | str_ (unicode_) (kind=U) [Python 3]\n | |\n | \\\\-> void (kind=V)\n \\\\-> object_ (not used much) (kind=O)\n\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\nimport types as _types\nimport sys\nimport numbers\nimport warnings\n\nfrom numpy.compat import bytes, long\nfrom numpy.core.multiarray import (\n typeinfo, ndarray, array, empty, dtype, datetime_data,\n datetime_as_string, busday_offset, busday_count, is_busday,\n busdaycalendar\n )\n\n\n# we add more at the bottom\n__all__ = ['sctypeDict', 'sctypeNA', 'typeDict', 'typeNA', 'sctypes',\n 'ScalarType', 'obj2sctype', 'cast', 'nbytes', 'sctype2char',\n 'maximum_sctype', 'issctype', 'typecodes', 'find_common_type',\n 'issubdtype', 'datetime_data', 'datetime_as_string',\n 'busday_offset', 'busday_count', 'is_busday', 'busdaycalendar',\n ]\n\n\n# we don't export these for import *, but we do want them accessible\n# as numerictypes.bool, etc.\nif sys.version_info[0] >= 3:\n from builtins import bool, int, float, complex, object, str\n unicode = str\nelse:\n from __builtin__ import bool, int, float, complex, object, unicode, str\n\n\n# String-handling utilities to avoid locale-dependence.\n\n# \"import string\" is costly to import!\n# Construct the translation tables directly\n# \"A\" = chr(65), \"a\" = chr(97)\n_all_chars = [chr(_m) for _m in range(256)]\n_ascii_upper = _all_chars[65:65+26]\n_ascii_lower = _all_chars[97:97+26]\nLOWER_TABLE = \"\".join(_all_chars[:65] + _ascii_lower + _all_chars[65+26:])\nUPPER_TABLE = \"\".join(_all_chars[:97] + _ascii_upper + _all_chars[97+26:])\n\n\ndef english_lower(s):\n \"\"\" Apply English case rules to convert ASCII strings to all lower case.\n\n This is an internal utility function to replace calls to str.lower() such\n that we can avoid changing behavior with changing locales. In particular,\n Turkish has distinct dotted and dotless variants of the Latin letter \"I\" in\n both lowercase and uppercase. Thus, \"I\".lower() != \"i\" in a \"tr\" locale.\n\n Parameters\n ----------\n s : str\n\n Returns\n -------\n lowered : str\n\n Examples\n --------\n >>> from numpy.core.numerictypes import english_lower\n >>> english_lower('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_')\n 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789_'\n >>> english_lower('')\n ''\n \"\"\"\n lowered = s.translate(LOWER_TABLE)\n return lowered\n\ndef english_upper(s):\n \"\"\" Apply English case rules to convert ASCII strings to all upper case.\n\n This is an internal utility function to replace calls to str.upper() such\n that we can avoid changing behavior with changing locales. In particular,\n Turkish has distinct dotted and dotless variants of the Latin letter \"I\" in\n both lowercase and uppercase. Thus, \"i\".upper() != \"I\" in a \"tr\" locale.\n\n Parameters\n ----------\n s : str\n\n Returns\n -------\n uppered : str\n\n Examples\n --------\n >>> from numpy.core.numerictypes import english_upper\n >>> english_upper('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_')\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'\n >>> english_upper('')\n ''\n \"\"\"\n uppered = s.translate(UPPER_TABLE)\n return uppered\n\ndef english_capitalize(s):\n \"\"\" Apply English case rules to convert the first character of an ASCII\n string to upper case.\n\n This is an internal utility function to replace calls to str.capitalize()\n such that we can avoid changing behavior with changing locales.\n\n Parameters\n ----------\n s : str\n\n Returns\n -------\n capitalized : str\n\n Examples\n --------\n >>> from numpy.core.numerictypes import english_capitalize\n >>> english_capitalize('int8')\n 'Int8'\n >>> english_capitalize('Int8')\n 'Int8'\n >>> english_capitalize('')\n ''\n \"\"\"\n if s:\n return english_upper(s[0]) + s[1:]\n else:\n return s\n\n\nsctypeDict = {} # Contains all leaf-node scalar types with aliases\nsctypeNA = {} # Contails all leaf-node types -> numarray type equivalences\nallTypes = {} # Collect the types we will add to the module here\n\ndef _evalname(name):\n k = 0\n for ch in name:\n if ch in '0123456789':\n break\n k += 1\n try:\n bits = int(name[k:])\n except ValueError:\n bits = 0\n base = name[:k]\n return base, bits\n\ndef bitname(obj):\n \"\"\"Return a bit-width name for a given type object\"\"\"\n name = obj.__name__\n base = ''\n char = ''\n try:\n if name[-1] == '_':\n newname = name[:-1]\n else:\n newname = name\n info = typeinfo[english_upper(newname)]\n assert(info.type == obj) # sanity check\n bits = info.bits\n\n except KeyError: # bit-width name\n base, bits = _evalname(name)\n char = base[0]\n\n if name == 'bool_':\n char = 'b'\n base = 'bool'\n elif name == 'void':\n char = 'V'\n base = 'void'\n elif name == 'object_':\n char = 'O'\n base = 'object'\n bits = 0\n elif name == 'datetime64':\n char = 'M'\n elif name == 'timedelta64':\n char = 'm'\n\n if sys.version_info[0] >= 3:\n if name == 'bytes_':\n char = 'S'\n base = 'bytes'\n elif name == 'str_':\n char = 'U'\n base = 'str'\n else:\n if name == 'string_':\n char = 'S'\n base = 'string'\n elif name == 'unicode_':\n char = 'U'\n base = 'unicode'\n\n bytes = bits // 8\n\n if char != '' and bytes != 0:\n char = \"%s%d\" % (char, bytes)\n\n return base, bits, char\n\n\ndef _add_types():\n for type_name, info in typeinfo.items():\n name = english_lower(type_name)\n if not isinstance(info, type):\n # define C-name and insert typenum and typechar references also\n allTypes[name] = info.type\n sctypeDict[name] = info.type\n sctypeDict[info.char] = info.type\n sctypeDict[info.num] = info.type\n\n else: # generic class\n allTypes[name] = info\n_add_types()\n\ndef _add_aliases():\n for type_name, info in typeinfo.items():\n if isinstance(info, type):\n continue\n name = english_lower(type_name)\n\n # insert bit-width version for this class (if relevant)\n base, bit, char = bitname(info.type)\n if base[-3:] == 'int' or char[0] in 'ui':\n continue\n if base != '':\n myname = \"%s%d\" % (base, bit)\n if (name not in ('longdouble', 'clongdouble') or\n myname not in allTypes):\n base_capitalize = english_capitalize(base)\n if base == 'complex':\n na_name = '%s%d' % (base_capitalize, bit//2)\n elif base == 'bool':\n na_name = base_capitalize\n else:\n na_name = \"%s%d\" % (base_capitalize, bit)\n\n allTypes[myname] = info.type\n\n # add mapping for both the bit name and the numarray name\n sctypeDict[myname] = info.type\n sctypeDict[na_name] = info.type\n\n # add forward, reverse, and string mapping to numarray\n sctypeNA[na_name] = info.type\n sctypeNA[info.type] = na_name\n sctypeNA[info.char] = na_name\n if char != '':\n sctypeDict[char] = info.type\n sctypeNA[char] = na_name\n_add_aliases()\n\n# Integers are handled so that the int32 and int64 types should agree\n# exactly with NPY_INT32, NPY_INT64. We need to enforce the same checking\n# as is done in arrayobject.h where the order of getting a bit-width match\n# is long, longlong, int, short, char.\ndef _add_integer_aliases():\n _ctypes = ['LONG', 'LONGLONG', 'INT', 'SHORT', 'BYTE']\n for ctype in _ctypes:\n i_info = typeinfo[ctype]\n u_info = typeinfo['U'+ctype]\n bits = i_info.bits # same for both\n\n for info, charname, intname, Intname in [\n (i_info,'i%d' % (bits//8,), 'int%d' % bits, 'Int%d' % bits),\n (u_info,'u%d' % (bits//8,), 'uint%d' % bits, 'UInt%d' % bits)]:\n if intname not in allTypes.keys():\n allTypes[intname] = info.type\n sctypeDict[intname] = info.type\n sctypeDict[Intname] = info.type\n sctypeDict[charname] = info.type\n sctypeNA[Intname] = info.type\n sctypeNA[charname] = info.type\n sctypeNA[info.type] = Intname\n sctypeNA[info.char] = Intname\n_add_integer_aliases()\n\n# We use these later\nvoid = allTypes['void']\ngeneric = allTypes['generic']\n\n#\n# Rework the Python names (so that float and complex and int are consistent\n# with Python usage)\n#\ndef _set_up_aliases():\n type_pairs = [('complex_', 'cdouble'),\n ('int0', 'intp'),\n ('uint0', 'uintp'),\n ('single', 'float'),\n ('csingle', 'cfloat'),\n ('singlecomplex', 'cfloat'),\n ('float_', 'double'),\n ('intc', 'int'),\n ('uintc', 'uint'),\n ('int_', 'long'),\n ('uint', 'ulong'),\n ('cfloat', 'cdouble'),\n ('longfloat', 'longdouble'),\n ('clongfloat', 'clongdouble'),\n ('longcomplex', 'clongdouble'),\n ('bool_', 'bool'),\n ('unicode_', 'unicode'),\n ('object_', 'object')]\n if sys.version_info[0] >= 3:\n type_pairs.extend([('bytes_', 'string'),\n ('str_', 'unicode'),\n ('string_', 'string')])\n else:\n type_pairs.extend([('str_', 'string'),\n ('string_', 'string'),\n ('bytes_', 'string')])\n for alias, t in type_pairs:\n allTypes[alias] = allTypes[t]\n sctypeDict[alias] = sctypeDict[t]\n # Remove aliases overriding python types and modules\n to_remove = ['ulong', 'object', 'unicode', 'int', 'long', 'float',\n 'complex', 'bool', 'string', 'datetime', 'timedelta']\n if sys.version_info[0] >= 3:\n # Py3K\n to_remove.append('bytes')\n to_remove.append('str')\n to_remove.remove('unicode')\n to_remove.remove('long')\n for t in to_remove:\n try:\n del allTypes[t]\n del sctypeDict[t]\n except KeyError:\n pass\n_set_up_aliases()\n\n# Now, construct dictionary to lookup character codes from types\n_sctype2char_dict = {}\ndef _construct_char_code_lookup():\n for name, info in typeinfo.items():\n if not isinstance(info, type):\n if info.char not in ['p', 'P']:\n _sctype2char_dict[info.type] = info.char\n_construct_char_code_lookup()\n\n\nsctypes = {'int': [],\n 'uint':[],\n 'float':[],\n 'complex':[],\n 'others':[bool, object, bytes, unicode, void]}\n\ndef _add_array_type(typename, bits):\n try:\n t = allTypes['%s%d' % (typename, bits)]\n except KeyError:\n pass\n else:\n sctypes[typename].append(t)\n\ndef _set_array_types():\n ibytes = [1, 2, 4, 8, 16, 32, 64]\n fbytes = [2, 4, 8, 10, 12, 16, 32, 64]\n for bytes in ibytes:\n bits = 8*bytes\n _add_array_type('int', bits)\n _add_array_type('uint', bits)\n for bytes in fbytes:\n bits = 8*bytes\n _add_array_type('float', bits)\n _add_array_type('complex', 2*bits)\n _gi = dtype('p')\n if _gi.type not in sctypes['int']:\n indx = 0\n sz = _gi.itemsize\n _lst = sctypes['int']\n while (indx < len(_lst) and sz >= _lst[indx](0).itemsize):\n indx += 1\n sctypes['int'].insert(indx, _gi.type)\n sctypes['uint'].insert(indx, dtype('P').type)\n_set_array_types()\n\n\ngenericTypeRank = ['bool', 'int8', 'uint8', 'int16', 'uint16',\n 'int32', 'uint32', 'int64', 'uint64', 'int128',\n 'uint128', 'float16',\n 'float32', 'float64', 'float80', 'float96', 'float128',\n 'float256',\n 'complex32', 'complex64', 'complex128', 'complex160',\n 'complex192', 'complex256', 'complex512', 'object']\n\ndef maximum_sctype(t):\n \"\"\"\n Return the scalar type of highest precision of the same kind as the input.\n\n Parameters\n ----------\n t : dtype or dtype specifier\n The input data type. This can be a `dtype` object or an object that\n is convertible to a `dtype`.\n\n Returns\n -------\n out : dtype\n The highest precision data type of the same kind (`dtype.kind`) as `t`.\n\n See Also\n --------\n obj2sctype, mintypecode, sctype2char\n dtype\n\n Examples\n --------\n >>> np.maximum_sctype(int)\n <type 'numpy.int64'>\n >>> np.maximum_sctype(np.uint8)\n <type 'numpy.uint64'>\n >>> np.maximum_sctype(complex)\n <type 'numpy.complex192'>\n\n >>> np.maximum_sctype(str)\n <type 'numpy.string_'>\n\n >>> np.maximum_sctype('i2')\n <type 'numpy.int64'>\n >>> np.maximum_sctype('f4')\n <type 'numpy.float96'>\n\n \"\"\"\n g = obj2sctype(t)\n if g is None:\n return t\n t = g\n name = t.__name__\n base, bits = _evalname(name)\n if bits == 0:\n return t\n else:\n return sctypes[base][-1]\n\n\ndef issctype(rep):\n \"\"\"\n Determines whether the given object represents a scalar data-type.\n\n Parameters\n ----------\n rep : any\n If `rep` is an instance of a scalar dtype, True is returned. If not,\n False is returned.\n\n Returns\n -------\n out : bool\n Boolean result of check whether `rep` is a scalar dtype.\n\n See Also\n --------\n issubsctype, issubdtype, obj2sctype, sctype2char\n\n Examples\n --------\n >>> np.issctype(np.int32)\n True\n >>> np.issctype(list)\n False\n >>> np.issctype(1.1)\n False\n\n Strings are also a scalar type:\n\n >>> np.issctype(np.dtype('str'))\n True\n\n \"\"\"\n if not isinstance(rep, (type, dtype)):\n return False\n try:\n res = obj2sctype(rep)\n if res and res != object_:\n return True\n return False\n except Exception:\n return False\n\ndef obj2sctype(rep, default=None):\n \"\"\"\n Return the scalar dtype or NumPy equivalent of Python type of an object.\n\n Parameters\n ----------\n rep : any\n The object of which the type is returned.\n default : any, optional\n If given, this is returned for objects whose types can not be\n determined. If not given, None is returned for those objects.\n\n Returns\n -------\n dtype : dtype or Python type\n The data type of `rep`.\n\n See Also\n --------\n sctype2char, issctype, issubsctype, issubdtype, maximum_sctype\n\n Examples\n --------\n >>> np.obj2sctype(np.int32)\n <type 'numpy.int32'>\n >>> np.obj2sctype(np.array([1., 2.]))\n <type 'numpy.float64'>\n >>> np.obj2sctype(np.array([1.j]))\n <type 'numpy.complex128'>\n\n >>> np.obj2sctype(dict)\n <type 'numpy.object_'>\n >>> np.obj2sctype('string')\n <type 'numpy.string_'>\n\n >>> np.obj2sctype(1, default=list)\n <type 'list'>\n\n \"\"\"\n # prevent abtract classes being upcast\n if isinstance(rep, type) and issubclass(rep, generic):\n return rep\n # extract dtype from arrays\n if isinstance(rep, ndarray):\n return rep.dtype.type\n # fall back on dtype to convert\n try:\n res = dtype(rep)\n except Exception:\n return default\n else:\n return res.type\n\n\ndef issubclass_(arg1, arg2):\n \"\"\"\n Determine if a class is a subclass of a second class.\n\n `issubclass_` is equivalent to the Python built-in ``issubclass``,\n except that it returns False instead of raising a TypeError if one\n of the arguments is not a class.\n\n Parameters\n ----------\n arg1 : class\n Input class. True is returned if `arg1` is a subclass of `arg2`.\n arg2 : class or tuple of classes.\n Input class. If a tuple of classes, True is returned if `arg1` is a\n subclass of any of the tuple elements.\n\n Returns\n -------\n out : bool\n Whether `arg1` is a subclass of `arg2` or not.\n\n See Also\n --------\n issubsctype, issubdtype, issctype\n\n Examples\n --------\n >>> np.issubclass_(np.int32, int)\n True\n >>> np.issubclass_(np.int32, float)\n False\n\n \"\"\"\n try:\n return issubclass(arg1, arg2)\n except TypeError:\n return False\n\ndef issubsctype(arg1, arg2):\n \"\"\"\n Determine if the first argument is a subclass of the second argument.\n\n Parameters\n ----------\n arg1, arg2 : dtype or dtype specifier\n Data-types.\n\n Returns\n -------\n out : bool\n The result.\n\n See Also\n --------\n issctype, issubdtype,obj2sctype\n\n Examples\n --------\n >>> np.issubsctype('S8', str)\n True\n >>> np.issubsctype(np.array([1]), int)\n True\n >>> np.issubsctype(np.array([1]), float)\n False\n\n \"\"\"\n return issubclass(obj2sctype(arg1), obj2sctype(arg2))\n\ndef issubdtype(arg1, arg2):\n \"\"\"\n Returns True if first argument is a typecode lower/equal in type hierarchy.\n\n Parameters\n ----------\n arg1, arg2 : dtype_like\n dtype or string representing a typecode.\n\n Returns\n -------\n out : bool\n\n See Also\n --------\n issubsctype, issubclass_\n numpy.core.numerictypes : Overview of numpy type hierarchy.\n\n Examples\n --------\n >>> np.issubdtype('S1', np.string_)\n True\n >>> np.issubdtype(np.float64, np.float32)\n False\n\n \"\"\"\n if not issubclass_(arg1, generic):\n arg1 = dtype(arg1).type\n if not issubclass_(arg2, generic):\n arg2_orig = arg2\n arg2 = dtype(arg2).type\n if not isinstance(arg2_orig, dtype):\n # weird deprecated behaviour, that tried to infer np.floating from\n # float, and similar less obvious things, such as np.generic from\n # basestring\n mro = arg2.mro()\n arg2 = mro[1] if len(mro) > 1 else mro[0]\n\n def type_repr(x):\n \"\"\" Helper to produce clear error messages \"\"\"\n if not isinstance(x, type):\n return repr(x)\n elif issubclass(x, generic):\n return \"np.{}\".format(x.__name__)\n else:\n return x.__name__\n\n # 1.14, 2017-08-01\n warnings.warn(\n \"Conversion of the second argument of issubdtype from `{raw}` \"\n \"to `{abstract}` is deprecated. In future, it will be treated \"\n \"as `{concrete} == np.dtype({raw}).type`.\".format(\n raw=type_repr(arg2_orig),\n abstract=type_repr(arg2),\n concrete=type_repr(dtype(arg2_orig).type)\n ),\n FutureWarning, stacklevel=2\n )\n\n return issubclass(arg1, arg2)\n\n\n# This dictionary allows look up based on any alias for an array data-type\nclass _typedict(dict):\n \"\"\"\n Base object for a dictionary for look-up with any alias for an array dtype.\n\n Instances of `_typedict` can not be used as dictionaries directly,\n first they have to be populated.\n\n \"\"\"\n\n def __getitem__(self, obj):\n return dict.__getitem__(self, obj2sctype(obj))\n\nnbytes = _typedict()\n_alignment = _typedict()\n_maxvals = _typedict()\n_minvals = _typedict()\ndef _construct_lookups():\n for name, info in typeinfo.items():\n if isinstance(info, type):\n continue\n obj = info.type\n nbytes[obj] = info.bits // 8\n _alignment[obj] = info.alignment\n if len(info) > 5:\n _maxvals[obj] = info.max\n _minvals[obj] = info.min\n else:\n _maxvals[obj] = None\n _minvals[obj] = None\n\n_construct_lookups()\n\ndef sctype2char(sctype):\n \"\"\"\n Return the string representation of a scalar dtype.\n\n Parameters\n ----------\n sctype : scalar dtype or object\n If a scalar dtype, the corresponding string character is\n returned. If an object, `sctype2char` tries to infer its scalar type\n and then return the corresponding string character.\n\n Returns\n -------\n typechar : str\n The string character corresponding to the scalar type.\n\n Raises\n ------\n ValueError\n If `sctype` is an object for which the type can not be inferred.\n\n See Also\n --------\n obj2sctype, issctype, issubsctype, mintypecode\n\n Examples\n --------\n >>> for sctype in [np.int32, float, complex, np.string_, np.ndarray]:\n ... print(np.sctype2char(sctype))\n l\n d\n D\n S\n O\n\n >>> x = np.array([1., 2-1.j])\n >>> np.sctype2char(x)\n 'D'\n >>> np.sctype2char(list)\n 'O'\n\n \"\"\"\n sctype = obj2sctype(sctype)\n if sctype is None:\n raise ValueError(\"unrecognized type\")\n return _sctype2char_dict[sctype]\n\n# Create dictionary of casting functions that wrap sequences\n# indexed by type or type character\n\n\ncast = _typedict()\ntry:\n ScalarType = [_types.IntType, _types.FloatType, _types.ComplexType,\n _types.LongType, _types.BooleanType,\n _types.StringType, _types.UnicodeType, _types.BufferType]\nexcept AttributeError:\n # Py3K\n ScalarType = [int, float, complex, int, bool, bytes, str, memoryview]\n\nScalarType.extend(_sctype2char_dict.keys())\nScalarType = tuple(ScalarType)\nfor key in _sctype2char_dict.keys():\n cast[key] = lambda x, k=key: array(x, copy=False).astype(k)\n\n# Create the typestring lookup dictionary\n_typestr = _typedict()\nfor key in _sctype2char_dict.keys():\n if issubclass(key, allTypes['flexible']):\n _typestr[key] = _sctype2char_dict[key]\n else:\n _typestr[key] = empty((1,), key).dtype.str[1:]\n\n# Make sure all typestrings are in sctypeDict\nfor key, val in _typestr.items():\n if val not in sctypeDict:\n sctypeDict[val] = key\n\n# Add additional strings to the sctypeDict\n\nif sys.version_info[0] >= 3:\n _toadd = ['int', 'float', 'complex', 'bool', 'object',\n 'str', 'bytes', 'object', ('a', allTypes['bytes_'])]\nelse:\n _toadd = ['int', 'float', 'complex', 'bool', 'object', 'string',\n ('str', allTypes['string_']),\n 'unicode', 'object', ('a', allTypes['string_'])]\n\nfor name in _toadd:\n if isinstance(name, tuple):\n sctypeDict[name[0]] = name[1]\n else:\n sctypeDict[name] = allTypes['%s_' % name]\n\ndel _toadd, name\n\n# Now add the types we've determined to this module\nfor key in allTypes:\n globals()[key] = allTypes[key]\n __all__.append(key)\n\ndel key\n\ntypecodes = {'Character':'c',\n 'Integer':'bhilqp',\n 'UnsignedInteger':'BHILQP',\n 'Float':'efdg',\n 'Complex':'FDG',\n 'AllInteger':'bBhHiIlLqQpP',\n 'AllFloat':'efdgFDG',\n 'Datetime': 'Mm',\n 'All':'?bhilqpBHILQPefdgFDGSUVOMm'}\n\n# backwards compatibility --- deprecated name\ntypeDict = sctypeDict\ntypeNA = sctypeNA\n\n# b -> boolean\n# u -> unsigned integer\n# i -> signed integer\n# f -> floating point\n# c -> complex\n# M -> datetime\n# m -> timedelta\n# S -> string\n# U -> Unicode string\n# V -> record\n# O -> Python object\n_kind_list = ['b', 'u', 'i', 'f', 'c', 'S', 'U', 'V', 'O', 'M', 'm']\n\n__test_types = '?'+typecodes['AllInteger'][:-2]+typecodes['AllFloat']+'O'\n__len_test_types = len(__test_types)\n\n# Keep incrementing until a common type both can be coerced to\n# is found. Otherwise, return None\ndef _find_common_coerce(a, b):\n if a > b:\n return a\n try:\n thisind = __test_types.index(a.char)\n except ValueError:\n return None\n return _can_coerce_all([a, b], start=thisind)\n\n# Find a data-type that all data-types in a list can be coerced to\ndef _can_coerce_all(dtypelist, start=0):\n N = len(dtypelist)\n if N == 0:\n return None\n if N == 1:\n return dtypelist[0]\n thisind = start\n while thisind < __len_test_types:\n newdtype = dtype(__test_types[thisind])\n numcoerce = len([x for x in dtypelist if newdtype >= x])\n if numcoerce == N:\n return newdtype\n thisind += 1\n return None\n\ndef _register_types():\n numbers.Integral.register(integer)\n numbers.Complex.register(inexact)\n numbers.Real.register(floating)\n numbers.Number.register(number)\n\n_register_types()\n\ndef find_common_type(array_types, scalar_types):\n \"\"\"\n Determine common type following standard coercion rules.\n\n Parameters\n ----------\n array_types : sequence\n A list of dtypes or dtype convertible objects representing arrays.\n scalar_types : sequence\n A list of dtypes or dtype convertible objects representing scalars.\n\n Returns\n -------\n datatype : dtype\n The common data type, which is the maximum of `array_types` ignoring\n `scalar_types`, unless the maximum of `scalar_types` is of a\n different kind (`dtype.kind`). If the kind is not understood, then\n None is returned.\n\n See Also\n --------\n dtype, common_type, can_cast, mintypecode\n\n Examples\n --------\n >>> np.find_common_type([], [np.int64, np.float32, complex])\n dtype('complex128')\n >>> np.find_common_type([np.int64, np.float32], [])\n dtype('float64')\n\n The standard casting rules ensure that a scalar cannot up-cast an\n array unless the scalar is of a fundamentally different kind of data\n (i.e. under a different hierarchy in the data type hierarchy) then\n the array:\n\n >>> np.find_common_type([np.float32], [np.int64, np.float64])\n dtype('float32')\n\n Complex is of a different type, so it up-casts the float in the\n `array_types` argument:\n\n >>> np.find_common_type([np.float32], [complex])\n dtype('complex128')\n\n Type specifier strings are convertible to dtypes and can therefore\n be used instead of dtypes:\n\n >>> np.find_common_type(['f4', 'f4', 'i4'], ['c8'])\n dtype('complex128')\n\n \"\"\"\n array_types = [dtype(x) for x in array_types]\n scalar_types = [dtype(x) for x in scalar_types]\n\n maxa = _can_coerce_all(array_types)\n maxsc = _can_coerce_all(scalar_types)\n\n if maxa is None:\n return maxsc\n\n if maxsc is None:\n return maxa\n\n try:\n index_a = _kind_list.index(maxa.kind)\n index_sc = _kind_list.index(maxsc.kind)\n except ValueError:\n return None\n\n if index_sc > index_a:\n return _find_common_coerce(maxsc, maxa)\n else:\n return maxa\n"
] |
[
[
"numpy.core.multiarray.empty",
"numpy.core.multiarray.typeinfo.items",
"numpy.core.multiarray.array",
"numpy.core.multiarray.dtype"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tongni1975/tf-explain
|
[
"1d13fbac19389630f4d25473fda10687635dcd6a"
] |
[
"tests/callbacks/test_grad_cam.py"
] |
[
"import numpy as np\nfrom tf_explain.callbacks.grad_cam import GradCAMCallback\n\n\ndef test_should_call_grad_cam_callback(\n random_data, convolutional_model, output_dir, mocker\n):\n mock_explainer = mocker.MagicMock(explain=mocker.MagicMock(return_value=0))\n mocker.patch(\"tf_explain.callbacks.grad_cam.GradCAM\", return_value=mock_explainer)\n mock_image_summary = mocker.patch(\"tf_explain.callbacks.grad_cam.tf.summary.image\")\n\n images, labels = random_data\n\n callbacks = [\n GradCAMCallback(\n validation_data=random_data,\n class_index=0,\n layer_name=\"activation_1\",\n output_dir=output_dir,\n )\n ]\n\n convolutional_model.fit(images, labels, batch_size=2, epochs=1, callbacks=callbacks)\n\n mock_explainer.explain.assert_called_once_with(\n random_data, convolutional_model, \"activation_1\", 0\n )\n mock_image_summary.assert_called_once_with(\"Grad CAM\", np.array([0]), step=0)\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wgcban/spin_roadmapper
|
[
"2c1c8f22073d989753dc6f95d1f547198a76414b"
] |
[
"model/unet.py"
] |
[
"import torch\nimport torchvision\nfrom torch import nn\nfrom torchvision.utils import save_image\nimport torch.nn.functional as F\n\nclass unet(nn.Module):\n def __init__(self, in_channels=3, num_classes=2):\n super(unet, self).__init__()\n \n self.encoder1 = nn.Conv2d(in_channels, 32, 3, stride=1, padding=1) # b, 16, 10, 10\n self.encoder2= nn.Conv2d(32, 64, 3, stride=1, padding=1) # b, 8, 3, 3\n self.encoder3= nn.Conv2d(64, 128, 3, stride=1, padding=1)\n self.encoder4= nn.Conv2d(128, 256, 3, stride=1, padding=1)\n self.encoder5= nn.Conv2d(256, 512, 3, stride=1, padding=1)\n \n self.decoder1 = nn.Conv2d(512, 256, 3, stride=1,padding=1) # b, 16, 5, 5\n self.decoder2 = nn.Conv2d(256, 128, 3, stride=1, padding=1) # b, 8, 15, 1\n self.decoder3 = nn.Conv2d(128, 64, 3, stride=1, padding=1) # b, 1, 28, 28\n self.decoder4 = nn.Conv2d(64, 32, 3, stride=1, padding=1)\n self.decoder5 = nn.Conv2d(32, num_classes, 3, stride=1, padding=1)\n \n self.soft = nn.Softmax(dim =1)\n\n def forward(self, x):\n\n out = F.relu(F.max_pool2d(self.encoder1(x),2,2))\n t1 = out\n out = F.relu(F.max_pool2d(self.encoder2(out),2,2))\n t2 = out\n out = F.relu(F.max_pool2d(self.encoder3(out),2,2))\n t3 = out\n out = F.relu(F.max_pool2d(self.encoder4(out),2,2))\n t4 = out\n out = F.relu(F.max_pool2d(self.encoder5(out),2,2))\n \n # t2 = out\n out = F.relu(F.interpolate(self.decoder1(out),scale_factor=(2,2),mode ='bilinear'))\n # print(out.shape,t4.shape)\n out = torch.add(out,t4)\n out = F.relu(F.interpolate(self.decoder2(out),scale_factor=(2,2),mode ='bilinear'))\n out = torch.add(out,t3)\n out = F.relu(F.interpolate(self.decoder3(out),scale_factor=(2,2),mode ='bilinear'))\n out = torch.add(out,t2)\n out = F.relu(F.interpolate(self.decoder4(out),scale_factor=(2,2),mode ='bilinear'))\n out = torch.add(out,t1)\n out = F.relu(F.interpolate(self.decoder5(out),scale_factor=(2,2),mode ='bilinear'))\n # print(out.shape)\n \n # out = self.soft(out)\n return out\n"
] |
[
[
"torch.nn.Softmax",
"torch.nn.Conv2d",
"torch.add"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Daiver/np_draw_tools
|
[
"091f09aba090263aee29b941b91bb7c96600018f"
] |
[
"examples/grid_example.py"
] |
[
"import numpy as np\nimport cv2\nimport np_draw_tools\n\n\ndef main():\n img1 = np.zeros((256, 128, 3), dtype=np.uint8)\n img2 = np.zeros((256, 128, 3), dtype=np.uint8)\n img3 = np.zeros((256, 128, 3), dtype=np.uint8)\n\n cv2.circle(img1, (64, 40), radius=10, color=(0, 255, 0), thickness=-1)\n\n img2[:] = 255\n cv2.circle(img2, (5, 60), radius=10, color=(255, 255, 0), thickness=-1)\n\n img3[:] = 128\n cv2.circle(img3, (128, 69), radius=10, color=(0, 0, 255), thickness=-1)\n\n grid1 = np_draw_tools.make_grid([img1, img2, img3, img3, img1, img2], margin=20, background_color=(25, 55, 200))\n grid2 = np_draw_tools.make_grid(\n [None, img2, img3, img3, None, img2],\n n_items_in_row=3,\n background_color=(0, 255, 0)\n )\n\n grid3_images = [\n cv2.cvtColor(x, cv2.COLOR_BGR2GRAY)\n for x in [img1, img2, img3, img3, img1, img2]\n ]\n grid3 = np_draw_tools.make_grid(grid3_images, n_items_in_row=2, background_color=15)\n\n grid4 = np_draw_tools.make_grid(\n [None, img2, img3, img3, img1],\n n_items_in_row=3,\n background_color=(128, 85, 85),\n margin=10\n )\n\n cv2.imshow(\"grid1\", grid1)\n cv2.imshow(\"grid2\", grid2)\n cv2.imshow(\"grid3\", grid3)\n cv2.imshow(\"grid4\", grid4)\n cv2.waitKey()\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SaVoAMP/stumpy
|
[
"d63963caaf6a8b64448953f638c1d3345e05a36a",
"d63963caaf6a8b64448953f638c1d3345e05a36a",
"d63963caaf6a8b64448953f638c1d3345e05a36a",
"d63963caaf6a8b64448953f638c1d3345e05a36a"
] |
[
"tests/test_gpu_mpdist.py",
"tests/test_scrump.py",
"tests/test_stimp.py",
"stumpy/stimp.py"
] |
[
"import numpy as np\nimport numpy.testing as npt\nfrom stumpy import gpu_mpdist, config\nfrom numba import cuda\n\ntry:\n from numba.errors import NumbaPerformanceWarning\nexcept ModuleNotFoundError:\n from numba.core.errors import NumbaPerformanceWarning\nimport pytest\nimport naive\n\nconfig.THREADS_PER_BLOCK = 10\n\nif not cuda.is_available(): # pragma: no cover\n pytest.skip(\"Skipping Tests No GPUs Available\", allow_module_level=True)\n\n\ntest_data = [\n (\n np.array([9, 8100, -60, 7], dtype=np.float64),\n np.array([584, -11, 23, 79, 1001, 0, -19], dtype=np.float64),\n ),\n (\n np.random.uniform(-1000, 1000, [8]).astype(np.float64),\n np.random.uniform(-1000, 1000, [64]).astype(np.float64),\n ),\n]\n\n\[email protected](\"ignore\", category=NumbaPerformanceWarning)\[email protected](\"T_A, T_B\", test_data)\ndef test_gpu_mpdist(T_A, T_B):\n m = 3\n ref_mpdist = naive.mpdist(T_A, T_B, m)\n comp_mpdist = gpu_mpdist(T_A, T_B, m)\n\n npt.assert_almost_equal(ref_mpdist, comp_mpdist)\n",
"import numpy as np\nimport numpy.testing as npt\nfrom stumpy import scrump, stump, config\nfrom stumpy.scrump import prescrump\nimport pytest\nimport naive\n\n\ntest_data = [\n (\n np.array([9, 8100, -60, 7], dtype=np.float64),\n np.array([584, -11, 23, 79, 1001, 0, -19], dtype=np.float64),\n ),\n (\n np.random.uniform(-1000, 1000, [8]).astype(np.float64),\n np.random.uniform(-1000, 1000, [64]).astype(np.float64),\n ),\n]\n\nwindow_size = [8, 16, 32]\nsubstitution_locations = [(slice(0, 0), 0, -1, slice(1, 3), [0, 3])]\nsubstitution_values = [np.nan, np.inf]\npercentages = [(0.01, 0.1, 1.0)]\n\n\[email protected](\"T_A, T_B\", test_data)\ndef test_prescrump_self_join(T_A, T_B):\n m = 3\n zone = int(np.ceil(m / 4))\n for s in range(1, zone + 1):\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_P, ref_I = naive.prescrump(T_B, m, T_B, s=s, exclusion_zone=zone)\n\n np.random.seed(seed)\n comp_P, comp_I = prescrump(T_B, m, s=s)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n\n\[email protected](\"T_A, T_B\", test_data)\ndef test_prescrump_A_B_join(T_A, T_B):\n m = 3\n zone = int(np.ceil(m / 4))\n for s in range(1, zone + 1):\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_P, ref_I = naive.prescrump(T_A, m, T_B, s=s)\n\n np.random.seed(seed)\n comp_P, comp_I = prescrump(T_A, m, T_B=T_B, s=s)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n\n\[email protected](\"T_A, T_B\", test_data)\ndef test_prescrump_A_B_join_swap(T_A, T_B):\n m = 3\n zone = int(np.ceil(m / 4))\n for s in range(1, zone + 1):\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_P, ref_I = naive.prescrump(T_B, m, T_A, s=s)\n\n np.random.seed(seed)\n comp_P, comp_I = prescrump(T_B, m, T_B=T_A, s=s)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n\n\[email protected](\"T_A, T_B\", test_data)\[email protected](\"m\", window_size)\ndef test_prescrump_self_join_larger_window(T_A, T_B, m):\n if len(T_B) > m:\n zone = int(np.ceil(m / 4))\n for s in range(1, zone + 1):\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_P, ref_I = naive.prescrump(T_B, m, T_B, s=s, exclusion_zone=zone)\n\n np.random.seed(seed)\n comp_P, comp_I = prescrump(T_B, m, s=s)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n\n\ndef test_scrump_int_input():\n with pytest.raises(TypeError):\n scrump(np.arange(10), 5, ignore_trivial=True, percentage=1.0, pre_scrump=False)\n\n\[email protected](\"T_A, T_B\", test_data)\[email protected](\"percentages\", percentages)\ndef test_scrump_self_join(T_A, T_B, percentages):\n m = 3\n zone = int(np.ceil(m / 4))\n\n for percentage in percentages:\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_mp = naive.scrump(T_B, m, T_B, percentage, zone, False, None)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n np.random.seed(seed)\n approx = scrump(\n T_B, m, ignore_trivial=True, percentage=percentage, pre_scrump=False\n )\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"T_A, T_B\", test_data)\[email protected](\"percentages\", percentages)\ndef test_scrump_A_B_join(T_A, T_B, percentages):\n m = 3\n\n for percentage in percentages:\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_mp = naive.scrump(T_A, m, T_B, percentage, None, False, None)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n np.random.seed(seed)\n approx = scrump(\n T_A, m, T_B, ignore_trivial=False, percentage=percentage, pre_scrump=False\n )\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"T_A, T_B\", test_data)\[email protected](\"percentages\", percentages)\ndef test_scrump_A_B_join_swap(T_A, T_B, percentages):\n m = 3\n\n for percentage in percentages:\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_mp = naive.scrump(T_B, m, T_A, percentage, None, False, None)\n ref_P = ref_mp[:, 0]\n # ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n np.random.seed(seed)\n approx = scrump(\n T_B, m, T_A, ignore_trivial=False, percentage=percentage, pre_scrump=False\n )\n approx.update()\n comp_P = approx.P_\n # comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"T_A, T_B\", test_data)\[email protected](\"m\", window_size)\[email protected](\"percentages\", percentages)\ndef test_scrump_self_join_larger_window(T_A, T_B, m, percentages):\n if len(T_B) > m:\n zone = int(np.ceil(m / 4))\n\n for percentage in percentages:\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_mp = naive.scrump(T_B, m, T_B, percentage, zone, False, None)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n np.random.seed(seed)\n approx = scrump(\n T_B, m, ignore_trivial=True, percentage=percentage, pre_scrump=False\n )\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"T_A, T_B\", test_data)\ndef test_scrump_self_join_full(T_A, T_B):\n m = 3\n zone = int(np.ceil(m / 4))\n\n ref_mp = naive.stump(T_B, m, exclusion_zone=zone, row_wise=True)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n approx = scrump(T_B, m, ignore_trivial=True, percentage=1.0, pre_scrump=False)\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n ref_mp = stump(T_B, m, ignore_trivial=True)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"T_A, T_B\", test_data)\ndef test_scrump_A_B_join_full(T_A, T_B):\n\n m = 3\n\n ref_mp = naive.stump(T_A, m, T_B=T_B, row_wise=True)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n approx = scrump(T_A, m, T_B, ignore_trivial=False, percentage=1.0, pre_scrump=False)\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n ref_mp = stump(T_A, m, T_B=T_B, ignore_trivial=False)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"T_A, T_B\", test_data)\ndef test_scrump_A_B_join_full_swap(T_A, T_B):\n\n m = 3\n\n ref_mp = naive.stump(T_B, m, T_B=T_A, row_wise=True)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n approx = scrump(T_B, m, T_A, ignore_trivial=False, percentage=1.0, pre_scrump=False)\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"T_A, T_B\", test_data)\[email protected](\"m\", window_size)\ndef test_scrump_self_join_full_larger_window(T_A, T_B, m):\n if len(T_B) > m:\n zone = int(np.ceil(m / 4))\n\n ref_mp = naive.stump(T_B, m, exclusion_zone=zone, row_wise=True)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n approx = scrump(T_B, m, ignore_trivial=True, percentage=1.0, pre_scrump=False)\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"T_A, T_B\", test_data)\[email protected](\"percentages\", percentages)\ndef test_scrump_plus_plus_self_join(T_A, T_B, percentages):\n m = 3\n zone = int(np.ceil(m / 4))\n\n for s in range(1, zone + 1):\n for percentage in percentages:\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_P, ref_I = naive.prescrump(T_B, m, T_B, s=s, exclusion_zone=zone)\n ref_mp = naive.scrump(T_B, m, T_B, percentage, zone, True, s)\n for i in range(ref_mp.shape[0]):\n if ref_P[i] < ref_mp[i, 0]:\n ref_mp[i, 0] = ref_P[i]\n ref_mp[i, 1] = ref_I[i]\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n # ref_left_I = ref_mp[:, 2]\n # ref_right_I = ref_mp[:, 3]\n\n np.random.seed(seed)\n approx = scrump(\n T_B, m, ignore_trivial=True, percentage=percentage, pre_scrump=True, s=s\n )\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n # comp_left_I = approx.left_I_\n # comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_I)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n # npt.assert_almost_equal(ref_left_I, comp_left_I)\n # npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"T_A, T_B\", test_data)\[email protected](\"percentages\", percentages)\ndef test_scrump_plus_plus_A_B_join(T_A, T_B, percentages):\n m = 3\n zone = int(np.ceil(m / 4))\n\n for s in range(1, zone + 1):\n for percentage in percentages:\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_P, ref_I = naive.prescrump(T_A, m, T_B, s=s)\n ref_mp = naive.scrump(T_A, m, T_B, percentage, None, False, None)\n for i in range(ref_mp.shape[0]):\n if ref_P[i] < ref_mp[i, 0]:\n ref_mp[i, 0] = ref_P[i]\n ref_mp[i, 1] = ref_I[i]\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n approx = scrump(\n T_A,\n m,\n T_B,\n ignore_trivial=False,\n percentage=percentage,\n pre_scrump=True,\n s=s,\n )\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"T_A, T_B\", test_data)\ndef test_scrump_plus_plus_self_join_full(T_A, T_B):\n m = 3\n zone = int(np.ceil(m / 4))\n\n ref_mp = naive.stump(T_B, m, exclusion_zone=zone, row_wise=True)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n approx = scrump(\n T_B, m, ignore_trivial=True, percentage=1.0, pre_scrump=True, s=zone\n )\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"T_A, T_B\", test_data)\ndef test_scrump_plus_plus_A_B_join_full(T_A, T_B):\n m = 3\n zone = int(np.ceil(m / 4))\n\n ref_mp = naive.stump(T_A, m, T_B=T_B, row_wise=True)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n approx = scrump(\n T_A, m, T_B=T_B, ignore_trivial=False, percentage=1.0, pre_scrump=True, s=zone\n )\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"T_A, T_B\", test_data)\ndef test_scrump_plus_plus_A_B_join_full_swap(T_A, T_B):\n m = 3\n zone = int(np.ceil(m / 4))\n\n ref_mp = naive.stump(T_B, m, T_B=T_A, row_wise=True)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n approx = scrump(\n T_B, m, T_B=T_A, ignore_trivial=False, percentage=1.0, pre_scrump=True, s=zone\n )\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"percentages\", percentages)\ndef test_scrump_constant_subsequence_self_join(percentages):\n T = np.concatenate((np.zeros(20, dtype=np.float64), np.ones(5, dtype=np.float64)))\n\n m = 3\n zone = int(np.ceil(m / 4))\n\n for percentage in percentages:\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_mp = naive.scrump(T, m, T, percentage, zone, False, None)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n np.random.seed(seed)\n approx = scrump(\n T, m, ignore_trivial=True, percentage=percentage, pre_scrump=False\n )\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"percentages\", percentages)\ndef test_scrump_identical_subsequence_self_join(percentages):\n identical = np.random.rand(8)\n T = np.random.rand(20)\n T[1 : 1 + identical.shape[0]] = identical\n T[11 : 11 + identical.shape[0]] = identical\n m = 3\n zone = int(np.ceil(m / 4))\n\n for percentage in percentages:\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_mp = naive.scrump(T, m, T, percentage, zone, False, None)\n ref_P = ref_mp[:, 0]\n # ref_I = ref_mp[:, 1]\n # ref_left_I = ref_mp[:, 2]\n # ref_right_I = ref_mp[:, 3]\n\n np.random.seed(seed)\n approx = scrump(\n T, m, ignore_trivial=True, percentage=percentage, pre_scrump=False\n )\n approx.update()\n comp_P = approx.P_\n # comp_I = approx.I_\n # comp_left_I = approx.left_I_\n # comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P, decimal=config.STUMPY_TEST_PRECISION)\n # npt.assert_almost_equal(ref_I, comp_I)\n # npt.assert_almost_equal(ref_left_I, comp_left_I)\n # npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"T_A, T_B\", test_data)\[email protected](\"substitute\", substitution_values)\[email protected](\"substitution_locations\", substitution_locations)\[email protected](\"percentages\", percentages)\ndef test_scrump_nan_inf_self_join(\n T_A, T_B, substitute, substitution_locations, percentages\n):\n m = 3\n\n T_B_sub = T_B.copy()\n\n for substitution_location in substitution_locations:\n T_B_sub[:] = T_B[:]\n T_B_sub[substitution_location] = substitute\n\n zone = int(np.ceil(m / 4))\n\n for percentage in percentages:\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_mp = naive.scrump(T_B_sub, m, T_B_sub, percentage, zone, False, None)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n np.random.seed(seed)\n approx = scrump(T_B_sub, m, percentage=percentage, pre_scrump=False)\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n\n\[email protected](\"percentages\", percentages)\ndef test_scrump_nan_zero_mean_self_join(percentages):\n T = np.array([-1, 0, 1, np.inf, 1, 0, -1])\n\n m = 3\n zone = int(np.ceil(m / 4))\n\n for percentage in percentages:\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n ref_mp = naive.scrump(T, m, T, percentage, zone, False, None)\n ref_P = ref_mp[:, 0]\n ref_I = ref_mp[:, 1]\n ref_left_I = ref_mp[:, 2]\n ref_right_I = ref_mp[:, 3]\n\n np.random.seed(seed)\n approx = scrump(T, m, percentage=percentage, pre_scrump=False)\n approx.update()\n comp_P = approx.P_\n comp_I = approx.I_\n comp_left_I = approx.left_I_\n comp_right_I = approx.right_I_\n\n naive.replace_inf(ref_P)\n naive.replace_inf(comp_P)\n\n npt.assert_almost_equal(ref_P, comp_P)\n npt.assert_almost_equal(ref_I, comp_I)\n npt.assert_almost_equal(ref_left_I, comp_left_I)\n npt.assert_almost_equal(ref_right_I, comp_right_I)\n",
"import numpy as np\nimport numpy.testing as npt\nfrom stumpy import stimp, stimped\n\nfrom dask.distributed import Client, LocalCluster\nimport pytest\nimport naive\n\n\nT = [\n np.array([584, -11, 23, 79, 1001, 0, -19], dtype=np.float64),\n np.random.uniform(-1000, 1000, [64]).astype(np.float64),\n]\n\n\[email protected](scope=\"module\")\ndef dask_cluster():\n cluster = LocalCluster(n_workers=2, threads_per_worker=2)\n yield cluster\n cluster.close()\n\n\[email protected](\"T\", T)\ndef test_stimp_1_percent(T):\n threshold = 0.2\n percentage = 0.01\n min_m = 3\n n = T.shape[0] - min_m + 1\n\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n pan = stimp(\n T,\n min_m=min_m,\n max_m=None,\n step=1,\n percentage=percentage,\n pre_scrump=True,\n # normalize=True,\n )\n\n for i in range(n):\n pan.update()\n\n ref_PAN = np.full((pan.M_.shape[0], T.shape[0]), fill_value=np.inf)\n\n np.random.seed(seed)\n for idx, m in enumerate(pan.M_[:n]):\n zone = int(np.ceil(m / 4))\n s = zone\n tmp_P, tmp_I = naive.prescrump(T, m, T, s=s, exclusion_zone=zone)\n ref_mp = naive.scrump(T, m, T, percentage, zone, True, s)\n for i in range(ref_mp.shape[0]):\n if tmp_P[i] < ref_mp[i, 0]:\n ref_mp[i, 0] = tmp_P[i]\n ref_mp[i, 1] = tmp_I[i]\n ref_PAN[pan._bfs_indices[idx], : ref_mp.shape[0]] = ref_mp[:, 0]\n\n # Compare raw pan\n cmp_PAN = pan._PAN\n\n naive.replace_inf(ref_PAN)\n naive.replace_inf(cmp_PAN)\n\n npt.assert_almost_equal(ref_PAN, cmp_PAN)\n\n # Compare transformed pan\n cmp_pan = pan.PAN_\n ref_pan = naive.transform_pan(\n pan._PAN, pan._M, threshold, pan._bfs_indices, pan._n_processed\n )\n\n naive.replace_inf(ref_pan)\n naive.replace_inf(cmp_pan)\n\n npt.assert_almost_equal(ref_pan, cmp_pan)\n\n\[email protected](\"T\", T)\ndef test_stimp_max_m(T):\n threshold = 0.2\n percentage = 0.01\n min_m = 3\n max_m = 5\n n = T.shape[0] - min_m + 1\n\n seed = np.random.randint(100000)\n\n np.random.seed(seed)\n pan = stimp(\n T,\n min_m=min_m,\n max_m=max_m,\n step=1,\n percentage=percentage,\n pre_scrump=True,\n # normalize=True,\n )\n\n for i in range(n):\n pan.update()\n\n ref_PAN = np.full((pan.M_.shape[0], T.shape[0]), fill_value=np.inf)\n\n np.random.seed(seed)\n for idx, m in enumerate(pan.M_[:n]):\n zone = int(np.ceil(m / 4))\n s = zone\n tmp_P, tmp_I = naive.prescrump(T, m, T, s=s, exclusion_zone=zone)\n ref_mp = naive.scrump(T, m, T, percentage, zone, True, s)\n for i in range(ref_mp.shape[0]):\n if tmp_P[i] < ref_mp[i, 0]:\n ref_mp[i, 0] = tmp_P[i]\n ref_mp[i, 1] = tmp_I[i]\n ref_PAN[pan._bfs_indices[idx], : ref_mp.shape[0]] = ref_mp[:, 0]\n\n # Compare raw pan\n cmp_PAN = pan._PAN\n\n naive.replace_inf(ref_PAN)\n naive.replace_inf(cmp_PAN)\n\n npt.assert_almost_equal(ref_PAN, cmp_PAN)\n\n # Compare transformed pan\n cmp_pan = pan.PAN_\n ref_pan = naive.transform_pan(\n pan._PAN, pan._M, threshold, pan._bfs_indices, pan._n_processed\n )\n\n naive.replace_inf(ref_pan)\n naive.replace_inf(cmp_pan)\n\n npt.assert_almost_equal(ref_pan, cmp_pan)\n\n\[email protected](\"T\", T)\ndef test_stimp_100_percent(T):\n threshold = 0.2\n percentage = 1.0\n min_m = 3\n n = T.shape[0] - min_m + 1\n\n pan = stimp(\n T,\n min_m=min_m,\n max_m=None,\n step=1,\n percentage=percentage,\n pre_scrump=True,\n # normalize=True,\n )\n\n for i in range(n):\n pan.update()\n\n ref_PAN = np.full((pan.M_.shape[0], T.shape[0]), fill_value=np.inf)\n\n for idx, m in enumerate(pan.M_[:n]):\n zone = int(np.ceil(m / 4))\n ref_mp = naive.stump(T, m, T_B=None, exclusion_zone=zone)\n ref_PAN[pan._bfs_indices[idx], : ref_mp.shape[0]] = ref_mp[:, 0]\n\n # Compare raw pan\n cmp_PAN = pan._PAN\n\n naive.replace_inf(ref_PAN)\n naive.replace_inf(cmp_PAN)\n\n npt.assert_almost_equal(ref_PAN, cmp_PAN)\n\n # Compare transformed pan\n cmp_pan = pan.PAN_\n ref_pan = naive.transform_pan(\n pan._PAN, pan._M, threshold, pan._bfs_indices, pan._n_processed\n )\n\n naive.replace_inf(ref_pan)\n naive.replace_inf(cmp_pan)\n\n npt.assert_almost_equal(ref_pan, cmp_pan)\n\n\[email protected](\"ignore:numpy.dtype size changed\")\[email protected](\"ignore:numpy.ufunc size changed\")\[email protected](\"ignore:numpy.ndarray size changed\")\[email protected](\"ignore:\\\\s+Port 8787 is already in use:UserWarning\")\[email protected](\"T\", T)\ndef test_stimped(T, dask_cluster):\n with Client(dask_cluster) as dask_client:\n threshold = 0.2\n min_m = 3\n n = T.shape[0] - min_m + 1\n\n pan = stimped(\n dask_client,\n T,\n min_m=min_m,\n max_m=None,\n step=1,\n # normalize=True,\n )\n\n for i in range(n):\n pan.update()\n\n ref_PAN = np.full((pan.M_.shape[0], T.shape[0]), fill_value=np.inf)\n\n for idx, m in enumerate(pan.M_[:n]):\n zone = int(np.ceil(m / 4))\n ref_mp = naive.stump(T, m, T_B=None, exclusion_zone=zone)\n ref_PAN[pan._bfs_indices[idx], : ref_mp.shape[0]] = ref_mp[:, 0]\n\n # Compare raw pan\n cmp_PAN = pan._PAN\n\n naive.replace_inf(ref_PAN)\n naive.replace_inf(cmp_PAN)\n\n npt.assert_almost_equal(ref_PAN, cmp_PAN)\n\n # Compare transformed pan\n cmp_pan = pan.PAN_\n ref_pan = naive.transform_pan(\n pan._PAN, pan._M, threshold, pan._bfs_indices, pan._n_processed\n )\n\n naive.replace_inf(ref_pan)\n naive.replace_inf(cmp_pan)\n\n npt.assert_almost_equal(ref_pan, cmp_pan)\n",
"# STUMPY\n# Copyright 2019 TD Ameritrade. Released under the terms of the 3-Clause BSD license.\n# STUMPY is a trademark of TD Ameritrade IP Company, Inc. All rights reserved.\n\nimport numpy as np\nfrom . import core, stump, scrump, stumped\nfrom .aamp_stimp import aamp_stimp, aamp_stimped\n\n\ndef _normalize_pan(pan, ms, bfs_indices, n_processed):\n \"\"\"\n Normalize the pan matrix profile nearest neighbor distances (inplace) relative\n to the corresponding subsequence length from which they were computed\n\n Parameters\n ----------\n pan : numpy.ndarray\n The pan matrix profile\n\n ms : numpy.ndarray\n The breadth-first-search sorted subsequence window sizes\n\n bfs_indices : numpy.ndarray\n The breadth-first-search indices\n\n n_processed : numpy.ndarray\n The number of subsequence window sizes and breadth-first-search indices to\n normalize\n\n Returns\n -------\n None\n \"\"\"\n idx = bfs_indices[:n_processed]\n norm = 1.0 / (2.0 * np.sqrt(ms[:n_processed]))\n pan[idx] = np.minimum(1.0, pan[idx] * norm[:, np.newaxis])\n\n\nclass _stimp:\n \"\"\"\n Compute the Pan Matrix Profile\n\n This is based on the SKIMP algorithm.\n\n Parameters\n ----------\n T : numpy.ndarray\n The time series or sequence for which to compute the pan matrix profile\n\n m_start : int, default 3\n The starting (or minimum) subsequence window size for which a matrix profile\n may be computed\n\n m_stop : int, default None\n The stopping (or maximum) subsequence window size for which a matrix profile\n may be computed. When `m_stop = Non`, this is set to the maximum allowable\n subsequence window size\n\n m_step : int, default 1\n The step between subsequence window sizes\n\n percentage : float, default 0.01\n The percentage of the full matrix profile to compute for each subsequence\n window size. When `percentage < 1.0`, then the `scrump` algorithm is used.\n Otherwise, the `stump` algorithm is used when the exact matrix profile is\n requested.\n\n pre_scrump : bool, default True\n A flag for whether or not to perform the PreSCRIMP calculation prior to\n computing SCRIMP. If set to `True`, this is equivalent to computing\n SCRIMP++. This parameter is ignored when `percentage = 1.0`.\n\n dask_client : client, default None\n A Dask Distributed client that is connected to a Dask scheduler and\n Dask workers. Setting up a Dask distributed cluster is beyond the\n scope of this library. Please refer to the Dask Distributed\n documentation.\n\n device_id : int or list, default None\n The (GPU) device number to use. The default value is `0`. A list of\n valid device ids (int) may also be provided for parallel GPU-STUMP\n computation. A list of all valid device ids can be obtained by\n executing `[device.id for device in numba.cuda.list_devices()]`.\n\n mp_func : object, default stump\n The matrix profile function to use when `percentage = 1.0`\n\n Attributes\n ----------\n PAN_ : numpy.ndarray\n The transformed (i.e., normalized, contrasted, binarized, and repeated)\n pan matrix profile\n\n M_ : numpy.ndarray\n The full list of (breadth first search (level) ordered) subsequence window\n sizes\n\n Methods\n -------\n update():\n Compute the next matrix profile using the next available (breadth-first-search\n (level) ordered) subsequence window size and update the pan matrix profile\n\n Notes\n -----\n `DOI: 10.1109/ICBK.2019.00031 \\\n <https://www.cs.ucr.edu/~eamonn/PAN_SKIMP%20%28Matrix%20Profile%20XX%29.pdf>`__\n\n See Table 2\n \"\"\"\n\n def __init__(\n self,\n T,\n min_m=3,\n max_m=None,\n step=1,\n percentage=0.01,\n pre_scrump=True,\n dask_client=None,\n device_id=None,\n mp_func=stump,\n ):\n \"\"\"\n Initialize the `stimp` object and compute the Pan Matrix Profile\n\n Parameters\n ----------\n T : numpy.ndarray\n The time series or sequence for which to compute the pan matrix profile\n\n min_m : int, default 3\n The minimum subsequence window size to consider computing a matrix profile\n for\n\n max_m : int, default None\n The maximum subsequence window size to consider computing a matrix profile\n for. When `max_m = None`, this is set to the maximum allowable subsequence\n window size\n\n step : int, default 1\n The step between subsequence window sizes\n\n percentage : float, default 0.01\n The percentage of the full matrix profile to compute for each subsequence\n window size. When `percentage < 1.0`, then the `scrump` algorithm is used.\n Otherwise, the `stump` algorithm is used when the exact matrix profile is\n requested.\n\n pre_scrump : bool, default True\n A flag for whether or not to perform the PreSCRIMP calculation prior to\n computing SCRIMP. If set to `True`, this is equivalent to computing\n SCRIMP++. This parameter is ignored when `percentage = 1.0`.\n\n dask_client : client, default None\n A Dask Distributed client that is connected to a Dask scheduler and\n Dask workers. Setting up a Dask distributed cluster is beyond the\n scope of this library. Please refer to the Dask Distributed\n documentation.\n\n device_id : int or list, default None\n The (GPU) device number to use. The default value is `0`. A list of\n valid device ids (int) may also be provided for parallel GPU-STUMP\n computation. A list of all valid device ids can be obtained by\n executing `[device.id for device in numba.cuda.list_devices()]`.\n\n mp_func : object, default stump\n The matrix profile function to use when `percentage = 1.0`\n \"\"\"\n self._T = T.copy()\n if max_m is None:\n max_m = max(min_m + 1, core.get_max_window_size(self._T.shape[0]))\n M = np.arange(min_m, max_m + 1, step).astype(np.int64)\n else:\n min_m, max_m = sorted([min_m, max_m])\n M = np.arange(\n max(3, min_m),\n min(core.get_max_window_size(self._T.shape[0]), max_m) + 1,\n step,\n ).astype(np.int64)\n self._bfs_indices = core._bfs_indices(M.shape[0])\n self._M = M[self._bfs_indices]\n self._n_processed = 0\n percentage = np.clip(percentage, 0.0, 1.0)\n self._percentage = percentage\n self._pre_scrump = pre_scrump\n partial_mp_func = core._get_partial_mp_func(\n mp_func, dask_client=dask_client, device_id=device_id\n )\n self._mp_func = partial_mp_func\n\n self._PAN = np.full(\n (self._M.shape[0], self._T.shape[0]), fill_value=np.inf, dtype=np.float64\n )\n\n def update(self):\n \"\"\"\n Update the pan matrix profile by computing a single matrix profile using the\n next available subsequence window size\n\n Notes\n -----\n `DOI: 10.1109/ICBK.2019.00031 \\\n <https://www.cs.ucr.edu/~eamonn/PAN_SKIMP%20%28Matrix%20Profile%20XX%29.pdf>`__\n\n See Table 2\n \"\"\"\n if self._n_processed < self._M.shape[0]:\n m = self._M[self._n_processed]\n if self._percentage < 1.0:\n approx = scrump(\n self._T,\n m,\n ignore_trivial=True,\n percentage=self._percentage,\n pre_scrump=self._pre_scrump,\n )\n approx.update()\n self._PAN[\n self._bfs_indices[self._n_processed], : approx.P_.shape[0]\n ] = approx.P_\n else:\n out = self._mp_func(\n self._T,\n m,\n ignore_trivial=True,\n )\n self._PAN[\n self._bfs_indices[self._n_processed], : out[:, 0].shape[0]\n ] = out[:, 0]\n self._n_processed += 1\n\n def pan(self, threshold=0.2, normalize=True, contrast=True, binary=True, clip=True):\n \"\"\"\n Generate a transformed (i.e., normalized, contrasted, binarized, and repeated)\n pan matrix profile\n\n Parameters\n ----------\n threshold : float, default 0.2\n The distance `threshold` in which to center the pan matrix profile around\n for best contrast and this value is also used for binarizing the pan matrix\n profile\n\n normalize : bool, default True\n A flag for whether or not each individual matrix profile within the pan\n matrix profile is normalized by its corresponding subsequence window size.\n If set to `True`, normalization is performed.\n\n contrast : bool, default True\n A flag for whether or not the pan matrix profile is centered around the\n desired `threshold` in order to provide higher contrast. If set to `True`,\n centering is performed.\n\n binary : bool, default True\n A flag for whether or not the pan matrix profile is binarized. If set to\n `True`, all values less than or equal to `threshold` are set to `0.0` while\n all other values are set to `1.0`.\n\n clip : bool, default True\n A flag for whether or not the pan matrix profile is clipped. If set to\n `True`, all values are ensured to be clipped between `0.0` and `1.0`.\n\n Returns\n -------\n None\n \"\"\"\n PAN = self._PAN.copy()\n # Retrieve the row indices where the matrix profile was actually computed\n idx = self._bfs_indices[: self._n_processed]\n sorted_idx = np.sort(idx)\n PAN[PAN == np.inf] = np.nan\n\n if normalize:\n _normalize_pan(PAN, self._M, self._bfs_indices, self._n_processed)\n if contrast:\n core._contrast_pan(PAN, threshold, self._bfs_indices, self._n_processed)\n if binary:\n core._binarize_pan(PAN, threshold, self._bfs_indices, self._n_processed)\n if clip:\n PAN[idx] = np.clip(PAN[idx], 0.0, 1.0)\n\n # Below, for each matrix profile that was computed, we take that matrix profile\n # and copy/repeat it downwards to replace other rows in the `PAN` where the\n # matrix profile has yet to be computed. Instead of only having lines/values in\n # the rows where matrix profiles were computed, this gives us the \"blocky\" look\n nrepeat = np.diff(np.append(-1, sorted_idx))\n PAN[: np.sum(nrepeat)] = np.repeat(PAN[sorted_idx], nrepeat, axis=0)\n PAN[np.isnan(PAN)] = np.nanmax(PAN)\n\n return PAN\n\n @property\n def PAN_(self):\n \"\"\"\n Get the transformed (i.e., normalized, contrasted, binarized, and repeated) pan\n matrix profile\n \"\"\"\n return self.pan().astype(np.float64)\n\n @property\n def M_(self):\n \"\"\"\n Get all of the (breadth first searched (level) ordered) subsequence window sizes\n \"\"\"\n return self._M.astype(np.int64)\n\n # @property\n # def bfs_indices_(self):\n # \"\"\"\n # Get the breadth first search (level order) indices\n # \"\"\"\n # return self._bfs_indices.astype(np.int64)\n\n # @property\n # def n_processed_(self): # pragma: no cover\n # \"\"\"\n # Get the total number of windows that have been processed\n # \"\"\"\n # return self._n_processed\n\n\[email protected]_normalized(\n aamp_stimp,\n exclude=[\"pre_scrump\", \"normalize\", \"p\", \"pre_scraamp\"],\n replace={\"pre_scrump\": \"pre_scraamp\"},\n)\nclass stimp(_stimp):\n \"\"\"\n Compute the Pan Matrix Profile\n\n This is based on the SKIMP algorithm.\n\n Parameters\n ----------\n T : numpy.ndarray\n The time series or sequence for which to compute the pan matrix profile\n\n m_start : int, default 3\n The starting (or minimum) subsequence window size for which a matrix profile\n may be computed\n\n m_stop : int, default None\n The stopping (or maximum) subsequence window size for which a matrix profile\n may be computed. When `m_stop = Non`, this is set to the maximum allowable\n subsequence window size\n\n m_step : int, default 1\n The step between subsequence window sizes\n\n percentage : float, default 0.01\n The percentage of the full matrix profile to compute for each subsequence\n window size. When `percentage < 1.0`, then the `scrump` algorithm is used.\n Otherwise, the `stump` algorithm is used when the exact matrix profile is\n requested.\n\n pre_scrump : bool, default True\n A flag for whether or not to perform the PreSCRIMP calculation prior to\n computing SCRIMP. If set to `True`, this is equivalent to computing\n SCRIMP++. This parameter is ignored when `percentage = 1.0`.\n\n normalize : bool, default True\n When set to `True`, this z-normalizes subsequences prior to computing distances.\n Otherwise, this function gets re-routed to its complementary non-normalized\n equivalent set in the `@core.non_normalized` function decorator.\n\n p : float, default 2.0\n The p-norm to apply for computing the Minkowski distance. This parameter is\n ignored when `normalize == True`.\n\n Attributes\n ----------\n PAN_ : numpy.ndarray\n The transformed (i.e., normalized, contrasted, binarized, and repeated)\n pan matrix profile\n\n M_ : numpy.ndarray\n The full list of (breadth first search (level) ordered) subsequence window\n sizes\n\n Methods\n -------\n update():\n Compute the next matrix profile using the next available (breadth-first-search\n (level) ordered) subsequence window size and update the pan matrix profile\n\n See Also\n --------\n stumpy.stimped : Compute the Pan Matrix Profile with a distributed dask cluster\n stumpy.gpu_stimp : Compute the Pan Matrix Profile with with one or more GPU devices\n\n Notes\n -----\n `DOI: 10.1109/ICBK.2019.00031 \\\n <https://www.cs.ucr.edu/~eamonn/PAN_SKIMP%20%28Matrix%20Profile%20XX%29.pdf>`__\n\n See Table 2\n\n Examples\n --------\n >>> pmp = stumpy.stimp(np.array([584., -11., 23., 79., 1001., 0., -19.]))\n >>> pmp.update()\n >>> pmp.PAN_\n array([[0., 1., 1., 1., 1., 1., 1.],\n [0., 1., 1., 1., 1., 1., 1.]])\n \"\"\"\n\n def __init__(\n self,\n T,\n min_m=3,\n max_m=None,\n step=1,\n percentage=0.01,\n pre_scrump=True,\n normalize=True,\n p=2.0,\n ):\n \"\"\"\n Initialize the `stimp` object and compute the Pan Matrix Profile\n\n Parameters\n ----------\n T : numpy.ndarray\n The time series or sequence for which to compute the pan matrix profile\n\n min_m : int, default 3\n The minimum subsequence window size to consider computing a matrix profile\n for\n\n max_m : int, default None\n The maximum subsequence window size to consider computing a matrix profile\n for. When `max_m = None`, this is set to the maximum allowable subsequence\n window size\n\n step : int, default 1\n The step between subsequence window sizes\n\n percentage : float, default 0.01\n The percentage of the full matrix profile to compute for each subsequence\n window size. When `percentage < 1.0`, then the `scrump` algorithm is used.\n Otherwise, the `stump` algorithm is used when the exact matrix profile is\n requested.\n\n pre_scrump : bool, default True\n A flag for whether or not to perform the PreSCRIMP calculation prior to\n computing SCRIMP. If set to `True`, this is equivalent to computing\n SCRIMP++. This parameter is ignored when `percentage = 1.0`.\n\n normalize : bool, default True\n When set to `True`, this z-normalizes subsequences prior to computing\n distances. Otherwise, this function gets re-routed to its complementary\n non-normalized equivalent set in the `@core.non_normalized` function\n decorator.\n\n p : float, default 2.0\n The p-norm to apply for computing the Minkowski distance. This parameter is\n ignored when `normalize == True`.\n \"\"\"\n super().__init__(\n T,\n min_m=min_m,\n max_m=max_m,\n step=step,\n percentage=percentage,\n pre_scrump=pre_scrump,\n mp_func=stump,\n )\n\n\[email protected]_normalized(\n aamp_stimped,\n exclude=[\"pre_scrump\", \"normalize\", \"p\", \"pre_scraamp\"],\n replace={\"pre_scrump\": \"pre_scraamp\"},\n)\nclass stimped(_stimp):\n \"\"\"\n Compute the Pan Matrix Profile with a distributed dask cluster\n\n This is based on the SKIMP algorithm.\n\n Parameters\n ----------\n dask_client : client\n A Dask Distributed client that is connected to a Dask scheduler and\n Dask workers. Setting up a Dask distributed cluster is beyond the\n scope of this library. Please refer to the Dask Distributed\n documentation.\n\n T : numpy.ndarray\n The time series or sequence for which to compute the pan matrix profile\n\n m_start : int, default 3\n The starting (or minimum) subsequence window size for which a matrix profile\n may be computed\n\n m_stop : int, default None\n The stopping (or maximum) subsequence window size for which a matrix profile\n may be computed. When `m_stop = Non`, this is set to the maximum allowable\n subsequence window size\n\n m_step : int, default 1\n The step between subsequence window sizes\n\n normalize : bool, default True\n When set to `True`, this z-normalizes subsequences prior to computing distances.\n Otherwise, this function gets re-routed to its complementary non-normalized\n equivalent set in the `@core.non_normalized` function decorator.\n\n p : float, default 2.0\n The p-norm to apply for computing the Minkowski distance. This parameter is\n ignored when `normalize == True`.\n\n Attributes\n ----------\n PAN_ : numpy.ndarray\n The transformed (i.e., normalized, contrasted, binarized, and repeated)\n pan matrix profile\n\n M_ : numpy.ndarray\n The full list of (breadth first search (level) ordered) subsequence window\n sizes\n\n Methods\n -------\n update():\n Compute the next matrix profile using the next available (breadth-first-search\n (level) ordered) subsequence window size and update the pan matrix profile\n\n See Also\n --------\n stumpy.stimp : Compute the Pan Matrix Profile\n stumpy.gpu_stimp : Compute the Pan Matrix Profile with with one or more GPU devices\n\n Notes\n -----\n `DOI: 10.1109/ICBK.2019.00031 \\\n <https://www.cs.ucr.edu/~eamonn/PAN_SKIMP%20%28Matrix%20Profile%20XX%29.pdf>`__\n\n See Table 2\n\n Examples\n --------\n >>> from dask.distributed import Client\n >>> if __name__ == \"__main__\":\n ... dask_client = Client()\n ... pmp = stumpy.stimped(\n ... dask_client,\n ... np.array([584., -11., 23., 79., 1001., 0., -19.]))\n ... pmp.update()\n ... pmp.PAN_\n array([[0., 1., 1., 1., 1., 1., 1.],\n [0., 1., 1., 1., 1., 1., 1.]])\n \"\"\"\n\n def __init__(\n self,\n dask_client,\n T,\n min_m=3,\n max_m=None,\n step=1,\n normalize=True,\n p=2.0,\n ):\n \"\"\"\n Initialize the `stimp` object and compute the Pan Matrix Profile\n\n Parameters\n ----------\n dask_client : client\n A Dask Distributed client that is connected to a Dask scheduler and\n Dask workers. Setting up a Dask distributed cluster is beyond the\n scope of this library. Please refer to the Dask Distributed\n documentation.\n\n T : numpy.ndarray\n The time series or sequence for which to compute the pan matrix profile\n\n min_m : int, default 3\n The minimum subsequence window size to consider computing a matrix profile\n for\n\n max_m : int, default None\n The maximum subsequence window size to consider computing a matrix profile\n for. When `max_m = None`, this is set to the maximum allowable subsequence\n window size\n\n step : int, default 1\n The step between subsequence window sizes\n\n normalize : bool, default True\n When set to `True`, this z-normalizes subsequences prior to computing\n distances. Otherwise, this function gets re-routed to its complementary\n non-normalized equivalent set in the `@core.non_normalized` function\n decorator.\n\n p : float, default 2.0\n The p-norm to apply for computing the Minkowski distance. This parameter is\n ignored when `normalize == True`.\n \"\"\"\n super().__init__(\n T,\n min_m=min_m,\n max_m=max_m,\n step=step,\n percentage=1.0,\n pre_scrump=False,\n dask_client=dask_client,\n mp_func=stumped,\n )\n"
] |
[
[
"numpy.testing.assert_almost_equal",
"numpy.array",
"numpy.random.uniform"
],
[
"numpy.random.seed",
"numpy.arange",
"numpy.ones",
"numpy.testing.assert_almost_equal",
"numpy.ceil",
"numpy.random.rand",
"numpy.random.uniform",
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
],
[
"numpy.random.seed",
"numpy.full",
"numpy.testing.assert_almost_equal",
"numpy.ceil",
"numpy.random.uniform",
"numpy.array",
"numpy.random.randint"
],
[
"numpy.nanmax",
"numpy.minimum",
"numpy.sqrt",
"numpy.clip",
"numpy.isnan",
"numpy.arange",
"numpy.sort",
"numpy.full",
"numpy.append",
"numpy.repeat",
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ashiqimran/CNTK
|
[
"22c7c3cbf95f5bcb239d3d956f08efdf43253ab2"
] |
[
"bindings/python/cntk/tests/onnx_op_test.py"
] |
[
"# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE.md file in the project root\n# for full license information.\n# ==============================================================================\n\nimport os\nimport numpy as np\nimport cntk as C\nimport pytest\nonnx = pytest.importorskip(\"onnx\")\nfrom copy import deepcopy\nfrom cntk.ops.tests.ops_test_utils import cntk_device\nfrom itertools import product\nfrom .onnx_test_helper import transpose_dynamic_axis, create_and_populate_onnx_test_case_with_model_conversion, save_test_data, compare_model_for_output_data_transpose\nfrom .onnx_test_helper import CNTK_FREEDIM_AXIS_DENOTATION, DIM_SIZE_FOR_NON_BATCH_OPS, is_list_of_sparse, sparse_to_dense\n\n# This is a list of all ops in CNTK that are exported as ONNX ops\n# that have a batch axis defined by spec (e.g. convolution, pooling)\n# When adding a test for a new op, please check to see if \n# that op needs to be added to this list (i.e. does that op \n# get exported to an ONNX op with defined batch axis).\nset_of_batch_ops = {'Pooling', 'Convolution', 'GlobalAveragePooling', 'GlobalMaxPooling', 'DepthToSpace', 'SpaceToDepth', 'LocalResponseNormalization', 'MeanVarianceNormalization', 'LayerNormalization', 'BatchNormalization', 'ImageScaler', 'Crop'}\n\n# List of CNTK ops for which output shape doesn't change regardless\n# of whether the input has batch axis or not.\n# Basically, for these ops we don't prepend 1 to the output shape\n# when the input has batch axis.\nset_of_batch_irrelevant_ops = {}\n\n##########################################\n## helper verification functions\n##########################################\n\ndef init_empty_node_names(model):\n # Most of the unit tests here don't specify names for nodes.\n # Try to replace empty node names, and check if names are preserved after export/import\n # in later tests.\n class UpdateNodeName(object):\n i = 0\n @classmethod\n def step(cls, node):\n if node.name == \"\":\n try:\n node.name = \"test_node_name_\" + str(cls.i)\n cls.i += 1\n except:\n return True\n return True\n C.logging.graph.depth_first_search(model, UpdateNodeName.step)\n\ndef verify_node_names(model1, model2):\n # Verify if all the node names in original model appears at least as prefix of some node names\n # in reloaded model. Because alternations of nodes are occasionally necessary in exporting and importing,\n # in these cases node names might be appended with different postfixes.\n model1_names = [node.name for node in C.logging.graph.depth_first_search(model1, lambda x : True)]\n model2_names = [node.name for node in C.logging.graph.depth_first_search(model2, lambda x : True)]\n\n names_preserved = [name == '' or any([new_name.startswith(name) for new_name in model2_names])\n for name in model1_names]\n assert all(names_preserved) == True\n\ndef verify_no_input(model, tmpdir, name):\n init_empty_node_names(model)\n\n opname = model.owner.op_name\n\n loaded_model = None\n loaded_model, _, _, _ = create_and_populate_onnx_test_case_with_model_conversion(model, tmpdir, name, loaded_model)\n\n model_shape = model.shape\n dim_denotation = None\n if model.output.dynamic_axes == (C.Axis('defaultBatchAxis'),) and opname not in set_of_batch_ops:\n dim_denotation = DIM_SIZE_FOR_NON_BATCH_OPS\n elif opname in set_of_batch_ops:\n dim_denotation = CNTK_FREEDIM_AXIS_DENOTATION\n if not dim_denotation is None and opname not in set_of_batch_irrelevant_ops:\n model_shape = (dim_denotation, ) + model_shape\n\n assert model_shape == loaded_model.shape\n\n o0 = model.eval()\n o1 = loaded_model.eval()\n\n if (type(o0) is list):\n o0 = o0[0]\n if (type(o1) is list):\n o1 = o1[0]\n\n assert np.allclose(o0, o1)\n verify_node_names(model, loaded_model)\n return loaded_model\n\ndef verify_one_input(model, data, tmpdir, name, device=None, loaded_model=None, rtol = 1e-05, atol = 1e-08):\n # TODO: eventually we want this test method to be more general to suport \n # models with multiple inputs instead of just one input.\n assert len(model.arguments) == 1\n assert not model.arguments[0].has_sequence_axis()\n\n init_empty_node_names(model)\n\n # data here is reference to the outside data object. create deepcopy to avoid changing the outside data since it might get reused.\n data = deepcopy(data)\n\n # outputs share the same owner\n opname = model.outputs[0].owner.op_name\n\n loaded_model, onnx_model, test_model_path, test_data_path = create_and_populate_onnx_test_case_with_model_conversion(model, tmpdir, name, loaded_model)\n\n # TODO: it is better to compare data.shape with model.arguments[0] and\n # to pad batch dimension as needed.\n # Some tests have already expanded batch axis to data (i.e. reduction test) \n if model.arguments[0].has_batch_axis() and type(data)!=list:\n data.shape = (1, ) + data.shape\n\n assert len(model.outputs) == len(loaded_model.outputs)\n\n dim_denotation = CNTK_FREEDIM_AXIS_DENOTATION if opname in set_of_batch_ops else DIM_SIZE_FOR_NON_BATCH_OPS\n for i in range(0, len(model.outputs)):\n assert not model.outputs[i].has_sequence_axis()\n output_shape = model.outputs[i].shape\n if opname not in set_of_batch_irrelevant_ops:\n if model.outputs[i].has_batch_axis():\n output_shape = (dim_denotation, ) + output_shape\n assert output_shape == loaded_model.outputs[i].shape\n\n if device:\n o0 = model.eval({model.arguments[0]:data}, device=device)\n o1 = loaded_model.eval({loaded_model.arguments[0]:data}, device=device)\n else:\n o0 = model.eval({model.arguments[0]:data})\n o1 = loaded_model.eval({loaded_model.arguments[0]:data})\n\n if len(model.outputs) == 1:\n assert np.allclose(o0, o1, rtol, atol)\n else:\n matched_indices = []\n for i in range(0, len(model.outputs)):\n # outputs of loaded model are not necessarily in the same order as the original model.\n # output uid is likely changed too.\n # the only way to verify the data is to find match for every output. \n o0i = o0[model.outputs[i]]\n for j in range(0, len(loaded_model.outputs)):\n if j not in matched_indices:\n o1i = o1[loaded_model.outputs[j]]\n if np.shape(o0i) == np.shape(o1i) and np.allclose(o0i, o1i):\n matched_indices.append(j)\n break\n assert len(matched_indices) == i+1\n\n save_test_data(model, onnx_model, test_data_path, data, o0, name, tmpdir)\n\n verify_node_names(model, loaded_model)\n return loaded_model\n\ndef run_model(model, data, device=None):\n feed = {}\n if len(model.arguments) == 1:\n feed[model.arguments[0]] = data\n elif len(model.arguments) > 1:\n assert len(model.arguments) == len(data)\n for i in range(len(model.arguments)):\n feed[model.arguments[i]] = data[i]\n \n o = model.eval(feed, device=device)\n return o\n\ndef verify_sequence_model(model, data, tmpdir, name, device=None, loaded_model=None):\n # data here is reference to the outside data object. create deepcopy to avoid changing the outside data since it might get reused.\n data = deepcopy(data)\n\n # onnx does not specify sparse tensor. to run imported model, a sparse matrix needs to be converted to a dense matrix \n dataOnnx = None\n if is_list_of_sparse(data):\n dataOnnx = transpose_dynamic_axis(sparse_to_dense(data))\n else:\n if (type(data) == list):\n dataOnnx = []\n for i in range(0, len(data)):\n if (model.arguments[i].has_sequence_axis()):\n dataOnnx.append(transpose_dynamic_axis(data[i]))\n else:\n dataOnnx.append(data[i])\n else:\n dataOnnx = transpose_dynamic_axis(data)\n\n loaded_model, onnx_model, test_model_path, test_data_path = create_and_populate_onnx_test_case_with_model_conversion(model, tmpdir, name, loaded_model)\n\n o0 = run_model(model, data, device=device)\n o1 = run_model(loaded_model, dataOnnx, device=device)\n\n ## if there is a sequence axis in the output, it must be swapped with batch axis \n ## to match the original CNTK model's output \n if len(model.outputs) == 1:\n o0 = np.array(o0)\n o1 = np.array(o1)\n if compare_model_for_output_data_transpose(model.outputs[0], loaded_model.outputs[0]):\n o1 = transpose_dynamic_axis(np.array(o1))\n assert np.allclose(o0, o1)\n else:\n matched_indices = []\n for i in range(0, len(model.outputs)):\n # outputs of loaded model are not necessarily in the same order as the original model.\n # output uid is likely changed too.\n # the only way to verify the data is to find match for every output. \n o0i = o0[model.outputs[i]]\n for j in range(0, len(loaded_model.outputs)):\n if j not in matched_indices:\n o1i = o1[loaded_model.outputs[j]]\n if compare_model_for_output_data_transpose(model.outputs[i], loaded_model.outputs[j]):\n o1i = transpose_dynamic_axis(o1i)\n if np.shape(o0i) == np.shape(o1i) and np.allclose(o0i, o1i):\n matched_indices.append(j)\n break\n assert len(matched_indices) == i+1\n \n\n save_test_data(model, onnx_model, test_data_path, data, o0, name, tmpdir)\n\ndef verify_two_input(model, data1, data2, tmpdir, name):\n init_empty_node_names(model)\n\n # data here is reference to the outside data object. create deepcopy to avoid changing the outside data since it might get reused.\n data1 = deepcopy(data1)\n data2 = deepcopy(data2)\n\n filename = os.path.join(str(tmpdir), name + R'.onnx')\n model.save(filename, format=C.ModelFormat.ONNX)\n opname = model.owner.op_name\n\n loaded_model = C.Function.load(filename, format=C.ModelFormat.ONNX)\n\n filename_resave = os.path.join(str(tmpdir), name + R'_resave.onnx')\n loaded_model.save(filename_resave, format=C.ModelFormat.ONNX)\n\n model_shape = model.shape\n if model.output.dynamic_axes == (C.Axis('defaultBatchAxis'),):\n dim_denotation = CNTK_FREEDIM_AXIS_DENOTATION if opname in set_of_batch_ops else DIM_SIZE_FOR_NON_BATCH_OPS\n if opname not in set_of_batch_irrelevant_ops:\n model_shape = (dim_denotation, ) + model_shape\n data1.shape = (1, ) + data1.shape\n data2.shape = (1, ) + data2.shape\n assert model_shape == loaded_model.shape\n\n o0 = model.eval({model.arguments[0]:data1, model.arguments[1]:data2})\n o1 = loaded_model.eval({loaded_model.arguments[0]:data1, loaded_model.arguments[1]:data2})\n\n if (type(o0) is list):\n o0 = o0[0]\n if (type(o1) is list):\n o1 = o1[0]\n\n assert np.allclose(o0, o1)\n verify_node_names(model, loaded_model)\n\n#Shared Test Configs\nDType_Config = (np.float32, np.float16)\n\n#Abs\[email protected](\"dtype\", DType_Config)\ndef test_Abs(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n shape = (4, 5)\n data = np.random.rand(*shape).astype(dtype)\n\n model = C.abs(data)\n verify_no_input(model, tmpdir, 'Abs_0')\n\n x = C.input_variable(shape)\n model = C.abs(x)\n\n verify_one_input(model, data, tmpdir, 'Abs_1')\n\n#Add\[email protected](\"dtype\", DType_Config)\ndef test_Add(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n shape = (4, 5)\n data1 = np.random.rand(*shape).astype(dtype)\n data2 = np.random.rand(*shape).astype(dtype)\n model = C.plus(data1, data2)\n verify_no_input(model, tmpdir, 'Add_0')\n\n x = C.input_variable(shape)\n model = C.plus(x, data2)\n\n verify_one_input(model, data1, tmpdir, 'Add_1')\n\n y = C.input_variable(shape)\n model = C.plus(x, y)\n\n verify_two_input(model, data1, data2, tmpdir, 'Add_2')\n\n#And\[email protected](\"dtype\", DType_Config)\ndef test_And(tmpdir, dtype):\n data1 = np.asarray([[1, 1, 0, 0],[1, 1, 1, 1]], dtype)\n data2 = np.asarray([1, 0, 1, 0], dtype)\n\n model = C.element_and(data1, data2)\n verify_no_input(model, tmpdir, 'And_0')\n\n x = C.input_variable(np.shape(data1))\n y = C.input_variable(np.shape(data2))\n\n model = C.element_and(x, data2)\n verify_one_input(model, data1, tmpdir, 'And_1')\n\n model = C.element_and(x, y)\n verify_two_input(model, data1, data2, tmpdir, 'And_2')\n\n#Or\ndef test_Or(tmpdir):\n data1 = np.asarray([[1, 1, 0, 0],[1, 1, 1, 1]], np.float32)\n data2 = np.asarray([1, 0, 1, 0], np.float32)\n\n model = C.element_or(data1, data2)\n verify_no_input(model, tmpdir, 'Or_0')\n\n x = C.input_variable(np.shape(data1))\n y = C.input_variable(np.shape(data2))\n\n model = C.element_or(x, data2)\n verify_one_input(model, data1, tmpdir, 'Or_1')\n\n model = C.element_or(x, y)\n verify_two_input(model, data1, data2, tmpdir, 'Or_2')\n\n#Xor\ndef test_Xor(tmpdir):\n data1 = np.asarray([[1, 1, 0, 0],[1, 1, 1, 1]], np.float32)\n data2 = np.asarray([1, 0, 1, 0], np.float32)\n\n model = C.element_xor(data1, data2)\n verify_no_input(model, tmpdir, 'Xor_0')\n\n x = C.input_variable(np.shape(data1))\n y = C.input_variable(np.shape(data2))\n\n model = C.element_xor(x, data2)\n verify_one_input(model, data1, tmpdir, 'Xor_1')\n\n model = C.element_xor(x, y)\n verify_two_input(model, data1, data2, tmpdir, 'Xor_2')\n\n#Not\[email protected](\"dtype\", DType_Config)\ndef test_Not(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data1 = np.asarray([[1, 1, 0, 0],[1, 1, 1, 1]]).astype(dtype)\n\n model = C.element_not(data1)\n verify_no_input(model, tmpdir, 'Not_0')\n\n x = C.input_variable(np.shape(data1))\n\n model = C.element_not(x)\n verify_one_input(model, data1, tmpdir, 'Not_1')\n\n#ArgMax\[email protected](\"dtype\", DType_Config)\ndef test_ArgMax(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n shape = (4, 5)\n data = np.random.rand(*shape).astype(dtype)\n model = C.argmax(data, 0)\n\n verify_no_input(model, tmpdir, 'ArgMax_0')\n\n x = C.input_variable(shape)\n model = C.argmax(x, 0)\n verify_one_input(model, data, tmpdir, 'ArgMax_1')\n\n#ArgMin\[email protected](\"dtype\", DType_Config)\ndef test_ArgMin(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n shape = (4, 5)\n data = np.random.rand(*shape).astype(dtype)\n model = C.argmin(data, 0)\n\n verify_no_input(model, tmpdir, 'ArgMin_0')\n\n#AveragePool\[email protected](\"dtype\", DType_Config)\ndef test_AveragePool(tmpdir, dtype, device_id):\n if device_id == -1 and dtype == np.float16:\n pytest.skip('Test is skipped on CPU with float16 data')\n device = cntk_device(device_id)\n with C.default_options(dtype=dtype):\n img = np.reshape(np.arange(16, dtype = dtype), [1, 4, 4])\n x = C.input_variable(img.shape)\n model = C.pooling(x, C.AVG_POOLING, (2,2), (2,2))\n\n verify_one_input(model, img, tmpdir, 'AveragePool_1', device)\n\n # test for case of not padding but with ceilOutDim=True\n img = np.reshape(np.arange(49, dtype=dtype), [1, 7, 7])\n x = C.input_variable(img.shape)\n model = C.pooling(x, C.AVG_POOLING, (7, 7), auto_padding = [False, False, False], ceil_out_dim=True)\n\n verify_one_input(model, img, tmpdir, 'AveragePool_2', device)\n\n#BatchNormalization\ndef verify_BN(x, init_scale, init_bias, mean, var, epsilon, spatial, tmpdir, dtype):\n with C.default_options(dtype = dtype):\n scale = C.Parameter(init=init_scale, dtype=np.float32)\n bias = C.Parameter(init=init_bias, dtype=np.float32)\n run_mean = C.ops.constant(mean, shape=mean.shape, dtype=np.float32)\n run_variance = C.ops.constant(var, shape=var.shape, dtype=np.float32)\n run_count = C.ops.constant(0, dtype=np.float32)\n\n a = C.input_variable(shape=x.shape[1:], dtype=dtype, needs_gradient=False, name='a')\n\n op_node = C.batch_normalization(a, scale, bias, run_mean, run_variance, running_count=run_count, spatial=spatial,\n epsilon=epsilon)\n\n loaded_model = None\n test_base_name = 'Spatial' if spatial else ''\n test_base_name = test_base_name + ('BatchNormalization_float16' if dtype==np.float16 else 'BatchNormalization_float32')\n\n for i in range(len(x)):\n if dtype==np.float16:\n loaded_model = verify_one_input(op_node, x[i], tmpdir, test_base_name + str(i), loaded_model=loaded_model, rtol = 1e-03, atol = 1e-03)\n else:\n loaded_model = verify_one_input(op_node, x[i], tmpdir, test_base_name + str(i), loaded_model=loaded_model)\n\nnon_spatial_float16_skip_message = str('Test is skipped with float16 data because CNTK ONNX importer in float16 case assumes mean/var inputs being constant.'\n 'this is not always true because in CNTK non-spatial case mean/var may need to be reshaped before pass to the BN function.'\n 'In general import of BatchNormalization(float16) need to be fixed to take any input as mean/var, etc.')\n# Case 1 - Non-Spatial BN with More > 1 batches \[email protected](\"dtype\", DType_Config)\ndef test_BatchNormalization(tmpdir, dtype):\n if dtype == np.float16:\n pytest.skip(non_spatial_float16_skip_message)\n sample = [ # 5 samples having 4 classes\n [1, 1, 2, 3],\n [0, 0, 0, 0],\n [3, 3, 4, 4],\n [1000, 1000, 1000, 1000],\n [10000, 10000, 10000, 10000]]\n\n np.random.seed(1)\n x = np.array(sample).reshape(-1,1).astype(dtype)\n scale = np.array([3]).astype(np.float32)\n bias = np.array([4]).astype(np.float32)\n mean = np.array([1]).astype(np.float32)\n var = np.array([2]).astype(np.float32)\n epsilon = 0.00001\n\n verify_BN(x, scale, bias, mean, var, epsilon, False, tmpdir, dtype)\n \n# Case 2 - Spatial BN with More > 1 batches \[email protected](\"dtype\", DType_Config)\ndef test_SpatialBatchNormalization(tmpdir, dtype):\n np.random.seed(0)\n x = np.random.randn(2, 3, 4, 5).astype(dtype)\n scale = np.random.randn(3).astype(np.float32)\n bias = np.random.randn(3).astype(np.float32)\n mean = np.random.randn(3).astype(np.float32)\n var = np.random.rand(3).astype(np.float32)\n epsilon = 1e-2\n\n verify_BN(x, scale, bias, mean, var, epsilon, True, tmpdir, dtype)\n\n#Cast\nCast_Type_Config = (np.float64, np.float32, np.float16)\[email protected](\"from_type\", Cast_Type_Config)\[email protected](\"to_type\", Cast_Type_Config)\ndef test_Cast(tmpdir, from_type, to_type):\n test_name = \"cast_\" + from_type.__name__ + \"_to_\" + to_type.__name__\n shape = (3, 10, 15)\n input_var = C.input_variable(shape, dtype = from_type, name='features') \n model = C.cast(input_var, dtype=to_type)\n data = np.random.rand(*shape).astype(from_type)\n verify_one_input(model, data, tmpdir, test_name)\n\n# Ceil\[email protected](\"dtype\", DType_Config)\ndef test_Ceil(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.asarray([0.2, 1.3, 4., 5.5, 0.0], dtype)\n model = C.ceil(data)\n\n verify_no_input(model, tmpdir, 'ceil_0')\n\n x = C.input_variable(data.shape)\n\n model = C.ceil(x)\n\n verify_one_input(model, data, tmpdir, 'ceil_1')\n\n#Clip\[email protected](\"dtype\", DType_Config)\ndef test_Clip(tmpdir, dtype):\n if (dtype == np.float16):\n pytest.skip(\"TO BE FIXED\")\n with C.default_options(dtype = dtype):\n data = np.asarray([0.2, 1.3, 4., 5.5, 0.0], dtype)\n min_v = 2\n max_v = 4\n model = C.clip(data, min_v, max_v)\n\n verify_no_input(model, tmpdir, 'clip_0')\n\n x = C.input_variable(data.shape)\n\n model = C.clip(x, min_v, max_v)\n\n verify_one_input(model, data, tmpdir, 'clip_1')\n\n#Concat\[email protected](\"dtype\", DType_Config)\ndef test_Concat(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data1 = np.asarray([[[1, 2], [4, 5]]], dtype=dtype)\n x = C.constant(value=data1)\n # create 3x2 matrix in a sequence of length 1 in a batch of one sample\n data2 = np.asarray([[[10, 20], \n [30, 40], \n [50, 60]]],dtype=dtype)\n y = C.constant(value=data2)\n\n # splice both inputs on axis=0 returns a 5x2 matrix\n model = C.splice(x, y, axis=1)\n\n verify_no_input(model, tmpdir, 'Concat_0')\n\n x = C.input_variable(data1.shape)\n\n model = C.splice(x, y, axis=1)\n\n verify_one_input(model, data1, tmpdir, 'Concat_1')\n\[email protected](\"dtype\", DType_Config)\ndef test_Concat_With_Broadcast(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n # TODO: add test cast with exchanged shape1 and shape2\n shape1 = [2,3,1,1,3]\n shape2 = [1,3,4,1]\n shape3 = [2,4,1]\n axis = 2\n data1 = np.random.uniform(-10, 10, shape1).astype(dtype)\n data2 = np.random.uniform(-10, 10, shape2).astype(dtype)\n data3 = np.random.uniform(-10, 10, shape3).astype(dtype)\n x = C.input_variable(shape1)\n y = C.constant(value=data2)\n z = C.constant(value=data3)\n model = C.splice(x, y, z, axis=axis)\n verify_one_input(model, data1, tmpdir, 'Concat_Braodcast')\n\[email protected](\"dtype\", DType_Config)\ndef test_Conv(tmpdir, dtype, device_id):\n if device_id == -1 and dtype == np.float16:\n pytest.skip('Test is skipped on CPU with float16 data')\n device = cntk_device(device_id)\n with C.default_options(dtype=dtype):\n input_shape = (3, 20, 32) \n img = np.reshape(np.arange(np.prod(input_shape), dtype = dtype), input_shape) \n\n x = C.input_variable(input_shape)\n\n kernel_shape = (64, 3, 3, 3) # For convolution the shape is (O x I x W x H)\n kernel = C.constant(value = np.ones(shape=(kernel_shape), dtype = dtype))\n\n conv_model = C.convolution(kernel, x, auto_padding = [False, True, True])\n\n verify_one_input(conv_model, img, tmpdir, 'Conv_0', device)\n\[email protected](\"dtype\", DType_Config)\ndef test_Conv_SpecialCase(tmpdir, dtype, device_id):\n if device_id == -1 and dtype == np.float16:\n pytest.skip('Test is skipped on CPU with float16 data')\n device = cntk_device(device_id)\n with C.default_options(dtype=dtype):\n input_shape = (3, 20, 32) \n img = np.reshape(np.arange(np.prod(input_shape), dtype = dtype), input_shape) \n\n x = C.input_variable(input_shape)\n\n kernel_shape = (3, 3, 3) # For convolution the shape is (O x I x W x H). Here O is omitted which is often the case in CNTK models. \n kernel = C.constant(value = np.ones(shape=(kernel_shape), dtype = dtype))\n\n conv_model = C.convolution(kernel, x, auto_padding = [False, True, True])\n\n verify_one_input(conv_model, img, tmpdir, 'Conv_1', device)\n\n kernel = C.Parameter((kernel_shape), init=C.glorot_uniform(), dtype=dtype, device=device)\n conv_model = C.convolution(kernel, x, auto_padding = [False, True, True])\n\n verify_one_input(conv_model, img, tmpdir, 'Conv_2', device)\n\[email protected](\"dtype\", DType_Config)\ndef test_Conv_SpecialCase_Autopad(tmpdir, dtype, device_id):\n if device_id == -1 and dtype == np.float16:\n pytest.skip('Test is skipped on CPU with float16 data')\n elif dtype == np.float16:\n pytest.skip('Test is skipped on GPU with float16 data: asymmetric padding not supported by cuDnn')\n device = cntk_device(device_id)\n with C.default_options(dtype=dtype):\n # special case where for one axis CNTK pads upper, for other lower.\n input_shape = (3, 7, 8)\n img = np.reshape(np.arange(np.prod(input_shape), dtype=dtype), input_shape)\n x = C.input_variable(input_shape)\n\n kernel_shape = (3, 2, 3)\n kernel = C.constant(value = np.ones(shape=(kernel_shape), dtype=dtype))\n strides = (1, 2)\n\n conv_model = C.convolution(kernel, x, auto_padding = [False, True, True], strides=strides)\n verify_one_input(conv_model, img, tmpdir, 'Conv_3', device)\n\n\[email protected](\"dtype\", DType_Config)\ndef test_ConvTranspose(tmpdir, dtype, device_id):\n if device_id == -1 and dtype == np.float16:\n pytest.skip('Test is skipped on CPU with float16 data')\n device = cntk_device(device_id)\n with C.default_options(dtype=dtype):\n # Keep the shapes below as they are, because this tests an earlier bug.\n input_shape = (24, 8, 8) \n img = np.reshape(np.arange(np.prod(input_shape), dtype = dtype), input_shape) \n\n x = C.input_variable(input_shape)\n\n kernel_shape = (24, 16, 3, 3) # For convolution_transpose the shape is (I x O x W x H)\n kernel = C.constant(value = np.ones(shape=(kernel_shape), dtype = dtype))\n\n conv_trans_model_with_output_shape = C.convolution_transpose(kernel, x, strides=(2, 2), auto_padding = [False, True, True], output_shape=(16, 16, 16))\n verify_one_input(conv_trans_model_with_output_shape, img, tmpdir, 'ConvTranspose_with_OutputShape_0', device)\n\n # test without outputShape\n conv_trans_model_without_output_shape = C.convolution_transpose(kernel, x, strides=(2, 2), auto_padding = [False, True, True])\n verify_one_input(conv_trans_model_without_output_shape, img, tmpdir, 'ConvTranspose_without_OutputShape_0', device)\n\n# DepthToSpace\[email protected](\"dtype\", DType_Config)\ndef test_DepthToSpace(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n num_channels = 9\n block_size = 3\n image_shape = (4, 5)\n input_val = np.array(np.reshape(range(num_channels), (num_channels, 1, 1)), dtype=dtype)\n input_val = np.tile(input_val, (1,) + image_shape)\n img = C.input_variable((num_channels,) + image_shape, dtype=dtype)\n model = C.depth_to_space(img, block_size)\n\n verify_one_input(model, input_val, tmpdir, 'DepthToSpace')\n\n#Div\ndef test_Div(tmpdir):\n def run_div_test(shape1, shape2, tmpdir):\n broadcast = 'no_broadcast'\n if (shape1 != shape2):\n broadcast = 'with_broadcast'\n\n data1 = np.random.rand(*shape1).astype(np.float32)\n data2 = np.random.rand(*shape2).astype(np.float32)\n\n x = C.input_variable(shape1)\n y = C.input_variable(shape2)\n\n model = C.element_divide(data1, data2)\n verify_no_input(model, tmpdir, 'Div_' + broadcast + '_d1d2')\n\n model = C.element_divide(x, data2)\n verify_one_input(model, data1, tmpdir, 'Div_' + broadcast + '_xd2')\n\n model = C.element_divide(data1, y)\n verify_one_input(model, data2, tmpdir, 'Div_' + broadcast + '_d1y')\n\n model = C.element_divide(x, y)\n verify_two_input(model, data1, data2, tmpdir, 'Div_' + broadcast + '_xy')\n\n shape1 = (2, 3, 4, 5)\n shape2 = shape1\n # without broadcast\n run_div_test(shape1, shape2, tmpdir)\n\n # with broadcast\n shape2 = (1, 3, 1, 1)\n run_div_test(shape1, shape2, tmpdir)\n\n#Dropout\[email protected](\"dtype\", DType_Config)\ndef test_Dropout(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.asarray([[10, 20],[30, 40],[50, 60]], dtype=dtype)\n model = C.dropout(data, 0.5)\n verify_no_input(model, tmpdir, 'Dropout_0')\n\n x = C.input_variable(data.shape)\n model = C.dropout(x, 0.5)\n verify_one_input(model, data, tmpdir, 'Dropout_1')\n\n#Elu\[email protected](\"dtype\", DType_Config)\ndef test_Elu(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.asarray([[-1, -0.5, 0, 1, 2]], dtype=dtype)\n model = C.elu(data)\n verify_no_input(model, tmpdir, 'Elu_0')\n\n x1 = C.input_variable(data.shape)\n model = C.elu(x1)\n verify_one_input(model, data, tmpdir, 'Elu_1')\n\n x2 = C.input_variable(data.shape)\n model = C.elu(x2, alpha=2.0)\n verify_one_input(model, data, tmpdir, 'Elu_2')\n\n#Equal\[email protected](\"dtype\", DType_Config)\ndef test_Equal(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data0 = np.asarray([41., 42., 43.], dtype=dtype)\n data1 = np.asarray([42., 42., 42.], dtype=dtype)\n model = C.equal(data0, data1)\n verify_no_input(model, tmpdir, 'Equal_0')\n\n#Exp\[email protected](\"dtype\", DType_Config)\ndef test_Exp(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.asarray([0., 1.], dtype=dtype)\n model = C.exp(data)\n verify_no_input(model, tmpdir, 'Exp_0')\n\n x = C.input_variable(data.shape)\n model = C.exp(x)\n verify_one_input(model, data, tmpdir, 'Exp_1')\n\n#Flatten\[email protected](\"dtype\", DType_Config)\ndef test_Flatten(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n shape = (2, 3, 4, 5)\n data = np.reshape(np.arange(np.prod(shape), dtype = dtype), shape)\n model = C.flatten(data, 1)\n verify_no_input(model, tmpdir, 'Flatten_0')\n\n x = C.input_variable(data.shape)\n model = C.flatten(x, 1)\n verify_one_input(model, data, tmpdir, 'Flatten_1')\n\n#Floor\[email protected](\"dtype\", DType_Config)\ndef test_Floor(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.asarray([0.2, 1.3, 4., 5.5, 0.0], dtype=dtype)\n model = C.floor(data)\n verify_no_input(model, tmpdir, 'Floor_0')\n\n x = C.input_variable(data.shape)\n model = C.floor(x)\n verify_one_input(model, data, tmpdir, 'Floor_1')\n\n#Gather\[email protected](\"dtype\", DType_Config)\ndef test_Gather(tmpdir, dtype):\n if (dtype == np.float16):\n pytest.skip(\"TO BE FIXED\")\n with C.default_options(dtype = dtype):\n c = np.asarray([[0],[1]]).astype(dtype) \n x = C.input_variable((2,1))\n d = np.arange(12).reshape(6,2).astype(dtype)\n y = C.constant(d)\n x_constant = C.constant(c)\n model = C.gather(y, x_constant)\n verify_no_input(model, tmpdir, 'Gather_0')\n\n model = C.gather(y, x)\n verify_one_input(model, c, tmpdir, 'Gather_1')\n\n#Gather\[email protected](\"dtype\", DType_Config)\ndef test_Gather_With_Axis(tmpdir, dtype):\n if (dtype == np.float16):\n pytest.skip(\"TO BE FIXED\")\n with C.default_options(dtype = dtype):\n data = np.asarray( [[ [111, 112], [121, 122], [131, 132], ],[ [211, 212], [221, 222], [231, 232], ]]).astype(dtype)\n indices = np.asarray([[0, 1, 1], [1, 1, 1]])\n x = C.input_variable(np.shape(data))\n y = C.input_variable(np.shape(indices))\n axis = 1\n\n model = C.gather(data, y, axis, 'gather_with_axis')\n verify_one_input(model, indices, tmpdir, 'Gather_With_Axis_1')\n\n#GlobalAveragePool\[email protected](\"dtype\", DType_Config)\ndef test_GlobalAveragePool(tmpdir, dtype, device_id):\n if device_id == -1 and dtype == np.float16:\n pytest.skip('Test is skipped on CPU with float16 data')\n device = cntk_device(device_id)\n input_shape = [3, 7, 7]\n with C.default_options(dtype=dtype):\n img = np.reshape(np.arange(np.prod(input_shape), dtype = dtype), input_shape)\n x = C.input_variable(img.shape)\n model = C.layers.GlobalAveragePooling()(x)\n\n verify_one_input(model, img, tmpdir, 'GlobalAveragePool_1', device)\n\n#GlobalMaxPool\[email protected](\"dtype\", DType_Config)\ndef test_GlobalMaxPool(tmpdir, dtype, device_id):\n if device_id == -1 and dtype == np.float16:\n pytest.skip('Test is skipped on CPU with float16 data')\n device = cntk_device(device_id)\n input_shape = [4, 8, 8]\n with C.default_options(dtype=dtype):\n img = np.reshape(np.arange(np.prod(input_shape), dtype = dtype), input_shape)\n x = C.input_variable(img.shape)\n model = C.layers.GlobalMaxPooling()(x)\n\n verify_one_input(model, img, tmpdir, 'GlobalMaxPool_1', device) \n\n#Greater\[email protected](\"dtype\", DType_Config)\ndef test_Greater(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n model = C.greater([41., 42., 43.], [42., 42., 42.])\n verify_no_input(model, tmpdir, 'Greater_0')\n\n#GRU\[email protected](\"dtype\", DType_Config)\ndef test_GRU(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n def MakeGRUNameFromConfig(backward, initial_state, activition):\n model_name = 'GRU.' + activition.__name__\n if (initial_state != 0):\n model_name += '.initial'\n if (backward):\n model_name += '.backward'\n else: \n model_name += '.forward'\n return model_name \n\n direction_options = [False, True]\n activation_options = [C.tanh]\n initial_state_options = [0]\n\n input_dim = 2\n cell_dim = 3\n batch_size = 1\n sequence_len = 5\n\n for config in list(product(direction_options, initial_state_options, activation_options)):\n model_filename = MakeGRUNameFromConfig(*config)\n backward, initial_state, activation = config\n \n x = C.input_variable(input_dim, dynamic_axes=[C.Axis.default_batch_axis(), C.Axis('sequenceAxis')]) \n GRUModel = C.layers.Recurrence(C.layers.GRU(cell_dim, \n activation = activation), \n initial_state = initial_state, \n go_backwards=backward)(x)\n data = np.random.uniform(low=0.0, high=1.0, size=(batch_size, sequence_len, input_dim)).astype(dtype)\n verify_sequence_model(GRUModel, data, tmpdir, model_filename)\n\n\n#Hardmax\[email protected](\"dtype\", DType_Config)\ndef test_Hardmax(tmpdir, dtype):\n data = np.asarray([1., 1., 2., 3.], dtype)\n model = C.hardmax(data)\n verify_no_input(model, tmpdir, 'Hardmax_0')\n\n data = np.asarray([[1, 2, 3], [6, 5, 4]], dtype)\n model = C.hardmax(data)\n verify_no_input(model, tmpdir, 'Hardmax_2d_0')\n\n\n#HardSigmiod\[email protected](\"dtype\", DType_Config)\ndef test_HardSigmiod(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n shape = (2,3)\n x = C.input_variable(shape=shape, dtype=dtype)\n alpha = 1.2\n beta = 2.5\n model = C.hard_sigmoid(x, alpha, beta, 'hardSigmoid')\n\n data = np.random.rand(*shape).astype(dtype)\n verify_one_input(model, data, tmpdir, 'HardSigmoid_1')\n\n#ImageScaler\[email protected](\"dtype\", DType_Config)\ndef test_ImageScaler(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n input_height = 32\n input_width = 32\n channels = 3\n image = np.ones([channels, input_height, input_width]).astype(dtype)\n scalar = 1.5\n bias = [10, 20, 30]\n\n model = C.image_scaler(image, scalar, bias)\n verify_no_input(model, tmpdir, 'ImageScaler_0')\n\n x = C.input_variable(np.shape(image)) \n model = C.image_scaler(x, scalar, bias)\n verify_one_input(model, image, tmpdir, 'ImageScaler_1')\n\n#LayerNormalization\[email protected](\"dtype\", DType_Config)\ndef test_LayerNormalization(tmpdir, dtype, device_id):\n if device_id == -1 and dtype == np.float16:\n pytest.skip('Test is skipped on CPU with float16 data')\n # Currently there is a bug on build test. GPU environment is not set correctly for this test. \n # Thus this test will fail as it will fall back to use CPU with float16.\n if dtype == np.float16:\n pytest.skip('Test is skipped on float16 to pass build test')\n\n # This test point tests the LayerNormalization round trip with defaultepsilon. We loose always the epsilon value when \n # exporting to ONNX (because ONNX MeanVarianceNormalization does not have an epsilon attribute). When loading back \n # from ONNX, CNTK always uses the default eposilon value (0.00001). That's why test below has the default epsilon \n # value. It is not expected to pass with any other epsilon value until something changes.\n with C.default_options(dtype = dtype):\n test_shapes = [(3, 5, 7), (10, ), (20, 31)]\n for shape in test_shapes:\n data = np.reshape(np.arange(np.prod(shape), dtype = dtype), shape)\n input_operand = C.input_variable(shape=shape)\n model0 = C.layers.LayerNormalization(initial_scale=1, initial_bias=2, epsilon=0.00001)(input_operand)\n verify_one_input(model0, data, tmpdir, 'LayerNorm_0' + str(shape).replace(',', '_'))\n\n # This test point tests especially with epsilon = 0, because that creates a graph with \n # different number of ops. However, we don't expect the numbers to match in round trip\n # because we only support default epislon (0.00001) when loading from ONNX. Therefore,\n # this is just a load/save test.\n model1 = C.layers.LayerNormalization(epsilon=0.0)(input_operand)\n filename = os.path.join(str(tmpdir), R'LayerNorm_1.onnx')\n model1.save(filename, format=C.ModelFormat.ONNX)\n loaded_model = C.Function.load(filename, format=C.ModelFormat.ONNX)\n model_shape = model1.shape\n if model1.output.dynamic_axes == (C.Axis('defaultBatchAxis'),):\n opname = model1.owner.op_name\n dim_denotation = CNTK_FREEDIM_AXIS_DENOTATION if opname in set_of_batch_ops else DIM_SIZE_FOR_NON_BATCH_OPS\n model_shape = (dim_denotation, ) + model_shape\n assert model_shape == loaded_model.shape\n\n#LeakyRelu\[email protected](\"dtype\", DType_Config)\ndef test_LeakyRelu(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.asarray([[-1, -0.5, 0, 1, 2]], dtype=dtype)\n model = C.leaky_relu(data)\n verify_no_input(model, tmpdir, 'LeakyRelu_0')\n\n#Less\[email protected](\"dtype\", DType_Config)\ndef test_Less(tmpdir, dtype):\n if (dtype == np.float16):\n pytest.skip(\"TO BE FIXED\")\n\n with C.default_options(dtype = dtype):\n data0 = np.asarray([41., 42., 43.], dtype=dtype)\n data1 = np.asarray([42., 42., 42.], dtype=dtype)\n\n model = C.less(data0, data1)\n verify_no_input(model, tmpdir, 'Less_0')\n\n#Log\[email protected](\"dtype\", DType_Config)\ndef test_Log(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.asarray([1., 2.], dtype=dtype)\n model = C.log(data)\n verify_no_input(model, tmpdir, 'Log_0')\n\n#LogSoftmax\[email protected](\"dtype\", DType_Config)\ndef test_LogSoftmax(tmpdir, dtype):\n data = np.array([[1, 1, 2, 3]], dtype)\n model = C.log_softmax(data)\n verify_no_input(model, tmpdir, 'LogSoftmax_0')\n\n x = C.input_variable(data.shape, dtype=dtype)\n model = C.log_softmax(x)\n verify_one_input(model, data, tmpdir, 'LogSoftmax_1')\n\n#LogAddExp\[email protected](\"dtype\", DType_Config)\ndef test_LogAddExp(tmpdir, dtype):\n shape = (2,3,4)\n\n data_x = np.random.rand(*shape).astype(np.float32)\n data_y = np.random.rand(*shape).astype(np.float32)\n\n x = C.input_variable(shape)\n y = C.input_variable(shape)\n\n model = C.log_add_exp(x, y)\n\n verify_two_input(model, data_x, data_y, tmpdir, 'LogAddExp_0')\n\[email protected](\"dtype\", DType_Config)\ndef test_LogAddExp_Broadcast(tmpdir, dtype):\n shape_x_arr = [(2,1,4), (2,1,4), (2,2,3,4)]\n shape_y_arr = [(1,3,1), (3,1), (1,1)]\n\n for i, (shape_x, shape_y) in enumerate(list(zip(shape_x_arr, shape_y_arr))):\n data_x = np.random.rand(*shape_x).astype(np.float32)\n data_y = np.random.rand(*shape_y).astype(np.float32)\n\n x = C.input_variable(shape_x)\n y = C.input_variable(shape_y)\n\n model = C.log_add_exp(x, y)\n\n verify_two_input(model, data_x, data_y, tmpdir, 'LogAddExp_Broadcast_' + str(i))\n\n#LRN\[email protected](\"dtype\", DType_Config)\ndef test_LRN(tmpdir, dtype, device_id):\n if device_id == -1 and dtype == np.float16:\n pytest.skip('Test is skipped on CPU with float16 data, because it uses convolution.')\n device = cntk_device(device_id)\n with C.default_options(dtype=dtype):\n img_shape = (64, 32, 32)\n img = np.asarray(np.random.uniform(-1, 1, img_shape), dtype=dtype)\n x_r = C.input_variable(shape=img_shape, dtype=dtype)\n model = C.local_response_normalization(x_r, 2, 1.0, 0.0001, 0.75)\n verify_one_input(model, img, tmpdir, 'LRN_1', device)\n # test with edge case kernel size > channel size\n # also test in lotus such that we are getting the value right.\n # in onnx spec and lotus implementation, alpha is divided by size. \n # so it seems even if size is > and rounded down to channel size,\n # its original value is still used in dividing alpha.\n img_shape = (5, 32, 32)\n img = np.asarray(np.random.uniform(-1, 1, img_shape), dtype=dtype)\n x_r = C.input_variable(shape=img_shape, dtype=dtype)\n model = C.local_response_normalization(x_r, 4, 1.0, 0.0001, 0.75)\n verify_one_input(model, img, tmpdir, 'LRN_2', device)\n\n#LSTM\[email protected](\"dtype\", DType_Config)\ndef test_LSTM(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n def CreateLSTMModel(activation, \n peepholes, \n self_stabilization, \n cell_dim, \n initial_state): \n return C.layers.Sequential([ \n C.layers.Recurrence(C.layers.LSTM(cell_dim, \n use_peepholes = peepholes, \n activation = activation, \n enable_self_stabilization = self_stabilization), \n initial_state = initial_state) \n ])\n\n\n def MakeLSTMNameFromConfig(use_peepholes, enable_self_stabilization, initial_state, activition):\n model_name = 'LSTM.' + activition.__name__\n if (use_peepholes): \n model_name += '.peephole'\n if(enable_self_stabilization): \n model_name += '.stabilize'\n if (initial_state != 0):\n model_name += '.initial'\n return model_name \n\n # lstm attributes\n use_peepholes_options = [False]\n enable_self_stabilization_options = [False]\n activation_options = [C.tanh]\n\n #Recurrence attributes\n initial_state_options = [0, 0.23]\n\n input_dim = 2\n cell_dim = 3\n batch_size = 1\n sequence_len = 5\n\n for config in list(product(use_peepholes_options, enable_self_stabilization_options, \n initial_state_options, activation_options)):\n model_filename = MakeLSTMNameFromConfig(*config)\n use_peepholes, enable_self_stabilization, initial_state, activation = config\n \n x = C.input_variable(input_dim, dynamic_axes=[C.Axis.default_batch_axis(), C.Axis('sequenceAxis')]) \n LSTMmodel = CreateLSTMModel(peepholes = use_peepholes, \n activation = activation,\n initial_state = initial_state,\n cell_dim = cell_dim,\n self_stabilization = enable_self_stabilization)(x)\n data = np.random.uniform(low=0.0, high=1.0, size=(batch_size, sequence_len, input_dim)).astype(dtype)\n verify_sequence_model(LSTMmodel, data, tmpdir, model_filename)\n\n#MatMul\[email protected](\"dtype\", DType_Config)\ndef test_MatMul(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data0 = np.asarray([[1,2],[3,4]], dtype=dtype)\n data1 = np.asarray([[5],[6]], dtype=dtype)\n model = C.times(data0, data1)\n verify_no_input(model, tmpdir, 'MatMul_0')\n\n#MatMul 2d\[email protected](\"dtype\", DType_Config)\ndef test_MatMul_2d(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data0 = np.asarray([[1,2],[3,4]], dtype=dtype)\n data1 = np.asarray([[5,7,9],[6,8,10]], dtype=dtype)\n model = C.times(data0, data1)\n verify_no_input(model, tmpdir, 'MatMul_1')\n\n#MatMul 2d with 2 inputs\[email protected](\"dtype\", DType_Config)\ndef test_MatMul_2d_2inputs(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data0 = np.asarray([[1,2],[3,4]], dtype=dtype)\n data1 = np.asarray([[5,7,9],[6,8,10]], dtype=dtype)\n\n x = C.input_variable(np.shape(data0))\n y = C.input_variable(np.shape(data1))\n model = C.times(x, y)\n verify_two_input(model, data0, data1, tmpdir, 'MatMul_1_1')\n\n#MatMul nd\[email protected](\"dtype\", DType_Config)\ndef test_MatMul_nd(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n np.random.seed(0)\n\n data0 = np.random.randn(3, 2, 3, 4).astype(np.float32)\n data1 = np.random.randn(2, 3, 4, 5).astype(np.float32)\n model = C.times(data0, data1)\n verify_no_input(model, tmpdir, 'MatMul_n_0')\n\n#MatMul nd\[email protected](\"dtype\", DType_Config)\ndef test_MatMul_nd_2(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n np.random.seed(0)\n\n data0 = np.random.randn(3, 3, 4).astype(np.float32)\n data1 = np.random.randn(3, 4, 5).astype(np.float32)\n model = C.times(data0, data1)\n verify_no_input(model, tmpdir, 'MatMul_n_1')\n\n#MatMul nd with 2 inputs\[email protected](\"dtype\", DType_Config)\ndef test_MatMul_nd_2inputs(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n np.random.seed(0)\n\n data0 = np.random.randn(3, 2, 3, 4).astype(np.float32)\n data1 = np.random.randn(2, 3, 4, 5).astype(np.float32)\n\n x = C.input_variable(np.shape(data0))\n y = C.input_variable(np.shape(data1))\n model = C.times(x, y)\n verify_two_input(model, data0, data1, tmpdir, 'MatMul_n_2')\n\n#MatMul nd with 2 inputs\[email protected](\"dtype\", DType_Config)\ndef test_MatMul_nd_2inputs_2(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n np.random.seed(0)\n\n data0 = np.random.randn(3, 3, 4).astype(np.float32)\n data1 = np.random.randn(3, 4, 5).astype(np.float32)\n\n x = C.input_variable(np.shape(data0))\n y = C.input_variable(np.shape(data1))\n model = C.times(x, y)\n verify_two_input(model, data0, data1, tmpdir, 'MatMul_n_3')\n\[email protected](\"dtype\", DType_Config)\ndef test_CNTK_Times_To_ONNX_MatMul(tmpdir, dtype):\n def generate_matmul_data(input_variable, batch_size, sequence_size):\n np.random.seed(0)\n data_shape = ()\n if input_variable.has_batch_axis():\n data_shape = data_shape + (batch_size,)\n if input_variable.has_sequence_axis():\n data_shape = data_shape + (sequence_size,)\n data_shape = data_shape + input_variable.shape\n data = np.random.standard_normal(data_shape).astype(np.float32)\n return data\n\n batch_size = 1\n sequence_length = 3\n input1_shape = (2, 3, 4)\n input2_shape = (3, 4, 5, 6)\n output_rank = 2\n\n ## data_x_data\n x = C.input_variable(input1_shape, dynamic_axes = [])\n y = C.input_variable(input2_shape, dynamic_axes = [])\n model = C.times(x, y, output_rank = output_rank)\n data0 = generate_matmul_data(x, batch_size, sequence_length)\n data1 = generate_matmul_data(y, batch_size, sequence_length)\n verify_two_input(model, data0, data1, tmpdir, 'times_data_x_data')\n\n ###batch_x_data\n x = C.input_variable(input1_shape, name = \"x\")\n y = C.input_variable(input2_shape, dynamic_axes = [], name = \"y\")\n model = C.times(x, y, output_rank = output_rank)\n data0 = generate_matmul_data(x, batch_size, sequence_length)\n data1 = generate_matmul_data(y, batch_size, sequence_length)\n verify_two_input(model, data0, data1, tmpdir, 'batch_x_data')\n\n ## data_x_batch\n x = C.input_variable(input1_shape, dynamic_axes = [])\n y = C.input_variable(input2_shape)\n model = C.times(x, y, output_rank = output_rank)\n data0 = generate_matmul_data(x, batch_size, sequence_length)\n data1 = generate_matmul_data(y, batch_size, sequence_length)\n verify_two_input(model, data0, data1, tmpdir, 'data_x_batch')\n\n ## batch_x_batch\n x = C.input_variable(input1_shape)\n y = C.input_variable(input2_shape)\n model = C.times(x, y, output_rank = output_rank)\n data0 = generate_matmul_data(x, batch_size, sequence_length)\n data1 = generate_matmul_data(y, batch_size, sequence_length)\n verify_two_input(model, data0, data1, tmpdir, 'batch_x_batch')\n\n ### sequence_x_data\n # TODO: ONNX importer cannot handle sequence and batch axes both being free diemention static axis\n #x = C.sequence.input_variable(input1_shape)\n #y = C.input_variable(input2_shape, dynamic_axes = [])\n #model = C.times(x, y, output_rank = output_rank)\n #data0 = generate_matmul_data(x, batch_size, sequence_length)\n #data1 = generate_matmul_data(y, batch_size, sequence_length)\n #verify_sequence_model(model, [data0, data1], tmpdir, 'sequence_x_data')\n\n ### data_x_sequence\n #TODO: ONNX importer cannot handle sequence and batch axes both being free diemention static axis\n #x = C.input_variable(input1_shape, dynamic_axes = [])\n #y = C.sequence.input_variable(input2_shape)\n #model = C.times(x, y, output_rank = output_rank)\n #data0 = generate_matmul_data(x, batch_size, sequence_length)\n #data1 = generate_matmul_data(y, batch_size, sequence_length)\n #verify_sequence_model(model, [data0, data1], tmpdir, 'data_x_sequence')\n\n ## sequence_x_sequence\n # TODO: ONNX importer cannot handle sequence and batch axes both being free diemention static axis\n #x = C.sequence.input_variable(input1_shape)\n #y = C.sequence.input_variable(input2_shape)\n #model = C.times(x, y, output_rank = output_rank)\n #data0 = generate_matmul_data(x, batch_size, sequence_length)\n #data1 = generate_matmul_data(y, batch_size, sequence_length)\n #verify_sequence_model(model, [data0, data1], tmpdir, 'sequence_x_sequence')\n\n ## sequence_x_batch\n # TODO: ONNX importer cannot handle sequence and batch axes both being free diemention static axis\n #x = C.sequence.input_variable(input1_shape)\n #y = C.input_variable(input2_shape)\n #model = C.times(x, y, output_rank = output_rank)\n #data0 = generate_matmul_data(x, batch_size, sequence_length)\n #data1 = generate_matmul_data(y, batch_size, sequence_length)\n #verify_sequence_model(model, [data0, data1], tmpdir, 'sequence_x_batch')\n\n ## batch_x_sequence\n # TODO: ONNX importer cannot handle sequence and batch axes both being free diemention static axis\n #x = C.input_variable(input1_shape)\n #y = C.sequence.input_variable(input2_shape)\n #model = C.times(x, y, output_rank = output_rank)\n #data0 = generate_matmul_data(x, batch_size, sequence_length)\n #data1 = generate_matmul_data(y, batch_size, sequence_length)\n #verify_sequence_model(model, [data0, data1], tmpdir, 'batch_x_sequence')\n\n#Max\[email protected](\"dtype\", DType_Config)\ndef test_Max(tmpdir, dtype):\n data0 = np.asarray([1., 1., 1., 1.], dtype=dtype)\n data1 = np.asarray([0.5, 0.25, 0.125, 0.], dtype=dtype)\n model = C.element_max(data0, data1)\n verify_no_input(model, tmpdir, 'Max_0')\n\n data2 = np.asarray([-0.5, 0.26, 0.124, -0.1], dtype=dtype)\n data3 = np.asarray([0.5, -0.26, -0.124, 0.1], dtype=dtype)\n model = C.element_max(data0, data1, data2, data3)\n verify_no_input(model, tmpdir, 'Max_0_4_inputs')\n\n#MaxPool\[email protected](\"dtype\", DType_Config)\ndef test_MaxPool(tmpdir, dtype, device_id): \n if device_id == -1 and dtype == np.float16:\n pytest.skip('Test is skipped on CPU with float16 data')\n device = cntk_device(device_id)\n with C.default_options(dtype=dtype):\n img = np.reshape(np.arange(16, dtype = dtype), [1, 4, 4])\n x = C.input_variable(img.shape)\n model = C.pooling(x, C.MAX_POOLING, (2,2), (3,3))\n verify_one_input(model, img, tmpdir, 'MaxPool_1', device)\n\n # test for case of not padding but with ceilOutDim=True\n img = np.reshape(np.arange(112*112, dtype=dtype), [1, 112, 112])\n x = C.input_variable(img.shape)\n model = C.pooling(x, C.MAX_POOLING, (3, 3), (2, 2), auto_padding=[False, False, False], ceil_out_dim=True)\n verify_one_input(model, img, tmpdir, 'MaxPool_2', device)\n\n#MaxRoiPool\[email protected](\"dtype\", DType_Config)\ndef test_MaxRoiPool(tmpdir, dtype):\n pytest.skip('MaxRoiPool is failing with ONNX shape inference (input rois). RuntimeError: [ShapeInferenceError] RoIs tensor must have 2 dimensions')\n with C.default_options(dtype = dtype):\n input_map = [[[1., 2., 3.], # (1, 3, 3) input operand (conv feature map)\n [4., 5., 6.],\n [7., 8., 9.]]]\n input_rois = [[1, 1, 2, 2]]\n\n conv_input = np.asarray(input_map, dtype=dtype)\n roi_input = np.asarray(input_rois, dtype=dtype)\n\n a = C.input_variable(shape=conv_input.shape,\n dtype=dtype,\n needs_gradient=True,\n name='a')\n\n b = C.input_variable(shape=roi_input.shape,\n dtype=dtype,\n needs_gradient=False,\n name='b')\n\n # adding batch and sequence axis\n conv_input.shape = (1,) + conv_input.shape\n roi_input.shape = (1,) + roi_input.shape\n\n model = C.roipooling(a, b, C.MAX_POOLING, (3,3), 1.)\n\n verify_two_input(model, conv_input, roi_input, tmpdir, 'MaxRoiPool_1')\n\n#Mean\[email protected](\"dtype\", DType_Config)\ndef test_Mean(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n in1 = C.input_variable((4,))\n in2 = C.input_variable((4,))\n model = C.mean([in1, in2])\n\n in1_data = np.asarray([[1., 2., 3., 4.]], dtype = dtype)\n in2_data = np.asarray([[0., 5., -3., 2.]], dtype = dtype)\n\n verify_two_input(model, in1_data, in2_data, tmpdir, 'Mean_2')\n \n#MeanVarianceNormalization\[email protected](\"dtype\", DType_Config)\ndef test_MeanVarianceNormalization(tmpdir, dtype):\n pytest.skip('test_MeanVarianceNormalization is skipped. Work is needed to make CNTK MVN compatible with ONNX Ver 9.')\n with C.default_options(dtype = dtype):\n shape = (3, 5, 7)\n data = np.reshape(np.arange(np.prod(shape), dtype = dtype), shape)\n\n input_operand = C.input_variable(shape=shape)\n\n model0 = C.mean_variance_normalization(input_operand, use_stats_across_channels=False, do_variance_scaling=True)\n verify_one_input(model0, data, tmpdir, 'MVN_0')\n\n model1 = C.mean_variance_normalization(input_operand, use_stats_across_channels=False, do_variance_scaling=False)\n verify_one_input(model1, data, tmpdir, 'MVN_1')\n\n model2 = C.mean_variance_normalization(input_operand, use_stats_across_channels=True, do_variance_scaling=True)\n verify_one_input(model2, data, tmpdir, 'MVN_2')\n\n # The test below tests the round trip with epsilon. We loose always the epsilon value when exporting to ONNX\n # (because ONNX MeanVarianceNormalization does not have an epsilon attribute). When loading back from ONNX, CNTK\n # always uses the default eposilon value (0.00001). That's why test below has the default epsilon value. It is \n # not expected to pass with any other epsilon value until something changes.\n model3 = C.mean_variance_normalization(input_operand, epsilon=0.00001, use_stats_across_channels=False, do_variance_scaling=True)\n verify_one_input(model3, data, tmpdir, 'MVN_3')\n\n#Min\[email protected](\"dtype\", DType_Config)\ndef test_Min(tmpdir, dtype):\n data0 = np.asarray([1., 1., 1., 1.], dtype=dtype)\n data1 = np.asarray([0.5, 0.25, 0.125, 0.], dtype=dtype)\n model = C.element_min(data0, data1)\n verify_no_input(model, tmpdir, 'Min_0')\n\n data2 = np.asarray([-0.5, 0.26, 0.124, -0.1], dtype=dtype)\n data3 = np.asarray([0.5, -0.26, -0.124, 0.1], dtype=dtype)\n model = C.element_min(data0, data1, data2, data3)\n verify_no_input(model, tmpdir, 'Min_0_4_inputs')\n\n#Mul\[email protected](\"dtype\", DType_Config)\ndef test_Mul(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data0 = np.asarray([1., 1., 1., 1.], dtype=dtype)\n data1 = np.asarray([0.5, 0.25, 0.125, 0.], dtype=dtype)\n model = C.element_times(data0, data1)\n verify_no_input(model, tmpdir, 'ElementTimes_0')\n\n#Neg\[email protected](\"dtype\", DType_Config)\ndef test_Neg(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data0 = np.asarray([1., -1., -2., 1.], dtype=dtype)\n model = C.negate(data0)\n verify_no_input(model, tmpdir, 'Neg_0')\n\n#OptimizedRNNStack\nOPTIM_RNN_STACK_CONFIGS = ((True, 1, 2, 3, 'lstm'), (False, 1, 4, 8, 'lstm'),\n (True, 2, 2, 3, 'lstm'), (True, 2, 4, 8, 'lstm'), (True, 2, 6, 8, 'lstm'), \n (True, 4, 2, 3, 'lstm'), (False, 2, 2, 3, 'lstm'), (False, 2, 6, 8, 'lstm'), (False, 4, 4, 8, 'lstm'),\n (True, 1, 2, 3, 'rnnReLU'), (True, 4, 4, 8, 'rnnReLU'), (False, 2, 6, 8, 'rnnReLU'), \n (True, 4, 2, 3, 'rnnTanh'), (False, 2, 2, 3, 'rnnTanh'), (True, 1, 2, 3, 'rnnTanh'))\[email protected](\"bidirectional, num_layers, input_size, hidden_size, recurrent_op\", OPTIM_RNN_STACK_CONFIGS)\ndef test_OptimizedRNNStack(bidirectional, num_layers, input_size, hidden_size, recurrent_op, tmpdir, device_id):\n if device_id == -1:\n pytest.skip('Test only runs on GPU')\n dev = cntk_device(device_id)\n from _cntk_py import constant_initializer\n model_filename = 'optimized_rnn_stack_' + ('bi' if bidirectional else 'uni') + '_layers' + str(num_layers) + '_inp' + str(input_size) + '_hid' + str(hidden_size)\n W = C.parameter((C.InferredDimension, input_size), constant_initializer(0.1), device=dev)\n x = C.sequence.input_variable(shape=(input_size,))\n s = np.asarray(np.random.uniform(-1, 1, (1, 5, input_size)), dtype=np.float32)\n f = C.optimized_rnnstack(x, W, hidden_size, num_layers, bidirectional=bidirectional, recurrent_op=recurrent_op, name='MyRnnStack')\n f.parameters[0].value = np.reshape(np.arange(np.prod(f.parameters[0].value.shape), dtype=np.float32), f.parameters[0].value.shape)\n verify_sequence_model(f, s, tmpdir, model_filename)\n\n#Pad\[email protected](\"dtype\", DType_Config)\ndef test_Pad(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n shape = (4, 5)\n data = np.random.rand(*shape).astype(dtype)\n\n model = C.pad(data, pattern=[(1,1),(2,2)], mode=C.ops.CONSTANT_PAD, constant_value=1)\n verify_no_input(model, tmpdir, 'Pad_0')\n\n x = C.input_variable(shape)\n model = C.pad(x, pattern=[(1,1),(2,2)], mode=C.ops.REFLECT_PAD)\n\n verify_one_input(model, data, tmpdir, 'Pad_1')\n\n#PRelu\[email protected](\"dtype\", DType_Config)\ndef test_PRelu(tmpdir, dtype):\n # no input\n x_data = np.asarray([[-1, -0.5, 0, 1, 2]], dtype=dtype)\n x = C.constant(value=x_data, dtype=dtype)\n alpha_data = np.asarray([[0.5, 0.5, 0.5, 0.5, 0.5]], dtype=dtype)\n alpha = C.constant(value=alpha_data, dtype=dtype)\n model = C.param_relu(alpha, x)\n verify_no_input(model, tmpdir, 'PRelu_0')\n\n # one input\n x = C.input_variable(x_data.shape, dtype=dtype)\n model = C.param_relu(alpha, x)\n verify_one_input(model, x_data, tmpdir, 'PRelu_1')\n\n # two input\n x = C.input_variable(x_data.shape, dtype=dtype)\n alpha = C.input_variable(alpha_data.shape, dtype=dtype)\n model = C.param_relu(alpha, x)\n verify_two_input(model, alpha_data, x_data, tmpdir, 'PRelu_2')\n\n#Pow\[email protected](\"dtype\", DType_Config)\ndef test_Pow(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n model = C.pow(np.array([1, 2, -2]).astype(dtype), np.array([3, -2, 3]).astype(dtype))\n verify_no_input(model, tmpdir, 'Pow_0')\n\n#Reciprocal\[email protected](\"dtype\", DType_Config)\ndef test_Reciprocal(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n model = C.reciprocal(np.array([-1/3, 1/5, -2, 3]).astype(dtype))\n verify_no_input(model, tmpdir, 'Reciprocal_0')\n\[email protected](\"dtype\", DType_Config)\ndef test_ReduceL1(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.array([[[1,2], [3,4]],[[5,6], [7,8]],[[9,10], [11,12]]], dtype=dtype)\n model = C.reduce_l1(data, 1)\n verify_no_input(model, tmpdir, 'ReduceL1_0')\n\n x = C.input_variable(np.shape(data))\n model = C.reduce_l1(x, 1)\n verify_one_input(model, data, tmpdir, 'ReduceL1_1')\n\n model = C.reduce_l1(data, C.Axis.all_static_axes())\n verify_no_input(model, tmpdir, 'ReduceL1_2')\n\n x = C.input_variable(data.shape)\n model = C.reduce_l1(x, C.Axis.default_batch_axis())\n verify_one_input(model, data, tmpdir, 'ReduceL1_3')\n\n model = C.reduce_l1(x, C.Axis.all_axes())\n verify_one_input(model, data, tmpdir, 'ReduceL1_4')\n\[email protected](\"dtype\", DType_Config)\ndef test_ReduceL2(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.array([[[1,2], [3,4]],[[5,6], [7,8]],[[9,10], [11,12]]], dtype=dtype)\n model = C.reduce_l2(data, 0)\n verify_no_input(model, tmpdir, 'ReduceL2_0')\n\n model = C.reduce_l2(data, C.Axis.all_static_axes())\n verify_no_input(model, tmpdir, 'ReduceL2_1')\n\n x = C.input_variable(data.shape)\n model = C.reduce_l2(x, C.Axis.default_batch_axis())\n verify_one_input(model, data, tmpdir, 'ReduceL2_2')\n\[email protected](\"dtype\", DType_Config)\ndef test_ReduceSumSquare(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.array([[[1,2], [3,4]],[[5,6], [7,8]],[[9,10], [11,12]]], dtype=dtype)\n model = C.reduce_sum_square(data, 0)\n verify_no_input(model, tmpdir, 'ReduceSumSquare_0')\n\n model = C.reduce_sum_square(data, C.Axis.all_static_axes())\n verify_no_input(model, tmpdir, 'ReduceSumSquare_1')\n\n x = C.input_variable(data.shape)\n model = C.reduce_sum_square(x, C.Axis.default_batch_axis())\n verify_one_input(model, data, tmpdir, 'ReduceSumSquare_2')\n\n model = C.reduce_sum_square(x, C.Axis.all_axes())\n verify_one_input(model, data, tmpdir, 'ReduceSumSquare_3')\n\n#ReduceLogSum\[email protected](\"dtype\", DType_Config)\ndef test_ReduceLogSum(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.array([[[5,1], [20,2]],[[30,1], [40,2]],[[55,1], [60,2]]], dtype=dtype)\n model = C.reduce_log_sum_exp(data, axis=0)\n\n verify_no_input(model, tmpdir, 'ReduceLogSum_0')\n\n model = C.reduce_log_sum_exp(data, C.Axis.all_static_axes())\n verify_no_input(model, tmpdir, 'ReduceLogSum_1')\n\n x = C.input_variable(data.shape)\n model = C.reduce_log_sum_exp(x, C.Axis.default_batch_axis())\n verify_one_input(model, data, tmpdir, 'ReduceLogSum_2')\n\n#ReduceMax\[email protected](\"dtype\", DType_Config)\ndef test_ReduceMax(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.array([[[5,1], [20,2]],[[30,1], [40,2]],[[55,1], [60,2]]], dtype=dtype)\n model = C.reduce_max(data, 0)\n verify_no_input(model, tmpdir, 'ReduceMax_0')\n\n model = C.reduce_max(data, C.Axis.all_static_axes())\n verify_no_input(model, tmpdir, 'ReduceMax_1')\n\n x = C.input_variable(data.shape)\n model = C.reduce_max(x, C.Axis.default_batch_axis())\n verify_one_input(model, data, tmpdir, 'ReduceMax_2')\n\n#ReduceMean\[email protected](\"dtype\", DType_Config)\ndef test_ReduceMean(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.array([[[5,1], [20,2]],[[30,1], [40,2]],[[55,1], [60,2]]], dtype=dtype)\n model = C.reduce_mean(data, 0)\n verify_no_input(model, tmpdir, 'ReduceMean_0')\n\n model = C.reduce_mean(data, C.Axis.all_static_axes())\n verify_no_input(model, tmpdir, 'ReduceMean_1')\n\n x = C.input_variable(data.shape)\n model = C.reduce_mean(x, C.Axis.default_batch_axis())\n verify_one_input(model, data, tmpdir, 'ReduceMean_2')\n\n#ReduceMin\[email protected](\"dtype\", DType_Config)\ndef test_ReduceMin(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.array([[[5,1], [20,2]],[[30,1], [40,2]],[[55,1], [60,2]]], dtype=dtype)\n model = C.reduce_min(data, 0)\n verify_no_input(model, tmpdir, 'ReduceMin_0')\n\n model = C.reduce_min(data, C.Axis.all_static_axes())\n verify_no_input(model, tmpdir, 'ReduceMin_1')\n\n x = C.input_variable(data.shape)\n model = C.reduce_min(x, C.Axis.default_batch_axis())\n verify_one_input(model, data, tmpdir, 'ReduceMin_2')\n\n#ReduceProd\[email protected](\"dtype\", DType_Config)\ndef test_ReduceProd(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.array([[[5,1], [20,2]],[[30,1], [40,2]],[[55,1], [60,2]]], dtype=dtype)\n model = C.reduce_prod(data, 0)\n verify_no_input(model, tmpdir, 'ReduceProd_0')\n\n model = C.reduce_prod(data, C.Axis.all_static_axes())\n verify_no_input(model, tmpdir, 'ReduceProd_1')\n\n x = C.input_variable(data.shape)\n model = C.reduce_prod(x, C.Axis.default_batch_axis())\n verify_one_input(model, data, tmpdir, 'ReduceProd_2')\n\n#ReduceSum\[email protected](\"dtype\", DType_Config)\ndef test_ReduceSum(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.array([[[5,1], [20,2]],[[30,1], [40,2]],[[55,1], [60,2]]], dtype=dtype)\n model = C.reduce_sum(data, 0)\n verify_no_input(model, tmpdir, 'ReduceSum_0')\n\n model = C.reduce_sum(data, [0, 1, 2])\n verify_no_input(model, tmpdir, 'ReduceSum_1')\n\n model = C.reduce_sum(data, [0, 2])\n verify_no_input(model, tmpdir, 'ReduceSum_2')\n\n model = C.reduce_sum(data, [0, 2], keepdims=False)\n verify_no_input(model, tmpdir, 'ReduceSum_3')\n\n model = C.reduce_sum(data, C.Axis.all_static_axes())\n verify_no_input(model, tmpdir, 'ReduceSum_4')\n\n x = C.input_variable(data.shape)\n model = C.reduce_sum(x, C.Axis.default_batch_axis())\n verify_one_input(model, data, tmpdir, 'ReduceSum_5')\n\n model = C.reduce_sum(x, C.Axis.all_axes())\n verify_one_input(model, data, tmpdir, 'ReduceSum_6')\n\n#Relu\[email protected](\"dtype\", DType_Config)\ndef test_Relu(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.array([[-1, -0.5, 0, 1, 2]], dtype = dtype)\n model = C.relu(data)\n verify_no_input(model, tmpdir, 'Relu_0')\n\n#Reshape\[email protected](\"dtype\", DType_Config)\ndef test_Reshape(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.asarray([[[0., 1.],[2., 3.],[4., 5.]]], dtype)\n i1 = C.input_variable(shape=(3,2))\n model = C.reshape(i1, (2,3))\n verify_one_input(model, data, tmpdir, 'Reshape_1')\n\n#RNN\[email protected](\"dtype\", DType_Config)\ndef test_RNN(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n def CreatRNN(cell_dim, \n activation, \n initial_state,\n direction, \n num_layers, \n init=C.default_override_or(C.glorot_uniform()), \n init_bias=C.default_override_or(0)):\n if direction == 'bidirectional': \n return C.layers.Sequential([ \n C.layers.For(range(num_layers), lambda i: [ \n (C.layers.Recurrence(C.layers.RNNStep(cell_dim, \n activation = activation, \n init = init, \n init_bias = init_bias), \n initial_state = initial_state, \n return_full_state = False, go_backwards=False), \n C.layers.Recurrence(C.layers.RNNStep(cell_dim, activation = activation, \n init = init, \n init_bias = init_bias), \n initial_state = initial_state, \n return_full_state = False, go_backwards=True)), \n C.splice])])\n else:\n go_backward = False if direction == 'forward' else True\n return C.layers.Sequential([ \n C.layers.For(range(num_layers), lambda i: [ \n C.layers.Recurrence(C.layers.RNNStep(cell_dim, \n activation = activation, \n init = init, \n init_bias = init_bias), \n initial_state = initial_state, \n return_full_state = False, go_backwards=go_backward)])])\n\n def MakeRNNNameFromConfig(direction, num_layers, initial_state, activition):\n model_name = 'RNN.' + direction + '.'\n\n if num_layers == 1:\n model_name += 'one_layer.'\n else:\n assert (num_layers == 2), \"needs 1 or 2 layers!\"\n model_name += 'two_layer.'\n\n if (initial_state != 0):\n model_name += 'initial.'\n \n model_name += activition.__name__\n return model_name \n\n direction_options = ['forward', 'reverse', 'bidirectional']\n num_layers_options = [1, 2]\n initial_state_options = [0]\n activation_options = [C.tanh, C.relu, C.sigmoid]\n\n input_dim = 2\n hidden_dim = 3\n batch_size = 1\n sequence_len = 5\n\n for config in list(product(direction_options, num_layers_options, initial_state_options, activation_options)):\n model_filename = MakeRNNNameFromConfig(*config)\n direction, num_layers, initial_state, activation = config\n \n x = C.input_variable(input_dim, dynamic_axes=[C.Axis.default_batch_axis(), C.Axis('sequenceAxis')]) \n RNNModel = CreatRNN(\n hidden_dim, \n activation, \n initial_state, \n direction, \n num_layers)(x)\n data = np.random.uniform(low=0.0, high=1.0, size=(batch_size, sequence_len, input_dim)).astype(dtype)\n verify_sequence_model(RNNModel, data, tmpdir, model_filename)\n\n#Selu\[email protected](\"dtype\", DType_Config)\ndef test_Selu(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n model = C.selu(np.array([[-1, -0.5, 0, 1, 2]]).astype(dtype))\n verify_no_input(model, tmpdir, 'Selu_0')\n\n#Sigmoid\[email protected](\"dtype\", DType_Config)\ndef test_Sigmoid(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n model = C.sigmoid(np.array([-2, -1., 0., 1., 2.]).astype(dtype))\n verify_no_input(model, tmpdir, 'Sigmoid_0')\n\n#Slice\[email protected](\"dtype\", DType_Config)\ndef test_Slice(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.asarray([[1,2,-3], [4, 5, 6]],dtype=dtype)\n x1 = C.input_variable((2,3))\n\n model = C.slice(data, 0, 1, 2)\n verify_no_input(model, tmpdir, 'Slice_0')\n\n model = C.slice(x1, 0, 1, 2)\n verify_one_input(model, data, tmpdir, 'Slice_1')\n\n model = C.slice(x1, [0,1], [1,0], [2,1]);\n verify_one_input(model, data, tmpdir, 'Slice2_1')\n\n#Sequence.Slice \[email protected](\"beginIndex, endIndex\", ( \n (-2, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-4, 2), (0, 1), (1, 2)))\[email protected](\"dtype\", DType_Config)\ndef test_SequenceSlice(tmpdir, dtype, beginIndex, endIndex):\n batch_size = 1\n sequence_length = 5\n input_size = 3\n feature_shape = (input_size,)\n shape = (batch_size, sequence_length, input_size)\n data = np.reshape(range(0, np.prod(shape)), shape).astype(dtype)\n testName = \"test_sequence_slice_{0}.{1}\".format(beginIndex, endIndex)\n model = C.sequence.slice(C.sequence.input_variable((feature_shape)), beginIndex, endIndex)\n verify_sequence_model(model, data, tmpdir, testName)\n\[email protected](\"dtype\", DType_Config)\ndef test_SequenceFirst(tmpdir, dtype):\n x = C.sequence.input_variable(shape=(3,2))\n y = C.sequence.first(x)\n # create one sequence of 4 tensors each with shape (3,2)\n x0 = np.reshape(np.arange(24.0,dtype=np.float32),(1,4,3,2))\n verify_sequence_model(y, x0, tmpdir, \"SequenceFirst\")\n\[email protected](\"dtype\", DType_Config)\ndef test_SequenceLast(tmpdir, dtype):\n x = C.sequence.input_variable(shape=(3,2))\n y = C.sequence.last(x)\n # create one sequence of 4 tensors each with shape (3,2)\n x0 = np.reshape(np.arange(24.0,dtype=np.float32),(1,4,3,2))\n verify_sequence_model(y, x0, tmpdir, \"SequenceLast\")\n\[email protected](\"dtype\", DType_Config)\ndef test_SequenceReduceSum(tmpdir, dtype):\n x = C.sequence.input_variable(shape=(3,2))\n # create one sequence of 4 tensors each with shape (3,2)\n x0 = np.reshape(np.arange(24.0,dtype=np.float32),(1,4,3,2))\n y = C.sequence.reduce_sum(x)\n #y.eval({x:x0})\n verify_sequence_model(y, x0, tmpdir, \"SequenceReduceSum\")\n\[email protected](\"dtype\", DType_Config)\ndef test_SequenceReduceMax(tmpdir, dtype):\n x = C.sequence.input_variable(shape=(3,2))\n # create one sequence of 4 tensors each with shape (3,2)\n x0 = np.reshape(np.arange(24.0,dtype=np.float32),(1,4,3,2))\n y = C.sequence.reduce_max(x)\n #y.eval({x:x0})\n verify_sequence_model(y, x0, tmpdir, \"SequenceReduceMax\")\n\[email protected](\"dtype\", DType_Config)\ndef test_SequenceSoftmax(tmpdir, dtype):\n if dtype==np.float16:\n pytest.skip('Test is skipped with float16 data. Implementation of sequence.softmax is not numerically stable.')\n batch_size, sequence_length, input_size = 1, 2, 1\n a = np.array([[[1],[0]]], dtype)\n src = C.sequence.input_variable(shape=(input_size), sequence_axis=C.Axis(\"Seq\"), dtype=dtype)\n out = C.sequence.softmax(src)\n verify_sequence_model(out, a, tmpdir, \"SequenceSoftmax\")\n\n#Softmax\[email protected](\"dtype\", DType_Config)\ndef test_Softmax(tmpdir, dtype):\n data = np.array([[1, 1, 2, 3]], dtype)\n model = C.softmax(data)\n verify_no_input(model, tmpdir, 'Softmax_0')\n\n x = C.input_variable(data.shape, dtype=dtype)\n model = C.softmax(x)\n verify_one_input(model, data, tmpdir, 'Softmax_1')\n\n#Softplus\[email protected](\"dtype\", DType_Config)\ndef test_Softplus(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n model = C.softplus([[-1, -0.5, 0, 1, 2]])\n verify_no_input(model, tmpdir, 'Softplus_0')\n\n#Softsign\[email protected](\"dtype\", DType_Config)\ndef test_Softsign(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n model = C.softsign(np.array([[-1, -0.5, 0, 1, 2]]).astype(dtype))\n verify_no_input(model, tmpdir, 'Softsign_0')\n\n#Squeeze\n#def test_Squeeze(tmpdir):\n# x0 = np.arange(12).reshape((2, 2, 1, 3)).astype('f')\n# x = C.input_variable((2, 1, 3))\n# model = C.squeeze(x)\n# verify_one_input(model, x0, tmpdir, 'Squeeze_0')\n\n#Sum\[email protected](\"dtype\", DType_Config)\ndef test_Sum(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n in1_data = np.asarray([[1., 2., 3., 4.]], dtype = dtype)\n in2_data = np.asarray([[0., 5., -3., 2.]], dtype = dtype)\n\n in1 = C.input_variable(np.shape(in1_data))\n in2 = C.input_variable(np.shape(in2_data))\n model = C.sum([in1, in2])\n\n verify_two_input(model, in1_data, in2_data, tmpdir, 'Sum_2')\n\n model = C.sum([in1])\n verify_one_input(model, in1_data, tmpdir, 'Sum_1')\n\n model = C.sum([in1, in2, in1])\n verify_two_input(model, in1_data, in2_data, tmpdir, 'Sum_3')\n\n# SpaceToDepth\[email protected](\"dtype\", DType_Config)\ndef test_SpaceToDepth(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n num_channels = 3\n block_size = 3\n image_shape = (12, 15)\n input_val = np.array(np.reshape(range(num_channels), (num_channels, 1, 1)), dtype=dtype)\n input_val = np.tile(input_val, (1,) + image_shape)\n img = C.input_variable((num_channels,) + image_shape, dtype=dtype)\n model = C.space_to_depth(img, block_size)\n\n verify_one_input(model, input_val, tmpdir, 'SpaceToDepth')\n\n#Sqrt\[email protected](\"dtype\", DType_Config)\ndef test_Sqrt(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n model = C.sqrt(np.array([0., 4.]).astype(dtype))\n verify_no_input(model, tmpdir, 'Sqrt_0')\n\n#Sub\[email protected](\"dtype\", DType_Config)\ndef test_Sub(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n model = C.minus(np.array([1, 2, 3]).astype(dtype), np.array([4, 5, 6]).astype(dtype))\n verify_no_input(model, tmpdir, 'Sub_0')\n\n#Tanh\[email protected](\"dtype\", DType_Config)\ndef test_Tanh(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n model = C.tanh(np.array([[1,2],[3,4]]).astype(dtype))\n verify_no_input(model, tmpdir, 'Tanh_0')\n\n#TopK\[email protected](\"dtype\", DType_Config)\ndef test_TopK(tmpdir, dtype):\n input_size = 10\n data = (np.arange(input_size,dtype=dtype)*0.1).reshape(1, input_size)\n x = C.input_variable(input_size)\n model = C.top_k(-x * C.log(x), 3)\n verify_one_input(model, data, tmpdir, \"top_k\")\n\n#TimesTranspose\[email protected](\"dtype\", DType_Config)\ndef test_TimesTranspose(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n np.random.seed(1)\n data0 = np.random.rand(3, 4).astype(dtype)\n input0 = C.input_variable(data0.shape, dtype = data0.dtype)\n\n data1 = np.random.rand(4).astype(dtype)\n input1 = C.input_variable(data1.shape, dtype = data1.dtype)\n model = C.times_transpose(input0, input1)\n verify_two_input(model, data0, data1, tmpdir, 'TimesTranspose_0')\n\n data1 = np.random.rand(5, 4).astype(dtype)\n input1 = C.input_variable(data1.shape, dtype = data1.dtype)\n model = C.times_transpose(input0, input1)\n verify_two_input(model, data0, data1, tmpdir, 'TimesTranspose_1')\n\n#Transpose\[email protected](\"dtype\", DType_Config)\ndef test_Transpose(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.arange(24).reshape(2,3,4).astype(dtype)\n x = C.input_variable(np.shape(data))\n\n model = C.transpose(data, perm=(2, 0, 1))\n verify_no_input(model, tmpdir, 'Transpose_0')\n\n model = C.transpose(x, perm=(2, 0, 1))\n verify_one_input(model, data, tmpdir, 'Transpose_1')\n\n model = C.transpose(x, perm=(0, 2, 1))\n verify_one_input(model, data, tmpdir, 'Transpose_1_2')\n\n#Transpose\[email protected](\"dtype\", DType_Config)\ndef test_TransposeAxes(tmpdir, dtype):\n with C.default_options(dtype = dtype):\n data = np.array([[[0,1],[2,3],[4,5]]]).astype(dtype)\n model = C.swapaxes(data, 1, 2)\n verify_no_input(model, tmpdir, 'TransposeAxes_0')\n\n # TODO: there is probably a bug in C.swapaxes which does not allow \n # evaluation of model with data\n #x = C.input_variable(np.shape(data))\n #model = C.swapaxes(x, 1, 2)\n #verify_one_input(model, data, tmpdir, 'TransposeAxes_1')\n\n\n# Select\[email protected](\"flag, if_true, if_false\", (\n ((-100., -1.2, -1.0, -0.5, 0.0, 0.1, 1.0, 100.),\n (1., 2., 3., 4., 5., 6., 7., 8.),\n (11., 12., 13., 14., 15., 16., 17., 18.)),\n (((1, 0, 3), (4, 5, 0)),\n ((1, 2, 3), (4, 5, 6)),\n ((-1, -2, -3), (-4, -5, -6))),\n ((((0, 1), (0, 1)), ((0, 1), (0, 1))),\n (((1, 2), (3, 4)), ((5, 6), (7, 8))),\n (((9, 10), (11, 12)), ((13, 14), (15, 16)))),\n))\ndef test_Select(flag, if_true, if_false, tmpdir):\n flag = np.asarray(flag, dtype=np.float32)\n if_true = np.asarray(if_true, dtype=np.float32)\n if_false = np.asarray(if_false, dtype=np.float32)\n\n model = C.element_select(flag, if_true, if_false)\n verify_no_input(model, tmpdir, 'Select_0')\n\n flag_var = C.input_variable(np.shape(flag))\n if_true_var = C.input_variable(np.shape(if_true))\n if_false_var = C.input_variable(np.shape(if_false))\n\n model = C.element_select(flag_var, if_true, if_false)\n verify_one_input(model, flag, tmpdir, 'Select_1_flag')\n\n model = C.element_select(flag, if_true_var, if_false)\n verify_one_input(model, if_true, tmpdir, 'Select_1_if_true')\n\n model = C.element_select(flag, if_true, if_false_var)\n verify_one_input(model, if_false, tmpdir, 'Select_1_if_false')\n\n# Cos\[email protected](\"dtype\", DType_Config)\ndef test_Cos(tmpdir, dtype):\n data = np.asarray([0.0, -0.5, 0.5, 10, 20], dtype)\n model = C.cos(data)\n verify_no_input(model, tmpdir, 'Cos_0')\n\n# Sin\[email protected](\"dtype\", DType_Config)\ndef test_Sin(tmpdir, dtype):\n data = np.asarray([0.0, -0.5, 0.5, 10, 20], dtype)\n model = C.sin(data)\n verify_no_input(model, tmpdir, 'Sin_0')\n\n# Tan\[email protected](\"dtype\", DType_Config)\ndef test_Tan(tmpdir, dtype):\n data = np.asarray([0.0, -0.5, 0.5, 10, 20], dtype)\n model = C.tan(data)\n verify_no_input(model, tmpdir, 'Tan_0')\n\n# Acos\[email protected](\"dtype\", DType_Config)\ndef test_Acos(tmpdir, dtype):\n data = np.asarray([0.0, -0.5, 0.5, 1, -1], dtype)\n model = C.acos(data)\n verify_no_input(model, tmpdir, 'Acos_0')\n\n# Asin\[email protected](\"dtype\", DType_Config)\ndef test_Asin(tmpdir, dtype):\n data = np.asarray([0.0, -0.5, 0.5, 1, -1], dtype)\n model = C.asin(data)\n verify_no_input(model, tmpdir, 'Asin_0')\n\n# Atan\[email protected](\"dtype\", DType_Config)\ndef test_Atan(tmpdir, dtype):\n data = np.asarray([0.0, -0.5, 0.5, 1, -1], dtype)\n model = C.atan(data)\n verify_no_input(model, tmpdir, 'Atan_0')\n\n# Crop\[email protected](\"dtype\", DType_Config)\ndef test_Crop_Manual(tmpdir, dtype):\n x = C.input_variable((1,4,4), dtype=np.float32, name='feature')\n y = C.constant(np.ones((1,2,1), dtype=np.float32))\n model = C.crop_manual(x, y, 1, 2, name='crop_manual')\n data = np.asarray(range(4*4), dtype=np.float32).reshape((1,4,4))\n verify_one_input(model, data, tmpdir, \"Crop_Manual_0\")"
] |
[
[
"numpy.allclose",
"numpy.random.seed",
"numpy.asarray",
"numpy.arange",
"numpy.random.standard_normal",
"numpy.tile",
"numpy.ones",
"numpy.shape",
"numpy.random.randn",
"numpy.random.rand",
"numpy.prod",
"numpy.random.uniform",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
RaphaelaHeil/strikethrough-removal-cyclegans
|
[
"91555b22cac6b6a379597aa94c23bdf02c9970a7"
] |
[
"strikethrough_identification/src/utils.py"
] |
[
"\"\"\"\nUtility module.\n\"\"\"\nfrom math import ceil\n\nimport torch\nfrom PIL import Image, ImageOps\nfrom torchvision import models\nfrom torchvision.transforms import Resize, Grayscale, ToTensor, Compose\n\nfrom .configuration import Configuration, ModelName\n\n\nclass PadToSize:\n \"\"\"\n Custom transformation that maintains the words original aspect ratio by scaling it to the given height and padding\n it to achieve the desired width.\n \"\"\"\n\n def __init__(self, height: int, width: int, padWith: int = 1):\n self.width = width\n self.height = height\n self.padWith = padWith\n\n def __call__(self, image: Image) -> Image:\n oldWidth, oldHeight = image.size\n if oldWidth != self.width or oldHeight != self.height:\n scaleFactor = self.height / oldHeight\n intermediateWidth = ceil(oldWidth * scaleFactor)\n if intermediateWidth > self.width:\n intermediateWidth = self.width\n resized = image.resize((intermediateWidth, self.height), resample=Image.BICUBIC)\n preprocessed = Image.new('L', (self.width, self.height), self.padWith)\n preprocessed.paste(resized)\n return preprocessed\n else:\n return image\n\n def __repr__(self) -> str:\n return self.__class__.__name__ + '()'\n\n\ndef composeTransformations(config: Configuration) -> Compose:\n \"\"\"\n Composes various transformations based on the given experiment configuration. :class:`ToTensor` is always the final\n transformation.\n\n Parameters\n ----------\n config : Configuration\n experiment configuration\n\n Returns\n -------\n Compose\n the composed transformations\n \"\"\"\n transforms = []\n if config.padScale:\n transforms.append(PadToSize(config.padHeight, config.padWidth, 255))\n transforms.extend([Resize((config.imageHeight, config.imageWidth)), Grayscale(num_output_channels=1)])\n if config.invertImages:\n transforms.append(ImageOps.invert)\n transforms.append(ToTensor())\n return Compose(transforms)\n\n\ndef getModelByName(modelName: ModelName) -> torch.nn.Module:\n \"\"\"\n Returns the model defined by modelName, adapted to single-channel inputs.\n\n Parameters\n ----------\n modelName : ModelName\n name of the model that shall be returned\n\n Returns\n -------\n torch.nn.Module\n Model definition. Default: ResNet18\n \"\"\"\n if modelName == ModelName.DENSE:\n model = models.densenet121(progress=False, num_classes=2)\n # change densenet to single channel input:\n originalLayer = model.features.conv0\n model.features.conv0 = torch.nn.Conv2d(in_channels=1, out_channels=originalLayer.out_channels,\n kernel_size=originalLayer.kernel_size,\n stride=originalLayer.stride, padding=originalLayer.padding,\n dilation=originalLayer.dilation, groups=originalLayer.groups,\n bias=originalLayer.bias, padding_mode=originalLayer.padding_mode)\n else:\n model = models.resnet18(progress=False, num_classes=2)\n originalLayer = model.conv1\n # change resnet to single channel input:\n model.conv1 = torch.nn.Conv2d(in_channels=1, out_channels=originalLayer.out_channels,\n kernel_size=originalLayer.kernel_size,\n stride=originalLayer.stride, padding=originalLayer.padding,\n dilation=originalLayer.dilation, groups=originalLayer.groups,\n bias=originalLayer.bias, padding_mode=originalLayer.padding_mode)\n return model\n"
] |
[
[
"torch.nn.Conv2d"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dgrechka/bengaliai-cv19
|
[
"9ef15c5b140628337ae6efe0d76e7ec5d291dc17"
] |
[
"code/dgrechka/train_mobileNetV2_bottleneck.py"
] |
[
"import tensorflow as tf\n\nimport sys\nimport os\nsys.path.append(os.path.join(__file__,'..','..'))\n\nfrom tfDataIngest import tfDataSetParquet as tfDsParquet\nfrom tfDataIngest import tfDataSetParquetAnnotateTrain as tfDsParquetAnnotation\nimport os\nimport pandas as pd\nfrom tqdm import tqdm\nfrom glob import glob\nfrom models.MobileNetV2 import GetModel\n\ninputDataDir = sys.argv[1]\nvalidationFile = sys.argv[2]\nexperiment_output_dir = sys.argv[3]\ndropoutRate = 0.2\nbatchSize = 8\nseed = 313143\n\nprint(\"validation set samples listing: {0}\".format(validationFile))\n\nvalDf = pd.read_csv(validationFile)\nvalIds = set(valDf.image_id)\nprint(\"{0} samples will be used for validation\".format(len(valIds)))\n\nif __name__ == \"__main__\": \n tf.random.set_seed(seed+563)\n\n print(\"Data dir is {0}\".format(inputDataDir))\n dataFileNames = glob(\"{0}/train*.parquet\".format(inputDataDir))\n trainLabelsFileName = \"{0}/train.csv\".format(inputDataDir)\n\n N = len(pd.read_csv(trainLabelsFileName))\n #N = 5000\n print(\"There are {0} training samples in total\".format(N))\n\n print(\"Parquet files count is {0}\".format(len(dataFileNames)))\n print(\"First is {0}\".format(dataFileNames[0]))\n\n def constructAllSamplesDs():\n ds = tfDsParquet.create_parquet_dataset(dataFileNames)\n ds = tfDsParquetAnnotation.annotate(ds,trainLabelsFileName) \n return ds \n\n\n # reshaping to match the input shape\n def prepareInput(_,labels,pixels):\n #pixels = tf.cast(pixels, tf.float32)\n root,vowel,consonant = tf.unstack(labels,3)\n root = tf.one_hot(root, 168, dtype=tf.uint8)\n vowel = tf.one_hot(vowel, 11, dtype=tf.uint8)\n consonant = tf.one_hot(consonant, 7, dtype=tf.uint8)\n\n colored = tf.tile(tf.expand_dims(pixels,-1),[1,1,3])\n\n pixels = tf.image.resize(colored, [224,224], method='gaussian')\n #HEIGHT = 137\n #WIDTH = 236\n\n #pixels = tf.pad(colored,[[43,44],[0,0],[0,0]])[:,6:230,:]\n labelsDict = {\n \"root\": tf.reshape(root,(168,)),\n \"vowel\": tf.reshape(vowel,(11,)),\n \"consonant\": tf.reshape(consonant,(7,))\n }\n return pixels, labelsDict \n\n def inValidationFilter(ident): \n identBytes = ident.numpy()\n identStr = identBytes.decode('utf-8')\n return identStr in valIds\n def inValFilter(ident,_dummy_1,_dummy_2):\n return tf.py_function(inValidationFilter, [ident], (tf.bool))\n def inTrainFilter(ident,_dummy_1,_dummy_2):\n return not(tf.py_function(inValidationFilter, [ident], (tf.bool)))\n \n allDs = constructAllSamplesDs()\n allDs = allDs.take(N)\n allDs = allDs.cache()\n\n trDs = allDs.filter(inTrainFilter) \n trDs = trDs.map(prepareInput) #tf.data.experimental.AUTOTUNE\n #trDs = trDs.take(1000)\n #trDs = trDs.cache(os.path.join(cacheLocation,'trCache'))\n \n\n print(\"Caching all DS\")\n #for element in tqdm(allDs.as_numpy_iterator(),ascii=True,total=N):\n for element in allDs.as_numpy_iterator():\n ()\n\n trDs = trDs.repeat()\n #trDs = trDs.prefetch(128)\n trDs = trDs.shuffle(512,seed=seed+123678, reshuffle_each_iteration=True) \n trDs = trDs.batch(batchSize)\n #trDs = trDs.prefetch(128)\n\n #valDs = constructAllSamplesDs()\n valDs = allDs.filter(inValFilter)\n valDs = valDs.map(prepareInput) \n valDs = valDs.batch(batchSize)\n #valDs = valDs.cache(os.path.join(cacheLocation,'vaCache'))\n #valDs = valDs.cache()\n\n print(\"Training dataSet is {0}\".format(trDs))\n print(\"Validation dataSet is {0}\".format(valDs))\n\n model,cnn = GetModel(dropoutRate, seed+44)\n\n print(\"Model constructed\")\n print(model.summary())\n \n def catCeFromLogitsDoubled(y_true, y_pred): \n return tf.keras.losses.categorical_crossentropy(y_true, y_pred, from_logits=True)*2.0\n def catCeFromLogits(y_true, y_pred): \n return tf.keras.losses.categorical_crossentropy(y_true, y_pred, from_logits=True) \n\n class RecallForLogits2(tf.keras.metrics.Metric):\n def __init__(self, name='recall', **kwargs):\n self.M = 200\n super(RecallForLogits, self).__init__(name=name, **kwargs) \n self.true_positives = self.add_weight(name='tp', initializer='zeros',shape=(self.M,))\n self.false_negatives = self.add_weight(name='fn', initializer='zeros',shape=(self.M,))\n\n def update_state(self, y_true, y_pred_logit, sample_weight=None):\n # shape is: B x M(ClassesCount)\n #y_pred_shape = tf.shape(y_pred_logit)\n #B = y_pred_shape[0]\n idx_max = tf.math.argmax(y_pred_logit,1) # (B,)\n \n y_pred_bool = tf.one_hot(idx_max,self.M,on_value=True, off_value=False) # BxM\n\n #print(\"y_pred_bool shape: {0}\".format(y_pred_bool.shape))\n #y_pred_bool = tf.expand_dims(y_pred_bool,0)\n #y_pred_bool = tf.tile(y_pred_bool,[B,1])\n\n y_true_bool = tf.cast(y_true,dtype=tf.bool)\n \n not_pred_bool = tf.math.logical_not(y_pred_bool)\n\n\n localTP = tf.math.reduce_sum(tf.cast(tf.math.logical_and(y_pred_bool,y_true_bool),dtype=tf.float32),0) # along Batch\n localFN = tf.math.reduce_sum(tf.cast(tf.math.logical_and(not_pred_bool,y_true_bool),dtype=tf.float32),0) # along Batch\n\n # print(\"true_positives shape: {0}\".format(self.true_positives.shape))\n # print(\"false_negatives shape: {0}\".format(self.false_negatives.shape))\n # print(\"localTP shape: {0}\".format(localTP.shape))\n # print(\"localFN shape: {0}\".format(localFN.shape))\n\n self.true_positives.assign_add(localTP)\n self.false_negatives.assign_add(localFN) \n\n def result(self):\n print(\"result self.true_positives shape: {0}\".format(self.true_positives.shape))\n nom = tf.cast(self.true_positives,dtype=tf.float32) # shape (M,)\n denom = tf.cast(self.true_positives + self.false_negatives,dtype=tf.float32) # shape (M,) \n print(\"denom shape: {0}\".format(denom.shape))\n perClassRecall = tf.cond(denom < 0.5, lambda: tf.zeros([self.M],dtype=tf.float32), lambda: nom/denom)\n print(\"perClassRecall shape: {0}\".format(perClassRecall.shape))\n macroRecallNom = tf.math.reduce_sum(perClassRecall)\n print(\"macroRecallNom shape: {0}\".format(macroRecallNom.shape))\n macroRecallDenom = tf.reduce_sum(tf.cast(denom > 0.0,dtype=tf.float32))\n print(\"macroRecallDenom shape: {0}\".format(macroRecallDenom.shape))\n macroRecall = macroRecallNom/macroRecallDenom\n print(\"macroRecall shape: {0}\".format(macroRecall.shape))\n return macroRecall\n \n class RecallForLogits(tf.keras.metrics.Recall):\n def __init__(self, name='recall', **kwargs):\n super(RecallForLogits, self).__init__(name=name, **kwargs) \n\n def update_state(self, y_true, y_pred, sample_weight=None):\n probs = tf.nn.softmax(y_pred)\n super().update_state(y_true, probs, sample_weight) \n\n def result(self):\n return super().result()\n\n model.compile(\n #optimizer=tf.keras.optimizers.SGD(momentum=.5,nesterov=True, clipnorm=1.),\n #optimizer=tf.keras.optimizers.RMSprop(),\n optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4),\n loss= {\n \"root\":catCeFromLogitsDoubled,\n \"vowel\":catCeFromLogits,\n \"consonant\":catCeFromLogits\n },\n metrics=[RecallForLogits()]\n )\n print(\"model compiled\")\n\n print(model.summary())\n\n csv_logger = tf.keras.callbacks.CSVLogger(os.path.join(experiment_output_dir,'training_log.csv'),append=False)\n callbacks = [\n # Interrupt training if `val_loss` stops improving for over 2 epochs\n tf.keras.callbacks.EarlyStopping(patience=int(5), monitor='root_loss',mode='min'),\n # Write TensorBoard logs to `./logs` directory\n # tf.keras.callbacks.TensorBoard(log_dir=experiment_output_dir, histogram_freq = 0, profile_batch=0),\n tf.keras.callbacks.ModelCheckpoint(\n filepath=os.path.join(experiment_output_dir,\"weights.hdf5\"),\n save_best_only=True,\n verbose=True,\n mode='min',\n save_weights_only=True,\n monitor='root_loss'),\n tf.keras.callbacks.TerminateOnNaN(),\n csv_logger,\n #reduce_lr\n ]\n\n spe = (N-len(valIds))//batchSize\n #spe = N//batchSize\n print(\"Steps per epoch {0}\".format(spe))\n fitHisotry = model.fit(x = trDs, \\\n validation_data = valDs, \n verbose = 2,\n callbacks=callbacks,\n shuffle=False, # dataset is shuffled explicilty\n steps_per_epoch= spe,\n #steps_per_epoch= N//batchSize,\n #steps_per_epoch= 4096,\n #epochs=int(10000)\n epochs = 10\n ) \n print(\"Done\")"
] |
[
[
"tensorflow.math.argmax",
"pandas.read_csv",
"tensorflow.nn.softmax",
"tensorflow.unstack",
"tensorflow.zeros",
"tensorflow.keras.losses.categorical_crossentropy",
"tensorflow.reshape",
"tensorflow.cast",
"tensorflow.expand_dims",
"tensorflow.math.logical_not",
"tensorflow.image.resize",
"tensorflow.keras.callbacks.TerminateOnNaN",
"tensorflow.one_hot",
"tensorflow.math.reduce_sum",
"tensorflow.keras.optimizers.Adam",
"tensorflow.math.logical_and",
"tensorflow.py_function",
"tensorflow.random.set_seed"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
usertianqin/X2Paddle
|
[
"b554a8094ca3e255ef4bd2e80337222a35625133"
] |
[
"x2paddle/project_convertor/pytorch/torch2paddle/vision_transforms.py"
] |
[
"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport paddle\nimport PIL\nimport numbers\nimport numpy as np\nfrom PIL import Image\nfrom paddle.vision.transforms import BaseTransform\nfrom paddle.vision.transforms import functional as F\n\n\nclass ToPILImage(BaseTransform):\n def __init__(self, mode=None, keys=None):\n super(ToTensor, self).__init__(keys)\n self.data_format = data_format\n\n def _apply_image(self, pic):\n \"\"\"\n Args:\n pic (Tensor|np.ndarray): Image to be converted to PIL Image.\n Returns:\n PIL: Converted image.\n \"\"\"\n if not (isinstance(pic, paddle.Tensor) or isinstance(pic, np.ndarray)):\n raise TypeError('pic should be Tensor or ndarray. Got {}.'.format(\n type(pic)))\n\n elif isinstance(pic, paddle.Tensor):\n if pic.ndimension() not in {2, 3}:\n raise ValueError(\n 'pic should be 2/3 dimensional. Got {} dimensions.'.format(\n pic.ndimension()))\n\n elif pic.ndimension() == 2:\n # if 2D image, add channel dimension (CHW)\n pic = pic.unsqueeze(0)\n\n elif isinstance(pic, np.ndarray):\n if pic.ndim not in {2, 3}:\n raise ValueError(\n 'pic should be 2/3 dimensional. Got {} dimensions.'.format(\n pic.ndim))\n\n elif pic.ndim == 2:\n # if 2D image, add channel dimension (HWC)\n pic = np.expand_dims(pic, 2)\n\n npimg = pic\n if isinstance(pic, paddle.Tensor) and \"float\" in str(pic.numpy(\n ).dtype) and mode != 'F':\n pic = pic.mul(255).byte()\n if isinstance(pic, paddle.Tensor):\n npimg = np.transpose(pic.numpy(), (1, 2, 0))\n\n if not isinstance(npimg, np.ndarray):\n raise TypeError(\n 'Input pic must be a paddle.Tensor or NumPy ndarray, ' +\n 'not {}'.format(type(npimg)))\n\n if npimg.shape[2] == 1:\n expected_mode = None\n npimg = npimg[:, :, 0]\n if npimg.dtype == np.uint8:\n expected_mode = 'L'\n elif npimg.dtype == np.int16:\n expected_mode = 'I;16'\n elif npimg.dtype == np.int32:\n expected_mode = 'I'\n elif npimg.dtype == np.float32:\n expected_mode = 'F'\n if mode is not None and mode != expected_mode:\n raise ValueError(\n \"Incorrect mode ({}) supplied for input type {}. Should be {}\"\n .format(mode, np.dtype, expected_mode))\n mode = expected_mode\n\n elif npimg.shape[2] == 2:\n permitted_2_channel_modes = ['LA']\n if mode is not None and mode not in permitted_2_channel_modes:\n raise ValueError(\"Only modes {} are supported for 2D inputs\".\n format(permitted_2_channel_modes))\n\n if mode is None and npimg.dtype == np.uint8:\n mode = 'LA'\n\n elif npimg.shape[2] == 4:\n permitted_4_channel_modes = ['RGBA', 'CMYK', 'RGBX']\n if mode is not None and mode not in permitted_4_channel_modes:\n raise ValueError(\"Only modes {} are supported for 4D inputs\".\n format(permitted_4_channel_modes))\n\n if mode is None and npimg.dtype == np.uint8:\n mode = 'RGBA'\n else:\n permitted_3_channel_modes = ['RGB', 'YCbCr', 'HSV']\n if mode is not None and mode not in permitted_3_channel_modes:\n raise ValueError(\"Only modes {} are supported for 3D inputs\".\n format(permitted_3_channel_modes))\n if mode is None and npimg.dtype == np.uint8:\n mode = 'RGB'\n\n if mode is None:\n raise TypeError('Input type {} is not supported'.format(\n npimg.dtype))\n\n return Image.fromarray(npimg, mode=mode)\n\n\nclass ToTensor(BaseTransform):\n \"\"\"Convert a ``PIL.Image`` or ``numpy.ndarray`` to ``numpy.ndarray`` with shapr (C x H x W).\n Args:\n data_format (str, optional): Data format of output tensor, should be 'HWC' or\n 'CHW'. Default: 'CHW'.\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n \"\"\"\n\n def __init__(self, data_format='CHW', keys=None):\n super(ToTensor, self).__init__(keys)\n self.data_format = data_format\n\n def _apply_image(self, img):\n \"\"\"\n Args:\n img (PIL.Image|np.ndarray): Image to be converted to tensor.\n Returns:\n np.ndarray: Converted image.\n \"\"\"\n if isinstance(img, PIL.JpegImagePlugin.JpegImageFile) or isinstance(\n img, PIL.Image.Image):\n img = np.array(img)\n img = img / 255.0\n img = img.transpose((2, 0, 1)).astype(\"float32\")\n img = paddle.to_tensor(img)\n return img\n\n\nclass Normalize(BaseTransform):\n \"\"\"Normalize the input data with mean and standard deviation.\n Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels,\n this transform will normalize each channel of the input data.\n ``output[channel] = (input[channel] - mean[channel]) / std[channel]``\n Args:\n mean (int|float|list): Sequence of means for each channel.\n std (int|float|list): Sequence of standard deviations for each channel.\n \"\"\"\n\n def __init__(self, mean=0.0, std=1.0, inplace=False):\n key = None\n super(Normalize, self).__init__(key)\n if isinstance(mean, numbers.Number):\n mean = [mean, mean, mean]\n\n if isinstance(std, numbers.Number):\n std = [std, std, std]\n\n self.mean = mean\n self.std = std\n\n def _apply_image(self, img):\n if isinstance(img, paddle.Tensor):\n img = img.numpy()\n return F.normalize(img, self.mean, self.std, 'CHW', False)\n\n\nclass Lambda(BaseTransform):\n \"\"\"Apply a user-defined lambda as a transform. This transform does not support torchscript.\n Args:\n lambd (function): Lambda/function to be used for transform.\n \"\"\"\n\n def __init__(self, lambd):\n if not callable(lambd):\n raise TypeError(\"Argument lambd should be callable, got {}\".format(\n repr(type(lambd).__name__)))\n self.lambd = lambd\n\n def _apply_image(self, img):\n return self.lambd(img)\n"
] |
[
[
"numpy.array",
"numpy.expand_dims"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
huhuzwxy/keras_classfication
|
[
"0a2c801f210141e447ef3c5346ce44e2e33125bb"
] |
[
"data_gen_label.py"
] |
[
"# -*- coding: utf-8 -*-\nimport codecs\nimport math\nimport os\nimport random\nfrom glob import glob\n\nimport keras\nimport numpy as np\nfrom PIL import Image\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils import np_utils, Sequence\nfrom sklearn.model_selection import train_test_split\nfrom random_eraser import get_random_eraser\nimport matplotlib.pyplot as plt\nimport pylab\n\ndef get_submodules_from_kwargs(kwargs):\n backend = keras.backend\n layers = keras.backend\n models = keras.models\n keras_utils = keras.utils\n\n return backend, layers, models, keras_utils\n\n\n\"\"\"\n这个文件是实现数据提取的文件,生成数据提取器。\n\"\"\"\n\n\nclass BaseSequence(Sequence):\n \"\"\"\n 基础的数据流生成器,每次迭代返回一个batch\n BaseSequence可直接用于fit_generator的generator参数\n fit_generator会将BaseSequence再次封装为一个多进程的数据流生成器\n 而且能保证在多进程下的一个epoch中不会重复取相同的样本\n \"\"\"\n\n def __init__(self, img_paths, labels, batch_size, img_size, use, preprocess_input):\n assert len(img_paths) == len(labels), \"len(img_paths) must equal to len(lables)\"\n assert img_size[0] == img_size[1], \"img_size[0] must equal to img_size[1]\"\n self.x_y = np.hstack((np.array(img_paths).reshape(len(img_paths), 1), np.array(labels)))\n self.batch_size = batch_size\n self.img_size = img_size\n self.use = use\n self.preprocess_input = preprocess_input\n self.eraser = get_random_eraser( s_h=0.3,pixel_level=True)\n\n\n def __len__(self):\n return math.ceil(len(self.x_y) / self.batch_size)\n\n @staticmethod\n def center_img(img, size=None, fill_value=255):\n \"\"\"\n center img in a square background\n \"\"\"\n h, w = img.shape[:2]\n if size is None:\n size = max(h, w)\n shape = (size, size) + img.shape[2:]\n background = np.full(shape, fill_value, np.uint8)\n center_x = (size - w) // 2\n center_y = (size - h) // 2\n background[center_y:center_y + h, center_x:center_x + w] = img\n return background\n\n def preprocess_img(self, img_path):\n \"\"\"\n image preprocessing\n you can add your special preprocess method here\n \"\"\"\n img = Image.open(img_path)\n resize_scale = self.img_size[0] / max(img.size[:2])\n img = img.resize((int(img.size[0] * resize_scale), int(img.size[1] * resize_scale)))\n img = img.convert('RGB')\n img = np.array(img)\n\n # 数据增强\n if self.use:\n\n img = self.eraser(img)\n datagen = ImageDataGenerator(\n width_shift_range=0.05,\n height_shift_range=0.05,\n # rotation_range=90,\n # shear_range=0.1,\n # zoom_range=0.1,\n # brightness_range=(1, 1.3),\n horizontal_flip=True,\n vertical_flip=True,\n )\n img = datagen.random_transform(img)\n \n img = img[:, :, ::-1]\n \n img = self.center_img(img, self.img_size[0])\n # print(img)\n return img\n\n def __getitem__(self, idx):\n\n batch_x = self.x_y[idx * self.batch_size: (idx + 1) * self.batch_size, 0]\n batch_y = self.x_y[idx * self.batch_size: (idx + 1) * self.batch_size, 1:]\n\n batch_x = np.array([self.preprocess_img(img_path) for img_path in batch_x])\n batch_y = np.array(batch_y).astype(np.float32)\n # print(batch_y[1])\n\n # 获取归一化数据\n batch_x = self.preprocess_input(batch_x)\n\n return batch_x, batch_y\n\n def on_epoch_end(self):\n\n np.random.shuffle(self.x_y)\n\n\ndef smooth_labels(y, smooth_factor=0.1):\n\n assert len(y.shape) == 2\n if 0 <= smooth_factor <= 1:\n # label smoothing ref: https://www.robots.ox.ac.uk/~vgg/rg/papers/reinception.pdf\n y *= 1 - smooth_factor\n y += smooth_factor / y.shape[1]\n else:\n raise Exception(\n 'Invalid label smoothing factor: ' + str(smooth_factor))\n return y\n\n\ndef data_flow(train_data_dir, batch_size, num_classes, input_size, preprocess_input):\n label_files = glob(os.path.join(train_data_dir, 'img*.txt'))\n random.shuffle(label_files)\n img_paths = []\n labels = []\n for index, file_path in enumerate(label_files):\n with codecs.open(file_path, 'r', 'utf-8') as f:\n line = f.readline( )\n line_split = line.strip( ).split(', ')\n if len(line_split) != 2:\n print('%s contain error lable' % os.path.basename(file_path))\n continue\n img_name = line_split[0]\n label = int(line_split[1])\n img_paths.append(os.path.join(train_data_dir, img_name))\n labels.append(label)\n labels = np_utils.to_categorical(labels, num_classes)\n # 标签平滑\n labels = smooth_labels(labels)\n train_img_paths, validation_img_paths, train_labels, validation_labels = \\\n train_test_split(img_paths, labels, test_size=0.001, random_state=0)\n print('total samples: %d, training samples: %d, validation samples: %d' % (\n len(img_paths), len(train_img_paths), len(validation_img_paths)))\n\n train_sequence = BaseSequence(train_img_paths, train_labels, batch_size, [input_size, input_size],\n use=True, preprocess_input=preprocess_input)\n validation_sequence = BaseSequence(validation_img_paths, validation_labels, batch_size, [input_size, input_size],\n use=False, preprocess_input=preprocess_input)\n return train_sequence, validation_sequence\n\n\n"
] |
[
[
"numpy.array",
"sklearn.model_selection.train_test_split",
"numpy.random.shuffle",
"numpy.full"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mt-edwards/classy-text
|
[
"5d33f935e4879f4649d08d927d8428a3cec11a29"
] |
[
"classy_text/train_ngram_model.py"
] |
[
"\"\"\"Module to train n-gram model.\n\nVectorizes training and validation texts into n-grams and uses that for\ntraining a n-gram model - a simple multi-layer perceptron model. We use n-gram\nmodel for text classification when the ratio of number of samples to number of\nwords per sample for the given dataset is very small (<~1500).\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport time\n\nimport tensorflow as tf\nimport numpy as np\n\nimport classy_text.build_model as build_model\nimport classy_text.load_data as load_data\nimport classy_text.vectorize_data as vectorize_data\nimport classy_text.explore_data as explore_data\n\nFLAGS = None\n\n\ndef train_ngram_model(data,\n learning_rate=1e-3,\n epochs=1000,\n batch_size=128,\n layers=2,\n units=64,\n dropout_rate=0.2):\n \"\"\"Trains n-gram model on the given dataset.\n\n # Arguments\n data: tuples of training and test texts and labels.\n learning_rate: float, learning rate for training model.\n epochs: int, number of epochs.\n batch_size: int, number of samples per batch.\n layers: int, number of `Dense` layers in the model.\n units: int, output dimension of Dense layers in the model.\n dropout_rate: float: percentage of input to drop at Dropout layers.\n\n # Raises\n ValueError: If validation data has label values which were not seen\n in the training data.\n \"\"\"\n # Get the data.\n (train_texts, train_labels), (val_texts, val_labels) = data\n\n # Verify that validation labels are in the same range as training labels.\n num_classes = explore_data.get_num_classes(train_labels)\n unexpected_labels = [v for v in val_labels if v not in range(num_classes)]\n if len(unexpected_labels):\n raise ValueError('Unexpected label values found in the validation set:'\n ' {unexpected_labels}. Please make sure that the '\n 'labels in the validation set are in the same range '\n 'as training labels.'.format(\n unexpected_labels=unexpected_labels))\n\n # Vectorize texts.\n x_train, x_val = vectorize_data.ngram_vectorize(\n train_texts, train_labels, val_texts)\n\n # Create model instance.\n model = build_model.mlp_model(layers=layers,\n units=units,\n dropout_rate=dropout_rate,\n input_shape=x_train.shape[1:],\n num_classes=num_classes)\n\n # Compile model with learning parameters.\n if num_classes == 2:\n loss = 'binary_crossentropy'\n else:\n loss = 'sparse_categorical_crossentropy'\n optimizer = tf.keras.optimizers.Adam(lr=learning_rate)\n model.compile(optimizer=optimizer, loss=loss, metrics=['acc'])\n\n # Create callback for early stopping on validation loss. If the loss does\n # not decrease in two consecutive tries, stop training.\n callbacks = [tf.keras.callbacks.EarlyStopping(\n monitor='val_loss', patience=2)]\n\n # Train and validate model.\n history = model.fit(\n x_train,\n train_labels,\n epochs=epochs,\n callbacks=callbacks,\n validation_data=(x_val, val_labels),\n verbose=2, # Logs once per epoch.\n batch_size=batch_size)\n\n # Print results.\n history = history.history\n print('Validation accuracy: {acc}, loss: {loss}'.format(\n acc=history['val_acc'][-1], loss=history['val_loss'][-1]))\n\n # Save model.\n model.save('imdb_mlp_model.h5')\n return history['val_acc'][-1], history['val_loss'][-1]\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', type=str, default='./data',\n help='input data directory')\n FLAGS, unparsed = parser.parse_known_args()\n\n # Using the IMDb movie reviews dataset to demonstrate training n-gram model\n data = load_data.load_imdb_sentiment_analysis_dataset(FLAGS.data_dir)\n train_ngram_model(data)\n"
] |
[
[
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.callbacks.EarlyStopping"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
HarrySpearing/GPflow
|
[
"02cd9000f72f4302f24a9fa1b28237f86140e04e",
"02cd9000f72f4302f24a9fa1b28237f86140e04e",
"02cd9000f72f4302f24a9fa1b28237f86140e04e",
"02cd9000f72f4302f24a9fa1b28237f86140e04e"
] |
[
"tests/gpflow/conditionals/test_multioutput.py",
"tests/gpflow/quadrature/test_quadrature_equivalence.py",
"gpflow/utilities/misc.py",
"gpflow/models/training_mixins.py"
] |
[
"import numpy as np\nimport pytest\nimport scipy\nimport tensorflow as tf\n\nimport gpflow\nimport gpflow.inducing_variables.multioutput as mf\nimport gpflow.kernels.multioutput as mk\nfrom gpflow import set_trainable\nfrom gpflow.conditionals import sample_conditional\nfrom gpflow.conditionals.util import (\n fully_correlated_conditional,\n fully_correlated_conditional_repeat,\n independent_interdomain_conditional,\n sample_mvn,\n)\nfrom gpflow.config import default_float, default_jitter\nfrom gpflow.inducing_variables import InducingPoints\nfrom gpflow.kernels import SquaredExponential\nfrom gpflow.likelihoods import Gaussian\nfrom gpflow.models import SVGP\n\nfloat_type = default_float()\nrng = np.random.RandomState(99201)\n\n\n# ------------------------------------------\n# Helpers\n# ------------------------------------------\n\n\ndef predict(model, Xnew, full_cov, full_output_cov):\n m, v = model.predict_f(Xnew, full_cov=full_cov, full_output_cov=full_output_cov)\n return [m, v]\n\n\ndef predict_all(models, Xnew, full_cov, full_output_cov):\n \"\"\"\n Returns the mean and variance of f(Xnew) for each model in `models`.\n \"\"\"\n ms, vs = [], []\n for model in models:\n m, v = predict(model, Xnew, full_cov, full_output_cov)\n ms.append(m)\n vs.append(v)\n return ms, vs\n\n\ndef assert_all_array_elements_almost_equal(arr, decimal):\n \"\"\"\n Check if consecutive elements of `arr` are almost equal.\n \"\"\"\n for i in range(len(arr) - 1):\n np.testing.assert_allclose(arr[i], arr[i + 1], atol=1e-5)\n\n\ndef check_equality_predictions(data, models, decimal=3):\n \"\"\"\n Executes a couple of checks to compare the equality of predictions\n of different models. The models should be configured with the same\n training data (X, Y). The following checks are done:\n - check if elbo is (almost) equal for all models\n - check if predicted mean is (almost) equal\n - check if predicted variance is (almost) equal.\n All possible variances over the inputs and outputs are calculated\n and equality is checked.\n - check if variances within model are consistent. Parts of the covariance\n matrices should overlap, and this is tested.\n \"\"\"\n\n elbos = [m.elbo(data) for m in models]\n\n # Check equality of log likelihood\n assert_all_array_elements_almost_equal(elbos, decimal=5)\n\n # Predict: full_cov = True and full_output_cov = True\n means_tt, vars_tt = predict_all(models, Data.Xs, full_cov=True, full_output_cov=True)\n # Predict: full_cov = True and full_output_cov = False\n means_tf, vars_tf = predict_all(models, Data.Xs, full_cov=True, full_output_cov=False)\n # Predict: full_cov = False and full_output_cov = True\n means_ft, vars_ft = predict_all(models, Data.Xs, full_cov=False, full_output_cov=True)\n # Predict: full_cov = False and full_output_cov = False\n means_ff, vars_ff = predict_all(models, Data.Xs, full_cov=False, full_output_cov=False)\n\n # check equality of all the means\n all_means = means_tt + means_tf + means_ft + means_ff\n assert_all_array_elements_almost_equal(all_means, decimal=decimal)\n\n # check equality of all the variances within a category\n # (e.g. full_cov=True and full_output_cov=False)\n all_vars = [vars_tt, vars_tf, vars_ft, vars_ff]\n _ = [assert_all_array_elements_almost_equal(var, decimal=decimal) for var in all_vars]\n\n # Here we check that the variance in different categories are equal\n # after transforming to the right shape.\n var_tt = vars_tt[0] # N x P x N x P\n var_tf = vars_tf[0] # P x N x c\n var_ft = vars_ft[0] # N x P x P\n var_ff = vars_ff[0] # N x P\n\n np.testing.assert_almost_equal(\n np.diagonal(var_tt, axis1=1, axis2=3),\n np.transpose(var_tf, [1, 2, 0]),\n decimal=decimal,\n )\n np.testing.assert_almost_equal(\n np.diagonal(var_tt, axis1=0, axis2=2),\n np.transpose(var_ft, [1, 2, 0]),\n decimal=decimal,\n )\n np.testing.assert_almost_equal(\n np.diagonal(np.diagonal(var_tt, axis1=0, axis2=2)), var_ff, decimal=decimal\n )\n\n\ndef expand_cov(q_sqrt, W):\n \"\"\"\n :param G: cholesky of covariance matrices, L x M x M\n :param W: mixing matrix (square), L x L\n :return: cholesky of 1 x LM x LM covariance matrix\n \"\"\"\n q_cov = np.matmul(q_sqrt, q_sqrt.transpose([0, 2, 1])) # [L, M, M]\n q_cov_expanded = scipy.linalg.block_diag(*q_cov) # [LM, LM]\n q_sqrt_expanded = np.linalg.cholesky(q_cov_expanded) # [LM, LM]\n return q_sqrt_expanded[None, ...]\n\n\ndef create_q_sqrt(M, L):\n \"\"\" returns an array of L lower triangular matrices of size M x M \"\"\"\n return np.array([np.tril(rng.randn(M, M)) for _ in range(L)]) # [L, M, M]\n\n\n# ------------------------------------------\n# Data classes: storing constants\n# ------------------------------------------\n\n\nclass Data:\n N, Ntest = 20, 5\n D = 1 # input dimension\n M = 3 # inducing points\n L = 2 # latent gps\n P = 3 # output dimension\n MAXITER = int(15e2)\n X = tf.random.normal((N,), dtype=tf.float64)[:, None] * 10 - 5\n G = np.hstack((0.5 * np.sin(3 * X) + X, 3.0 * np.cos(X) - X))\n Ptrue = np.array([[0.5, -0.3, 1.5], [-0.4, 0.43, 0.0]]) # [L, P]\n\n Y = tf.convert_to_tensor(G @ Ptrue)\n G = tf.convert_to_tensor(np.hstack((0.5 * np.sin(3 * X) + X, 3.0 * np.cos(X) - X)))\n Ptrue = tf.convert_to_tensor(np.array([[0.5, -0.3, 1.5], [-0.4, 0.43, 0.0]])) # [L, P]\n Y += tf.random.normal(Y.shape, dtype=tf.float64) * [0.2, 0.2, 0.2]\n Xs = tf.convert_to_tensor(np.linspace(-6, 6, Ntest)[:, None])\n data = (X, Y)\n\n\nclass DataMixedKernelWithEye(Data):\n \"\"\" Note in this class L == P \"\"\"\n\n M, L = 4, 3\n W = np.eye(L)\n\n G = np.hstack(\n [0.5 * np.sin(3 * Data.X) + Data.X, 3.0 * np.cos(Data.X) - Data.X, 1.0 + Data.X]\n ) # [N, P]\n\n mu_data = tf.random.uniform((M, L), dtype=tf.float64) # [M, L]\n sqrt_data = create_q_sqrt(M, L) # [L, M, M]\n\n mu_data_full = tf.reshape(mu_data @ W, [-1, 1]) # [L, 1]\n sqrt_data_full = expand_cov(sqrt_data, W) # [1, LM, LM]\n\n Y = tf.convert_to_tensor(G @ W)\n G = tf.convert_to_tensor(G)\n W = tf.convert_to_tensor(W)\n sqrt_data = tf.convert_to_tensor(sqrt_data)\n sqrt_data_full = tf.convert_to_tensor(sqrt_data_full)\n Y += tf.random.normal(Y.shape, dtype=tf.float64) * tf.ones((L,), dtype=tf.float64) * 0.2\n data = (Data.X, Y)\n\n\nclass DataMixedKernel(Data):\n M = 5\n L = 2\n P = 3\n W = rng.randn(P, L)\n G = np.hstack([0.5 * np.sin(3 * Data.X) + Data.X, 3.0 * np.cos(Data.X) - Data.X]) # [N, L]\n\n mu_data = tf.random.normal((M, L), dtype=tf.float64) # [M, L]\n sqrt_data = create_q_sqrt(M, L) # [L, M, M]\n\n Y = tf.convert_to_tensor(G @ W.T)\n G = tf.convert_to_tensor(G)\n W = tf.convert_to_tensor(W)\n sqrt_data = tf.convert_to_tensor(sqrt_data)\n Y += tf.random.normal(Y.shape, dtype=tf.float64) * tf.ones((P,), dtype=tf.float64) * 0.1\n data = (Data.X, Y)\n\n\n# ------------------------------------------\n# Test sample conditional\n# ------------------------------------------\n\n\ndef test_sample_mvn(full_cov):\n \"\"\"\n Draws 10,000 samples from a distribution\n with known mean and covariance. The test checks\n if the mean and covariance of the samples is\n close to the true mean and covariance.\n \"\"\"\n N, D = 10000, 2\n means = tf.ones((N, D), dtype=float_type)\n if full_cov:\n covs = tf.eye(D, batch_shape=[N], dtype=float_type)\n else:\n covs = tf.ones((N, D), dtype=float_type)\n\n samples = sample_mvn(means, covs, full_cov)\n samples_mean = np.mean(samples, axis=0)\n samples_cov = np.cov(samples, rowvar=False)\n\n np.testing.assert_array_almost_equal(samples_mean, [1.0, 1.0], decimal=1)\n np.testing.assert_array_almost_equal(samples_cov, [[1.0, 0.0], [0.0, 1.0]], decimal=1)\n\n\ndef test_sample_conditional(whiten, full_cov, full_output_cov):\n if full_cov and full_output_cov:\n return\n\n q_mu = tf.random.uniform((Data.M, Data.P), dtype=tf.float64) # [M, P]\n q_sqrt = tf.convert_to_tensor(\n [np.tril(tf.random.uniform((Data.M, Data.M), dtype=tf.float64)) for _ in range(Data.P)]\n ) # [P, M, M]\n\n Z = Data.X[: Data.M, ...] # [M, D]\n Xs = np.ones((Data.N, Data.D), dtype=float_type)\n\n inducing_variable = InducingPoints(Z)\n kernel = SquaredExponential()\n\n # Path 1\n value_f, mean_f, var_f = sample_conditional(\n Xs,\n inducing_variable,\n kernel,\n q_mu,\n q_sqrt=q_sqrt,\n white=whiten,\n full_cov=full_cov,\n full_output_cov=full_output_cov,\n num_samples=int(1e5),\n )\n value_f = value_f.numpy().reshape((-1,) + value_f.numpy().shape[2:])\n\n # Path 2\n if full_output_cov:\n pytest.skip(\n \"sample_conditional with X instead of inducing_variable does not support full_output_cov\"\n )\n\n value_x, mean_x, var_x = sample_conditional(\n Xs,\n Z,\n kernel,\n q_mu,\n q_sqrt=q_sqrt,\n white=whiten,\n full_cov=full_cov,\n full_output_cov=full_output_cov,\n num_samples=int(1e5),\n )\n value_x = value_x.numpy().reshape((-1,) + value_x.numpy().shape[2:])\n\n # check if mean and covariance of samples are similar\n np.testing.assert_array_almost_equal(\n np.mean(value_x, axis=0), np.mean(value_f, axis=0), decimal=1\n )\n np.testing.assert_array_almost_equal(\n np.cov(value_x, rowvar=False), np.cov(value_f, rowvar=False), decimal=1\n )\n np.testing.assert_allclose(mean_x, mean_f)\n np.testing.assert_allclose(var_x, var_f)\n\n\ndef test_sample_conditional_mixedkernel():\n q_mu = tf.random.uniform((Data.M, Data.L), dtype=tf.float64) # M x L\n q_sqrt = tf.convert_to_tensor(\n [np.tril(tf.random.uniform((Data.M, Data.M), dtype=tf.float64)) for _ in range(Data.L)]\n ) # L x M x M\n\n Z = Data.X[: Data.M, ...] # M x D\n N = int(10e5)\n Xs = np.ones((N, Data.D), dtype=float_type)\n\n # Path 1: mixed kernel: most efficient route\n W = np.random.randn(Data.P, Data.L)\n mixed_kernel = mk.LinearCoregionalization([SquaredExponential() for _ in range(Data.L)], W)\n optimal_inducing_variable = mf.SharedIndependentInducingVariables(InducingPoints(Z))\n\n value, mean, var = sample_conditional(\n Xs, optimal_inducing_variable, mixed_kernel, q_mu, q_sqrt=q_sqrt, white=True\n )\n\n # Path 2: independent kernels, mixed later\n separate_kernel = mk.SeparateIndependent([SquaredExponential() for _ in range(Data.L)])\n fallback_inducing_variable = mf.SharedIndependentInducingVariables(InducingPoints(Z))\n\n value2, mean2, var2 = sample_conditional(\n Xs, fallback_inducing_variable, separate_kernel, q_mu, q_sqrt=q_sqrt, white=True\n )\n value2 = np.matmul(value2, W.T)\n # check if mean and covariance of samples are similar\n np.testing.assert_array_almost_equal(np.mean(value, axis=0), np.mean(value2, axis=0), decimal=1)\n np.testing.assert_array_almost_equal(\n np.cov(value, rowvar=False), np.cov(value2, rowvar=False), decimal=1\n )\n\n\[email protected](\n name=\"fully_correlated_q_sqrt_factory\",\n params=[lambda _, __: None, lambda LM, R: tf.eye(LM, batch_shape=(R,))],\n)\ndef _q_sqrt_factory_fixture(request):\n return request.param\n\n\[email protected](\"R\", [1, 2, 5])\ndef test_fully_correlated_conditional_repeat_shapes_fc_and_foc(\n R, fully_correlated_q_sqrt_factory, full_cov, full_output_cov, whiten\n):\n\n L, M, N, P = Data.L, Data.M, Data.N, Data.P\n\n Kmm = tf.ones((L * M, L * M)) + default_jitter() * tf.eye(L * M)\n Kmn = tf.ones((L * M, N, P))\n\n if full_cov and full_output_cov:\n Knn = tf.ones((N, P, N, P))\n expected_v_shape = [R, N, P, N, P]\n elif not full_cov and full_output_cov:\n Knn = tf.ones((N, P, P))\n expected_v_shape = [R, N, P, P]\n elif full_cov and not full_output_cov:\n Knn = tf.ones((P, N, N))\n expected_v_shape = [R, P, N, N]\n else:\n Knn = tf.ones((N, P))\n expected_v_shape = [R, N, P]\n\n f = tf.ones((L * M, R))\n q_sqrt = fully_correlated_q_sqrt_factory(L * M, R)\n\n m, v = fully_correlated_conditional_repeat(\n Kmn,\n Kmm,\n Knn,\n f,\n full_cov=full_cov,\n full_output_cov=full_output_cov,\n q_sqrt=q_sqrt,\n white=whiten,\n )\n\n assert m.shape.as_list() == [R, N, P]\n assert v.shape.as_list() == expected_v_shape\n\n\ndef test_fully_correlated_conditional_repeat_whiten(whiten):\n \"\"\"\n This test checks the effect of the `white` flag, which changes the projection matrix `A`.\n\n The impact of the flag on the value of `A` can be easily verified by its effect on the\n predicted mean. While the predicted covariance is also a function of `A` this test does not\n inspect that value.\n \"\"\"\n N, P = Data.N, Data.P\n\n Lm = np.random.randn(1, 1).astype(np.float32) ** 2\n Kmm = Lm * Lm + default_jitter()\n\n Kmn = tf.ones((1, N, P))\n\n Knn = tf.ones((N, P))\n f = np.random.randn(1, 1).astype(np.float32)\n\n mean, _ = fully_correlated_conditional_repeat(\n Kmn,\n Kmm,\n Knn,\n f,\n white=whiten,\n )\n\n if whiten:\n expected_mean = (f * Kmn) / Lm\n else:\n expected_mean = (f * Kmn) / Kmm\n\n np.testing.assert_allclose(mean, expected_mean, rtol=1e-3)\n\n\ndef test_fully_correlated_conditional_shapes_fc_and_foc(\n fully_correlated_q_sqrt_factory, full_cov, full_output_cov, whiten\n):\n L, M, N, P = Data.L, Data.M, Data.N, Data.P\n\n Kmm = tf.ones((L * M, L * M)) + default_jitter() * tf.eye(L * M)\n Kmn = tf.ones((L * M, N, P))\n\n if full_cov and full_output_cov:\n Knn = tf.ones((N, P, N, P))\n expected_v_shape = [N, P, N, P]\n elif not full_cov and full_output_cov:\n Knn = tf.ones((N, P, P))\n expected_v_shape = [N, P, P]\n elif full_cov and not full_output_cov:\n Knn = tf.ones((P, N, N))\n expected_v_shape = [P, N, N]\n else:\n Knn = tf.ones((N, P))\n expected_v_shape = [N, P]\n\n f = tf.ones((L * M, 1))\n q_sqrt = fully_correlated_q_sqrt_factory(L * M, 1)\n\n m, v = fully_correlated_conditional(\n Kmn,\n Kmm,\n Knn,\n f,\n full_cov=full_cov,\n full_output_cov=full_output_cov,\n q_sqrt=q_sqrt,\n white=whiten,\n )\n\n assert m.shape.as_list() == [N, P]\n assert v.shape.as_list() == expected_v_shape\n\n\n# ------------------------------------------\n# Test Mok Output Dims\n# ------------------------------------------\n\n\ndef test_shapes_of_mok():\n data = DataMixedKernel\n\n kern_list = [SquaredExponential() for _ in range(data.L)]\n\n k1 = mk.LinearCoregionalization(kern_list, W=data.W)\n assert k1.num_latent_gps == data.L\n\n k2 = mk.SeparateIndependent(kern_list)\n assert k2.num_latent_gps == data.L\n\n dims = 5\n k3 = mk.SharedIndependent(SquaredExponential(), dims)\n assert k3.num_latent_gps == dims\n\n\n# ------------------------------------------\n# Test Mixed Mok Kgg\n# ------------------------------------------\n\n\ndef test_MixedMok_Kgg():\n data = DataMixedKernel\n kern_list = [SquaredExponential() for _ in range(data.L)]\n kernel = mk.LinearCoregionalization(kern_list, W=data.W)\n\n Kgg = kernel.Kgg(Data.X, Data.X) # L x N x N\n Kff = kernel.K(Data.X, Data.X) # N x P x N x P\n\n # Kff = W @ Kgg @ W^T\n Kff_infered = np.einsum(\"lnm,pl,ql->npmq\", Kgg, data.W, data.W)\n\n np.testing.assert_array_almost_equal(Kff, Kff_infered, decimal=5)\n\n\n# ------------------------------------------\n# Integration tests\n# ------------------------------------------\n\n\ndef test_shared_independent_mok():\n \"\"\"\n In this test we use the same kernel and the same inducing inducing\n for each of the outputs. The outputs are considered to be uncorrelated.\n This is how GPflow handled multiple outputs before the multioutput framework was added.\n We compare three models here:\n 1) an ineffient one, where we use a SharedIndepedentMok with InducingPoints.\n This combination will uses a Kff of size N x P x N x P, Kfu if size N x P x M x P\n which is extremely inefficient as most of the elements are zero.\n 2) efficient: SharedIndependentMok and SharedIndependentMof\n This combinations uses the most efficient form of matrices\n 3) the old way, efficient way: using Kernel and InducingPoints\n Model 2) and 3) follow more or less the same code path.\n \"\"\"\n np.random.seed(0)\n # Model 1\n q_mu_1 = np.random.randn(Data.M * Data.P, 1) # MP x 1\n q_sqrt_1 = np.tril(np.random.randn(Data.M * Data.P, Data.M * Data.P))[None, ...] # 1 x MP x MP\n kernel_1 = mk.SharedIndependent(SquaredExponential(variance=0.5, lengthscales=1.2), Data.P)\n inducing_variable = InducingPoints(Data.X[: Data.M, ...])\n model_1 = SVGP(\n kernel_1,\n Gaussian(),\n inducing_variable,\n q_mu=q_mu_1,\n q_sqrt=q_sqrt_1,\n num_latent_gps=Data.Y.shape[-1],\n )\n set_trainable(model_1, False)\n set_trainable(model_1.q_sqrt, True)\n\n gpflow.optimizers.Scipy().minimize(\n model_1.training_loss_closure(Data.data),\n variables=model_1.trainable_variables,\n options=dict(maxiter=500),\n method=\"BFGS\",\n compile=True,\n )\n\n # Model 2\n q_mu_2 = np.reshape(q_mu_1, [Data.M, Data.P]) # M x P\n q_sqrt_2 = np.array(\n [np.tril(np.random.randn(Data.M, Data.M)) for _ in range(Data.P)]\n ) # P x M x M\n kernel_2 = SquaredExponential(variance=0.5, lengthscales=1.2)\n inducing_variable_2 = InducingPoints(Data.X[: Data.M, ...])\n model_2 = SVGP(\n kernel_2,\n Gaussian(),\n inducing_variable_2,\n num_latent_gps=Data.P,\n q_mu=q_mu_2,\n q_sqrt=q_sqrt_2,\n )\n set_trainable(model_2, False)\n set_trainable(model_2.q_sqrt, True)\n\n gpflow.optimizers.Scipy().minimize(\n model_2.training_loss_closure(Data.data),\n variables=model_2.trainable_variables,\n options=dict(maxiter=500),\n method=\"BFGS\",\n compile=True,\n )\n\n # Model 3\n q_mu_3 = np.reshape(q_mu_1, [Data.M, Data.P]) # M x P\n q_sqrt_3 = np.array(\n [np.tril(np.random.randn(Data.M, Data.M)) for _ in range(Data.P)]\n ) # P x M x M\n kernel_3 = mk.SharedIndependent(SquaredExponential(variance=0.5, lengthscales=1.2), Data.P)\n inducing_variable_3 = mf.SharedIndependentInducingVariables(\n InducingPoints(Data.X[: Data.M, ...])\n )\n model_3 = SVGP(\n kernel_3,\n Gaussian(),\n inducing_variable_3,\n num_latent_gps=Data.P,\n q_mu=q_mu_3,\n q_sqrt=q_sqrt_3,\n )\n set_trainable(model_3, False)\n set_trainable(model_3.q_sqrt, True)\n\n gpflow.optimizers.Scipy().minimize(\n model_3.training_loss_closure(Data.data),\n variables=model_3.trainable_variables,\n options=dict(maxiter=500),\n method=\"BFGS\",\n compile=True,\n )\n\n check_equality_predictions(Data.data, [model_1, model_2, model_3])\n\n\ndef test_separate_independent_mok():\n \"\"\"\n We use different independent kernels for each of the output dimensions.\n We can achieve this in two ways:\n 1) efficient: SeparateIndependentMok with Shared/SeparateIndependentMof\n 2) inefficient: SeparateIndependentMok with InducingPoints\n However, both methods should return the same conditional,\n and after optimization return the same log likelihood.\n \"\"\"\n # Model 1 (Inefficient)\n q_mu_1 = np.random.randn(Data.M * Data.P, 1)\n q_sqrt_1 = np.tril(np.random.randn(Data.M * Data.P, Data.M * Data.P))[None, ...] # 1 x MP x MP\n\n kern_list_1 = [SquaredExponential(variance=0.5, lengthscales=1.2) for _ in range(Data.P)]\n kernel_1 = mk.SeparateIndependent(kern_list_1)\n inducing_variable_1 = InducingPoints(Data.X[: Data.M, ...])\n model_1 = SVGP(\n kernel_1,\n Gaussian(),\n inducing_variable_1,\n num_latent_gps=1,\n q_mu=q_mu_1,\n q_sqrt=q_sqrt_1,\n )\n set_trainable(model_1, False)\n set_trainable(model_1.q_sqrt, True)\n set_trainable(model_1.q_mu, True)\n\n gpflow.optimizers.Scipy().minimize(\n model_1.training_loss_closure(Data.data),\n variables=model_1.trainable_variables,\n method=\"BFGS\",\n compile=True,\n )\n\n # Model 2 (efficient)\n q_mu_2 = np.random.randn(Data.M, Data.P)\n q_sqrt_2 = np.array(\n [np.tril(np.random.randn(Data.M, Data.M)) for _ in range(Data.P)]\n ) # P x M x M\n kern_list_2 = [SquaredExponential(variance=0.5, lengthscales=1.2) for _ in range(Data.P)]\n kernel_2 = mk.SeparateIndependent(kern_list_2)\n inducing_variable_2 = mf.SharedIndependentInducingVariables(\n InducingPoints(Data.X[: Data.M, ...])\n )\n model_2 = SVGP(\n kernel_2,\n Gaussian(),\n inducing_variable_2,\n num_latent_gps=Data.P,\n q_mu=q_mu_2,\n q_sqrt=q_sqrt_2,\n )\n set_trainable(model_2, False)\n set_trainable(model_2.q_sqrt, True)\n set_trainable(model_2.q_mu, True)\n\n gpflow.optimizers.Scipy().minimize(\n model_2.training_loss_closure(Data.data),\n variables=model_2.trainable_variables,\n method=\"BFGS\",\n compile=True,\n )\n\n check_equality_predictions(Data.data, [model_1, model_2])\n\n\ndef test_separate_independent_mof():\n \"\"\"\n Same test as above but we use different (i.e. separate) inducing inducing\n for each of the output dimensions.\n \"\"\"\n np.random.seed(0)\n\n # Model 1 (INefficient)\n q_mu_1 = np.random.randn(Data.M * Data.P, 1)\n q_sqrt_1 = np.tril(np.random.randn(Data.M * Data.P, Data.M * Data.P))[None, ...] # 1 x MP x MP\n\n kernel_1 = mk.SharedIndependent(SquaredExponential(variance=0.5, lengthscales=1.2), Data.P)\n inducing_variable_1 = InducingPoints(Data.X[: Data.M, ...])\n model_1 = SVGP(kernel_1, Gaussian(), inducing_variable_1, q_mu=q_mu_1, q_sqrt=q_sqrt_1)\n set_trainable(model_1, False)\n set_trainable(model_1.q_sqrt, True)\n set_trainable(model_1.q_mu, True)\n\n gpflow.optimizers.Scipy().minimize(\n model_1.training_loss_closure(Data.data),\n variables=model_1.trainable_variables,\n method=\"BFGS\",\n compile=True,\n )\n\n # Model 2 (efficient)\n q_mu_2 = np.random.randn(Data.M, Data.P)\n q_sqrt_2 = np.array(\n [np.tril(np.random.randn(Data.M, Data.M)) for _ in range(Data.P)]\n ) # P x M x M\n kernel_2 = mk.SharedIndependent(SquaredExponential(variance=0.5, lengthscales=1.2), Data.P)\n inducing_variable_list_2 = [InducingPoints(Data.X[: Data.M, ...]) for _ in range(Data.P)]\n inducing_variable_2 = mf.SeparateIndependentInducingVariables(inducing_variable_list_2)\n model_2 = SVGP(kernel_2, Gaussian(), inducing_variable_2, q_mu=q_mu_2, q_sqrt=q_sqrt_2)\n set_trainable(model_2, False)\n set_trainable(model_2.q_sqrt, True)\n set_trainable(model_2.q_mu, True)\n\n gpflow.optimizers.Scipy().minimize(\n model_2.training_loss_closure(Data.data),\n variables=model_2.trainable_variables,\n method=\"BFGS\",\n compile=True,\n )\n\n # Model 3 (Inefficient): an idenitical inducing variable is used P times,\n # and treated as a separate one.\n q_mu_3 = np.random.randn(Data.M, Data.P)\n q_sqrt_3 = np.array(\n [np.tril(np.random.randn(Data.M, Data.M)) for _ in range(Data.P)]\n ) # P x M x M\n kern_list = [SquaredExponential(variance=0.5, lengthscales=1.2) for _ in range(Data.P)]\n kernel_3 = mk.SeparateIndependent(kern_list)\n inducing_variable_list_3 = [InducingPoints(Data.X[: Data.M, ...]) for _ in range(Data.P)]\n inducing_variable_3 = mf.SeparateIndependentInducingVariables(inducing_variable_list_3)\n model_3 = SVGP(kernel_3, Gaussian(), inducing_variable_3, q_mu=q_mu_3, q_sqrt=q_sqrt_3)\n set_trainable(model_3, False)\n set_trainable(model_3.q_sqrt, True)\n set_trainable(model_3.q_mu, True)\n\n gpflow.optimizers.Scipy().minimize(\n model_3.training_loss_closure(Data.data),\n variables=model_3.trainable_variables,\n method=\"BFGS\",\n compile=True,\n )\n\n check_equality_predictions(Data.data, [model_1, model_2, model_3])\n\n\ndef test_mixed_mok_with_Id_vs_independent_mok():\n data = DataMixedKernelWithEye\n # Independent model\n k1 = mk.SharedIndependent(SquaredExponential(variance=0.5, lengthscales=1.2), data.L)\n f1 = InducingPoints(data.X[: data.M, ...])\n model_1 = SVGP(k1, Gaussian(), f1, q_mu=data.mu_data_full, q_sqrt=data.sqrt_data_full)\n set_trainable(model_1, False)\n set_trainable(model_1.q_sqrt, True)\n\n gpflow.optimizers.Scipy().minimize(\n model_1.training_loss_closure(Data.data),\n variables=model_1.trainable_variables,\n method=\"BFGS\",\n compile=True,\n )\n\n # Mixed Model\n kern_list = [SquaredExponential(variance=0.5, lengthscales=1.2) for _ in range(data.L)]\n k2 = mk.LinearCoregionalization(kern_list, data.W)\n f2 = InducingPoints(data.X[: data.M, ...])\n model_2 = SVGP(k2, Gaussian(), f2, q_mu=data.mu_data_full, q_sqrt=data.sqrt_data_full)\n set_trainable(model_2, False)\n set_trainable(model_2.q_sqrt, True)\n\n gpflow.optimizers.Scipy().minimize(\n model_2.training_loss_closure(Data.data),\n variables=model_2.trainable_variables,\n method=\"BFGS\",\n compile=True,\n )\n\n check_equality_predictions(Data.data, [model_1, model_2])\n\n\ndef test_compare_mixed_kernel():\n data = DataMixedKernel\n\n kern_list = [SquaredExponential() for _ in range(data.L)]\n k1 = mk.LinearCoregionalization(kern_list, W=data.W)\n f1 = mf.SharedIndependentInducingVariables(InducingPoints(data.X[: data.M, ...]))\n model_1 = SVGP(k1, Gaussian(), inducing_variable=f1, q_mu=data.mu_data, q_sqrt=data.sqrt_data)\n\n kern_list = [SquaredExponential() for _ in range(data.L)]\n k2 = mk.LinearCoregionalization(kern_list, W=data.W)\n f2 = mf.SharedIndependentInducingVariables(InducingPoints(data.X[: data.M, ...]))\n model_2 = SVGP(k2, Gaussian(), inducing_variable=f2, q_mu=data.mu_data, q_sqrt=data.sqrt_data)\n\n check_equality_predictions(Data.data, [model_1, model_2])\n\n\ndef test_multioutput_with_diag_q_sqrt():\n data = DataMixedKernel\n\n q_sqrt_diag = np.ones((data.M, data.L)) * 2\n q_sqrt = np.repeat(np.eye(data.M)[None, ...], data.L, axis=0) * 2 # L x M x M\n\n kern_list = [SquaredExponential() for _ in range(data.L)]\n k1 = mk.LinearCoregionalization(kern_list, W=data.W)\n f1 = mf.SharedIndependentInducingVariables(InducingPoints(data.X[: data.M, ...]))\n model_1 = SVGP(\n k1,\n Gaussian(),\n inducing_variable=f1,\n q_mu=data.mu_data,\n q_sqrt=q_sqrt_diag,\n q_diag=True,\n )\n\n kern_list = [SquaredExponential() for _ in range(data.L)]\n k2 = mk.LinearCoregionalization(kern_list, W=data.W)\n f2 = mf.SharedIndependentInducingVariables(InducingPoints(data.X[: data.M, ...]))\n model_2 = SVGP(\n k2,\n Gaussian(),\n inducing_variable=f2,\n q_mu=data.mu_data,\n q_sqrt=q_sqrt,\n q_diag=False,\n )\n\n check_equality_predictions(Data.data, [model_1, model_2])\n\n\ndef test_MixedKernelSeparateMof():\n data = DataMixedKernel\n\n kern_list = [SquaredExponential() for _ in range(data.L)]\n inducing_variable_list = [InducingPoints(data.X[: data.M, ...]) for _ in range(data.L)]\n k1 = mk.LinearCoregionalization(kern_list, W=data.W)\n f1 = mf.SeparateIndependentInducingVariables(inducing_variable_list)\n model_1 = SVGP(k1, Gaussian(), inducing_variable=f1, q_mu=data.mu_data, q_sqrt=data.sqrt_data)\n\n kern_list = [SquaredExponential() for _ in range(data.L)]\n inducing_variable_list = [InducingPoints(data.X[: data.M, ...]) for _ in range(data.L)]\n k2 = mk.LinearCoregionalization(kern_list, W=data.W)\n f2 = mf.SeparateIndependentInducingVariables(inducing_variable_list)\n model_2 = SVGP(k2, Gaussian(), inducing_variable=f2, q_mu=data.mu_data, q_sqrt=data.sqrt_data)\n\n check_equality_predictions(Data.data, [model_1, model_2])\n\n\ndef test_separate_independent_conditional_with_q_sqrt_none():\n \"\"\"\n In response to bug #1523, this test checks that separate_independent_condtional\n does not fail when q_sqrt=None.\n \"\"\"\n q_sqrt = None\n data = DataMixedKernel\n\n kern_list = [SquaredExponential() for _ in range(data.L)]\n kernel = gpflow.kernels.SeparateIndependent(kern_list)\n inducing_variable_list = [InducingPoints(data.X[: data.M, ...]) for _ in range(data.L)]\n inducing_variable = mf.SeparateIndependentInducingVariables(inducing_variable_list)\n\n mu_1, var_1 = gpflow.conditionals.conditional(\n data.X,\n inducing_variable,\n kernel,\n data.mu_data,\n full_cov=False,\n full_output_cov=False,\n q_sqrt=q_sqrt,\n white=True,\n )\n\n\ndef test_independent_interdomain_conditional_bug_regression():\n \"\"\"\n Regression test for https://github.com/GPflow/GPflow/issues/818\n Not an exhaustive test\n \"\"\"\n M = 31\n N = 11\n D_lat = 5\n D_inp = D_lat * 7\n L = 2\n P = 3\n\n X = np.random.randn(N, D_inp)\n Zs = [np.random.randn(M, D_lat) for _ in range(L)]\n k = gpflow.kernels.SquaredExponential(lengthscales=np.ones(D_lat))\n\n def compute_Kmn(Z, X):\n return tf.stack([k(Z, X[:, i * D_lat : (i + 1) * D_lat]) for i in range(P)])\n\n def compute_Knn(X):\n return tf.stack([k(X[:, i * D_lat : (i + 1) * D_lat], full_cov=False) for i in range(P)])\n\n Kmm = tf.stack([k(Z) for Z in Zs]) # L x M x M\n Kmn = tf.stack([compute_Kmn(Z, X) for Z in Zs]) # L x P x M x N\n Kmn = tf.transpose(Kmn, [2, 0, 3, 1]) # -> M x L x N x P\n Knn = tf.transpose(compute_Knn(X)) # N x P\n q_mu = tf.convert_to_tensor(np.zeros((M, L)))\n q_sqrt = tf.convert_to_tensor(np.stack([np.eye(M) for _ in range(L)]))\n tf.debugging.assert_shapes(\n [\n (Kmm, [\"L\", \"M\", \"M\"]),\n (Kmn, [\"M\", \"L\", \"N\", \"P\"]),\n (Knn, [\"N\", \"P\"]),\n (q_mu, [\"M\", \"L\"]),\n (q_sqrt, [\"L\", \"M\", \"M\"]),\n ]\n )\n\n _, _ = independent_interdomain_conditional(\n Kmn, Kmm, Knn, q_mu, q_sqrt=q_sqrt, full_cov=False, full_output_cov=False\n )\n\n\ndef test_independent_interdomain_conditional_whiten(whiten):\n \"\"\"\n This test checks the effect of the `white` flag, which changes the projection matrix `A`.\n\n The impact of the flag on the value of `A` can be easily verified by its effect on the\n predicted mean. While the predicted covariance is also a function of `A` this test does not\n inspect that value.\n \"\"\"\n N, P = Data.N, Data.P\n\n Lm = np.random.randn(1, 1, 1).astype(np.float32) ** 2\n Kmm = Lm * Lm + default_jitter()\n\n Kmn = tf.ones((1, 1, N, P))\n\n Knn = tf.ones((N, P))\n f = np.random.randn(1, 1).astype(np.float32)\n\n mean, _ = independent_interdomain_conditional(\n Kmn,\n Kmm,\n Knn,\n f,\n white=whiten,\n )\n\n if whiten:\n expected_mean = (f * Kmn) / Lm\n else:\n expected_mean = (f * Kmn) / Kmm\n\n np.testing.assert_allclose(mean, expected_mean[0][0], rtol=1e-2)\n",
"# Copyright 2018 the GPflow authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport pytest\nimport tensorflow as tf\nfrom ndiagquad_old import ndiagquad as ndiagquad_old\nfrom numpy.testing import assert_allclose\n\nfrom gpflow.quadrature import ndiagquad\n\n\[email protected](\"mu\", [np.array([1.0, 1.3])])\[email protected](\"var\", [np.array([3.0, 3.5])])\ndef test_diagquad_1d(mu, var):\n num_gauss_hermite_points = 25\n quad = ndiagquad([lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var])\n quad_old = ndiagquad_old([lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var])\n assert_allclose(quad[0], quad_old[0])\n\n\[email protected](\"mu1\", [np.array([1.0, 1.3])])\[email protected](\"var1\", [np.array([3.0, 3.5])])\[email protected](\"mu2\", [np.array([-2.0, 0.3])])\[email protected](\"var2\", [np.array([4.0, 4.2])])\ndef test_diagquad_2d(mu1, var1, mu2, var2):\n alpha = 2.5\n # using logspace=True we can reduce this, see test_diagquad_logspace\n num_gauss_hermite_points = 35\n quad = ndiagquad(\n lambda *X: tf.exp(X[0] + alpha * X[1]),\n num_gauss_hermite_points,\n [mu1, mu2],\n [var1, var2],\n )\n quad_old = ndiagquad_old(\n lambda *X: tf.exp(X[0] + alpha * X[1]),\n num_gauss_hermite_points,\n [mu1, mu2],\n [var1, var2],\n )\n assert_allclose(quad, quad_old)\n\n\[email protected](\"mu1\", [np.array([1.0, 1.3])])\[email protected](\"var1\", [np.array([3.0, 3.5])])\[email protected](\"mu2\", [np.array([-2.0, 0.3])])\[email protected](\"var2\", [np.array([4.0, 4.2])])\ndef test_diagquad_logspace(mu1, var1, mu2, var2):\n alpha = 2.5\n num_gauss_hermite_points = 25\n quad = ndiagquad(\n lambda *X: (X[0] + alpha * X[1]),\n num_gauss_hermite_points,\n [mu1, mu2],\n [var1, var2],\n logspace=True,\n )\n quad_old = ndiagquad_old(\n lambda *X: (X[0] + alpha * X[1]),\n num_gauss_hermite_points,\n [mu1, mu2],\n [var1, var2],\n logspace=True,\n )\n assert_allclose(quad, quad_old)\n\n\[email protected](\"mu1\", [np.array([1.0, 1.3])])\[email protected](\"var1\", [np.array([3.0, 3.5])])\ndef test_diagquad_with_kwarg(mu1, var1):\n alpha = np.array([2.5, -1.3])\n num_gauss_hermite_points = 25\n quad = ndiagquad(lambda X, Y: tf.exp(X * Y), num_gauss_hermite_points, mu1, var1, Y=alpha)\n quad_old = ndiagquad_old(\n lambda X, Y: tf.exp(X * Y), num_gauss_hermite_points, mu1, var1, Y=alpha\n )\n assert_allclose(quad, quad_old)\n",
"# Copyright 2017-2021 The GPflow Contributors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Callable, Iterable, List, Optional, Union\n\nimport tensorflow as tf\n\nfrom ..config import default_float, default_int\nfrom .ops import cast\n\n__all__ = [\n \"to_default_float\",\n \"to_default_int\",\n \"set_trainable\",\n \"training_loop\",\n]\n\n\ndef to_default_int(x):\n return cast(x, dtype=default_int())\n\n\ndef to_default_float(x):\n return cast(x, dtype=default_float())\n\n\ndef set_trainable(model: Union[tf.Module, Iterable[tf.Module]], flag: bool) -> None:\n \"\"\"\n Set trainable flag for all `tf.Variable`s and `gpflow.Parameter`s in a `tf.Module` or collection\n of `tf.Module`s.\n \"\"\"\n modules = [model] if isinstance(model, tf.Module) else model\n\n for mod in modules:\n for variable in mod.variables:\n variable._trainable = flag\n\n\ndef training_loop(\n closure: Callable[[], tf.Tensor],\n optimizer: Optional[tf.optimizers.Optimizer] = None,\n var_list: List[tf.Variable] = None,\n maxiter=1e3,\n compile=False,\n):\n \"\"\"\n Simple generic training loop. At each iteration uses a GradientTape to compute\n the gradients of a loss function with respect to a set of variables.\n\n :param closure: Callable that constructs a loss function based on data and model being trained\n :param optimizer: tf.optimizers or tf.keras.optimizers that updates variables by applying the\n corresponding loss gradients. Adam is a default optimizer with default settings.\n :param var_list: List of model variables to be learnt during training\n :param maxiter: Maximum number of\n :return:\n \"\"\"\n\n optimizer = tf.optimizers.Adam() if optimizer is None else optimizer\n\n def optimization_step():\n with tf.GradientTape(watch_accessed_variables=False) as tape:\n tape.watch(var_list)\n loss = closure()\n grads = tape.gradient(loss, var_list)\n optimizer.apply_gradients(zip(grads, var_list))\n\n if compile:\n optimization_step = tf.function(optimization_step)\n\n for _ in range(int(maxiter)):\n optimization_step()\n",
"# Copyright 2020 The GPflow Contributors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis module provides mixin classes to be used in conjunction with inheriting\nfrom gpflow.models.BayesianModel (or its subclass gpflow.models.GPModel).\n\nThey provide a unified interface to obtain closures that return the training\nloss, to be passed as the first argument to the minimize() method of the\noptimizers defined in TensorFlow and GPflow.\n\nAll TrainingLossMixin classes assume that self._training_loss()\n(which is provided by the BayesianModel base class), will be available. Note\nthat new models only need to implement the maximum_log_likelihood_objective\nmethod that is defined as abstract in BayesianModel.\n\nThere are different mixins depending on whether the model already contains the\ntraining data (InternalDataTrainingLossMixin), or requires it to be passed in\nto the objective function (ExternalDataTrainingLossMixin).\n\"\"\"\n\nimport abc\nfrom typing import Callable, Iterator, Optional, Tuple, TypeVar, Union\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.data.ops.iterator_ops import OwnedIterator as DatasetOwnedIterator\n\nInputData = Union[tf.Tensor]\nOutputData = Union[tf.Tensor]\nRegressionData = Tuple[InputData, OutputData]\nData = TypeVar(\"Data\", RegressionData, InputData, OutputData)\n\n\nclass InternalDataTrainingLossMixin:\n \"\"\"\n Mixin utility for training loss methods for models that own their own data. It provides\n\n - a uniform API for the training loss :meth:`training_loss`\n - a convenience method :meth:`training_loss_closure` for constructing the closure expected by\n various optimizers, namely :class:`gpflow.optimizers.Scipy` and subclasses of\n `tf.optimizers.Optimizer`.\n\n See :class:`ExternalDataTrainingLossMixin` for an equivalent mixin for models that do **not**\n own their own data.\n \"\"\"\n\n def training_loss(self) -> tf.Tensor:\n \"\"\"\n Returns the training loss for this model.\n \"\"\"\n return self._training_loss()\n\n def training_loss_closure(self, *, compile=True) -> Callable[[], tf.Tensor]:\n \"\"\"\n Convenience method. Returns a closure which itself returns the training loss. This closure\n can be passed to the minimize methods on :class:`gpflow.optimizers.Scipy` and subclasses of\n `tf.optimizers.Optimizer`.\n\n :param compile: If `True` (default), compile the training loss function in a TensorFlow graph\n by wrapping it in tf.function()\n \"\"\"\n if compile:\n return tf.function(self.training_loss)\n return self.training_loss\n\n\nclass ExternalDataTrainingLossMixin:\n \"\"\"\n Mixin utility for training loss methods for models that do **not** own their own data.\n It provides\n\n - a uniform API for the training loss :meth:`training_loss`\n - a convenience method :meth:`training_loss_closure` for constructing the closure expected by\n various optimizers, namely :class:`gpflow.optimizers.Scipy` and subclasses of\n `tf.optimizers.Optimizer`.\n\n See :class:`InternalDataTrainingLossMixin` for an equivalent mixin for models that **do** own\n their own data.\n \"\"\"\n\n def training_loss(self, data: Data) -> tf.Tensor:\n \"\"\"\n Returns the training loss for this model.\n\n :param data: the data to be used for computing the model objective.\n \"\"\"\n return self._training_loss(data)\n\n def training_loss_closure(\n self,\n data: Union[Data, DatasetOwnedIterator],\n *,\n compile=True,\n ) -> Callable[[], tf.Tensor]:\n \"\"\"\n Returns a closure that computes the training loss, which by default is\n wrapped in tf.function(). This can be disabled by passing `compile=False`.\n\n :param data: the data to be used by the closure for computing the model\n objective. Can be the full dataset or an iterator, e.g.\n `iter(dataset.batch(batch_size))`, where dataset is an instance of\n tf.data.Dataset.\n :param compile: if True, wrap training loss in tf.function()\n \"\"\"\n training_loss = self.training_loss\n\n if isinstance(data, DatasetOwnedIterator):\n if compile:\n input_signature = [data.element_spec]\n training_loss = tf.function(training_loss, input_signature=input_signature)\n\n def closure():\n batch = next(data)\n return training_loss(batch)\n\n else:\n\n def closure():\n return training_loss(data)\n\n if compile:\n closure = tf.function(closure)\n\n return closure\n"
] |
[
[
"tensorflow.convert_to_tensor",
"numpy.einsum",
"numpy.linspace",
"numpy.mean",
"numpy.random.randn",
"numpy.reshape",
"numpy.eye",
"numpy.matmul",
"numpy.sin",
"numpy.zeros",
"numpy.testing.assert_array_almost_equal",
"tensorflow.random.uniform",
"numpy.cov",
"tensorflow.debugging.assert_shapes",
"numpy.testing.assert_allclose",
"numpy.linalg.cholesky",
"numpy.transpose",
"numpy.array",
"numpy.random.RandomState",
"numpy.diagonal",
"tensorflow.transpose",
"scipy.linalg.block_diag",
"numpy.random.seed",
"tensorflow.reshape",
"tensorflow.ones",
"tensorflow.eye",
"numpy.ones",
"numpy.cos",
"tensorflow.random.normal"
],
[
"numpy.array",
"tensorflow.exp",
"numpy.testing.assert_allclose"
],
[
"tensorflow.optimizers.Adam",
"tensorflow.function",
"tensorflow.GradientTape"
],
[
"tensorflow.function"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"0.12",
"0.10"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"2.7",
"2.6",
"2.4",
"2.3",
"2.9",
"2.5",
"2.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.2",
"2.3",
"2.4",
"2.9",
"2.5",
"2.8",
"2.10"
]
}
] |
nldias/chapel
|
[
"3a63044cd50b639dca8e851d4a505546b57bc299"
] |
[
"third-party/llvm/llvm-src/tools/clang/utils/analyzer/CmpRuns.py"
] |
[
"#!/usr/bin/env python\n\n\"\"\"\nCmpRuns - A simple tool for comparing two static analyzer runs to determine\nwhich reports have been added, removed, or changed.\n\nThis is designed to support automated testing using the static analyzer, from\ntwo perspectives:\n 1. To monitor changes in the static analyzer's reports on real code bases,\n for regression testing.\n\n 2. For use by end users who want to integrate regular static analyzer testing\n into a buildbot like environment.\n\nUsage:\n\n # Load the results of both runs, to obtain lists of the corresponding\n # AnalysisDiagnostic objects.\n #\n resultsA = load_results_from_single_run(singleRunInfoA, delete_empty)\n resultsB = load_results_from_single_run(singleRunInfoB, delete_empty)\n\n # Generate a relation from diagnostics in run A to diagnostics in run B\n # to obtain a list of triples (a, b, confidence).\n diff = compare_results(resultsA, resultsB)\n\n\"\"\"\nimport json\nimport os\nimport plistlib\nimport re\nimport sys\n\nfrom math import log\nfrom collections import defaultdict\nfrom copy import copy\nfrom enum import Enum\nfrom typing import (Any, cast, Dict, List, NamedTuple, Optional, Sequence,\n TextIO, TypeVar, Tuple, Union)\n\n\nNumber = Union[int, float]\nStats = Dict[str, Dict[str, Number]]\nPlist = Dict[str, Any]\nJSON = Dict[str, Any]\n# Type for generics\nT = TypeVar('T')\n\nSTATS_REGEXP = re.compile(r\"Statistics: (\\{.+\\})\", re.MULTILINE | re.DOTALL)\n\n\nclass Colors:\n \"\"\"\n Color for terminal highlight.\n \"\"\"\n RED = '\\x1b[2;30;41m'\n GREEN = '\\x1b[6;30;42m'\n CLEAR = '\\x1b[0m'\n\n\nclass HistogramType(str, Enum):\n RELATIVE = \"relative\"\n LOG_RELATIVE = \"log-relative\"\n ABSOLUTE = \"absolute\"\n\n\nclass ResultsDirectory(NamedTuple):\n path: str\n root: str = \"\"\n\n\nclass SingleRunInfo:\n \"\"\"\n Information about analysis run:\n path - the analysis output directory\n root - the name of the root directory, which will be disregarded when\n determining the source file name\n \"\"\"\n def __init__(self, results: ResultsDirectory,\n verbose_log: Optional[str] = None):\n self.path = results.path\n self.root = results.root.rstrip(\"/\\\\\")\n self.verbose_log = verbose_log\n\n\nclass AnalysisDiagnostic:\n def __init__(self, data: Plist, report: \"AnalysisReport\",\n html_report: Optional[str]):\n self._data = data\n self._loc = self._data['location']\n self._report = report\n self._html_report = html_report\n self._report_size = len(self._data['path'])\n\n def get_file_name(self) -> str:\n root = self._report.run.root\n file_name = self._report.files[self._loc['file']]\n\n if file_name.startswith(root) and len(root) > 0:\n return file_name[len(root) + 1:]\n\n return file_name\n\n def get_root_file_name(self) -> str:\n path = self._data['path']\n\n if not path:\n return self.get_file_name()\n\n p = path[0]\n if 'location' in p:\n file_index = p['location']['file']\n else: # control edge\n file_index = path[0]['edges'][0]['start'][0]['file']\n\n out = self._report.files[file_index]\n root = self._report.run.root\n\n if out.startswith(root):\n return out[len(root):]\n\n return out\n\n def get_line(self) -> int:\n return self._loc['line']\n\n def get_column(self) -> int:\n return self._loc['col']\n\n def get_path_length(self) -> int:\n return self._report_size\n\n def get_category(self) -> str:\n return self._data['category']\n\n def get_description(self) -> str:\n return self._data['description']\n\n def get_issue_identifier(self) -> str:\n id = self.get_file_name() + \"+\"\n\n if \"issue_context\" in self._data:\n id += self._data[\"issue_context\"] + \"+\"\n\n if \"issue_hash_content_of_line_in_context\" in self._data:\n id += str(self._data[\"issue_hash_content_of_line_in_context\"])\n\n return id\n\n def get_html_report(self) -> str:\n if self._html_report is None:\n return \" \"\n\n return os.path.join(self._report.run.path, self._html_report)\n\n def get_readable_name(self) -> str:\n if \"issue_context\" in self._data:\n funcname_postfix = \"#\" + self._data[\"issue_context\"]\n else:\n funcname_postfix = \"\"\n\n root_filename = self.get_root_file_name()\n file_name = self.get_file_name()\n\n if root_filename != file_name:\n file_prefix = f\"[{root_filename}] {file_name}\"\n else:\n file_prefix = root_filename\n\n line = self.get_line()\n col = self.get_column()\n return f\"{file_prefix}{funcname_postfix}:{line}:{col}\" \\\n f\", {self.get_category()}: {self.get_description()}\"\n\n # Note, the data format is not an API and may change from one analyzer\n # version to another.\n def get_raw_data(self) -> Plist:\n return self._data\n\n\nclass AnalysisRun:\n def __init__(self, info: SingleRunInfo):\n self.path = info.path\n self.root = info.root\n self.info = info\n self.reports: List[AnalysisReport] = []\n # Cumulative list of all diagnostics from all the reports.\n self.diagnostics: List[AnalysisDiagnostic] = []\n self.clang_version: Optional[str] = None\n self.raw_stats: List[JSON] = []\n\n def get_clang_version(self) -> Optional[str]:\n return self.clang_version\n\n def read_single_file(self, path: str, delete_empty: bool):\n with open(path, \"rb\") as plist_file:\n data = plistlib.load(plist_file)\n\n if 'statistics' in data:\n self.raw_stats.append(json.loads(data['statistics']))\n data.pop('statistics')\n\n # We want to retrieve the clang version even if there are no\n # reports. Assume that all reports were created using the same\n # clang version (this is always true and is more efficient).\n if 'clang_version' in data:\n if self.clang_version is None:\n self.clang_version = data.pop('clang_version')\n else:\n data.pop('clang_version')\n\n # Ignore/delete empty reports.\n if not data['files']:\n if delete_empty:\n os.remove(path)\n return\n\n # Extract the HTML reports, if they exists.\n if 'HTMLDiagnostics_files' in data['diagnostics'][0]:\n htmlFiles = []\n for d in data['diagnostics']:\n # FIXME: Why is this named files, when does it have multiple\n # files?\n assert len(d['HTMLDiagnostics_files']) == 1\n htmlFiles.append(d.pop('HTMLDiagnostics_files')[0])\n else:\n htmlFiles = [None] * len(data['diagnostics'])\n\n report = AnalysisReport(self, data.pop('files'))\n diagnostics = [AnalysisDiagnostic(d, report, h)\n for d, h in zip(data.pop('diagnostics'), htmlFiles)]\n\n assert not data\n\n report.diagnostics.extend(diagnostics)\n self.reports.append(report)\n self.diagnostics.extend(diagnostics)\n\n\nclass AnalysisReport:\n def __init__(self, run: AnalysisRun, files: List[str]):\n self.run = run\n self.files = files\n self.diagnostics: List[AnalysisDiagnostic] = []\n\n\ndef load_results(results: ResultsDirectory, delete_empty: bool = True,\n verbose_log: Optional[str] = None) -> AnalysisRun:\n \"\"\"\n Backwards compatibility API.\n \"\"\"\n return load_results_from_single_run(SingleRunInfo(results,\n verbose_log),\n delete_empty)\n\n\ndef load_results_from_single_run(info: SingleRunInfo,\n delete_empty: bool = True) -> AnalysisRun:\n \"\"\"\n # Load results of the analyzes from a given output folder.\n # - info is the SingleRunInfo object\n # - delete_empty specifies if the empty plist files should be deleted\n\n \"\"\"\n path = info.path\n run = AnalysisRun(info)\n\n if os.path.isfile(path):\n run.read_single_file(path, delete_empty)\n else:\n for dirpath, dirnames, filenames in os.walk(path):\n for f in filenames:\n if not f.endswith('plist'):\n continue\n\n p = os.path.join(dirpath, f)\n run.read_single_file(p, delete_empty)\n\n return run\n\n\ndef cmp_analysis_diagnostic(d):\n return d.get_issue_identifier()\n\n\nPresentInBoth = Tuple[AnalysisDiagnostic, AnalysisDiagnostic]\nPresentOnlyInOld = Tuple[AnalysisDiagnostic, None]\nPresentOnlyInNew = Tuple[None, AnalysisDiagnostic]\nComparisonResult = List[Union[PresentInBoth,\n PresentOnlyInOld,\n PresentOnlyInNew]]\n\n\ndef compare_results(results_old: AnalysisRun, results_new: AnalysisRun,\n histogram: Optional[HistogramType] = None\n ) -> ComparisonResult:\n \"\"\"\n compare_results - Generate a relation from diagnostics in run A to\n diagnostics in run B.\n\n The result is the relation as a list of triples (a, b) where\n each element {a,b} is None or a matching element from the respective run\n \"\"\"\n\n res: ComparisonResult = []\n\n # Map size_before -> size_after\n path_difference_data: List[float] = []\n\n # Quickly eliminate equal elements.\n neq_old: List[AnalysisDiagnostic] = []\n neq_new: List[AnalysisDiagnostic] = []\n\n diags_old = copy(results_old.diagnostics)\n diags_new = copy(results_new.diagnostics)\n\n diags_old.sort(key=cmp_analysis_diagnostic)\n diags_new.sort(key=cmp_analysis_diagnostic)\n\n while diags_old and diags_new:\n a = diags_old.pop()\n b = diags_new.pop()\n\n if a.get_issue_identifier() == b.get_issue_identifier():\n if a.get_path_length() != b.get_path_length():\n\n if histogram == HistogramType.RELATIVE:\n path_difference_data.append(\n float(a.get_path_length()) / b.get_path_length())\n\n elif histogram == HistogramType.LOG_RELATIVE:\n path_difference_data.append(\n log(float(a.get_path_length()) / b.get_path_length()))\n\n elif histogram == HistogramType.ABSOLUTE:\n path_difference_data.append(\n a.get_path_length() - b.get_path_length())\n\n res.append((a, b))\n\n elif a.get_issue_identifier() > b.get_issue_identifier():\n diags_new.append(b)\n neq_old.append(a)\n\n else:\n diags_old.append(a)\n neq_new.append(b)\n\n neq_old.extend(diags_old)\n neq_new.extend(diags_new)\n\n # FIXME: Add fuzzy matching. One simple and possible effective idea would\n # be to bin the diagnostics, print them in a normalized form (based solely\n # on the structure of the diagnostic), compute the diff, then use that as\n # the basis for matching. This has the nice property that we don't depend\n # in any way on the diagnostic format.\n\n for a in neq_old:\n res.append((a, None))\n for b in neq_new:\n res.append((None, b))\n\n if histogram:\n from matplotlib import pyplot\n pyplot.hist(path_difference_data, bins=100)\n pyplot.show()\n\n return res\n\n\ndef compute_percentile(values: Sequence[T], percentile: float) -> T:\n \"\"\"\n Return computed percentile.\n \"\"\"\n return sorted(values)[int(round(percentile * len(values) + 0.5)) - 1]\n\n\ndef derive_stats(results: AnalysisRun) -> Stats:\n # Assume all keys are the same in each statistics bucket.\n combined_data = defaultdict(list)\n\n # Collect data on paths length.\n for report in results.reports:\n for diagnostic in report.diagnostics:\n combined_data['PathsLength'].append(diagnostic.get_path_length())\n\n for stat in results.raw_stats:\n for key, value in stat.items():\n combined_data[str(key)].append(value)\n\n combined_stats: Stats = {}\n\n for key, values in combined_data.items():\n combined_stats[key] = {\n \"max\": max(values),\n \"min\": min(values),\n \"mean\": sum(values) / len(values),\n \"90th %tile\": compute_percentile(values, 0.9),\n \"95th %tile\": compute_percentile(values, 0.95),\n \"median\": sorted(values)[len(values) // 2],\n \"total\": sum(values)\n }\n\n return combined_stats\n\n\n# TODO: compare_results decouples comparison from the output, we should\n# do it here as well\ndef compare_stats(results_old: AnalysisRun, results_new: AnalysisRun,\n out: TextIO = sys.stdout):\n stats_old = derive_stats(results_old)\n stats_new = derive_stats(results_new)\n\n old_keys = set(stats_old.keys())\n new_keys = set(stats_new.keys())\n keys = sorted(old_keys & new_keys)\n\n for key in keys:\n out.write(f\"{key}\\n\")\n\n nested_keys = sorted(set(stats_old[key]) & set(stats_new[key]))\n\n for nested_key in nested_keys:\n val_old = float(stats_old[key][nested_key])\n val_new = float(stats_new[key][nested_key])\n\n report = f\"{val_old:.3f} -> {val_new:.3f}\"\n\n # Only apply highlighting when writing to TTY and it's not Windows\n if out.isatty() and os.name != 'nt':\n if val_new != 0:\n ratio = (val_new - val_old) / val_new\n if ratio < -0.2:\n report = Colors.GREEN + report + Colors.CLEAR\n elif ratio > 0.2:\n report = Colors.RED + report + Colors.CLEAR\n\n out.write(f\"\\t {nested_key} {report}\\n\")\n\n removed_keys = old_keys - new_keys\n if removed_keys:\n out.write(f\"REMOVED statistics: {removed_keys}\\n\")\n\n added_keys = new_keys - old_keys\n if added_keys:\n out.write(f\"ADDED statistics: {added_keys}\\n\")\n\n out.write(\"\\n\")\n\n\ndef dump_scan_build_results_diff(dir_old: ResultsDirectory,\n dir_new: ResultsDirectory,\n delete_empty: bool = True,\n out: TextIO = sys.stdout,\n show_stats: bool = False,\n stats_only: bool = False,\n histogram: Optional[HistogramType] = None,\n verbose_log: Optional[str] = None):\n \"\"\"\n Compare directories with analysis results and dump results.\n\n :param delete_empty: delete empty plist files\n :param out: buffer to dump comparison results to.\n :param show_stats: compare execution stats as well.\n :param stats_only: compare ONLY execution stats.\n :param histogram: optional histogram type to plot path differences.\n :param verbose_log: optional path to an additional log file.\n \"\"\"\n results_old = load_results(dir_old, delete_empty, verbose_log)\n results_new = load_results(dir_new, delete_empty, verbose_log)\n\n if show_stats or stats_only:\n compare_stats(results_old, results_new)\n if stats_only:\n return\n\n # Open the verbose log, if given.\n if verbose_log:\n auxLog: Optional[TextIO] = open(verbose_log, \"w\")\n else:\n auxLog = None\n\n diff = compare_results(results_old, results_new, histogram)\n found_diffs = 0\n total_added = 0\n total_removed = 0\n\n for res in diff:\n old, new = res\n if old is None:\n # TODO: mypy still doesn't understand that old and new can't be\n # both Nones, we should introduce a better type solution\n new = cast(AnalysisDiagnostic, new)\n out.write(f\"ADDED: {new.get_readable_name()}\\n\")\n found_diffs += 1\n total_added += 1\n if auxLog:\n auxLog.write(f\"('ADDED', {new.get_readable_name()}, \"\n f\"{new.get_html_report()})\\n\")\n\n elif new is None:\n out.write(f\"REMOVED: {old.get_readable_name()}\\n\")\n found_diffs += 1\n total_removed += 1\n if auxLog:\n auxLog.write(f\"('REMOVED', {old.get_readable_name()}, \"\n f\"{old.get_html_report()})\\n\")\n else:\n pass\n\n total_reports = len(results_new.diagnostics)\n out.write(f\"TOTAL REPORTS: {total_reports}\\n\")\n out.write(f\"TOTAL ADDED: {total_added}\\n\")\n out.write(f\"TOTAL REMOVED: {total_removed}\\n\")\n\n if auxLog:\n auxLog.write(f\"('TOTAL NEW REPORTS', {total_reports})\\n\")\n auxLog.write(f\"('TOTAL DIFFERENCES', {found_diffs})\\n\")\n auxLog.close()\n\n # TODO: change to NamedTuple\n return found_diffs, len(results_old.diagnostics), \\\n len(results_new.diagnostics)\n\n\nif __name__ == \"__main__\":\n print(\"CmpRuns.py should not be used on its own.\")\n print(\"Please use 'SATest.py compare' instead\")\n sys.exit(1)\n"
] |
[
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.hist"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sx-zhang/HOZ
|
[
"7be117f078a34c6f97ea6c64f60d7df7b47bef49"
] |
[
"models/hoztpn.py"
] |
[
"from __future__ import division\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torchvision.models as models\r\nfrom utils.model_util import norm_col_init, weights_init\r\n\r\nfrom .model_io import ModelOutput\r\n\r\nimport scipy.sparse as sp\r\nimport numpy as np\r\nimport scipy.io as scio\r\nimport os\r\nimport copy\r\nimport json\r\n\r\ndef normalize_adj(adj):\r\n adj = sp.coo_matrix(adj)\r\n rowsum = np.array(adj.sum(1))\r\n d_inv_sqrt = np.power(rowsum, -0.5).flatten()\r\n d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.0\r\n d_mat_inv_sqrt = sp.diags(d_inv_sqrt)\r\n return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()\r\n\r\ndef load_scene_graph(path):\r\n graph = {}\r\n scenes = ['Kitchens', 'Living_Rooms', 'Bedrooms', 'Bathrooms']\r\n for s in scenes:\r\n data = scio.loadmat(os.path.join(path, s+'.mat'))\r\n graph[s] = data\r\n\r\n return graph\r\n\r\ndef dijkstra(graph, src):\r\n length = len(graph)\r\n type_ = type(graph)\r\n if type_ == list:\r\n nodes = [i for i in range(length)]\r\n elif type_ == dict:\r\n nodes = graph.keys()\r\n\r\n visited = [src]\r\n path = {src:{src:[]}}\r\n nodes.remove(src)\r\n distance_graph = {src:0}\r\n pre = next = src\r\n\r\n while nodes:\r\n distance = float('inf')\r\n for v in visited:\r\n for d in nodes:\r\n new_dist = graph[src][v] + graph[v][d]\r\n if new_dist <= distance:\r\n distance = new_dist\r\n next = d\r\n pre = v\r\n graph[src][d] = new_dist\r\n\r\n\r\n path[src][next] = [i for i in path[src][pre]]\r\n path[src][next].append(next)\r\n\r\n distance_graph[next] = distance\r\n\r\n visited.append(next)\r\n nodes.remove(next)\r\n\r\n return distance_graph, path\r\n\r\n\r\ndef normalize(x):\r\n x = -np.log(x)\r\n nozero_x = x[np.nonzero(x)]\r\n new_array = np.zeros(x.shape)\r\n x_max = np.max(nozero_x)\r\n x_min = np.min(nozero_x)\r\n x_ = x_max-x_min\r\n for i in range(x.shape[0]):\r\n for j in range(x.shape[1]):\r\n if x[i][j] == 0:\r\n continue\r\n else:\r\n new_array[i][j] = (x[i][j]-x_min)/x_\r\n return new_array.tolist()\r\n\r\n\r\nclass MetaMemoryHOZ(torch.nn.Module):\r\n def __init__(self, args):\r\n action_space = args.action_space\r\n self.num_cate = args.num_category\r\n resnet_embedding_sz = args.hidden_state_sz\r\n hidden_state_sz = args.hidden_state_sz\r\n super(MetaMemoryHOZ, self).__init__()\r\n\r\n self.conv1 = nn.Conv2d(resnet_embedding_sz, 64, 1)\r\n self.maxp1 = nn.MaxPool2d(2, 2)\r\n\r\n self.action_at_a = nn.Parameter(torch.tensor([0.0, 0.0, 0.0, 0.0, 0.0, 1.0]), requires_grad=False)\r\n self.action_at_b = nn.Parameter(torch.tensor([1.0, 1.0, 1.0, 1.0, 1.0, 0.0]), requires_grad=False)\r\n self.action_at_scale = nn.Parameter(torch.tensor(0.58), requires_grad=False)\r\n\r\n self.graph_detection_feature = nn.Sequential(\r\n nn.Linear(518, 128),\r\n nn.ReLU(),\r\n nn.Linear(128, 49),\r\n )\r\n\r\n self.graph_detection_other_info_linear_1 = nn.Linear(6, self.num_cate)\r\n self.graph_detection_other_info_linear_2 = nn.Linear(self.num_cate, self.num_cate)\r\n self.graph_detection_other_info_linear_3 = nn.Linear(self.num_cate, self.num_cate)\r\n self.graph_detection_other_info_linear_4 = nn.Linear(self.num_cate, self.num_cate)\r\n self.graph_detection_other_info_linear_5 = nn.Linear(self.num_cate, self.num_cate)\r\n\r\n self.embed_action = nn.Linear(action_space, 10)\r\n\r\n pointwise_in_channels = 64 + self.num_cate + 10 + self.num_cate + 4\r\n\r\n self.pointwise = nn.Conv2d(pointwise_in_channels, 64, 1, 1)\r\n\r\n self.lstm_input_sz = 7 * 7 * 64\r\n\r\n self.hidden_state_sz = hidden_state_sz\r\n self.lstm = nn.LSTM(self.lstm_input_sz, hidden_state_sz, 2)\r\n num_outputs = action_space\r\n self.critic_linear_1 = nn.Linear(hidden_state_sz, 64)\r\n self.critic_linear_2 = nn.Linear(64, 1)\r\n self.actor_linear = nn.Linear(hidden_state_sz, num_outputs)\r\n self.softmax = nn.Softmax(dim=1)\r\n\r\n self.multi_heads = args.multi_heads\r\n\r\n self.meta_current_state_embedding = nn.Sequential(\r\n nn.Linear(512, 256),\r\n nn.LayerNorm(256),\r\n nn.ReLU(),\r\n nn.Linear(256, 512),\r\n nn.LayerNorm(512),\r\n )\r\n self.meta_current_action_embedding = nn.Linear(6, 6)\r\n self.meta_memory_embedding = nn.Sequential(\r\n nn.Linear(518, 1024),\r\n nn.LayerNorm(1024),\r\n nn.ReLU(),\r\n nn.Linear(1024, 518),\r\n nn.LayerNorm(518)\r\n )\r\n\r\n self.meta_learning_residual_block = nn.Sequential(\r\n nn.Linear(1030, 512),\r\n nn.LayerNorm(512),\r\n nn.ReLU(),\r\n nn.Linear(512, 1030),\r\n nn.LayerNorm(1030)\r\n )\r\n self.meta_learning_predict = nn.Sequential(\r\n nn.Linear(1030, 512),\r\n nn.ReLU(),\r\n nn.Linear(512, 6)\r\n )\r\n\r\n self.apply(weights_init)\r\n relu_gain = nn.init.calculate_gain(\"relu\")\r\n self.conv1.weight.data.mul_(relu_gain)\r\n\r\n self.actor_linear.weight.data = norm_col_init(\r\n self.actor_linear.weight.data, 0.01\r\n )\r\n self.actor_linear.bias.data.fill_(0)\r\n\r\n self.critic_linear_1.weight.data = norm_col_init(\r\n self.critic_linear_1.weight.data, 1.0\r\n )\r\n self.critic_linear_1.bias.data.fill_(0)\r\n self.critic_linear_2.weight.data = norm_col_init(\r\n self.critic_linear_2.weight.data, 1.0\r\n )\r\n self.critic_linear_2.bias.data.fill_(0)\r\n\r\n self.lstm.bias_ih_l0.data.fill_(0)\r\n self.lstm.bias_ih_l1.data.fill_(0)\r\n self.lstm.bias_hh_l0.data.fill_(0)\r\n self.lstm.bias_hh_l1.data.fill_(0)\r\n\r\n self.dropout = nn.Dropout(p=args.dropout_rate)\r\n self.info_embedding = nn.Linear(5,49)\r\n self.scene_embedding = nn.Conv2d(86,64,1,1)\r\n self.scene_classifier = nn.Linear(64*7*7,4)\r\n\r\n self.graph_data = load_scene_graph('./scence_graph')\r\n self.zone_number, self.feature_length = self.graph_data['Kitchens']['node_features'].shape\r\n self.gcn_input = nn.Parameter(torch.zeros((self.zone_number, self.feature_length)), requires_grad=False)\r\n self.zones_feature = nn.Parameter(torch.zeros((self.zone_number, self.feature_length)), requires_grad=False)\r\n self.graph_buffer = [None for i in range(4)]\r\n self.scene_num = None\r\n self.fuse_scale = nn.Parameter(torch.tensor(0.005), requires_grad=True)\r\n self.state_index = 0\r\n self.target_index = 0\r\n self.sub_goal_index = 0\r\n # get and normalize adjacency matrix.\r\n self.adj_list = {}\r\n for k, v in self.graph_data.items():\r\n A_raw = v['edges']\r\n # rand e\r\n # A_raw = 0.2*np.ones((8,8))+0.002*np.random.rand(8,8)\r\n # Used to search shortest path\r\n self.adj_list[k] = normalize(A_raw)\r\n # Used to gcn compute\r\n A = normalize_adj(A_raw).tocsr().toarray()\r\n self.graph_data[k]['edges'] = A\r\n\r\n # last layer of resnet18.\r\n resnet18 = models.resnet18(pretrained=True)\r\n modules = list(resnet18.children())[-2:]\r\n self.resnet18 = nn.Sequential(*modules)\r\n for p in self.resnet18.parameters():\r\n p.requires_grad = False\r\n\r\n self.W0 = nn.Linear(22, 22, bias=False)\r\n\r\n\r\n def reset(self):\r\n self.graph_buffer = [None for i in range(4)]\r\n\r\n def gcn_embed(self, scene_name):\r\n x = self.gcn_input\r\n A = torch.from_numpy(self.graph_data[scene_name]['edges']).float().to(x.device)\r\n x = torch.mm(A, x)\r\n x = F.relu(self.W0(x))\r\n # x = torch.mm(A, x)\r\n # x = F.relu(self.W1(x))\r\n state_embedding = x[self.state_index]\r\n subgoal_embedding = x[self.sub_goal_index]\r\n target_embedding = x[self.target_index]\r\n # out = torch.cat((state_embedding.view(1, 512), target_embedding.view(1, 512)), dim=1)\r\n return state_embedding, subgoal_embedding, target_embedding\r\n\r\n def sub_goal(self, scene_vec, target_object, state):\r\n # scene_name, scene_vec = self.find_scene(scene)\r\n # scene_vec = scene_vec.to(state.device)\r\n scenes = ['Kitchens', 'Living_Rooms', 'Bedrooms', 'Bathrooms']\r\n scene_name = scenes[torch.argmax(scene_vec).item()]\r\n scene_graph = self.graph_data[scene_name]\r\n state_zone_feature = self.state_zone(scene_graph, state)\r\n target_zone_feature = self.target_zone(scene_graph, target_object)\r\n self.get_subgoal_index(scene_name)\r\n return state_zone_feature, target_zone_feature, scene_vec, scene_name\r\n\r\n def state_zone(self, scene_graph, feature):\r\n if self.graph_buffer[self.scene_num] is None:\r\n self.zones_feature.data = torch.from_numpy(scene_graph['node_features']).float().to(self.zones_feature.device)\r\n else:\r\n self.zones_feature.data = self.graph_buffer[self.scene_num]\r\n self.gcn_input.data = self.zones_feature.data\r\n state_feature = feature.view(1, 22).repeat(self.zone_number, 1)\r\n distance = F.pairwise_distance(state_feature, self.zones_feature, p=2)\r\n index = distance.argmin()\r\n self.gcn_input.data[index] = self.fuse_scale*feature.squeeze() + (1-self.fuse_scale)*self.zones_feature[index]\r\n self.graph_buffer[self.scene_num] = copy.deepcopy(self.gcn_input.data)\r\n self.state_index = index\r\n\r\n return self.zones_feature[index]\r\n\r\n def target_zone(self, scene_graph, target_object):\r\n index = torch.nonzero(target_object.squeeze())[0]\r\n # contain_objects = torch.from_numpy(scene_graph['node_features']).to(self.zones_feature.device)\r\n contain_objects = self.zones_feature\r\n max_index = contain_objects[:, index].argmax()\r\n self.target_index = max_index\r\n return self.zones_feature[max_index]\r\n\r\n def get_subgoal_index(self, scene_name):\r\n state_index = int(self.state_index)\r\n target_index = int(self.target_index)\r\n distance, path = dijkstra(self.adj_list[scene_name], state_index)\r\n trajectory = path[state_index][target_index]\r\n if len(trajectory) == 0:\r\n self.sub_goal_index = self.target_index\r\n else:\r\n self.sub_goal_index = trajectory[0]\r\n\r\n def find_scene(self, scene):\r\n scenes = ['Kitchens', 'Living_Rooms', 'Bedrooms', 'Bathrooms']\r\n id_number = \"\".join(filter(str.isdigit, scene))\r\n if 0 < int(id_number) < 200:\r\n s = scenes[0]\r\n vec = torch.tensor([1.0, 0.0, 0.0, 0.0])\r\n elif 200 < int(id_number) < 300:\r\n s = scenes[1]\r\n vec = torch.tensor([0.0, 1.0, 0.0, 0.0])\r\n elif 300 < int(id_number) < 400:\r\n s = scenes[2]\r\n vec = torch.tensor([0.0, 0.0, 1.0, 0.0])\r\n elif 400 < int(id_number) < 500:\r\n s = scenes[3]\r\n vec = torch.tensor([0.0, 0.0, 0.0, 1.0])\r\n return s, vec.view(1, 4)\r\n\r\n def embedding(self, state, target, action_embedding_input, scene, target_object):\r\n at_v = torch.mul(target['info'][:, -1].view(target['info'].shape[0], 1), target['indicator'])\r\n at = torch.mul(torch.max(at_v), self.action_at_scale)\r\n action_at = torch.mul(at, self.action_at_a) + self.action_at_b\r\n\r\n info_embedding = F.relu(self.info_embedding(target['info']))\r\n\r\n stat_onehot_vec = torch.sign(target['info'][:, -1])\r\n target_object = target['indicator']\r\n target_info = torch.cat((target['info'], target['indicator']), dim=1)\r\n target_info = F.relu(self.graph_detection_other_info_linear_1(target_info))\r\n target_info = target_info.t()\r\n target_info = F.relu(self.graph_detection_other_info_linear_2(target_info))\r\n target_info = F.relu(self.graph_detection_other_info_linear_3(target_info))\r\n target_info = F.relu(self.graph_detection_other_info_linear_4(target_info))\r\n target_info = F.relu(self.graph_detection_other_info_linear_5(target_info))\r\n target_appear = torch.mm(target['appear'].t(), target_info).t()\r\n target = torch.cat((target_appear, target['info'], target['indicator']), dim=1)\r\n\r\n target = F.relu(self.graph_detection_feature(target))\r\n target_embedding = target.reshape(1, self.num_cate, 7, 7)\r\n\r\n action_embedding = F.relu(self.embed_action(action_embedding_input))\r\n action_reshaped = action_embedding.view(1, 10, 1, 1).repeat(1, 1, 7, 7)\r\n\r\n image_embedding = F.relu(self.conv1(state))\r\n\r\n scene_embedding = F.relu(self.scene_embedding(torch.cat((info_embedding.view(1,22,7,7),image_embedding),dim=1))).view(1,-1)\r\n scene_vec = F.softmax(self.scene_classifier(scene_embedding),dim=1).squeeze()\r\n self.scene_num = torch.argmax(scene_vec)\r\n\r\n x = self.dropout(image_embedding)\r\n\r\n state_zone, next_zone, scene_vec, scene_name = self.sub_goal(scene_vec, target_object, stat_onehot_vec)\r\n state_zone_embedding, subgoal_zone_embedding, target_zone_embedding = self.gcn_embed(scene_name)\r\n\r\n x = torch.cat((x, target_embedding, action_reshaped, scene_vec.view(1, 4, 1, 1).repeat(1, 1, 7, 7),\r\n subgoal_zone_embedding.view(1, 22, 1, 1).repeat(1, 1, 7, 7)), dim=1)\r\n\r\n\r\n x = F.relu(self.pointwise(x))\r\n x = self.dropout(x)\r\n out = x.view(x.size(0), -1)\r\n\r\n\r\n return out, image_embedding,action_at\r\n\r\n\r\n def a3clstm(self, embedding, prev_hidden_h, prev_hidden_c, action_probs, states_rep, states_memory, actions_memory,\r\n top_k=10):\r\n\r\n embedding = embedding.reshape([1, 1, self.lstm_input_sz])\r\n output, (hx, cx) = self.lstm(embedding, (prev_hidden_h, prev_hidden_c))\r\n x = output.reshape([1, self.hidden_state_sz])\r\n\r\n current_state_rep = F.relu(torch.add(x, self.meta_current_state_embedding(x)))\r\n if not torch.eq(action_probs, 0).all():\r\n last_state_memory = current_state_rep\r\n last_action_memory = F.relu(self.meta_current_action_embedding(action_probs))\r\n if not torch.eq(states_memory, 0).all():\r\n states_memory = torch.cat((states_memory, last_state_memory), dim=0)\r\n actions_memory = torch.cat((actions_memory, last_action_memory), dim=0)\r\n else:\r\n states_memory = last_state_memory\r\n actions_memory = last_action_memory\r\n else:\r\n last_state_memory = None\r\n last_action_memory = None\r\n\r\n attention_state_memory = current_state_rep\r\n for step in range(self.multi_heads):\r\n match_scores = torch.mm(attention_state_memory, states_rep.T)\r\n if top_k is not None and match_scores.shape[1] > top_k:\r\n match_scores, indices_topk = torch.topk(match_scores, top_k, dim=1, sorted=False)\r\n states_memory_topk = torch.squeeze(states_memory[indices_topk, :])\r\n actions_memory_topk = torch.squeeze(actions_memory[indices_topk, :])\r\n else:\r\n states_memory_topk = states_memory\r\n actions_memory_topk = actions_memory\r\n match_scores = self.softmax(match_scores)\r\n attention_state_memory = torch.mm(match_scores, states_memory_topk)\r\n attention_action_memory = torch.mm(match_scores, actions_memory_topk)\r\n attention_memory_step = torch.cat((attention_state_memory, attention_action_memory), dim=1)\r\n if step == 0:\r\n attention_memory = attention_memory_step\r\n else:\r\n attention_memory = attention_memory + attention_memory_step\r\n attention_memory = F.relu(self.meta_memory_embedding(attention_memory))\r\n\r\n meta_state_rep = torch.cat((current_state_rep, attention_memory), dim=1)\r\n meta_state_rep_residual = self.meta_learning_residual_block(meta_state_rep)\r\n meta_state_rep = F.relu(meta_state_rep + meta_state_rep_residual)\r\n meta_action_pred = self.meta_learning_predict(meta_state_rep)\r\n\r\n actor_out = self.actor_linear(x)\r\n critic_out = self.critic_linear_1(x)\r\n critic_out = self.critic_linear_2(critic_out)\r\n\r\n return actor_out, critic_out, (hx, cx), current_state_rep, last_state_memory, last_action_memory, meta_action_pred\r\n\r\n def forward(self, model_input, model_options):\r\n scene = model_input.scene\r\n target_object = model_input.target_object\r\n\r\n state = model_input.state\r\n (hx, cx) = model_input.hidden\r\n\r\n target = model_input.target_class_embedding\r\n action_probs = model_input.action_probs\r\n states_rep = model_input.states_rep\r\n states_memory = model_input.states_memory\r\n action_memory = model_input.action_memory\r\n\r\n x, image_embedding,action_at= self.embedding(state, target, action_probs, scene, target_object)\r\n actor_out, critic_out, (hx, cx), state_rep, state_memory, action_memory, meta_action = self.a3clstm(x, hx, cx, action_probs, states_rep, states_memory, action_memory)\r\n actor_out = torch.mul(actor_out, action_at)\r\n \r\n return ModelOutput(\r\n value=critic_out,\r\n logit=actor_out,\r\n hidden=(hx, cx),\r\n embedding=image_embedding,\r\n state_representation=state_rep,\r\n state_memory=state_memory,\r\n action_memory=action_memory,\r\n meta_action=meta_action,\r\n )\r\n"
] |
[
[
"torch.nn.Softmax",
"torch.max",
"torch.sign",
"torch.cat",
"torch.zeros",
"numpy.max",
"torch.topk",
"torch.nn.init.calculate_gain",
"scipy.sparse.coo_matrix",
"torch.nn.Dropout",
"torch.mm",
"torch.eq",
"scipy.sparse.diags",
"torch.from_numpy",
"torch.tensor",
"torch.nn.functional.relu",
"torch.mul",
"numpy.zeros",
"torch.squeeze",
"torch.nn.Sequential",
"numpy.log",
"numpy.nonzero",
"numpy.min",
"numpy.power",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.functional.pairwise_distance",
"torch.nn.LSTM",
"torch.nn.LayerNorm",
"torch.nn.MaxPool2d",
"torch.nn.ReLU",
"numpy.isinf",
"torch.argmax"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
nkgwer/tensorflow
|
[
"60028072a1c3b4376e145b6fea8e4ccd3324377f",
"60028072a1c3b4376e145b6fea8e4ccd3324377f",
"60028072a1c3b4376e145b6fea8e4ccd3324377f"
] |
[
"tensorflow/python/training/tracking/tracking_test.py",
"tensorflow/python/tpu/tensor_tracer_flags.py",
"tensorflow/python/framework/auto_control_deps_test.py"
] |
[
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nimport os\n\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import wrap_function\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training.tracking import data_structures\nfrom tensorflow.python.training.tracking import tracking\nfrom tensorflow.python.training.tracking import util\nfrom tensorflow.python.util import nest\n\n\ndef run_inside_wrap_function_in_eager_mode(graph_function):\n \"\"\"Decorator to execute the same graph code in eager and graph modes.\n\n In graph mode, we just execute the graph_function passed as argument. In eager\n mode, we wrap the function using wrap_function and then execute the wrapped\n result.\n\n Args:\n graph_function: python function containing graph code to be wrapped\n\n Returns:\n decorated function\n \"\"\"\n def wrap_and_execute(self):\n if context.executing_eagerly():\n wrapped = wrap_function.wrap_function(graph_function, [self])\n # use the wrapped graph function\n wrapped()\n else:\n # use the original function\n graph_function(self)\n return wrap_and_execute\n\n\nclass InterfaceTests(test.TestCase):\n\n def testMultipleAssignment(self):\n root = tracking.AutoTrackable()\n root.leaf = tracking.AutoTrackable()\n root.leaf = root.leaf\n duplicate_name_dep = tracking.AutoTrackable()\n with self.assertRaisesRegex(ValueError, \"already declared\"):\n root._track_trackable(duplicate_name_dep, name=\"leaf\")\n # No error; we're overriding __setattr__, so we can't really stop people\n # from doing this while maintaining backward compatibility.\n root.leaf = duplicate_name_dep\n root._track_trackable(duplicate_name_dep, name=\"leaf\", overwrite=True)\n self.assertIs(duplicate_name_dep, root._lookup_dependency(\"leaf\"))\n (_, dep_object), = root._checkpoint_dependencies\n self.assertIs(duplicate_name_dep, dep_object)\n\n def testRemoveDependency(self):\n root = tracking.AutoTrackable()\n root.a = tracking.AutoTrackable()\n self.assertEqual(1, len(root._checkpoint_dependencies))\n self.assertEqual(1, len(root._unconditional_checkpoint_dependencies))\n self.assertIs(root.a, root._checkpoint_dependencies[0].ref)\n del root.a\n self.assertFalse(hasattr(root, \"a\"))\n self.assertEqual(0, len(root._checkpoint_dependencies))\n self.assertEqual(0, len(root._unconditional_checkpoint_dependencies))\n root.a = tracking.AutoTrackable()\n self.assertEqual(1, len(root._checkpoint_dependencies))\n self.assertEqual(1, len(root._unconditional_checkpoint_dependencies))\n self.assertIs(root.a, root._checkpoint_dependencies[0].ref)\n\n def testListBasic(self):\n a = tracking.AutoTrackable()\n b = tracking.AutoTrackable()\n a.l = [b]\n c = tracking.AutoTrackable()\n a.l.append(c)\n a_deps = util.list_objects(a)\n self.assertIn(b, a_deps)\n self.assertIn(c, a_deps)\n direct_a_dep, = a._checkpoint_dependencies\n self.assertEqual(\"l\", direct_a_dep.name)\n self.assertIn(b, direct_a_dep.ref)\n self.assertIn(c, direct_a_dep.ref)\n\n @test_util.run_in_graph_and_eager_modes\n def testMutationDirtiesList(self):\n a = tracking.AutoTrackable()\n b = tracking.AutoTrackable()\n a.l = [b]\n c = tracking.AutoTrackable()\n a.l.insert(0, c)\n checkpoint = util.Checkpoint(a=a)\n with self.assertRaisesRegex(ValueError, \"A list element was replaced\"):\n checkpoint.save(os.path.join(self.get_temp_dir(), \"ckpt\"))\n\n @test_util.run_in_graph_and_eager_modes\n def testOutOfBandEditDirtiesList(self):\n a = tracking.AutoTrackable()\n b = tracking.AutoTrackable()\n held_reference = [b]\n a.l = held_reference\n c = tracking.AutoTrackable()\n held_reference.append(c)\n checkpoint = util.Checkpoint(a=a)\n with self.assertRaisesRegex(ValueError, \"The wrapped list was modified\"):\n checkpoint.save(os.path.join(self.get_temp_dir(), \"ckpt\"))\n\n @test_util.run_in_graph_and_eager_modes\n def testNestedLists(self):\n a = tracking.AutoTrackable()\n a.l = []\n b = tracking.AutoTrackable()\n a.l.append([b])\n c = tracking.AutoTrackable()\n a.l[0].append(c)\n a_deps = util.list_objects(a)\n self.assertIn(b, a_deps)\n self.assertIn(c, a_deps)\n a.l[0].append(1)\n d = tracking.AutoTrackable()\n a.l[0].append(d)\n a_deps = util.list_objects(a)\n self.assertIn(d, a_deps)\n self.assertIn(b, a_deps)\n self.assertIn(c, a_deps)\n self.assertNotIn(1, a_deps)\n e = tracking.AutoTrackable()\n f = tracking.AutoTrackable()\n a.l1 = [[], [e]]\n a.l1[0].append(f)\n a_deps = util.list_objects(a)\n self.assertIn(e, a_deps)\n self.assertIn(f, a_deps)\n checkpoint = util.Checkpoint(a=a)\n checkpoint.save(os.path.join(self.get_temp_dir(), \"ckpt\"))\n a.l[0].append(data_structures.NoDependency([]))\n a.l[0][-1].append(5)\n checkpoint.save(os.path.join(self.get_temp_dir(), \"ckpt\"))\n # Dirtying the inner list means the root object is unsaveable.\n a.l[0][1] = 2\n with self.assertRaisesRegex(ValueError, \"A list element was replaced\"):\n checkpoint.save(os.path.join(self.get_temp_dir(), \"ckpt\"))\n\n @test_util.run_in_graph_and_eager_modes\n def testAssertions(self):\n a = tracking.AutoTrackable()\n a.l = {\"k\": [np.zeros([2, 2])]}\n self.assertAllEqual(nest.flatten({\"k\": [np.zeros([2, 2])]}),\n nest.flatten(a.l))\n self.assertAllClose({\"k\": [np.zeros([2, 2])]}, a.l)\n nest.map_structure(self.assertAllClose, a.l, {\"k\": [np.zeros([2, 2])]})\n a.tensors = {\"k\": [array_ops.ones([2, 2]), array_ops.zeros([3, 3])]}\n self.assertAllClose({\"k\": [np.ones([2, 2]), np.zeros([3, 3])]},\n self.evaluate(a.tensors))\n\n\nclass _DummyResource(tracking.TrackableResource):\n\n def __init__(self, handle_name):\n self._handle_name = handle_name\n super(_DummyResource, self).__init__()\n\n def _create_resource(self):\n return self._handle_name\n\n\nclass _DummyResource1(tracking.TrackableResource):\n\n def __init__(self, handle_name):\n self._handle_name = handle_name\n self._value = 0\n super(_DummyResource1, self).__init__()\n\n def _create_resource(self):\n return self._handle_name\n\n\nclass ResourceTrackerTest(test.TestCase):\n\n def testBasic(self):\n resource_tracker = tracking.ResourceTracker()\n with tracking.resource_tracker_scope(resource_tracker):\n dummy_resource1 = _DummyResource(\"test1\")\n dummy_resource2 = _DummyResource(\"test2\")\n\n self.assertEqual(2, len(resource_tracker.resources))\n self.assertEqual(\"test1\", resource_tracker.resources[0].resource_handle)\n self.assertEqual(\"test2\", resource_tracker.resources[1].resource_handle)\n\n def testTwoScopes(self):\n resource_tracker1 = tracking.ResourceTracker()\n with tracking.resource_tracker_scope(resource_tracker1):\n dummy_resource1 = _DummyResource(\"test1\")\n\n resource_tracker2 = tracking.ResourceTracker()\n with tracking.resource_tracker_scope(resource_tracker2):\n dummy_resource2 = _DummyResource(\"test2\")\n\n self.assertEqual(1, len(resource_tracker1.resources))\n self.assertEqual(\"test1\", resource_tracker1.resources[0].resource_handle)\n self.assertEqual(1, len(resource_tracker2.resources))\n self.assertEqual(\"test2\", resource_tracker2.resources[0].resource_handle)\n\n def testNestedScopesScopes(self):\n resource_tracker = tracking.ResourceTracker()\n with tracking.resource_tracker_scope(resource_tracker):\n resource_tracker1 = tracking.ResourceTracker()\n with tracking.resource_tracker_scope(resource_tracker1):\n dummy_resource1 = _DummyResource(\"test1\")\n\n resource_tracker2 = tracking.ResourceTracker()\n with tracking.resource_tracker_scope(resource_tracker2):\n dummy_resource2 = _DummyResource(\"test2\")\n\n self.assertEqual(1, len(resource_tracker1.resources))\n self.assertEqual(\"test1\", resource_tracker1.resources[0].resource_handle)\n self.assertEqual(1, len(resource_tracker2.resources))\n self.assertEqual(\"test2\", resource_tracker2.resources[0].resource_handle)\n self.assertEqual(2, len(resource_tracker.resources))\n self.assertEqual(\"test1\", resource_tracker.resources[0].resource_handle)\n self.assertEqual(\"test2\", resource_tracker.resources[1].resource_handle)\n\n\nclass ResourceCreatorScopeTest(test.TestCase):\n\n @test_util.run_in_graph_and_eager_modes\n @run_inside_wrap_function_in_eager_mode\n def testResourceCreator(self):\n def resource_creator_fn(next_creator, *a, **kwargs):\n kwargs[\"handle_name\"] = \"forced_name\"\n return next_creator(*a, **kwargs)\n\n # test that two resource classes use the same creator function\n with ops.resource_creator_scope([\"_DummyResource\", \"_DummyResource1\"],\n resource_creator_fn):\n dummy_0 = _DummyResource(handle_name=\"fake_name_0\")\n dummy_1 = _DummyResource1(handle_name=\"fake_name_1\")\n\n self.assertEqual(dummy_0._handle_name, \"forced_name\")\n self.assertEqual(dummy_1._handle_name, \"forced_name\")\n\n @test_util.run_in_graph_and_eager_modes\n @run_inside_wrap_function_in_eager_mode\n def testResourceCreatorNestingError(self):\n\n def creator(next_creator, *a, **kwargs):\n return next_creator(*a, **kwargs)\n\n # Save the state so we can clean up at the end.\n graph = ops.get_default_graph()\n old_creator_stack = graph._resource_creator_stack[\"_DummyResource\"]\n\n try:\n scope = ops.resource_creator_scope(creator, \"_DummyResource\")\n scope.__enter__()\n with ops.resource_creator_scope(creator, \"_DummyResource\"):\n with self.assertRaises(RuntimeError):\n scope.__exit__(None, None, None)\n finally:\n graph._resource_creator_stack[\"_DummyResource\"] = old_creator_stack\n\n @test_util.run_in_graph_and_eager_modes\n @run_inside_wrap_function_in_eager_mode\n def testResourceCreatorNesting(self):\n\n def resource_creator_fn_0(next_creator, *a, **kwargs):\n instance = next_creator(*a, **kwargs)\n instance._value = 1\n return instance\n\n def resource_creator_fn_1(next_creator, *a, **kwargs):\n kwargs[\"handle_name\"] = \"forced_name1\"\n return next_creator(*a, **kwargs)\n\n with ops.resource_creator_scope([\"_DummyResource1\"], resource_creator_fn_0):\n with ops.resource_creator_scope([\"_DummyResource1\"],\n resource_creator_fn_1):\n dummy_0 = _DummyResource1(handle_name=\"fake_name\")\n\n self.assertEqual(dummy_0._handle_name, \"forced_name1\")\n self.assertEqual(dummy_0._value, 1)\n\n\nif __name__ == \"__main__\":\n test.main()\n",
"# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========================================================================\n\"\"\"Utilities to handle tensor tracer parameters.\"\"\"\n\n\nimport os\nimport os.path\nimport re\n\nfrom tensorflow.python.ops import linalg_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.platform import tf_logging as logging\n\nTRACE_MODE_PART_TENSOR = 'part-tensor'\nTRACE_MODE_FULL_TENSOR = 'full-tensor'\nTRACE_MODE_FULL_TENSOR_SUMMARY = 'full_tensor_summary'\n\nTRACE_MODE_NAN_INF = 'nan-inf'\nTRACE_MODE_NORM = 'norm'\nTRACE_MODE_MAX_ABS = 'max-abs'\nTRACE_MODE_SUMMARY = 'summary'\n# summary mode to collects a finite set of signatures for each traced tensor,\n# (such as norm, max, min, mean) and dumps it using tb summaries.\n\n# Full tensor mode dumps the whole tensor values for the traced tensors without\n# any processing on them; using tb summaries.\n\n_SUBMODE_BRIEF = 'brief'\n_SUBMODE_DETAILED = 'detailed'\n\n_FLAG_SINGLE_QUOTE_PAT = re.compile(r\"\\s*--([^=]+)='([^']*)'\")\n_FLAG_DOUBLE_QUOTE_PAT = re.compile(r'\\s*--([^=]+)=\"([^\"]*)\"')\n_FLAG_NO_QUOTE_PAT = re.compile(r'\\s*--([^=]+)=(\\S*)')\n_FLAG_NO_EQUAL_PAT = re.compile(r'\\s*--([^=]+)\\s*')\n\nFLAGS_ENV_VAR = 'TENSOR_TRACER_FLAGS'\nFLAG_NAME_ENABLE = 'enable'\nFLAG_NAME_TRACE_MODE = 'trace_mode'\nFLAG_NAME_TRACE_SCALAR_OPS = 'trace_scalar'\nFLAG_NAME_SUBMODE = 'submode'\nFLAG_NAME_EXCLUDED_OPNAMES = 'excluded_opnames'\nFLAG_NAME_EXCLUDED_OPTYPES = 'excluded_optypes'\nFLAG_NAME_INCLUDED_OPNAMES = 'included_opnames'\nFLAG_NAME_INCLUDED_OPTYPES = 'included_optypes'\nFLAG_NAME_TRACE_LEVEL = 'trace_level'\nFLAG_NAME_TRACE_DIR = 'trace_dir'\nFLAG_NAME_REPORT_FILE = 'report_file'\nFLAG_NAME_USE_TEST_UNDECLARED_OUTPUTS_DIR = 'use_test_undeclared_outputs_dir'\nFLAG_NAME_OP_RANGE = 'op_range'\n# Folder to dump the pre (before tensor tracer updates) and post graphs (after\n# tensor tracer updates).\nFLAG_NAME_DUMP_BEFORE_AFTER_GRAPHS = 'dump_graphs'\nFLAG_NAME_SUMMARY_SIGNATURES = 'signatures'\nFLAG_NAME_SUMMARY_PER_CORE = 'collect_summary_per_core'\nFLAG_NAME_TEMP_CACHE_VAR = 'use_temp_cache'\nFLAG_NAME_INSPECT_TRACE = 'inspect_trace'\nFLAG_NAME_FINGERPRINT_DIR = 'use_fingerprint_subdirectory'\nFLAG_FLUSH_SUMMARY = 'flush_summaries'\n\n# TODO(ckluk): This summary mode is only meaningful in TTv2. We should move\n# this over to tensor_tracer_v2_flags.py.\n# Flag used in v2 only.\nFLAG_SUMMARY_MODE_TYPE = 'summary_mode'\nUI_MODE = 'ui'\nTEXT_MODE = 'text'\nSAFE_MODE = 'safe'\n\n_OP_RANGE_PAT = re.compile(r'(\\d+):(\\d+)')\n_TEST_UNDECLARED_OUTPUTS_DIR_ENV_VAR = 'TEST_UNDECLARED_OUTPUTS_DIR'\n\n_TT_DEFAULT_TRACE_LEVEL = 3\n_TT_PREFIX = 'tensor_tracer'\n\n_TT_NORM = 'norm'\n_TT_MAX = 'max'\n_TT_MAX_ABS = 'max-abs'\n_TT_MIN = 'min'\n_TT_MEAN = 'mean'\n_TT_VAR = 'var'\n_TT_SIZE = 'size'\n\nTT_SUMMARY_NORM = '%s_%s' % (_TT_PREFIX, _TT_NORM)\nTT_SUMMARY_MAX = '%s_%s' % (_TT_PREFIX, _TT_MAX)\nTT_SUMMARY_MAX_ABS = '%s_%s' % (_TT_PREFIX, _TT_MAX_ABS)\nTT_SUMMARY_MIN = '%s_%s' % (_TT_PREFIX, _TT_MIN)\nTT_SUMMARY_MEAN = '%s_%s' % (_TT_PREFIX, _TT_MEAN)\nTT_SUMMARY_VAR = '%s_%s' % (_TT_PREFIX, _TT_VAR)\nTT_SUMMARY_SIZE = '%s_%s' % (_TT_PREFIX, _TT_SIZE)\n\nTT_SUMMARY_SIGNATURES = (TT_SUMMARY_NORM, TT_SUMMARY_MAX, TT_SUMMARY_MIN,\n TT_SUMMARY_MEAN, TT_SUMMARY_VAR, TT_SUMMARY_SIZE,\n TT_SUMMARY_MAX_ABS)\n\n\nclass TTParameters(object):\n \"\"\"A class that handles the parameters of Tensor Tracer.\"\"\"\n\n def __init__(self, env=None):\n if env:\n self._env = env\n else:\n self._env = os.environ\n self._validate_flag_names()\n self.trace_mode = self._get_trace_mode()\n self.submode = self._get_submode()\n self.trace_dir = self._get_trace_dir()\n self.report_file_path = self._get_report_filepath()\n self.op_range = self._get_op_range()\n self.excluded_opname_re_list = self._flag_value_to_re_list(\n FLAG_NAME_EXCLUDED_OPNAMES)\n self.excluded_optype_re_list = self._flag_value_to_re_list(\n FLAG_NAME_EXCLUDED_OPTYPES)\n\n self.included_opname_re_list = self._flag_value_to_re_list(\n FLAG_NAME_INCLUDED_OPNAMES)\n self.included_optype_re_list = self._flag_value_to_re_list(\n FLAG_NAME_INCLUDED_OPTYPES)\n\n self.trace_scalar_ops = self.is_flag_on(FLAG_NAME_TRACE_SCALAR_OPS)\n self.use_compact_trace = self.trace_mode in (TRACE_MODE_NAN_INF,\n TRACE_MODE_NORM,\n TRACE_MODE_MAX_ABS,\n TRACE_MODE_SUMMARY)\n self.use_temp_cache_var = self.is_flag_on(FLAG_NAME_TEMP_CACHE_VAR)\n self.inspect_trace = self.is_flag_on(FLAG_NAME_INSPECT_TRACE)\n self.use_fingerprint_subdir = self.is_flag_on(FLAG_NAME_FINGERPRINT_DIR)\n\n _, self.graph_dump_path = self.get_flag_value(\n FLAG_NAME_DUMP_BEFORE_AFTER_GRAPHS)\n self.trace_level = self._get_flag_int_value(FLAG_NAME_TRACE_LEVEL,\n _TT_DEFAULT_TRACE_LEVEL)\n self.summary_signatures = self._get_summary_signatures()\n self.collect_summary_per_core = self.is_flag_on(FLAG_NAME_SUMMARY_PER_CORE)\n self.flush_summaries_with_outside_compile = self.is_flag_on(\n FLAG_FLUSH_SUMMARY)\n self.summary_mode = self._get_summary_mode()\n # Do not produce errors or warnings if Tensor Tracer is not enabled.\n if self.is_enabled():\n self._check_flag_errors()\n\n def _check_flag_errors(self):\n if self.trace_mode in (TRACE_MODE_SUMMARY, TRACE_MODE_FULL_TENSOR_SUMMARY):\n if not self.trace_dir:\n raise ValueError('trace_dir must be explicitly provided in '\n 'TENSOR_TRACER_FLAGS when summary mode is used.')\n\n def _get_report_filepath(self):\n \"\"\"Sets the path of the output report file.\"\"\"\n\n found, report_file_path = self.get_flag_value(FLAG_NAME_REPORT_FILE)\n if found and report_file_path and self.use_test_undeclared_outputs_dir():\n if os.path.isabs(report_file_path):\n raise ValueError('If use_test_undeclared_outputs_dir is set,'\n 'report_file_path cannot be an absolute path (%s)'\n %report_file_path)\n outputs_dir = self._env.get(_TEST_UNDECLARED_OUTPUTS_DIR_ENV_VAR)\n report_file_path = os.path.join(outputs_dir, report_file_path)\n return report_file_path\n\n def _get_op_range(self):\n \"\"\"Sets the index range of the Ops that we will consider tracing.\"\"\"\n found, op_range = self.get_flag_value(FLAG_NAME_OP_RANGE)\n if not found or not op_range:\n op_range = (-1, -1) # this means including all ops.\n return op_range\n match = _OP_RANGE_PAT.match(op_range)\n if not match:\n op_range = (-1, -1) # this means including all ops.\n return op_range\n op_range = (int(match.group(1)), int(match.group(2)))\n return op_range\n\n def _get_trace_dir(self):\n found, trace_dir = self.get_flag_value(FLAG_NAME_TRACE_DIR)\n if found and trace_dir and self.use_test_undeclared_outputs_dir():\n raise ValueError(\n 'Cannot not use --%s and --%s at the same time' %\n (FLAG_NAME_TRACE_DIR, FLAG_NAME_USE_TEST_UNDECLARED_OUTPUTS_DIR))\n if self.use_test_undeclared_outputs_dir():\n trace_dir = self._env.get(_TEST_UNDECLARED_OUTPUTS_DIR_ENV_VAR)\n return trace_dir\n\n def _get_trace_mode(self):\n \"\"\"Checks if the given trace mode is valid.\"\"\"\n\n found, trace_mode = self.get_flag_value(FLAG_NAME_TRACE_MODE)\n if not found or not trace_mode:\n trace_mode = TRACE_MODE_NORM\n valid_trace_modes = [\n TRACE_MODE_NAN_INF, TRACE_MODE_PART_TENSOR, TRACE_MODE_FULL_TENSOR,\n TRACE_MODE_NORM, TRACE_MODE_MAX_ABS,\n TRACE_MODE_SUMMARY, TRACE_MODE_FULL_TENSOR_SUMMARY\n ]\n if trace_mode not in valid_trace_modes:\n raise ValueError('Invalid trace mode \"%s\" given to the Tensor_Tracer.'\n 'Valid trace modes are: %s'%(trace_mode,\n valid_trace_modes))\n return trace_mode\n\n def is_brief_mode(self):\n return self.submode == _SUBMODE_BRIEF\n\n def _get_submode(self):\n \"\"\"Checks if the given submode is valid.\"\"\"\n\n found, submode = self.get_flag_value(FLAG_NAME_SUBMODE)\n if not found or not submode:\n submode = _SUBMODE_DETAILED\n if not submode:\n return\n valid_submodes = [_SUBMODE_DETAILED, _SUBMODE_BRIEF]\n if submode not in valid_submodes:\n raise ValueError('Invalid submode \"%s\" given to the Tensor_Tracer.'\n 'Valid submodes are: %s'%(submode,\n valid_submodes))\n return submode\n\n @staticmethod\n def match_next_flag(flags, pos):\n \"\"\"Returns the match for the next TensorTracer flag.\n\n Args:\n flags: a string that contains the flags.\n pos: where in flags to start the search.\n\n Returns:\n A pair where the first element is the regular-expression\n match found and the second element indicates if the match\n has a value.\n \"\"\"\n\n match = _FLAG_DOUBLE_QUOTE_PAT.match(flags, pos)\n if match:\n return match, True\n match = _FLAG_SINGLE_QUOTE_PAT.match(flags, pos)\n if match:\n return match, True\n match = _FLAG_NO_QUOTE_PAT.match(flags, pos)\n if match:\n return match, True\n match = _FLAG_NO_EQUAL_PAT.match(flags, pos)\n if match:\n # The flag is found but is not given a value.\n return match, False\n # The flag is not found.\n return None, False\n\n def _validate_flag_names(self):\n \"\"\"Validates if the TensorTrace flags passed are valid.\"\"\"\n valid_flag_names = [\n FLAG_NAME_ENABLE, FLAG_NAME_TRACE_MODE,\n FLAG_NAME_TRACE_SCALAR_OPS,\n FLAG_NAME_SUBMODE, FLAG_NAME_EXCLUDED_OPNAMES,\n FLAG_NAME_EXCLUDED_OPTYPES, FLAG_NAME_INCLUDED_OPNAMES,\n FLAG_NAME_INCLUDED_OPTYPES, FLAG_NAME_TRACE_DIR,\n FLAG_NAME_REPORT_FILE,\n FLAG_NAME_USE_TEST_UNDECLARED_OUTPUTS_DIR,\n FLAG_NAME_OP_RANGE,\n FLAG_NAME_DUMP_BEFORE_AFTER_GRAPHS, FLAG_NAME_TRACE_LEVEL,\n FLAG_NAME_SUMMARY_SIGNATURES, FLAG_NAME_SUMMARY_PER_CORE,\n FLAG_NAME_TEMP_CACHE_VAR, FLAG_NAME_FINGERPRINT_DIR,\n FLAG_NAME_INSPECT_TRACE, FLAG_FLUSH_SUMMARY, FLAG_SUMMARY_MODE_TYPE\n ]\n tensor_tracer_flags = self._env.get(FLAGS_ENV_VAR)\n if not tensor_tracer_flags:\n return\n pos = 0\n while True:\n match, _ = TTParameters.match_next_flag(tensor_tracer_flags, pos)\n if not match:\n break\n flag_name = match.group(1)\n if flag_name not in valid_flag_names:\n raise ValueError(\n 'The flag name \"%s\" passed via the environment variable \"%s\" '\n 'is invalid. Valid flag names are:'\n '\\n%s' % (flag_name, FLAGS_ENV_VAR, valid_flag_names))\n pos = match.end()\n\n def _supported_signatures(self):\n \"\"\"Returns a tuple of supported signatures.\"\"\"\n return TT_SUMMARY_SIGNATURES\n\n def _get_summary_signatures(self):\n \"\"\"Verifies and returns the summary signatures.\n\n Returns:\n A dictionary of the signature identifiers {signature: index} that will be\n computed when trace_mode is summary.\n \"\"\"\n signatures = self._flag_value_as_list(FLAG_NAME_SUMMARY_SIGNATURES)\n supported_signatures = self._supported_signatures()\n\n tt_signatures = []\n for signature in signatures:\n signature_with_prefix = '%s_%s' % (_TT_PREFIX, signature)\n if signature in supported_signatures:\n tt_signatures.append(signature)\n elif signature_with_prefix in supported_signatures:\n tt_signatures.append(signature_with_prefix)\n else:\n logging.warning('Unknown signature:%s. Supported signatures: %s' %\n (signature, supported_signatures))\n if not tt_signatures:\n # Default case collects norm and max only.\n return {TT_SUMMARY_MAX_ABS: 0, TT_SUMMARY_NORM: 1}\n else:\n return {signature: idx for idx, signature in enumerate(tt_signatures)}\n\n def get_signature_to_agg_fn_map(self):\n \"\"\"Returns a map that contains the aggregate function for each signature.\"\"\"\n return {TRACE_MODE_NORM: linalg_ops.norm,\n TRACE_MODE_MAX_ABS: math_ops.reduce_max,\n TRACE_MODE_NAN_INF: math_ops.reduce_max,\n TT_SUMMARY_NORM: linalg_ops.norm,\n TT_SUMMARY_MAX: math_ops.reduce_max,\n TT_SUMMARY_MAX_ABS:\n lambda t, axis=0: math_ops.reduce_max(math_ops.abs(t), # pylint: disable=g-long-lambda\n axis=axis),\n TT_SUMMARY_MIN: math_ops.reduce_min,\n TT_SUMMARY_MEAN: math_ops.reduce_mean,\n TT_SUMMARY_VAR: math_ops.reduce_max, # Simply reduce max variance.\n TT_SUMMARY_SIZE: math_ops.reduce_sum}\n\n def _flag_value_as_list(self, wanted_flag_name):\n \"\"\"Returns the string list of a TensorTracer flag.\n\n Args:\n wanted_flag_name: the name of the flag we are looking for.\n\n Returns:\n The list value of the flag.\n \"\"\"\n string_value_list = []\n found, flag_value = self.get_flag_value(wanted_flag_name)\n\n if found:\n string_value_list = flag_value.split(',')\n return string_value_list\n\n def _flag_value_as_int_list(self, wanted_flag_name):\n \"\"\"Returns the integer list of a TensorTracer flag.\n\n Args:\n wanted_flag_name: the name of the flag we are looking for.\n\n Returns:\n the value of the flag.\n Raises:\n RuntimeError: If supposedly deadcode is reached.\n \"\"\"\n int_list = []\n found, flag_value = self.get_flag_value(wanted_flag_name)\n\n if found and flag_value:\n try:\n integer_values = flag_value.split(',')\n int_list = [int(int_val) for int_val in integer_values]\n except ValueError:\n logging.warning('Cannot convert %s to int for flag %s', int_list,\n wanted_flag_name)\n return int_list\n\n def _get_flag_int_value(self, wanted_flag_name, default_value):\n \"\"\"Returns the int value of a TensorTracer flag.\n\n Args:\n wanted_flag_name: the name of the flag we are looking for.\n default_value: the default value for the flag, if not provided.\n Returns:\n the value of the flag.\n Raises:\n RuntimeError: If supposedly deadcode is reached.\n \"\"\"\n flag_int_value = default_value\n found, flag_value = self.get_flag_value(wanted_flag_name)\n\n if found:\n try:\n flag_int_value = int(flag_value)\n except ValueError:\n logging.warning('Cannot convert %s to int for flag %s' % (\n flag_int_value, wanted_flag_name))\n return flag_int_value\n\n def get_flag_value(self, wanted_flag_name):\n \"\"\"Returns the value of a TensorTracer flags.\n\n Args:\n wanted_flag_name: the name of the flag we are looking for.\n\n Returns:\n A pair where the first element indicates if the flag is\n found and the second element is the value of the flag.\n\n Raises:\n RuntimeError: If supposedly deadcode is reached.\n \"\"\"\n\n tensor_tracer_flags = self._env.get(FLAGS_ENV_VAR)\n if not tensor_tracer_flags:\n return False, None\n pos = 0\n while True:\n match, has_value = TTParameters.match_next_flag(\n tensor_tracer_flags, pos)\n if not match:\n return False, None\n flag_name = match.group(1)\n if has_value:\n flag_value = match.group(2)\n else:\n flag_value = None\n if flag_name == wanted_flag_name:\n return True, flag_value\n pos = match.end()\n raise RuntimeError('Invalid tensor tracer flag. Could not recognize %s.' %\n flag_name)\n\n def _flag_value_to_re_list(self, flag_name):\n \"\"\"Converts list of strings to compiled RE.\"\"\"\n\n re_list = []\n found, flag_value = self.get_flag_value(flag_name)\n if not found or not flag_value:\n return re_list\n list_of_values = flag_value.split(',')\n for v in list_of_values:\n r = re.compile(v)\n re_list.append(r)\n return re_list\n\n def is_flag_on(self, flag_name):\n \"\"\"Returns True if the given flag is on.\"\"\"\n\n found, flag_value = self.get_flag_value(flag_name)\n if not found:\n return False\n if flag_value is None:\n return True\n # Depends on the flag value.\n flag_value = flag_value.lower()\n enabled = flag_value in ['1', 't', 'true', 'y', 'yes']\n return enabled\n\n def is_enabled(self):\n \"\"\"Returns True if TensorTracer is enabled.\"\"\"\n\n if self.is_flag_on(FLAG_NAME_ENABLE):\n logging.debug('Tensor Tracer is enabled with flags %s.',\n self._env.get(FLAGS_ENV_VAR))\n return True\n else:\n return False\n\n def use_test_undeclared_outputs_dir(self):\n \"\"\"Decides the output directory of the report and trace files.\n\n Args:\n None.\n\n Returns:\n True if the output files should be written to the\n test-undeclared-outputs-directory defined via an\n env variable.\n \"\"\"\n\n return self.is_flag_on(FLAG_NAME_USE_TEST_UNDECLARED_OUTPUTS_DIR)\n\n def _get_summary_mode(self):\n \"\"\"Returns the summary mode after checking if it is valid.\"\"\"\n\n found, summary_mode = self.get_flag_value(FLAG_SUMMARY_MODE_TYPE)\n if not found:\n summary_mode = UI_MODE\n\n valid_summary_modes = [UI_MODE, TEXT_MODE, SAFE_MODE]\n if summary_mode not in valid_summary_modes:\n raise ValueError('Invalid summary mode \"%s\" given to the Tensor_Tracer.'\n 'Valid submodes are: %s'%(summary_mode,\n valid_summary_modes))\n return summary_mode\n",
"# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nimport itertools\n\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.eager import function\nfrom tensorflow.python.framework import auto_control_deps as acd\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gen_resource_variable_ops\nfrom tensorflow.python.ops import gen_sendrecv_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training import adam\nfrom tensorflow.python.training import momentum\n\n\nclass AutomaticControlDependenciesTest(test.TestCase):\n\n def testBasic(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n with acd.AutomaticControlDependencies() as c:\n v.assign(v + 1)\n v.assign(2 * v)\n val = v.read_value()\n val = c.mark_as_return(val)\n self.assertAllEqual(val, 4.0)\n\n def testNoControlDepsBetweenVariableReads(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n with acd.AutomaticControlDependencies():\n read_op1 = gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype).op\n read_op2 = gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype).op\n gen_resource_variable_ops.assign_variable_op(v.handle, v + 1)\n self.assertNotIn(read_op1, read_op2.control_inputs)\n self.assertNotIn(read_op2, read_op1.control_inputs)\n\n def testVariableReadThenWrite(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n with acd.AutomaticControlDependencies():\n read_op1 = gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype).op\n read_op2 = gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype).op\n assign_op = gen_resource_variable_ops.assign_variable_op(\n v.handle, v + 1)\n # Writes should have control deps from \"all\" reads since last write\n # or start of the code block.\n self.assertIn(read_op1, assign_op.control_inputs)\n self.assertIn(read_op2, assign_op.control_inputs)\n # There should be no control deps between reads.\n self.assertNotIn(read_op1, read_op2.control_inputs)\n self.assertNotIn(read_op2, read_op1.control_inputs)\n\n def testVariableWriteThenRead(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n with acd.AutomaticControlDependencies():\n assign_op = gen_resource_variable_ops.assign_variable_op(\n v.handle, v + 1)\n read_op1 = gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype).op\n read_op2 = gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype).op\n # Reads should have a control dep from the last write.\n self.assertIn(assign_op, read_op1.control_inputs)\n self.assertIn(assign_op, read_op2.control_inputs)\n # There should be no control deps between reads.\n self.assertNotIn(read_op1, read_op2.control_inputs)\n self.assertNotIn(read_op2, read_op1.control_inputs)\n\n def testVariableReadsInOpsWithMustRun(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n with acd.AutomaticControlDependencies() as c:\n read_op = gen_resource_variable_ops.read_variable_op(v.handle,\n v.dtype).op\n # Read ops get added to control outputs only if they have consumers.\n c.mark_as_return(read_op.outputs[0])\n self.assertIn(read_op, c.ops_which_must_run)\n\n def testVariableMultipleReadsAndWrites(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n with acd.AutomaticControlDependencies() as c:\n # 2 reads -> 2 writes -> 2 reads -> 2 writes.\n read_op1 = gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype).op\n read_op2 = gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype).op\n assign_op1 = gen_resource_variable_ops.assign_variable_op(\n v.handle, v + 1)\n assign_op2 = gen_resource_variable_ops.assign_variable_op(\n v.handle, v + 1)\n read_op3 = gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype).op\n read_op4 = gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype).op\n assign_op3 = gen_resource_variable_ops.assign_variable_op(\n v.handle, v + 1)\n assign_op4 = gen_resource_variable_ops.assign_variable_op(\n v.handle, v + 1)\n # Read ops get added to control outputs only if they have consumers.\n c.mark_as_return(read_op1.outputs[0])\n c.mark_as_return(read_op2.outputs[0])\n c.mark_as_return(read_op3.outputs[0])\n c.mark_as_return(read_op4.outputs[0])\n\n # Verify the control edges.\n self.assertIn(read_op1, assign_op1.control_inputs)\n self.assertIn(read_op2, assign_op1.control_inputs)\n self.assertIn(assign_op1, assign_op2.control_inputs)\n self.assertIn(assign_op2, read_op3.control_inputs)\n self.assertIn(assign_op2, read_op4.control_inputs)\n self.assertIn(read_op3, assign_op3.control_inputs)\n self.assertIn(read_op4, assign_op3.control_inputs)\n self.assertIn(assign_op3, assign_op4.control_inputs)\n\n # There should be no control deps between reads.\n read_ops = [read_op1, read_op2, read_op3, read_op4]\n for src_op, tgt_op in itertools.product(read_ops, read_ops):\n self.assertNotIn(src_op, tgt_op.control_inputs)\n\n # Reads must be in `ops_which_must_run`.\n self.assertIn(read_op1, c.ops_which_must_run)\n self.assertIn(read_op2, c.ops_which_must_run)\n self.assertIn(read_op3, c.ops_which_must_run)\n self.assertIn(read_op4, c.ops_which_must_run)\n # Last write must be in `ops_which_must_run`.\n self.assertIn(assign_op4, c.ops_which_must_run)\n\n def testSendInOpsWithMustRun(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n with acd.AutomaticControlDependencies() as c:\n send_op = gen_sendrecv_ops.send(v, \"x\", \"/\", 0, \"/\")\n\n # Send must be in `ops_which_must_run`.\n self.assertIn(send_op, c.ops_which_must_run)\n\n def _testVariableReadInFunctionalOp(self, build_functional_op, op_type):\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n\n @def_function.function\n def read_var_in_while():\n gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype, name=\"read1\")\n\n result = build_functional_op(v)\n gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype, name=\"read2\")\n gen_resource_variable_ops.assign_variable_op(v.handle, v + 1)\n return result\n\n func_graph = read_var_in_while.get_concrete_function().graph\n assert len(func_graph.inputs) == 1\n\n def get_op(op_type, sub_name):\n operations = [\n op for op in func_graph.get_operations()\n if op.type == op_type and sub_name in op.name\n ]\n assert len(operations) == 1\n return operations[0]\n\n read1 = get_op(\"ReadVariableOp\", \"read1\")\n functional_op = get_op(op_type, \"\")\n read2 = get_op(\"ReadVariableOp\", \"read2\")\n assign_op = get_op(\"AssignVariableOp\", \"\")\n # Since the functional op only has reads, previous reads e.g. read1 do not\\\n # have a control edge to it and next future reads e.g. read2 do not have a\n # control edge from it.\n self.assertNotIn(read1, functional_op.control_inputs)\n self.assertNotIn(functional_op, read2.control_inputs)\n self.assertIn(read1, assign_op.control_inputs)\n self.assertIn(read2, assign_op.control_inputs)\n self.assertIn(functional_op, assign_op.control_inputs)\n\n def testVariableReadInWhileLoop(self):\n\n def build_functional_op(v):\n\n def body(_):\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n return control_flow_ops.while_loop(\n lambda i: True, body, [0.0], maximum_iterations=1)\n\n self._testVariableReadInFunctionalOp(build_functional_op, \"While\")\n\n def testVariableReadInCondTrueBranch(self):\n\n def build_functional_op(v):\n\n def then_branch():\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n def else_branch():\n return array_ops.zeros([], v.dtype)\n\n return control_flow_ops.cond(\n constant_op.constant(True), then_branch, else_branch)\n\n self._testVariableReadInFunctionalOp(build_functional_op, \"If\")\n\n def testVariableReadInCondFalseBranch(self):\n\n def build_functional_op(v):\n\n def then_branch():\n return array_ops.zeros([], v.dtype)\n\n def else_branch():\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n return control_flow_ops.cond(\n constant_op.constant(False), then_branch, else_branch)\n\n self._testVariableReadInFunctionalOp(build_functional_op, \"If\")\n\n def testVariableReadInCaseBranch0(self):\n\n def build_functional_op(v):\n\n def branch0():\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n def branch1():\n return array_ops.zeros([], v.dtype)\n\n return control_flow_ops.switch_case(\n constant_op.constant(0), [branch0, branch1])\n\n self._testVariableReadInFunctionalOp(build_functional_op, \"Case\")\n\n def testVariableReadInCaseBranch1(self):\n\n def build_functional_op(v):\n\n def branch0():\n return array_ops.zeros([], v.dtype)\n\n def branch1():\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n return control_flow_ops.switch_case(\n constant_op.constant(0), [branch0, branch1])\n\n self._testVariableReadInFunctionalOp(build_functional_op, \"Case\")\n\n def testVariableReadInFunction(self):\n\n def build_functional_op(v):\n\n @def_function.function\n def fn_with_read():\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n return fn_with_read()\n\n self._testVariableReadInFunctionalOp(build_functional_op,\n \"StatefulPartitionedCall\")\n\n def testVariableReadInNestedFunction(self):\n\n def build_functional_op(v):\n\n @def_function.function\n def fn_with_read():\n\n @def_function.function\n def inner_fn():\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n return inner_fn()\n\n return fn_with_read()\n\n self._testVariableReadInFunctionalOp(build_functional_op,\n \"StatefulPartitionedCall\")\n\n def testVariableReadInWhileInInnerFunc(self):\n\n def build_functional_op(v):\n\n @def_function.function\n def fn_with_read():\n\n @def_function.function\n def inner_fn():\n\n def body(_):\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n return control_flow_ops.while_loop(\n lambda i: True, body, [0.0], maximum_iterations=1)\n\n return inner_fn()\n\n return fn_with_read()\n\n self._testVariableReadInFunctionalOp(build_functional_op,\n \"StatefulPartitionedCall\")\n\n def testVariableReadInCondInInnerFunc(self):\n\n def build_functional_op(v):\n\n @def_function.function\n def fn_with_read():\n\n @def_function.function\n def inner_fn():\n\n def then_branch():\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n def else_branch():\n return array_ops.zeros([], v.dtype)\n\n return control_flow_ops.cond(\n constant_op.constant(True), then_branch, else_branch)\n\n return inner_fn()\n\n return fn_with_read()\n\n self._testVariableReadInFunctionalOp(build_functional_op,\n \"StatefulPartitionedCall\")\n\n def _testVariableWriteInFunctionalOp(self, build_functional_op, op_type):\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n\n @def_function.function\n def write_var_in_while():\n gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype, name=\"read1\")\n\n result = build_functional_op(v)\n gen_resource_variable_ops.read_variable_op(\n v.handle, v.dtype, name=\"read2\")\n gen_resource_variable_ops.assign_variable_op(v.handle, v + 1)\n return result\n\n func_graph = write_var_in_while.get_concrete_function().graph\n assert len(func_graph.inputs) == 1\n\n def get_op(op_type, sub_name):\n operations = [\n op for op in func_graph.get_operations()\n if op.type == op_type and sub_name in op.name\n ]\n assert len(operations) == 1\n return operations[0]\n\n read1 = get_op(\"ReadVariableOp\", \"read1\")\n functional_op = get_op(op_type, \"\")\n read2 = get_op(\"ReadVariableOp\", \"read2\")\n assign_op = get_op(\"AssignVariableOp\", \"\")\n # Since the While has writes, it has control edges from previous reads\n # e.g. `read1` and to future reads(`read2`) and writes(`assign_op`).\n self.assertIn(read1, functional_op.control_inputs)\n self.assertIn(functional_op, read2.control_inputs)\n self.assertIn(read2, assign_op.control_inputs)\n self.assertIn(functional_op, assign_op.control_inputs)\n\n def testVariableWriteInWhileLoop(self):\n\n def build_functional_op(v):\n\n def body(_):\n gen_resource_variable_ops.assign_variable_op(v.handle, v + 1)\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n return control_flow_ops.while_loop(\n lambda i: True, body, [0.0], maximum_iterations=1)\n\n self._testVariableWriteInFunctionalOp(build_functional_op, \"While\")\n\n def testVariableWriteInCondTrueBranch(self):\n\n def build_functional_op(v):\n\n def then_branch():\n gen_resource_variable_ops.assign_variable_op(v.handle, v + 1)\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n def else_branch():\n return array_ops.zeros([], v.dtype)\n\n return control_flow_ops.cond(\n constant_op.constant(True), then_branch, else_branch)\n\n self._testVariableWriteInFunctionalOp(build_functional_op, \"If\")\n\n def testVariableWriteInCondFalseBranch(self):\n\n def build_functional_op(v):\n\n def then_branch():\n return array_ops.zeros([], v.dtype)\n\n def else_branch():\n gen_resource_variable_ops.assign_variable_op(v.handle, v + 1)\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n return control_flow_ops.cond(\n constant_op.constant(False), then_branch, else_branch)\n\n self._testVariableWriteInFunctionalOp(build_functional_op, \"If\")\n\n def testVariableWriteInCaseBranch0(self):\n\n def build_functional_op(v):\n\n def branch0():\n gen_resource_variable_ops.assign_variable_op(v.handle, v + 1)\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n def branch1():\n return array_ops.zeros([], v.dtype)\n\n return control_flow_ops.switch_case(\n constant_op.constant(0), [branch0, branch1])\n\n self._testVariableWriteInFunctionalOp(build_functional_op, \"Case\")\n\n def testVariableWriteInCaseBranch1(self):\n\n def build_functional_op(v):\n\n def branch0():\n return array_ops.zeros([], v.dtype)\n\n def branch1():\n gen_resource_variable_ops.assign_variable_op(v.handle, v + 1)\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n return control_flow_ops.switch_case(\n constant_op.constant(0), [branch0, branch1])\n\n self._testVariableWriteInFunctionalOp(build_functional_op, \"Case\")\n\n def testVariableWriteInFunction(self):\n\n def build_functional_op(v):\n\n @def_function.function\n def fn_with_write():\n gen_resource_variable_ops.assign_variable_op(v.handle, v + 1)\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n return fn_with_write()\n\n self._testVariableWriteInFunctionalOp(build_functional_op,\n \"StatefulPartitionedCall\")\n\n def testVariableWriteInNestedFunction(self):\n\n def build_functional_op(v):\n\n @def_function.function\n def fn_with_write():\n\n @def_function.function\n def inner_fn():\n gen_resource_variable_ops.assign_variable_op(v.handle, v + 1)\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n return inner_fn()\n\n return fn_with_write()\n\n self._testVariableWriteInFunctionalOp(build_functional_op,\n \"StatefulPartitionedCall\")\n\n def testVariableWriteInWhileInInnerFunc(self):\n\n def build_functional_op(v):\n\n @def_function.function\n def fn_with_write():\n\n @def_function.function\n def inner_fn():\n\n def body(_):\n gen_resource_variable_ops.assign_variable_op(v.handle, v + 1)\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n return control_flow_ops.while_loop(\n lambda i: True, body, [0.0], maximum_iterations=1)\n\n return inner_fn()\n\n return fn_with_write()\n\n self._testVariableWriteInFunctionalOp(build_functional_op,\n \"StatefulPartitionedCall\")\n\n def testVariableWriteInCondInInnerFunc(self):\n\n def build_functional_op(v):\n\n @def_function.function\n def fn_with_write():\n\n @def_function.function\n def inner_fn():\n\n def then_branch():\n gen_resource_variable_ops.assign_variable_op(v.handle, v + 1)\n return gen_resource_variable_ops.read_variable_op(v.handle, v.dtype)\n\n def else_branch():\n return array_ops.zeros([], v.dtype)\n\n return control_flow_ops.cond(\n constant_op.constant(True), then_branch, else_branch)\n\n return inner_fn()\n\n return fn_with_write()\n\n self._testVariableWriteInFunctionalOp(build_functional_op,\n \"StatefulPartitionedCall\")\n\n @test_util.run_v1_only(\"b/120545219\")\n def testCondMustRun(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n p = array_ops.placeholder(dtype=dtypes.bool)\n with acd.AutomaticControlDependencies() as c:\n\n def true_fn():\n v.assign(v + 1)\n return 0.0\n\n def false_fn():\n v.assign(v + 4)\n return 1.0\n\n control_flow_ops.cond(p, true_fn, false_fn)\n val = v.read_value()\n val = c.mark_as_return(val)\n self.assertAllEqual(val.eval(feed_dict={p: False}), 5.0)\n self.assertAllEqual(val.eval(feed_dict={p: True}), 6.0)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testCondMustRunSeparateRead(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n p = array_ops.placeholder(dtype=dtypes.bool)\n with acd.AutomaticControlDependencies() as c:\n\n def true_fn():\n v.assign(v + 1)\n return 0.0\n\n def false_fn():\n v.assign(v + 4)\n return 1.0\n\n control_flow_ops.cond(p, true_fn, false_fn)\n one = constant_op.constant(1.0)\n one = c.mark_as_return(one)\n one.eval(feed_dict={p: False})\n self.assertAllEqual(v.read_value(), 5.0)\n one.eval(feed_dict={p: True})\n self.assertAllEqual(v.read_value(), 6.0)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testCondNested(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n p = array_ops.placeholder(dtype=dtypes.bool)\n q = array_ops.placeholder(dtype=dtypes.bool)\n with acd.AutomaticControlDependencies() as c:\n\n def true_fn():\n v.assign(v + 1, name=\"true\")\n return 1.0\n\n def false_fn():\n\n def inner_true_fn():\n v.assign(v * 2, name=\"false_true\")\n return 2.0\n\n def inner_false_fn():\n v.assign(v * 3, name=\"false_false\")\n return 3.0\n\n control_flow_ops.cond(q, inner_true_fn, inner_false_fn)\n return 1.0\n\n control_flow_ops.cond(p, true_fn, false_fn)\n with ops.name_scope(\"final\"):\n val = v.read_value()\n val = c.mark_as_return(val)\n self.assertAllEqual(val.eval(feed_dict={p: False, q: False}), 3.0)\n self.assertAllEqual(val.eval(feed_dict={p: False, q: True}), 6.0)\n self.assertAllEqual(val.eval(feed_dict={p: True, q: True}), 7.0)\n self.assertAllEqual(val.eval(feed_dict={p: True, q: False}), 8.0)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testCondOneBranch(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n p = array_ops.placeholder(dtype=dtypes.bool)\n with acd.AutomaticControlDependencies() as c:\n\n def true_fn():\n return 0.0\n\n def false_fn():\n v.assign(v + 4)\n return 1.0\n\n control_flow_ops.cond(p, true_fn, false_fn)\n val = v.read_value()\n val = c.mark_as_return(val)\n self.assertAllEqual(val.eval(feed_dict={p: False}), 5.0)\n self.assertAllEqual(val.eval(feed_dict={p: True}), 5.0)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testCondOneBranchUpdateBefore(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n p = array_ops.placeholder(dtype=dtypes.bool)\n with acd.AutomaticControlDependencies() as c:\n v.assign(v * 2)\n\n def true_fn():\n return 0.0\n\n def false_fn():\n v.assign(v + 4)\n return 1.0\n\n control_flow_ops.cond(p, true_fn, false_fn)\n val = v.read_value()\n val = c.mark_as_return(val)\n self.assertAllEqual(val.eval(feed_dict={p: False}), 6.0)\n self.assertAllEqual(val.eval(feed_dict={p: True}), 12.0)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testCondOneBranchUpdateAfter(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n p = array_ops.placeholder(dtype=dtypes.bool)\n with acd.AutomaticControlDependencies() as c:\n\n def true_fn():\n return 0.0\n\n def false_fn():\n v.assign(v + 4)\n return 1.0\n\n control_flow_ops.cond(p, true_fn, false_fn)\n v.assign(v * 2)\n val = v.read_value()\n val = c.mark_as_return(val)\n self.assertAllEqual(val.eval(feed_dict={p: False}), 10.0)\n self.assertAllEqual(val.eval(feed_dict={p: True}), 20.0)\n\n def testDefunWhileLoopWithCapturedLoopVars(self):\n n = 3\n x = constant_op.constant(list(range(n)))\n\n @function.defun\n def loop():\n c = lambda i, x: i < n\n b = lambda i, x: (i + 1, x + 1)\n i, out = control_flow_ops.while_loop(c, b, (0, x))\n return i, out\n\n i, out = loop()\n self.assertEqual(int(i), 3)\n self.assertAllEqual(out, [3, 4, 5])\n\n def testDecorator(self):\n with context.graph_mode(), self.cached_session():\n v = resource_variable_ops.ResourceVariable(1.0)\n self.evaluate(variables.global_variables_initializer())\n\n @acd.automatic_control_dependencies\n def f():\n v.assign(v + 1)\n v.assign(2 * v)\n return v.read_value()\n\n self.assertAllEqual(f(), 4.0)\n\n def testOptimizerInDefun(self):\n def loss(v):\n return v**2\n\n optimizer = momentum.MomentumOptimizer(learning_rate=1.0, momentum=1.0)\n\n @function.defun\n def train():\n self.v = resource_variable_ops.ResourceVariable(1.0)\n grad = backprop.implicit_grad(loss)(self.v)\n optimizer.apply_gradients(grad)\n return self.v.read_value()\n\n value = train()\n self.assertEqual(value.numpy(), -1.0)\n\n def testReturningNonTensorRaisesError(self):\n optimizer = momentum.MomentumOptimizer(learning_rate=1.0, momentum=1.0)\n optimizer.apply_gradients = function.defun(optimizer.apply_gradients)\n v = resource_variable_ops.ResourceVariable(1.0)\n grad = backprop.implicit_grad(lambda v: v**2)(v)\n\n with self.assertRaisesRegex(TypeError,\n \".*must return zero or more Tensors.*\"):\n # TODO(akshayka): We might want to allow defun-ing Python functions\n # that return operations (and just execute the op instead of running it).\n optimizer.apply_gradients(grad)\n\n # TODO(b/111663004): This should work when the outer context is graph\n # building.\n def testOptimizerNonSlotVarsInDefunNoError(self):\n def loss(v):\n return v**2\n\n optimizer = adam.AdamOptimizer(learning_rate=1.0)\n\n @function.defun\n def train():\n self.v = resource_variable_ops.ResourceVariable(1.0)\n grad = backprop.implicit_grad(loss)(self.v)\n optimizer.apply_gradients(grad)\n return self.v.read_value()\n\n train()\n\n def testOptimizerInDefunWithCapturedVariable(self):\n v = resource_variable_ops.ResourceVariable(1.0)\n def loss():\n return v**2\n\n optimizer = momentum.MomentumOptimizer(learning_rate=1.0, momentum=1.0)\n\n @function.defun\n def train():\n grad = backprop.implicit_grad(loss)()\n optimizer.apply_gradients(grad)\n\n train()\n self.assertEqual(v.numpy(), -1.0)\n\n def testRepeatedResourceInput(self):\n var = resource_variable_ops.ResourceVariable(1.0)\n\n @def_function.function\n def inner(var1, var2):\n return (resource_variable_ops.read_variable_op(var1, dtypes.float32) +\n resource_variable_ops.read_variable_op(var2, dtypes.float32))\n\n @def_function.function\n def outer():\n return inner(var.handle, var.handle)\n\n self.assertEqual(self.evaluate(outer()), 2.0)\n\n\nif __name__ == \"__main__\":\n ops.enable_eager_execution()\n test.main()\n"
] |
[
[
"tensorflow.python.framework.ops.resource_creator_scope",
"tensorflow.python.training.tracking.util.list_objects",
"tensorflow.python.training.tracking.tracking.AutoTrackable",
"tensorflow.python.training.tracking.data_structures.NoDependency",
"tensorflow.python.training.tracking.tracking.ResourceTracker",
"numpy.ones",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.training.tracking.tracking.resource_tracker_scope",
"tensorflow.python.eager.wrap_function.wrap_function",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.platform.test.main",
"numpy.zeros",
"tensorflow.python.ops.array_ops.ones",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.training.tracking.util.Checkpoint",
"tensorflow.python.util.nest.flatten"
],
[
"tensorflow.python.platform.tf_logging.warning",
"tensorflow.python.ops.math_ops.abs"
],
[
"tensorflow.python.ops.gen_resource_variable_ops.assign_variable_op",
"tensorflow.python.training.momentum.MomentumOptimizer",
"tensorflow.python.ops.control_flow_ops.while_loop",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.ops.control_flow_ops.cond",
"tensorflow.python.framework.ops.enable_eager_execution",
"tensorflow.python.framework.auto_control_deps.AutomaticControlDependencies",
"tensorflow.python.framework.test_util.run_v1_only",
"tensorflow.python.ops.resource_variable_ops.ResourceVariable",
"tensorflow.python.platform.test.main",
"tensorflow.python.eager.context.graph_mode",
"tensorflow.python.ops.gen_sendrecv_ops.send",
"tensorflow.python.eager.backprop.implicit_grad",
"tensorflow.python.eager.function.defun",
"tensorflow.python.training.adam.AdamOptimizer",
"tensorflow.python.ops.resource_variable_ops.read_variable_op",
"tensorflow.python.ops.gen_resource_variable_ops.read_variable_op",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.ops.variables.global_variables_initializer",
"tensorflow.python.framework.constant_op.constant"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"1.12",
"2.7",
"2.6",
"1.4",
"1.13",
"2.3",
"2.4",
"2.9",
"1.5",
"1.7",
"2.5",
"2.2",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"2.7",
"2.6",
"2.4",
"2.3",
"2.9",
"2.5",
"2.2",
"2.10"
]
}
] |
Mickey253/spherical-mds
|
[
"5c96f5ec0273233ac81adcd90a39ec35cfc83557"
] |
[
"experiments.py"
] |
[
"import numpy as np\nimport graph_tool.all as gt\nfrom graph_functions import apsp,sphere_stress, distortion\nfrom graph_io import write_to_json\nfrom SGD_MDS_sphere import SMDS\nfrom HMDS import HMDS\nfrom SGD_MDS2 import SGD\nimport pylab\nimport s_gd2\n\nsin,cos, acos, sqrt = np.sin, np.cos, np.arccos, np.sqrt\nacosh, cosh, sinh = np.arccosh, np.cosh, np.sinh\n\nsphere_geo = lambda x1,x2: acos( sin(x1[0])*sin(x2[0]) + cos(x1[0])*cos(x2[0])*cos(x1[1]-x2[1]) )\nhyper_geo = lambda u,v: acosh( cosh(u[1])*cosh(v[0]-u[0])*cosh(v[1]) - sinh(u[1])*sinh(v[1]) )\neuclid_geo = lambda u,v: np.linalg.norm(u-v)\n\ndef stress_curve():\n #G = gt.load_graph(\"graphs/can_96.dot\")\n G = gt.load_graph_from_csv(\"exp_graphs/cube.txt\",hashed=False)\n print(G.num_vertices())\n\n paths,graphs = exp_graphs()\n paths = paths\n\n cap = [0.05,0.1,0.15,0.2,0.3]\n for c in cap:\n stresses = np.zeros(60)\n for g in paths:\n G = gt.load_graph_from_csv(g,hashed=False)\n d = apsp(G)\n Xs,rs = SMDS(d,scale_heuristic=True).solve(num_iter=60,debug=True,cap=c,epsilon=1e-9,schedule='convergent')\n stresses += np.array([sphere_stress(X,d,r) for X,r in zip(Xs,rs)])\n stresses /= 10\n pylab.plot(np.arange(len(stresses)),stresses,label=\"Upper bound: {}\".format(c))\n# write_to_json(G,Xs[-1])\n #print(rs)\n\n pylab.xlabel(\"Iteration\")\n pylab.ylabel(\"Stress\")\n pylab.suptitle(\"Average stress over benchmark graphs\")\n pylab.legend()\n pylab.savefig('figs/upperbound_full.png')\n\ndef learning_rate(num_iter):\n\n rates = ['fixed', 'convergent', 'geometric', 'sqrt']\n paths, graphs = exp_graphs()\n\n data = np.empty( (0,60) )\n\n for i,(path,graph) in enumerate(zip(paths,graphs)):\n G = gt.load_graph_from_csv(path,hashed=False)\n print(G.num_vertices())\n d = apsp(G)\n\n stress_rate = np.zeros( (4,num_iter) )\n for j,rate in enumerate(rates):\n for k in range(5):\n Xs,rs = SMDS(d,scale_heuristic=True).solve(num_iter=num_iter,schedule=rate,debug=True,cap=0.1)\n stress_rate[j] += np.array([sphere_stress(X,d,r) for X,r in zip(Xs,rs)])\n stress_rate[j] /= 5\n pylab.plot(np.arange(stress_rate[j].shape[0]), stress_rate[j], label=rate)\n\n pylab.suptitle(\"Stress over iterations for different learning rates \\n Graph: {}\".format(graph))\n pylab.legend()\n pylab.yscale('log')\n pylab.savefig('figs/learning_rate/{}.png'.format(graph))\n pylab.clf()\n data = np.append(data,stress_rate,axis=0)\n\n np.savetxt('data/learning_rate_exp.txt',data,delimiter=',')\n\n\ndef euclid_compare(n=5):\n paths, graphs = exp_graphs()\n\n data = np.zeros( (len(paths),n) )\n\n for i ,(path,graph) in enumerate(zip(paths,graphs)):\n for j in range(n):\n G = gt.load_graph_from_csv(path,hashed=False)\n d = apsp(G)\n E = np.loadtxt(path,delimiter=',').astype(np.int32)\n u,v = E[:,0], E[:,1]\n\n X = s_gd2.layout_convergent(u,v)\n pos = G.new_vp('vector<float>')\n pos.set_2d_array(X.T)\n gt.graph_draw(G,pos=pos,output='sgd_drawings/{}.png'.format(graph))\n\n data[i,j] = distortion(X,d)\n np.savetxt('data/euclid_distortions.txt',data,delimiter=',')\n\ndef spherical_compare(n=5):\n paths, graphs = exp_graphs()\n\n data = np.zeros( (len(paths),n) )\n\n for i ,(path,graph) in enumerate(zip(paths,graphs)):\n for j in range(n):\n G = gt.load_graph_from_csv(path,hashed=False)\n d = apsp(G)\n\n X = SMDS(d,scale_heuristic=True).solve(epsilon=1e-9)\n write_to_json(G,X,fname='webapp/exp_drawings/{}.js'.format(graph))\n\n data[i,j] = distortion(X,d,sphere_geo)\n np.savetxt('data/spherical_distortions.txt',data,delimiter=',')\n\ndef hyperbolic_compare(n=5):\n paths, graphs = exp_graphs()\n\n data = np.zeros( (len(paths),n) )\n\n for i ,(path,graph) in enumerate(zip(paths,graphs)):\n print()\n print(i)\n print()\n for j in range(n):\n print(j)\n G = gt.load_graph_from_csv(path,hashed=False)\n d = apsp(G)\n\n X = HMDS(d).solve()\n #write_to_json(G,X,fname='webapp/exp_drawings/{}.js'.format(graph))\n\n data[i,j] = distortion(X,d,hyper_geo)\n print(data[i,j])\n np.savetxt('data/hyperbolic_distortions2.txt',data,delimiter=',')\n\n\ndef exp_graphs():\n\n import os\n\n path = 'exp_graphs/'\n graph_paths = os.listdir(path)\n\n Gs = np.array([gt.load_graph_from_csv(path+graph,hashed=False).num_vertices() for graph in graph_paths])\n ind = np.argsort(Gs)\n graph_paths = [graph_paths[i] for i in ind]\n\n graph_paths_fmt = [x for x in map(lambda s: s.split('.')[0], graph_paths) ]\n return [path+graph for graph in graph_paths], graph_paths_fmt\n\ndef mnist():\n Y = np.loadtxt('mnist/mnist2500_X.txt')\n labels = np.loadtxt('mnist/mnist2500_labels.txt').astype(np.int64)\n\n Y = Y[:1200,:]\n labels = labels[:1200]\n\n from sklearn.metrics import pairwise_distances\n d = pairwise_distances(Y)\n X = SMDS(d,scale_heuristic=True).solve(epsilon=1e-9)\n\n G = gt.Graph(directed=False)\n G.add_vertex(n=labels.shape[0])\n names = G.new_vertex_property('string')\n for v in G.iter_vertices(): names[v] = labels[v]\n\n write_to_json(G,X,name_map=names,classes = list(labels))\n\ndef scale_curve(n=5):\n G = gt.price_network(20,directed=False)\n d = apsp(G)\n print(d.max())\n\n y = np.linspace(0.01,5,100)\n data_E = np.zeros( (len(y), 2) )\n data_S = np.zeros( (len(y), 2) )\n data_H = np.zeros( (len(y), 2) )\n\n for i,a in enumerate(y):\n print(a)\n e_dist,s_dist,h_dist = 0,0,0\n for _ in range(n):\n X_E = SGD(a*d,weighted=False).solve()\n X_S = SMDS(a*d,scale_heuristic=False).solve(epsilon=1e-9)\n X_H = HMDS(a*d).solve()\n\n e_dist += distortion(X_E,a*d, lambda x1,x2: np.linalg.norm(x1-x2))\n s_dist += distortion(X_S,a*d, sphere_geo)\n h_dist += distortion(X_H,a*d, hyper_geo)\n\n e_dist /= n\n s_dist /= n\n h_dist /= n\n\n data_E[i] = [a, e_dist]\n data_S[i] = [a, s_dist]\n data_H[i] = [a, h_dist]\n\n pylab.suptitle(\"Scalar factor of tree graph\")\n pylab.plot(data_E[:,0],data_E[:,1],label=\"Euclidean MDS\")\n pylab.plot(data_S[:,0],data_S[:,1],label=\"Spherical MDS\")\n pylab.plot(data_H[:,0],data_H[:,1],label=\"Hyperbolic MDS\")\n pylab.xlabel('scale factor')\n pylab.ylabel('distortion')\n pylab.legend()\n pylab.ylim(0,1)\n pylab.show()\n\n return d.max()\n\n\n\nif __name__ == \"__main__\":\n hyperbolic_compare()\n"
] |
[
[
"sklearn.metrics.pairwise_distances",
"numpy.linspace",
"numpy.arange",
"numpy.linalg.norm",
"numpy.empty",
"numpy.append",
"numpy.savetxt",
"numpy.argsort",
"numpy.zeros",
"numpy.loadtxt"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AllisonShen/MalConv-Pytorch
|
[
"08f2a00890fcf5ec11e455bf949741ea845a24f5"
] |
[
"hexcnn_train.py"
] |
[
"# coding: utf-8\nimport os\nimport time\nimport sys\nimport yaml\nimport numpy as np\nimport pandas as pd\nfrom src.util import HexDumpDataset,write_pred\nfrom src.cnn_model import CNN_Model\nfrom torch.utils.data import DataLoader\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom torch.utils.data import WeightedRandomSampler\n\n\n# Load config file for experiment\ntry:\n config_path = sys.argv[1]\n seed = int(sys.argv[2])\n conf = yaml.load(open(config_path,'r'))\nexcept:\n print('Usage: python3 run_exp.py <config file path> <seed>')\n sys.exit()\n\n\nexp_name = conf['exp_name']+'_sdhex_'+str(seed)\nprint('Experiment:')\nprint('\\t',exp_name)\n\nnp.random.seed(seed)\ntorch.manual_seed(seed)\n\ntrain_data_path = conf['train_data_path']\ntrain_label_path = conf['train_label_path']\n\nvalid_data_path = conf['valid_data_path']\nvalid_label_path = conf['valid_label_path']\n\nlog_dir = conf['log_dir']\npred_dir = conf['pred_dir']\ncheckpoint_dir = conf['checkpoint_dir']\n\n\nlog_file_path = log_dir+exp_name+'.log'\nchkpt_acc_path = checkpoint_dir+exp_name+'.model'\npred_path = pred_dir+exp_name+'.pred'\n\n# Parameters\nuse_gpu = conf['use_gpu']\nuse_cpu = conf['use_cpu']\nlearning_rate = conf['learning_rate']\nmax_step = conf['max_step']\ntest_step = conf['test_step']\nbatch_size = conf['batch_size']\nfirst_n_byte = conf['first_n_byte']\nwindow_size = conf['window_size']\ndisplay_step = conf['display_step']\n\nsample_cnt = conf['sample_cnt']\n\n\n# Load Ground Truth.\ntr_label_table = pd.read_csv(train_label_path,header=None,index_col=0)\ntr_label_table.index=tr_label_table.index.str.upper()\ntr_label_table = tr_label_table.rename(columns={1:'ground_truth'})\nval_label_table = pd.read_csv(valid_label_path,header=None,index_col=0)\nval_label_table.index=val_label_table.index.str.upper()\nval_label_table = val_label_table.rename(columns={1:'ground_truth'})\n\n\n# Merge Tables and remove duplicate\ntr_table = tr_label_table.groupby(level=0).last()\ndel tr_label_table\nval_table = val_label_table.groupby(level=0).last()\ndel val_label_table\ntr_table = tr_table.drop(val_table.index.join(tr_table.index, how='inner'))\n\nprint('Training Set:')\nprint('\\tTotal',len(tr_table),'files')\nprint('\\tMalware Count :',tr_table['ground_truth'].value_counts()[1])\nprint('\\tGoodware Count:',tr_table['ground_truth'].value_counts()[0])\n\n\nprint('Validation Set:')\nprint('\\tTotal',len(val_table),'files')\nprint('\\tMalware Count :',val_table['ground_truth'].value_counts()[1])\nprint('\\tGoodware Count:',val_table['ground_truth'].value_counts()[0])\n\nif sample_cnt != 1:\n tr_table = tr_table.sample(n=sample_cnt,random_state=seed)\n\ntrainratio = np.bincount(tr_table['ground_truth'])\nclasscount = trainratio.tolist()\ntrain_weights = 1./torch.tensor(classcount, dtype=torch.float)\ntrain_sampleweights = train_weights[tr_table['ground_truth']]\ntrain_sampler = WeightedRandomSampler(weights=train_sampleweights, \nnum_samples = len(train_sampleweights))\n\ndataloader = DataLoader(HexDumpDataset(list(tr_table.index), train_data_path, list(tr_table.ground_truth),first_n_byte),\n batch_size=batch_size, num_workers=use_cpu, sampler=train_sampler)\nvalidloader = DataLoader(HexDumpDataset(list(val_table.index), valid_data_path, list(val_table.ground_truth),first_n_byte),\n batch_size=batch_size, shuffle=False, num_workers=use_cpu)\n\nvalid_idx = list(val_table.index)\ndel tr_table\ndel val_table\n\n\nmalconv = CNN_Model(input_length=first_n_byte,window_size=window_size)\n\nif os.path.isfile(chkpt_acc_path):\n malconv = torch.load(chkpt_acc_path)\n\nbce_loss = nn.BCEWithLogitsLoss()\nadam_optim = optim.Adam([{'params':malconv.parameters()}],lr=learning_rate, weight_decay=0.3)\nsigmoid = nn.Sigmoid()\n\nif use_gpu:\n malconv = malconv.cuda()\n bce_loss = bce_loss.cuda()\n sigmoid = sigmoid.cuda()\n\n\nstep_msg = 'step-{}-loss-{:.6f}-acc-{:.4f}-time-{:.2f}'\nvalid_msg = 'step-{}-tr_loss-{:.6f}-tr_acc-{:.4f}-val_loss-{:.6f}-val_acc-{:.4f}'\nlog_msg = '{}, {:.6f}, {:.4f}, {:.6f}, {:.4f}, {:.2f}'\nhistory = {}\nhistory['tr_loss'] = []\nhistory['tr_acc'] = []\n\nlog = open(log_file_path,'w')\nlog.write('step,tr_loss, tr_acc, val_loss, val_acc, time\\n')\n\nvalid_best_acc = 0.0\nvalid_best_precision = 0.0\nvalid_best_recall = 0.0\nvalid_best_f1 = 0.0\nvalid_best_fpr = 0.0\nvalid_best_fnr = 0.0\n\n\n\ntotal_step = 0\nstep_cost_time = 0\n\nPATIENCE = 60\n\nlocal_patience = PATIENCE\nwhile total_step < max_step:\n \n # Training \n for step,batch_data in enumerate(dataloader):\n start = time.time()\n \n adam_optim.zero_grad()\n \n cur_batch_size = batch_data[0].size(0)\n\n exe_input = batch_data[0].cuda() if use_gpu else batch_data[0]\n exe_input = Variable(exe_input.long(),requires_grad=False)\n \n label = batch_data[1].cuda() if use_gpu else batch_data[1]\n label = Variable(label.float(),requires_grad=False)\n \n pred = malconv(exe_input)\n loss = bce_loss(pred,label)\n loss.backward()\n adam_optim.step()\n history['tr_loss'].append(loss.cpu().data.numpy())\n # history['tr_loss'].append(loss.cpu().data.numpy()[0])\n history['tr_acc'].extend(list(label.cpu().data.numpy().astype(int)==(sigmoid(pred).cpu().data.numpy()+0.5).astype(int)))\n \n step_cost_time = time.time()-start\n \n if (step+1)%display_step == 0:\n print(step_msg.format(total_step,np.mean(history['tr_loss']),\n np.mean(history['tr_acc']),step_cost_time),end='\\r',flush=True)\n total_step += 1\n\n # Interupt for validation\n if total_step%test_step ==0:\n break\n \n \n # Testing\n history['val_loss'] = []\n history['val_acc'] = []\n history['val_pred'] = []\n\n # other evaluation metrics..\n tp = 0\n tn = 0\n fp = 0\n fn = 0\n \n for _,val_batch_data in enumerate(validloader):\n cur_batch_size = val_batch_data[0].size(0)\n\n exe_input = val_batch_data[0].cuda() if use_gpu else val_batch_data[0]\n exe_input = Variable(exe_input.long(),requires_grad=False)\n\n label = val_batch_data[1].cuda() if use_gpu else val_batch_data[1]\n label = Variable(label.float(),requires_grad=False)\n\n pred = malconv(exe_input)\n loss = bce_loss(pred,label)\n \n y_trues = list(label.cpu().data.numpy().astype(int))\n y_preds = list((sigmoid(pred).cpu().data.numpy()+0.5).astype(int))\n\n for y_true, y_pred in zip(y_trues, y_preds):\n if y_true == 1:\n if y_true == y_pred:\n tp = tp + 1\n else:\n fn = fn + 1\n else:\n if y_true == y_pred:\n tn = tn + 1\n else:\n fp = fp + 1\n\n history['val_loss'].append(loss.cpu().data.numpy())\n # history['val_loss'].append(loss.cpu().data.numpy()[0])\n history['val_acc'].extend(list(label.cpu().data.numpy().astype(int)==(sigmoid(pred).cpu().data.numpy()+0.5).astype(int)))\n history['val_pred'].append(list(sigmoid(pred).cpu().data.numpy()))\n\n print(log_msg.format(total_step, np.mean(history['tr_loss']), np.mean(history['tr_acc']),\n np.mean(history['val_loss']), np.mean(history['val_acc']),step_cost_time),\n file=log,flush=True)\n \n print(valid_msg.format(total_step,np.mean(history['tr_loss']),np.mean(history['tr_acc']),\n np.mean(history['val_loss']),np.mean(history['val_acc'])))\n\n precision = tp / (tp + fp + 1e-6)\n recall = tp / (tp + fn + 1e-6) # true positive rate\n f1 = 2*precision*recall / (precision + recall + 1e-6)\n fpr = fp / (fp + tn + 1e-6)\n fnr = fn / (fn + tp + 1e-6)\n\n print(f\"Precision: {precision:.2f}, Recall: {recall:.2f}, F1: {f1:.2f}, FPR: {fpr:.2f}, FNR: {fnr:.2f}\")\n\n \n if (valid_best_f1 <= f1):\n local_patience = PATIENCE\n\n valid_best_acc = np.mean(history['val_acc'])\n valid_best_precision = precision\n valid_best_recall = recall\n valid_best_fnr = fnr\n valid_best_fpr = fpr\n valid_best_f1 = f1\n\n torch.save(malconv,chkpt_acc_path)\n print('Checkpoint saved at',chkpt_acc_path)\n write_pred(history['val_pred'],valid_idx,pred_path)\n print('Prediction saved at', pred_path)\n else:\n local_patience = local_patience - 1\n if local_patience < 0:\n break\n\n history['tr_loss'] = []\n history['tr_acc'] = []\n\nprint(\"==============================END OF TRAINING======================================\")\nprint(f\"Accuracy: {valid_best_acc:.2f}, Precision: {valid_best_precision:.2f}, Recall: {valid_best_recall:.2f}, F1: {valid_best_f1:.2f}, FPR: {valid_best_fpr:.2f}, FNR: {valid_best_fnr:.2f}\")\n\n"
] |
[
[
"pandas.read_csv",
"numpy.random.seed",
"torch.load",
"torch.manual_seed",
"torch.nn.Sigmoid",
"torch.tensor",
"torch.nn.BCEWithLogitsLoss",
"numpy.mean",
"numpy.bincount",
"torch.save"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
sparsh-ai/recohut
|
[
"4121f665761ffe38c9b6337eaa9293b26bee2376",
"4121f665761ffe38c9b6337eaa9293b26bee2376",
"4121f665761ffe38c9b6337eaa9293b26bee2376",
"4121f665761ffe38c9b6337eaa9293b26bee2376",
"4121f665761ffe38c9b6337eaa9293b26bee2376",
"4121f665761ffe38c9b6337eaa9293b26bee2376"
] |
[
"recohut/datasets/movielens.py",
"recohut/models/ccpm.py",
"recohut/utils/data.py",
"recohut/visualization/eda.py",
"recohut/models/narm.py",
"recohut/models/dcn.py"
] |
[
"# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/datasets/datasets.movielens.ipynb (unless otherwise specified).\n\n__all__ = ['ML1mDataset', 'ML1mDataModule', 'ML1mDataset_v2', 'ML1mDataModule_v2', 'ML1mDataset_v3',\n 'ML1mDataModule_v3', 'ML1mDataset_v4', 'ML100kDataset', 'sparseFeature', 'create_ml_1m_dataset',\n 'create_implicit_ml_1m_dataset']\n\n# Cell\nfrom typing import Any, Iterable, List, Optional, Tuple, Union, Callable\nimport os\nimport json\n\nimport pandas as pd\nimport numpy as np\n\nimport torch\n\nfrom ..utils.common_utils import *\nfrom .bases.common import Dataset\nfrom .bases.interactions import InteractionsDataset, InteractionsDataModule\nfrom .bases.sequential import SequentialDataset, SequentialDataModule\nfrom ..utils.splitting import stratified_split_v2\n\n# Cell\nclass ML1mDataset(InteractionsDataset):\n url = \"http://files.grouplens.org/datasets/movielens/ml-1m.zip\"\n\n @property\n def raw_file_names(self):\n return 'ratings.dat'\n\n def download(self):\n path = download_url(self.url, self.raw_dir)\n extract_zip(path, self.raw_dir)\n from shutil import move, rmtree\n move(os.path.join(self.raw_dir, 'ml-1m', self.raw_file_names), self.raw_dir)\n rmtree(os.path.join(self.raw_dir, 'ml-1m'))\n os.unlink(path)\n\n def load_ratings_df(self):\n df = pd.read_csv(self.raw_paths[0], sep='::', header=None, engine='python')\n df.columns = ['uid', 'sid', 'rating', 'timestamp']\n # drop duplicate user-item pair records, keeping recent ratings only\n df.drop_duplicates(subset=['uid', 'sid'], keep='last', inplace=True)\n return df\n\n# Cell\nclass ML1mDataModule(InteractionsDataModule):\n dataset_cls = ML1mDataset\n\n# Cell\nclass ML1mDataset_v2(SequentialDataset):\n url = \"http://files.grouplens.org/datasets/movielens/ml-1m.zip\"\n\n @property\n def raw_file_names(self):\n return 'ratings.dat'\n\n def download(self):\n path = download_url(self.url, self.raw_dir)\n extract_zip(path, self.raw_dir)\n from shutil import move, rmtree\n move(os.path.join(self.raw_dir, 'ml-1m', self.raw_file_names), self.raw_dir)\n rmtree(os.path.join(self.raw_dir, 'ml-1m'))\n os.unlink(path)\n\n def load_ratings_df(self):\n df = pd.read_csv(self.raw_paths[0], sep='::', header=None, engine='python')\n df.columns = ['uid', 'sid', 'rating', 'timestamp']\n return df\n\n# Cell\nclass ML1mDataModule_v2(SequentialDataModule):\n dataset_cls = ML1mDataset_v2\n\n# Cell\nclass ML1mDataset_v3(SequentialDataset):\n url = \"http://files.grouplens.org/datasets/movielens/ml-1m.zip\"\n\n def __init__(self, data_dir, data_type='train', *args, **kwargs):\n super().__init__(data_dir, data_type, *args, **kwargs)\n if data_type == 'train':\n self.ratings_frame = pd.read_csv(self.processed_paths[0], delimiter=\",\")\n elif data_type == 'valid':\n self.ratings_frame = pd.read_csv(self.processed_paths[1], delimiter=\",\")\n elif data_type == 'test':\n self.ratings_frame = pd.read_csv(self.processed_paths[2], delimiter=\",\")\n\n @property\n def raw_file_names(self):\n return ['ratings.dat', 'movies.dat', 'users.dat']\n\n @property\n def processed_file_names(self):\n return ['train.csv', 'valid.csv', 'test.csv']\n\n def download(self):\n path = download_url(self.url, self.raw_dir)\n extract_zip(path, self.raw_dir)\n from shutil import move, rmtree\n for raw_file_name in self.raw_file_names:\n move(os.path.join(self.raw_dir, 'ml-1m', raw_file_name), self.raw_dir)\n rmtree(os.path.join(self.raw_dir, 'ml-1m'))\n os.unlink(path)\n\n def load_ratings_df(self):\n df = pd.read_csv(self.raw_paths[0], sep='::', header=None, engine='python')\n df.columns = ['uid', 'sid', 'rating', 'timestamp']\n return df\n\n def load_movies_df(self):\n df = pd.read_csv(self.raw_paths[1], sep='::', header=None, engine='python')\n df.columns = [\"sid\", \"title\", \"genres\"]\n return df\n\n def load_users_df(self):\n df = pd.read_csv(self.raw_paths[2], sep='::', header=None, engine='python')\n df.columns = [\"uid\", \"sex\", \"age_group\", \"occupation\", \"zip_code\"]\n return df\n\n def process(self):\n ## movies\n movies = self.load_movies_df()\n movies[\"year\"] = movies[\"title\"].apply(lambda x: x[-5:-1])\n movies.year = pd.Categorical(movies.year)\n movies[\"year\"] = movies.year.cat.codes\n movies[\"sid\"] = movies[\"sid\"].astype(str)\n\n genres = [\"Action\",\"Adventure\",\"Animation\",\"Children's\",\"Comedy\",\"Crime\",\n \"Documentary\",\"Drama\",\"Fantasy\",\"Film-Noir\",\"Horror\",\"Musical\",\n \"Mystery\",\"Romance\",\"Sci-Fi\",\"Thriller\",\"War\",\"Western\"]\n\n for genre in genres:\n movies[genre] = movies[\"genres\"].apply(\n lambda values: int(genre in values.split(\"|\"))\n )\n\n ## users\n users = self.load_users_df()\n users.sex = pd.Categorical(users.sex)\n users[\"sex\"] = users.sex.cat.codes\n users.age_group = pd.Categorical(users.age_group)\n users[\"age_group\"] = users.age_group.cat.codes\n users.occupation = pd.Categorical(users.occupation)\n users[\"occupation\"] = users.occupation.cat.codes\n users.zip_code = pd.Categorical(users.zip_code)\n users[\"zip_code\"] = users.zip_code.cat.codes\n users[\"uid\"] = users[\"uid\"].astype(str)\n\n # ratings\n ratings = self.load_ratings_df()\n ratings['timestamp'] = pd.to_datetime(ratings['timestamp'], unit='s')\n ratings[\"sid\"] = ratings[\"sid\"].astype(str)\n ratings[\"uid\"] = ratings[\"uid\"].astype(str)\n\n # Transform the movie ratings data into sequences\n # First, let's sort the the ratings data using the unix_timestamp,\n # and then group the movie_id values and the rating values by user_id.\n # The output DataFrame will have a record for each user_id, with two\n # ordered lists (sorted by rating datetime): the movies they have rated,\n # and their ratings of these movies.\n\n ratings_group = ratings.sort_values(by=[\"timestamp\"]).groupby(\"uid\")\n\n ratings_data = pd.DataFrame(\n data={\n \"uid\": list(ratings_group.groups.keys()),\n \"sids\": list(ratings_group.sid.apply(list)),\n \"ratings\": list(ratings_group.rating.apply(list)),\n \"timestamps\": list(ratings_group.timestamp.apply(list)),\n }\n )\n\n # Now, let's split the movie_ids list into a set of sequences of a fixed\n # length. We do the same for the ratings. Set the sequence_length variable\n # to change the length of the input sequence to the model. You can also\n # change the step_size to control the number of sequences to generate for\n # each user.\n ratings_data.sids = ratings_data.sids.apply(\n lambda ids: self.create_sequences(ids, self.history_size, self.step_size)\n )\n ratings_data.ratings = ratings_data.ratings.apply(\n lambda ids: self.create_sequences(ids, self.history_size, self.step_size)\n )\n del ratings_data[\"timestamps\"]\n\n # After that, we process the output to have each sequence in a separate\n # records in the DataFrame. In addition, we join the user features with\n # the ratings data.\n ratings_data_movies = ratings_data[[\"uid\", \"sids\"]].explode(\n \"sids\", ignore_index=True\n )\n ratings_data_rating = ratings_data[[\"ratings\"]].explode(\"ratings\", ignore_index=True)\n ratings_data_transformed = pd.concat([ratings_data_movies, ratings_data_rating], axis=1)\n ratings_data_transformed = ratings_data_transformed.join(\n users.set_index(\"uid\"), on=\"uid\"\n )\n ratings_data_transformed.sids = ratings_data_transformed.sids.apply(\n lambda x: \",\".join(x)\n )\n ratings_data_transformed.ratings = ratings_data_transformed.ratings.apply(\n lambda x: \",\".join([str(v) for v in x])\n )\n del ratings_data_transformed[\"zip_code\"]\n ratings_data_transformed.rename(\n columns={\"sids\": \"sequence_sids\", \"ratings\": \"sequence_ratings\"},\n inplace=True,\n )\n # Finally, we split the data into training and testing splits, with 85%\n # and 15% of the instances, respectively, and store them to CSV files.\n random_selection = np.random.rand(len(ratings_data_transformed.index)) <= 0.85\n train_data = ratings_data_transformed[random_selection]\n test_data = ratings_data_transformed[~random_selection]\n\n # save\n train_data.to_csv(self.processed_paths[0], index=False, sep=\",\")\n test_data.to_csv(self.processed_paths[1], index=False, sep=\",\")\n test_data.to_csv(self.processed_paths[2], index=False, sep=\",\")\n\n def __len__(self):\n return len(self.ratings_frame)\n\n def __getitem__(self, idx):\n data = self.ratings_frame.iloc[idx]\n user_id = data.uid\n movie_history = eval(data.sequence_sids)\n movie_history_ratings = eval(data.sequence_ratings)\n target_movie_id = movie_history[-1:][0]\n target_movie_rating = movie_history_ratings[-1:][0]\n movie_history = torch.LongTensor(movie_history[:-1])\n movie_history_ratings = torch.LongTensor(movie_history_ratings[:-1])\n sex, age_group, occupation = data.sex, data.age_group, data.occupation\n output = (user_id, movie_history, target_movie_id, movie_history_ratings,\n target_movie_rating, sex, age_group, occupation)\n return output\n\n# Cell\nclass ML1mDataModule_v3(SequentialDataModule):\n dataset_cls = ML1mDataset_v3\n\n# Cell\nclass ML1mDataset_v4(InteractionsDataset):\n url = \"http://files.grouplens.org/datasets/movielens/ml-1m.zip\"\n\n @property\n def raw_file_names(self):\n return 'ratings.dat'\n\n @property\n def processed_file_names(self):\n return 'data.json'\n\n def download(self):\n path = download_url(self.url, self.raw_dir)\n extract_zip(path, self.raw_dir)\n from shutil import move, rmtree\n move(os.path.join(self.raw_dir, 'ml-1m', self.raw_file_names), self.raw_dir)\n rmtree(os.path.join(self.raw_dir, 'ml-1m'))\n os.unlink(path)\n\n def load_ratings_df(self):\n df = pd.read_csv(self.raw_paths[0], sep='::', header=None, engine='python')\n df.columns = ['uid', 'sid', 'rating', 'timestamp']\n # drop duplicate user-item pair records, keeping recent ratings only\n df.drop_duplicates(subset=['uid', 'sid'], keep='last', inplace=True)\n return df\n\n def process(self):\n df = self.load_ratings_df()\n train, test = stratified_split_v2(df, ratio=0.7, col_user='uid', col_item='sid')\n\n min_session_length = 2\n session_len = test.groupby('uid').size()\n test = test[np.in1d(test['uid'], session_len[session_len >= min_session_length].index)]\n\n last_items = test.sort_values(by=['uid', 'timestamp']).groupby('uid').timestamp.idxmax()\n y_test = test.loc[last_items]\n x_test = test[~test.index.isin(y_test.index)]\n\n data = dict()\n\n def formatRecords(g):\n keys = ['uid','sid','rating']\n result = []\n for item in g.values.tolist():\n item = dict(zip(keys, item))\n result.append(item)\n return result\n\n data['x_train'] = list(train.groupby('uid').apply(lambda g: formatRecords(g)).to_dict().values())\n data['x_test'] = list(x_test.groupby('uid').apply(lambda g: formatRecords(g)).to_dict().values())\n data['y_test'] = list(y_test.groupby('uid').apply(lambda g: formatRecords(g)).to_dict().values())\n\n with open(self.processed_paths[0], \"w\") as f:\n json.dump(data, f)\n\n def load(self):\n with open(self.processed_paths[0]) as f:\n data = json.load(f)\n return data\n\n# Cell\nclass ML100kDataset(Dataset):\n url = 'https://files.grouplens.org/datasets/movielens/ml-100k.zip'\n\n def __init__(self, root):\n super().__init__(root)\n\n @property\n def raw_file_names(self) -> str:\n return ['u1.base', 'u1.test', 'u4.test', 'allbut.pl', 'u.item',\n 'ua.test', 'u.occupation', 'u3.test', 'u5.base', 'ub.test',\n 'u2.test', 'u3.base', 'u.genre', 'u.data', 'u4.base',\n 'u5.test', 'u.info', 'README', 'ub.base', 'mku.sh', 'u2.base',\n 'u.user', 'ua.base']\n\n @property\n def processed_file_names(self) -> str:\n raise NotImplementedError\n\n def download(self):\n path = download_url(self.url, self.raw_dir)\n extract_zip(path, self.raw_dir)\n from shutil import move, rmtree\n file_names = os.listdir(osp.join(self.raw_dir, 'ml-100k'))\n for file_name in file_names:\n move(osp.join(self.raw_dir, 'ml-100k', file_name), self.raw_dir)\n rmtree(osp.join(self.raw_dir, 'ml-100k'))\n os.unlink(path)\n\n def process(self):\n raise NotImplementedError\n\n# Cell\nimport pandas as pd\nimport numpy as np\nimport random\nfrom tqdm import tqdm\nfrom collections import defaultdict\n\n# Cell\ndef sparseFeature(feat, feat_num, embed_dim=4):\n \"\"\"\n create dictionary for sparse feature\n :param feat: feature name\n :param feat_num: the total number of sparse features that do not repeat\n :param embed_dim: embedding dimension\n :return:\n \"\"\"\n return {'feat': feat, 'feat_num': feat_num, 'embed_dim': embed_dim}\n\n# Cell\ndef create_ml_1m_dataset(file, trans_score=2, embed_dim=8, test_neg_num=100):\n \"\"\"\n :param file: A string. dataset path.\n :param trans_score: A scalar. Greater than it is 1, and less than it is 0.\n :param embed_dim: A scalar. latent factor.\n :param test_neg_num: A scalar. The number of test negative samples\n :return: user_num, item_num, train_df, test_df\n \"\"\"\n print('==========Data Preprocess Start=============')\n data_df = pd.read_csv(file, sep=\"::\", engine='python',\n names=['user_id', 'item_id', 'label', 'Timestamp'])\n # filtering\n data_df['item_count'] = data_df.groupby('item_id')['item_id'].transform('count')\n data_df = data_df[data_df.item_count >= 5]\n # trans score\n data_df = data_df[data_df.label >= trans_score]\n # sort\n data_df = data_df.sort_values(by=['user_id', 'Timestamp'])\n # split dataset and negative sampling\n print('============Negative Sampling===============')\n train_data, val_data, test_data = defaultdict(list), defaultdict(list), defaultdict(list)\n item_id_max = data_df['item_id'].max()\n for user_id, df in tqdm(data_df[['user_id', 'item_id']].groupby('user_id')):\n pos_list = df['item_id'].tolist()\n\n def gen_neg():\n neg = pos_list[0]\n while neg in set(pos_list):\n neg = random.randint(1, item_id_max)\n return neg\n\n neg_list = [gen_neg() for i in range(len(pos_list) + test_neg_num)]\n for i in range(1, len(pos_list)):\n hist_i = pos_list[:i]\n if i == len(pos_list) - 1:\n test_data['user_id'].append(user_id)\n test_data['pos_id'].append(pos_list[i])\n test_data['neg_id'].append(neg_list[i:])\n elif i == len(pos_list) - 2:\n val_data['user_id'].append(user_id)\n val_data['pos_id'].append(pos_list[i])\n val_data['neg_id'].append(neg_list[i])\n else:\n train_data['user_id'].append(user_id)\n train_data['pos_id'].append(pos_list[i])\n train_data['neg_id'].append(neg_list[i])\n # feature columns\n user_num, item_num = data_df['user_id'].max() + 1, data_df['item_id'].max() + 1\n feat_col = [sparseFeature('user_id', user_num, embed_dim),\n sparseFeature('item_id', item_num, embed_dim)]\n # shuffle\n random.shuffle(train_data)\n random.shuffle(val_data)\n train = [np.array(train_data['user_id']), np.array(train_data['pos_id']),\n np.array(train_data['neg_id'])]\n val = [np.array(val_data['user_id']), np.array(val_data['pos_id']),\n np.array(val_data['neg_id'])]\n test = [np.array(test_data['user_id']), np.array(test_data['pos_id']),\n np.array(test_data['neg_id'])]\n print('============Data Preprocess End=============')\n return feat_col, train, val, test\n\n# Cell\ndef create_implicit_ml_1m_dataset(file, trans_score=2, embed_dim=8, maxlen=40):\n \"\"\"\n :param file: A string. dataset path.\n :param trans_score: A scalar. Greater than it is 1, and less than it is 0.\n :param embed_dim: A scalar. latent factor.\n :param maxlen: A scalar. maxlen.\n :return: user_num, item_num, train_df, test_df\n \"\"\"\n print('==========Data Preprocess Start=============')\n data_df = pd.read_csv(file, sep=\"::\", engine='python',\n names=['user_id', 'item_id', 'label', 'Timestamp'])\n # implicit dataset\n data_df = data_df[data_df.label >= trans_score]\n\n # sort\n data_df = data_df.sort_values(by=['user_id', 'Timestamp'])\n\n train_data, val_data, test_data = [], [], []\n\n item_id_max = data_df['item_id'].max()\n for user_id, df in tqdm(data_df[['user_id', 'item_id']].groupby('user_id')):\n pos_list = df['item_id'].tolist()\n\n def gen_neg():\n neg = pos_list[0]\n while neg in pos_list:\n neg = random.randint(1, item_id_max)\n return neg\n\n neg_list = [gen_neg() for i in range(len(pos_list) + 100)]\n for i in range(1, len(pos_list)):\n hist_i = pos_list[:i]\n if i == len(pos_list) - 1:\n test_data.append([user_id, hist_i, pos_list[i], 1])\n for neg in neg_list[i:]:\n test_data.append([user_id, hist_i, neg, 0])\n elif i == len(pos_list) - 2:\n val_data.append([user_id, hist_i, pos_list[i], 1])\n val_data.append([user_id, hist_i, neg_list[i], 0])\n else:\n train_data.append([user_id, hist_i, pos_list[i], 1])\n train_data.append([user_id, hist_i, neg_list[i], 0])\n # item feature columns\n user_num, item_num = data_df['user_id'].max() + 1, data_df['item_id'].max() + 1\n feature_columns = [sparseFeature('user_id', user_num, embed_dim),\n sparseFeature('item_id', item_num, embed_dim)]\n\n # shuffle\n random.shuffle(train_data)\n random.shuffle(val_data)\n # random.shuffle(test_data)\n\n # create dataframe\n train = pd.DataFrame(train_data, columns=['user_id', 'hist', 'target_item', 'label'])\n val = pd.DataFrame(val_data, columns=['user_id', 'hist', 'target_item', 'label'])\n test = pd.DataFrame(test_data, columns=['user_id', 'hist', 'target_item', 'label'])\n\n print('==================Padding===================')\n from tensorflow.keras.preprocessing.sequence import pad_sequences\n train_X = [train['user_id'].values, pad_sequences(train['hist'], maxlen=maxlen), train['target_item'].values]\n train_y = train['label'].values\n val_X = [val['user_id'].values, pad_sequences(val['hist'], maxlen=maxlen), val['target_item'].values]\n val_y = val['label'].values\n test_X = [test['user_id'].values, pad_sequences(test['hist'], maxlen=maxlen), test['target_item'].values]\n test_y = test['label'].values.tolist()\n print('============Data Preprocess End=============')\n return feature_columns, (train_X, train_y), (val_X, val_y), (test_X, test_y)",
"# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/models/models.ccpm.ipynb (unless otherwise specified).\n\n__all__ = ['CCPM']\n\n# Cell\nimport torch\nfrom torch import nn\n\nfrom .layers.embedding import EmbeddingLayer\nfrom .layers.common import KMaxPooling\n\nfrom .bases.ctr import CTRModel\n\n# Internal Cell\ndef get_activation(activation):\n if isinstance(activation, str):\n if activation.lower() == \"relu\":\n return nn.ReLU()\n elif activation.lower() == \"sigmoid\":\n return nn.Sigmoid()\n elif activation.lower() == \"tanh\":\n return nn.Tanh()\n else:\n return getattr(nn, activation)()\n else:\n return activation\n\n# Internal Cell\nclass CCPM_ConvLayer(nn.Module):\n \"\"\"\n Input X: tensor of shape (batch_size, 1, num_fields, embedding_dim)\n \"\"\"\n def __init__(self, num_fields, channels=[3], kernel_heights=[3], activation=\"Tanh\"):\n super(CCPM_ConvLayer, self).__init__()\n if not isinstance(kernel_heights, list):\n kernel_heights = [kernel_heights] * len(channels)\n elif len(kernel_heights) != len(channels):\n raise ValueError(\"channels={} and kernel_heights={} should have the same length.\"\\\n .format(channels, kernel_heights))\n module_list = []\n self.channels = [1] + channels\n layers = len(kernel_heights)\n for i in range(1, len(self.channels)):\n in_channels = self.channels[i - 1]\n out_channels = self.channels[i]\n kernel_height = kernel_heights[i - 1]\n module_list.append(nn.ZeroPad2d((0, 0, kernel_height - 1, kernel_height - 1)))\n module_list.append(nn.Conv2d(in_channels, out_channels, kernel_size=(kernel_height, 1)))\n if i < layers:\n k = max(3, int((1 - pow(float(i) / layers, layers - i)) * num_fields))\n else:\n k = 3\n module_list.append(KMaxPooling(k, dim=2))\n module_list.append(get_activation(activation))\n self.conv_layer = nn.Sequential(*module_list)\n\n def forward(self, X):\n return self.conv_layer(X)\n\n# Cell\nclass CCPM(CTRModel):\n def __init__(self,\n feature_map,\n model_id=\"CCPM\",\n task=\"binary_classification\",\n learning_rate=1e-3,\n embedding_initializer=\"torch.nn.init.normal_(std=1e-4)\",\n embedding_dim=10,\n channels=[4, 4, 2],\n kernel_heights=[6, 5, 3],\n activation=\"Tanh\",\n **kwargs):\n super(CCPM, self).__init__(feature_map,\n model_id=model_id,\n **kwargs)\n self.embedding_layer = EmbeddingLayer(feature_map, embedding_dim)\n self.conv_layer = CCPM_ConvLayer(feature_map.num_fields,\n channels=channels,\n kernel_heights=kernel_heights,\n activation=activation)\n conv_out_dim = 3 * embedding_dim * channels[-1] # 3 is k-max-pooling size of the last layer\n self.fc = nn.Linear(conv_out_dim, 1)\n self.output_activation = self.get_final_activation(task)\n self.init_weights(embedding_initializer=embedding_initializer)\n\n def forward(self, inputs):\n feature_emb = self.embedding_layer(inputs)\n conv_in = torch.unsqueeze(feature_emb, 1) # shape (bs, 1, field, emb)\n conv_out = self.conv_layer(conv_in)\n flatten_out = torch.flatten(conv_out, start_dim=1)\n y_pred = self.fc(flatten_out)\n if self.output_activation is not None:\n y_pred = self.output_activation(y_pred)\n return y_pred",
"# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/utils/utils.data.ipynb (unless otherwise specified).\n\n__all__ = ['list_datasets', 'load_dataset', 'generate_time_series', 'generate_abtest_data']\n\n# Cell\nimport pandas as pd\nimport numpy as np\nimport tempfile\nimport os\nimport scipy.stats as stats\n\nfrom .common_utils import download_url\n\n# Cell\ndef list_datasets(top_n:int=None):\n \"\"\"\n Retruns a pandas dataframe of all the available datasets and info\n\n Args:\n top_n (int): returns only top_n rows\n \"\"\"\n url = 'https://docs.google.com/spreadsheets/d/1wY_83y2ltu6tzMNHFOQRNslrgb0VWH_wa7zP7lT6AvM/export?gid=0&format=csv'\n df = pd.read_csv(url, index_col=[0]).fillna('NA')\n if top_n:\n return df.head(top_n)\n return df\n\n# Cell\ndef load_dataset(data_id, data_dir=None, log=False):\n dataset_list = list(list_datasets().index)\n assert data_id in dataset_list, f'data id not exist, available ids are {dataset_list}'\n\n if data_dir is None:\n data_dir = os.path.join(tempfile.gettempdir(), data_id)\n\n data_info = list_datasets().loc[data_id]\n path = download_url(data_info.url, data_dir, log=log)\n\n if data_info.format == 'parquet.snappy':\n df = pd.read_parquet(path)\n\n return df\n\n# Cell\ndef generate_time_series(batch_size, n_steps, seed=42):\n np.random.seed(seed)\n freq1, freq2, offsets1, offsets2 = np.random.rand(4, batch_size, 1)\n time = np.linspace(0, 1, n_steps)\n series = 0.5 * np.sin((time - offsets1) * (freq1 * 10 + 10)) # wave 1\n series += 0.2 * np.sin((time - offsets2) * (freq2 * 20 + 20)) # + wave 2\n series += 0.1 * (np.random.rand(batch_size, n_steps) - 0.5) # + noise\n return series[..., np.newaxis].astype(np.float32)\n\n# Cell\ndef generate_abtest_data(N_A, N_B, bcr, d_hat, days=None, control_label='A',\n test_label='B', seed=None):\n \"\"\"Returns a pandas dataframe with synthetic A/B experiment data\n Example:\n Parameters:\n N_A (int): sample size for control group\n N_B (int): sample size for test group\n Note: final sample size may not match N_A provided because the\n group at each row is chosen at random (50/50).\n bcr (float): baseline conversion rate; conversion rate of control group\n d_hat (float): difference between the groups\n days (int): optional; if provided, a column for 'ts' will be included\n to divide the data in chunks of time\n Note: overflow data will be included in an extra day\n control_label (str)\n test_label (str)\n seed (int)\n Returns:\n pd.DataFrame: the generated ctr dataframe\n pd.DataFrame: summary dataframe\n \"\"\"\n p_A = bcr\n p_B = bcr + d_hat # conversion rate of test group\n\n if seed:\n np.random.seed(seed)\n\n # initiate empty container\n data = []\n\n # total amount of rows in the data\n N = N_A + N_B\n\n # distribute events based on proportion of group size\n group_bern = stats.bernoulli(N_A / (N_A + N_B))\n\n # initiate bernoulli distributions from which to randomly sample\n A_bern = stats.bernoulli(p_A)\n B_bern = stats.bernoulli(p_B)\n\n for idx in range(N):\n # initite empty row\n row = {}\n # for 'ts' column\n if days is not None:\n if type(days) == int:\n row['ts'] = idx // (N // days)\n else:\n raise ValueError(\"Provide an integer for the days parameter.\")\n # assign group based on 50/50 probability\n row['group'] = group_bern.rvs()\n\n if row['group'] == 0:\n # assign conversion based on provided parameters\n row['converted'] = A_bern.rvs()\n else:\n row['converted'] = B_bern.rvs()\n # collect row into data container\n data.append(row)\n\n # convert data into pandas dataframe\n df = pd.DataFrame(data)\n\n # transform group labels of 0s and 1s to user-defined group labels\n df['group'] = df['group'].apply(\n lambda x: control_label if x == 0 else test_label)\n\n # summary dataframe\n ab_summary = df.pivot_table(values='converted', index='group', aggfunc=np.sum)\n # add additional columns to the pivot table\n ab_summary['total'] = df.pivot_table(values='converted', index='group', aggfunc=lambda x: len(x))\n ab_summary['rate'] = df.pivot_table(values='converted', index='group')\n\n return df, ab_summary",
"# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/visualization/visualization.eda.ipynb (unless otherwise specified).\n\n__all__ = ['plot_sparse']\n\n# Cell\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Cell\ndef plot_sparse(cat_lst, tgt_lst):\n _df = pd.DataFrame.from_dict({\n 'cat':cat_lst,\n 'tgt':tgt_lst,\n })\n stats = _df.groupby('cat').agg(['count','mean'])\n stats = stats.reset_index()\n stats.columns = ['cat', 'count','mean']\n stats = stats.sort_values('count', ascending=False)\n fig, ax1 = plt.subplots(figsize=(15,4))\n ax2 = ax1.twinx()\n ax1.bar(stats['cat'].astype(str).values[0:20], stats['count'].values[0:20])\n ax1.set_xticklabels(stats['cat'].astype(str).values[0:20], rotation='vertical')\n ax2.plot(stats['mean'].values[0:20], color='red')\n ax2.set_ylim(0,1)\n ax2.set_ylabel('Mean Target')\n ax1.set_ylabel('Frequency')\n ax1.set_xlabel('Category')",
"# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/models/models.narm.ipynb (unless otherwise specified).\n\n__all__ = ['NARM']\n\n# Cell\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\n# Internal Cell\nclass NARMEmbedding(nn.Module):\n def __init__(self, args):\n super().__init__()\n vocab_size = args.num_items + 1\n embed_size = args.bert_hidden_units\n\n self.token = nn.Embedding(vocab_size, embed_size)\n self.embed_dropout = nn.Dropout(args.bert_dropout)\n\n def get_mask(self, x, lengths):\n if len(x.shape) > 2:\n return torch.ones(x.shape[:2])[:, :max(lengths)].to(x.device)\n else:\n return ((x > 0) * 1)[:, :max(lengths)]\n\n def forward(self, x, lengths):\n mask = self.get_mask(x, lengths)\n if len(x.shape) > 2:\n x = torch.matmul(x, self.token.weight)\n else:\n x = self.token(x)\n\n return self.embed_dropout(x), mask\n\n\nclass NARMModel(nn.Module):\n def __init__(self, args):\n super().__init__()\n embed_size = args.bert_hidden_units\n hidden_size = 2 * args.bert_hidden_units\n\n self.gru = nn.GRU(embed_size, hidden_size, num_layers=1, batch_first=True)\n self.a_global = nn.Linear(hidden_size, hidden_size, bias=False)\n self.a_local = nn.Linear(hidden_size, hidden_size, bias=False)\n self.act = HardSigmoid()\n self.v_vector = nn.Linear(hidden_size, 1, bias=False)\n self.proj_dropout = nn.Dropout(args.bert_attn_dropout)\n self.b_vetor = nn.Linear(embed_size, 2 * hidden_size, bias=False)\n\n def forward(self, x, embedding_weight, lengths, mask):\n x = pack_padded_sequence(x, lengths, batch_first=True, enforce_sorted=False)\n gru_out, hidden = self.gru(x)\n gru_out, _ = pad_packed_sequence(gru_out, batch_first=True)\n c_global = hidden[-1]\n\n state2 = self.a_local(gru_out)\n state1 = self.a_global(c_global).unsqueeze(1).expand_as(state2)\n state1 = mask.unsqueeze(2).expand_as(state2) * state1\n alpha = self.act(state1 + state2).view(-1, state1.size(-1))\n attn = self.v_vector(alpha).view(mask.size())\n attn = F.softmax(attn.masked_fill(mask == 0, -1e9), dim=-1)\n c_local = torch.sum(attn.unsqueeze(2).expand_as(gru_out) * gru_out, 1)\n\n proj = self.proj_dropout(torch.cat([c_global, c_local], 1))\n scores = torch.matmul(proj, self.b_vetor(embedding_weight).permute(1, 0))\n return scores\n\n\nclass HardSigmoid(nn.Module):\n def forward(self, x):\n return torch.clamp((x / 6 + 0.5), min=0., max=1.)\n\n# Cell\nclass NARM(nn.Module):\n def __init__(self, args):\n super(NARM, self).__init__()\n self.args = args\n self.embedding = NARMEmbedding(self.args)\n self.model = NARMModel(self.args)\n self.truncated_normal_init()\n\n def truncated_normal_init(self, mean=0, std=0.02, lower=-0.04, upper=0.04):\n with torch.no_grad():\n l = (1. + math.erf(((lower - mean) / std) / math.sqrt(2.))) / 2.\n u = (1. + math.erf(((upper - mean) / std) / math.sqrt(2.))) / 2.\n\n for p in self.parameters():\n p.uniform_(2 * l - 1, 2 * u - 1)\n p.erfinv_()\n p.mul_(std * math.sqrt(2.))\n p.add_(mean)\n\n def forward(self, x, lengths):\n x, mask = self.embedding(x, lengths)\n scores = self.model(x, self.embedding.token.weight, lengths, mask)\n return scores",
"# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/models/models.dcn.ipynb (unless otherwise specified).\n\n__all__ = ['DCN', 'CrossNetwork', 'DCNv2', 'DNN', 'CrossNet', 'DCNv3']\n\n# Cell\nfrom typing import Any, Iterable, List, Optional, Tuple, Union, Callable\n\nfrom .layers.common import MLP_Layer\nfrom .layers.embedding import EmbeddingLayer\nfrom .bases.ctr import CTRModel\n\nimport os\nimport numpy as np\n\nimport torch\nfrom torch import nn\n\n# Internal Cell\nclass CrossNet(nn.Module):\n def __init__(self, input_dim, num_layers):\n super(CrossNet, self).__init__()\n self.num_layers = num_layers\n self.cross_net = nn.ModuleList(CrossInteractionLayer(input_dim)\n for _ in range(self.num_layers))\n\n def forward(self, X_0):\n X_i = X_0 # b x dim\n for i in range(self.num_layers):\n X_i = X_i + self.cross_net[i](X_0, X_i)\n return X_i\n\n# Internal Cell\nclass CrossInteractionLayer(nn.Module):\n def __init__(self, input_dim):\n super(CrossInteractionLayer, self).__init__()\n self.weight = nn.Linear(input_dim, 1, bias=False)\n self.bias = nn.Parameter(torch.zeros(input_dim))\n\n def forward(self, X_0, X_i):\n interaction_out = self.weight(X_i) * X_0 + self.bias\n return interaction_out\n\n# Cell\nclass DCN(CTRModel):\n def __init__(self,\n feature_map,\n model_id=\"DCN\",\n task=\"binary_classification\",\n embedding_initializer=\"torch.nn.init.normal_(std=1e-4)\",\n embedding_dim=10,\n dnn_hidden_units=[],\n dnn_activations=\"ReLU\",\n crossing_layers=3,\n embedding_dropout=0,\n net_dropout=0,\n batch_norm=False,\n **kwargs):\n super(DCN, self).__init__(feature_map,\n model_id=model_id,\n **kwargs)\n self.embedding_layer = EmbeddingLayer(feature_map, embedding_dim)\n input_dim = feature_map.num_fields * embedding_dim\n self.dnn = MLP_Layer(input_dim=input_dim,\n output_dim=None, # output hidden layer\n hidden_units=dnn_hidden_units,\n hidden_activations=dnn_activations,\n output_activation=None,\n dropout_rates=net_dropout,\n batch_norm=batch_norm,\n use_bias=True) \\\n if dnn_hidden_units else None # in case of only crossing net used\n self.crossnet = CrossNet(input_dim, crossing_layers)\n final_dim = input_dim\n if isinstance(dnn_hidden_units, list) and len(dnn_hidden_units) > 0: # if use dnn\n final_dim += dnn_hidden_units[-1]\n self.fc = nn.Linear(final_dim, 1) # [cross_part, dnn_part] -> logit\n self.final_activation = self.get_final_activation(task)\n self.init_weights(embedding_initializer=embedding_initializer)\n\n def forward(self, inputs):\n feature_emb = self.embedding_layer(inputs)\n flat_feature_emb = feature_emb.flatten(start_dim=1)\n cross_out = self.crossnet(flat_feature_emb)\n if self.dnn is not None:\n dnn_out = self.dnn(flat_feature_emb)\n final_out = torch.cat([cross_out, dnn_out], dim=-1)\n else:\n final_out = cross_out\n y_pred = self.fc(final_out)\n if self.final_activation is not None:\n y_pred = self.final_activation(y_pred)\n return y_pred\n\n# Cell\nimport torch\n\nfrom .layers.common import FeaturesEmbedding, MultiLayerPerceptron\n\n\nclass CrossNetwork(torch.nn.Module):\n\n def __init__(self, input_dim, num_layers):\n super().__init__()\n self.num_layers = num_layers\n self.w = torch.nn.ModuleList([\n torch.nn.Linear(input_dim, 1, bias=False) for _ in range(num_layers)\n ])\n self.b = torch.nn.ParameterList([\n torch.nn.Parameter(torch.zeros((input_dim,))) for _ in range(num_layers)\n ])\n\n def forward(self, x):\n \"\"\"\n :param x: Float tensor of size ``(batch_size, num_fields, embed_dim)``\n \"\"\"\n x0 = x\n for i in range(self.num_layers):\n xw = self.w[i](x)\n x = x0 * xw + self.b[i] + x\n return x\n\nclass DCNv2(torch.nn.Module):\n \"\"\"\n A pytorch implementation of Deep & Cross Network.\n Reference:\n R Wang, et al. Deep & Cross Network for Ad Click Predictions, 2017.\n \"\"\"\n\n def __init__(self, field_dims, embed_dim, num_layers, mlp_dims, dropout):\n super().__init__()\n self.embedding = FeaturesEmbedding(field_dims, embed_dim)\n self.embed_output_dim = len(field_dims) * embed_dim\n self.cn = CrossNetwork(self.embed_output_dim, num_layers)\n self.mlp = MultiLayerPerceptron(self.embed_output_dim, mlp_dims, dropout, output_layer=False)\n self.linear = torch.nn.Linear(mlp_dims[-1] + self.embed_output_dim, 1)\n\n def forward(self, x):\n \"\"\"\n :param x: Long tensor of size ``(batch_size, num_fields)``\n \"\"\"\n embed_x = self.embedding(x).view(-1, self.embed_output_dim)\n x_l1 = self.cn(embed_x)\n h_l2 = self.mlp(embed_x)\n x_stack = torch.cat([x_l1, h_l2], dim=1)\n p = self.linear(x_stack)\n return torch.sigmoid(p.squeeze(1))\n\n# Cell\nimport torch\nimport torch.nn as nn\n\nfrom collections import defaultdict\n\n\nclass DNN(nn.Module):\n def __init__(self, inputs_dim, hidden_units, dropout_rate):\n super(DNN, self).__init__()\n self.inputs_dim = inputs_dim\n self.hidden_units = hidden_units\n self.dropout = nn.Dropout(dropout_rate)\n\n self.hidden_units = [inputs_dim] + list(self.hidden_units)\n self.linear = nn.ModuleList([\n nn.Linear(self.hidden_units[i], self.hidden_units[i+1]) for i in range(len(self.hidden_units)-1)\n ])\n for name, tensor in self.linear.named_parameters():\n if 'weight' in name:\n nn.init.normal_(tensor, mean=0, std=0.0001)\n\n # self.bn = nn.ModuleList([\n # nn.Linear(self.hidden_units[i], self.hidden_units[i + 1]) for i in range(len(self.hidden_units) - 1)\n # ])\n self.activation = nn.ReLU()\n\n def forward(self, X):\n inputs = X\n for i in range(len(self.linear)):\n fc = self.linear[i](inputs)\n fc = self.activation(fc)\n fc - self.dropout(fc)\n inputs = fc\n return inputs\n\n\nclass CrossNet(nn.Module):\n def __init__(self, in_features, layer_num=2, parameterization='vector', seed=2022):\n super(CrossNet, self).__init__()\n self.layer_num = layer_num\n self.parameterization = parameterization\n if self.parameterization == 'vector':\n self.kernels = nn.Parameter(torch.Tensor(self.layer_num, in_features, 1))\n elif self.parameterization == 'matrix':\n self.kernels = nn.Parameter(torch.Tensor(self.layer_num, in_features, in_features))\n self.bias = nn.Parameter(torch.Tensor(self.layer_num, in_features, 1))\n\n for i in range(self.kernels.shape[0]):\n nn.init.xavier_normal_(self.kernels[i])\n for i in range(self.bias.shape[0]):\n nn.init.zeros_(self.bias[0])\n\n def forward(self, inputs):\n x_0 = inputs.unsqueeze(2)\n x_1 = x_0\n for i in range(self.layer_num):\n if self.parameterization == 'vector':\n x1_w = torch.tensordot(x_1, self.kernels[i], dims=([1], [0]))\n dot_ = torch.matmul(x_0, x1_w)\n x_1 = dot_ + self.bias[i] + x_1\n else:\n x1_w = torch.tensordot(self.kernels[i], x_1)\n dot_ = x1_w + self.bias[i]\n x_1 = x_0 * dot_ + x_1\n x_1 = torch.squeeze(x_1, dim=2)\n return x_1\n\n\nclass DCNv3(nn.Module):\n \"\"\"DCN model implementation in pytorch\n\n Reference:\n 1. https://github.com/huangjunheng/recommendation_model/blob/master/DCN/dcn.py\n \"\"\"\n def __init__(self, feat_size, embedding_size, linear_feature_columns, dnn_feature_columns, cross_num=2,\n cross_param='vector', dnn_hidden_units=(128, 128,), init_std=0.0001, seed=2022, l2_reg=0.00001,\n drop_rate=0.5):\n super(DCNv3, self).__init__()\n self.feat_size = feat_size\n self.embedding_size = embedding_size\n self.dnn_hidden_units = dnn_hidden_units\n self.cross_num = 2\n self.cross_param = cross_param\n self.drop_rate = drop_rate\n self.l2_reg = 0.00001\n\n self.act = nn.ReLU()\n self.dropout = nn.Dropout(drop_rate)\n\n self.dense_feature_columns = list(filter(lambda x:x[1]=='dense', dnn_feature_columns))\n self.sparse_feature_columns = list(filter(lambda x:x[1]=='sparse', dnn_feature_columns))\n\n self.embedding_dic = nn.ModuleDict({feat[0]:nn.Embedding(feat_size[feat[0]], self.embedding_size, sparse=False)\n for feat in self.sparse_feature_columns})\n\n self.feature_index = defaultdict(int)\n start = 0\n for feat in self.feat_size:\n self.feature_index[feat] = start\n start += 1\n\n inputs_dim = len(self.dense_feature_columns)+self.embedding_size*len(self.sparse_feature_columns)\n self.dnn = DNN(inputs_dim,self.dnn_hidden_units, 0.5)\n self.crossnet = CrossNet(inputs_dim, layer_num=self.cross_num, parameterization=self.cross_param)\n self.dnn_linear = nn.Linear(inputs_dim+dnn_hidden_units[-1], 1, bias=False)\n dnn_hidden_units = [len(feat_size)] + list(dnn_hidden_units) + [1]\n self.linear = nn.ModuleList([\n nn.Linear(dnn_hidden_units[i], dnn_hidden_units[i+1]) for i in range(len(dnn_hidden_units)-1)\n ])\n for name, tensor in self.linear.named_parameters():\n if 'weight' in name:\n nn.init.normal_(tensor, mean=0, std=init_std)\n\n def forward(self, X):\n logit = X\n for i in range(len(self.linear)):\n fc = self.linear[i](logit)\n fc = self.act(fc)\n fc = self.dropout(fc)\n logit = fc\n\n sparse_embedding = [self.embedding_dic[feat[0]](X[:, self.feature_index[feat[0]]].long()).reshape(X.shape[0], 1, -1)\n for feat in self.sparse_feature_columns]\n dense_values = [X[:, self.feature_index[feat[0]]].reshape(-1, 1) for feat in self.dense_feature_columns]\n dense_input = torch.cat(dense_values, dim=1)\n sparse_input = torch.cat(sparse_embedding, dim=1)\n sparse_input = torch.flatten(sparse_input, start_dim=1)\n dnn_input = torch.cat((dense_input, sparse_input), dim=1)\n\n # print('sparse input size', sparse_input.shape)\n # print('dense input size', dense_input.shape)\n # print('dnn input size', dnn_input.shape)\n\n deep_out = self.dnn(dnn_input)\n cross_out = self.crossnet(dnn_input)\n stack_out = torch.cat((cross_out, deep_out), dim=-1)\n\n logit += self.dnn_linear(stack_out)\n #print('logit size', logit.shape)\n y_pred = torch.sigmoid(logit)\n #print('y_pred', y_pred.shape)\n return y_pred"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"pandas.to_datetime",
"torch.LongTensor",
"pandas.Categorical",
"numpy.in1d",
"pandas.DataFrame",
"numpy.array",
"tensorflow.keras.preprocessing.sequence.pad_sequences"
],
[
"torch.nn.ZeroPad2d",
"torch.nn.Sequential",
"torch.nn.Conv2d",
"torch.unsqueeze",
"torch.nn.Sigmoid",
"torch.nn.Tanh",
"torch.nn.Linear",
"torch.flatten",
"torch.nn.ReLU"
],
[
"pandas.read_csv",
"numpy.random.seed",
"numpy.linspace",
"pandas.DataFrame",
"numpy.sin",
"pandas.read_parquet",
"numpy.random.rand",
"scipy.stats.bernoulli"
],
[
"matplotlib.pyplot.subplots",
"pandas.DataFrame.from_dict"
],
[
"torch.nn.Dropout",
"torch.ones",
"torch.cat",
"torch.nn.GRU",
"torch.nn.utils.rnn.pack_padded_sequence",
"torch.nn.Embedding",
"torch.nn.Linear",
"torch.nn.utils.rnn.pad_packed_sequence",
"torch.matmul",
"torch.no_grad",
"torch.clamp"
],
[
"torch.tensordot",
"torch.nn.Dropout",
"torch.sigmoid",
"torch.Tensor",
"torch.cat",
"torch.zeros",
"torch.nn.init.zeros_",
"torch.nn.init.xavier_normal_",
"torch.nn.Embedding",
"torch.nn.Linear",
"torch.matmul",
"torch.nn.init.normal_",
"torch.flatten",
"torch.nn.ReLU",
"torch.squeeze"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mxgnsr/pyleecan
|
[
"2b0a04e4ae67c073a91362ab42332908fef53bdd",
"2b0a04e4ae67c073a91362ab42332908fef53bdd",
"2b0a04e4ae67c073a91362ab42332908fef53bdd",
"2b0a04e4ae67c073a91362ab42332908fef53bdd"
] |
[
"Tests/Validation/Simulation/test_CEFC_001.py",
"pyleecan/GUI/Tools/MachinePlotWidget.py",
"pyleecan/Methods/Output/OutElec/get_Nr.py",
"pyleecan/Methods/Machine/LamSlot/plot.py"
] |
[
"# -*- coding: utf-8 -*-\nimport pytest\nfrom pyleecan.Classes.Simu1 import Simu1\nfrom pyleecan.Classes.InputCurrent import InputCurrent\nfrom pyleecan.Classes.ImportGenVectLin import ImportGenVectLin\nfrom pyleecan.Classes.ImportMatrixVal import ImportMatrixVal\nfrom pyleecan.Classes.MagFEMM import MagFEMM\nfrom pyleecan.Classes.Output import Output\nfrom Tests.Validation.Simulation.CEFC_Lam import CEFC_Lam\nfrom numpy import ones, pi, array\n\n\[email protected]\[email protected]\[email protected]\ndef test_CEFC_001():\n \"\"\"Test compute the Flux in FEMM without slots and without sliding band.\"\"\"\n simu = Simu1(name=\"SM_CEFC_001\", machine=CEFC_Lam, struct=None)\n\n # Definition of the enforced output of the electrical module\n N0 = 3000\n Is = ImportMatrixVal(value=array([[2.25353053e02, 2.25353053e02, 2.25353053e02]]))\n time = ImportGenVectLin(start=0, stop=1, num=1, endpoint=True)\n angle = ImportGenVectLin(start=0, stop=2 * pi, num=1024, endpoint=False)\n\n simu.input = InputCurrent(\n Is=Is,\n Ir=None, # No winding on the rotor\n N0=N0,\n angle_rotor=None, # Will be computed\n time=time,\n angle=angle,\n )\n\n # Definition of the magnetic simulation (no symmetry)\n simu.mag = MagFEMM(type_BH_stator=2, type_BH_rotor=0, is_sliding_band=False)\n simu.force = None\n simu.struct = None\n\n out = Output(simu=simu)\n out.post.legend_name = \"Slotless lamination\"\n simu.run()\n",
"from PyQt5 import QtWidgets, QtGui, QtCore\nfrom matplotlib.backends.backend_qt5agg import FigureCanvas\nfrom matplotlib.pyplot import subplots\n\nimport numpy as np\n\n\nDEBUG = True\n\n# =============================================================================\nclass MachinePlotWidget(QtWidgets.QGroupBox):\n def __init__(self, parent, label=\"\", *args, **kwargs):\n QtWidgets.QGroupBox.__init__(self, label, *args, **kwargs)\n self.parent = parent\n self.setLayout(QtWidgets.QGridLayout())\n\n self.fig, self.axes = subplots()\n self.canvas = FigureCanvas(self.fig)\n\n self.layout().addWidget(self.canvas, 0, 0, 1, 1)\n\n self.axes.axis(\"equal\")\n\n def update(self):\n if self.parent.DesignWidget.machine is not None:\n self.axes.clear()\n # new method to be compatible with pyleecan's plot-methods\n self.fig.show = self.canvas.draw\n plot_obj = self.parent.DesignWidget.machine\n plot_obj.plot(fig=self.fig, sym=1, alpha=0, delta=0)\n",
"from numpy import ones\nfrom ....Classes.ImportMatrixVal import ImportMatrixVal\n\n\nclass OutElecError(Exception):\n pass\n\n\ndef get_Nr(self):\n \"\"\"Create speed in function of time vector Nr\n\n Parameters\n ----------\n self : OutElec\n An OutElec object\n\n Returns\n -------\n Nr: ndarray\n speed in function of time\n \"\"\"\n if self.time is None:\n raise OutElecError('You must define \"time\" property before calling get_Nr')\n if self.N0 is None:\n raise OutElecError('You must define \"N0\" before calling get_Nr.')\n\n # Same speed for every timestep\n Nr = self.N0 * ones(self.time.shape[0])\n return Nr\n",
"# -*- coding: utf-8 -*-\n\nfrom matplotlib.patches import Patch\nfrom matplotlib.pyplot import axis, legend\n\nfrom ....Functions.init_fig import init_fig\nfrom ....definitions import config_dict\n\nROTOR_COLOR = config_dict[\"PLOT\"][\"COLOR_DICT\"][\"ROTOR_COLOR\"]\nSTATOR_COLOR = config_dict[\"PLOT\"][\"COLOR_DICT\"][\"STATOR_COLOR\"]\n\n\ndef plot(\n self,\n fig=None,\n is_lam_only=False,\n sym=1,\n alpha=0,\n delta=0,\n is_edge_only=False,\n is_display=True,\n is_show=True,\n):\n \"\"\"Plot the Lamination with empty Slots in a matplotlib fig\n\n Parameters\n ----------\n self : LamSlot\n A LamSlot object\n fig :\n if None, open a new fig and plot, else add to the\n current one (Default value = None)\n is_lam_only: bool\n True to plot only the lamination (No effect for LamSlot)\n sym : int\n Symmetry factor (1= full machine, 2= half of the machine...)\n alpha : float\n Angle for rotation [rad]\n delta : complex\n Complex value for translation\n is_edge_only: bool\n To plot transparent Patches\n is_display : bool\n False to return the patches\n is_show : bool\n To call show at the end of the method\n Returns\n -------\n patches : list\n List of Patches\n \"\"\"\n\n if self.is_stator:\n lam_color = STATOR_COLOR\n else:\n lam_color = ROTOR_COLOR\n\n (fig, axes, patch_leg, label_leg) = init_fig(fig)\n\n surf_list = self.build_geometry(sym=sym, alpha=alpha, delta=delta)\n patches = list()\n for surf in surf_list:\n if \"Lamination\" in surf.label:\n patches.extend(surf.get_patches(color=lam_color, is_edge_only=is_edge_only))\n else:\n patches.extend(surf.get_patches(is_edge_only=is_edge_only))\n # Display the result\n if is_display:\n (fig, axes, patch_leg, label_leg) = init_fig(fig)\n axes.set_xlabel(\"(m)\")\n axes.set_ylabel(\"(m)\")\n for patch in patches:\n axes.add_patch(patch)\n\n # Axis Setup\n axis(\"equal\")\n\n # The Lamination is centered in the figure\n Lim = self.Rext * 1.5\n axes.set_xlim(-Lim, Lim)\n axes.set_ylim(-Lim, Lim)\n\n # Add the legend\n if not is_edge_only:\n if self.is_stator and \"Stator\" not in label_leg:\n patch_leg.append(Patch(color=STATOR_COLOR))\n label_leg.append(\"Stator\")\n axes.set_title(\"Stator with empty slot\")\n elif not self.is_stator and \"Rotor\" not in label_leg:\n patch_leg.append(Patch(color=ROTOR_COLOR))\n label_leg.append(\"Rotor\")\n axes.set_title(\"Rotor with empty slot\")\n\n legend(patch_leg, label_leg)\n if is_show:\n fig.show()\n else:\n return patches\n"
] |
[
[
"numpy.array"
],
[
"matplotlib.backends.backend_qt5agg.FigureCanvas",
"matplotlib.pyplot.subplots"
],
[
"numpy.ones"
],
[
"matplotlib.pyplot.legend",
"matplotlib.patches.Patch",
"matplotlib.pyplot.axis"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rflperry/double_descent
|
[
"5001613791b3bbfa77c86f8426458253e8989bea",
"5001613791b3bbfa77c86f8426458253e8989bea"
] |
[
"partition_decode/network.py",
"PGDL/sample_code_submission/internal_rep/matrix_funcs.py"
] |
[
"import numpy as np\nimport torch\nfrom torch import nn\n\nimport os\n\n## Network functions\n\n# Model\nclass Net(nn.Module):\n \"\"\"\n A class for a deep neural net architecture.\n\n Parameters\n ----------\n in_dim: int\n Input dimension.\n\n out_dim: int\n Output dimension.\n\n hidden_size: int, default = 10\n Number of nodes in every hidden layer.\n\n n_hidden: int, default = 2\n Number of hidden layers\n\n activation: ACTIVATION, default = torch.nn.ReLU()\n Activation function to be used by the hidden layers.\n\n bias: bool, default = False\n A boolean indicating if a bias shall be added.\n\n bn: bool, default = False\n A boolean indicating if batch norm shall be applied.\n\n \"\"\"\n\n def __init__(\n self,\n in_dim,\n out_dim,\n hidden_size=10,\n n_hidden=2,\n activation=torch.nn.ReLU(),\n bias=False,\n bn=False,\n ):\n super(Net, self).__init__()\n\n module = nn.ModuleList()\n module.append(nn.Linear(in_dim, hidden_size, bias=bias))\n\n for ll in range(n_hidden):\n module.append(activation)\n if bn:\n module.append(nn.BatchNorm1d(hidden_size))\n module.append(nn.Linear(hidden_size, hidden_size, bias=bias))\n\n module.append(activation)\n if bn:\n module.append(nn.BatchNorm1d(hidden_size))\n module.append(nn.Linear(hidden_size, out_dim, bias=bias))\n\n self.sequential = nn.Sequential(*module)\n\n def forward(self, x):\n return self.sequential(x)\n\n\n## functions\n\n\ndef weight_reset(m):\n \"\"\"\n Reinitializes parameters of a model [m] according to default initialization scheme.\n \"\"\"\n if isinstance(m, torch.nn.Conv2d) or isinstance(m, torch.nn.Linear):\n m.reset_parameters()\n\n\ndef train_model(model, train_x, train_y, multi_label=False, verbose=False):\n \"\"\"\n Performs training of a model given training data.\n\n Parameters\n ----------\n\n model : Net\n A deep neural net model to be trained\n\n train_x : Tensor\n Training features\n\n train_y: Tensor\n Training labels\n\n multi_label: bool, default = False\n A boolean indicating if it is a multi-label classification\n\n verbose: bool, default = False\n A boolean indicating the production of detailed logging information during training\n\n Returns\n -------\n losses : Tensor\n The accumulated losses during training.\n \"\"\"\n\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n loss_func = torch.nn.BCEWithLogitsLoss()\n\n losses = []\n\n for step in range(1000):\n optimizer.zero_grad()\n outputs = model(train_x)\n if multi_label:\n train_y = train_y.type_as(outputs)\n\n loss = loss_func(outputs, train_y)\n trainL = loss.detach().item()\n if verbose and (step % 500 == 0):\n print(\"train loss = \", trainL)\n losses.append(trainL)\n loss.backward()\n optimizer.step()\n\n return losses\n\n\ndef get_model(\n in_dim=2,\n out_dim=1,\n hidden_size=20,\n n_hidden=5,\n activation=torch.nn.ReLU(),\n bias=True,\n bn=False,\n use_gpu=True,\n):\n \"\"\"\n Initializes the deep neural net model and send to gpu\n\n Parameters\n ----------\n in_dim: int\n Input dimension.\n\n out_dim: int\n Output dimension.\n\n hidden_size: int, default = 10\n Number of nodes in every hidden layer\n\n n_hidden: int, default = 2\n Number of hidden layers\n\n activation: ACTIVATION, default = torch.nn.ReLU()\n Activation function to be used by the hidden layers\n\n bias: bool, default = False\n A boolean indicating if a bias shall be added\n\n bn: bool, default = False\n A boolean indicating if batch norm shall be applied\n\n use_gpu: bool, default = True\n A boolean indicating if a gpu is available\n\n Returns\n -------\n model : Net\n A deep neural net model\n \"\"\"\n\n model = Net(\n in_dim,\n out_dim,\n n_hidden=n_hidden,\n hidden_size=hidden_size,\n activation=activation,\n bias=bias,\n bn=bn,\n )\n\n if use_gpu:\n model = model.cuda()\n\n return model\n",
"import numpy as np\nimport scipy\nfrom scipy import stats\n\nfrom networkx.algorithms import bipartite\nimport scipy.linalg as la\nfrom numpy.linalg import matrix_rank, norm\nimport community\nfrom community import community_louvain\n\nimport pandas as pd\n\nimport copy\n\n\ndef ger_matrix_from_poly(model, dataset, poly_m):\n # L_matrices = {'0/1': [], 'true_label':[], 'est_label':[], 'est_poster':[]}\n L_matrices = []\n test_y, pred_y, test_acc = get_label_pred(model, dataset)\n print(pred_y.shape, poly_m.shape)\n unique_poly = np.unique(poly_m)\n n_poly = len(unique_poly)\n\n # for key in L_matrices:\n L_mat = np.zeros((len(poly_m), n_poly))\n for idx, poly_i in enumerate(poly_m):\n poly_idx = np.where(unique_poly == poly_i)\n L_mat[idx, poly_idx] = pred_y[idx] + 1\n # if key == '0/1':\n # L_mat[idx, poly_idx] = pred_label[idx]\n # elif key == 'true_label':\n # L_mat[idx, poly_idx] = 2*y_train[idx]-1\n # elif key == 'est_label':\n # L_mat[idx, poly_idx] = 2*pred_label[idx]-1\n # elif key == 'est_poster':\n # L_mat[idx, poly_idx] = 2*pred_poster[idx]-1\n # L_matrices[key].append(L_mat)\n\n # gen_gap = abs((1-test_acc) - (1-train_acc))\n test_gen_err = 1 - test_acc\n return np.array(L_mat), test_gen_err\n\n\ndef get_label_pred(model, dataset, computeOver=500, batchSize=50):\n\n it = iter(dataset.repeat(-1).shuffle(50000, seed=1).batch(batchSize))\n N = computeOver // batchSize\n batches = [next(it) for i in range(N)]\n\n test_y = [batch[1] for batch in batches]\n\n # ds = dataset.repeat(-1).shuffle(50000, seed=1).batch(batchSize)\n # preds = model.predict(x=ds, steps=N, verbose=False)\n # print(preds.shape)\n # preds = model.predict(x=dataset)\n # print(preds.shape)\n # pred_y = np.argmax(preds, axis=-1)\n\n model.compile(\n optimizer=\"adam\", loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"]\n )\n\n acc, size = 0, 0\n y_true = []\n preds = []\n for batch in batches:\n test_loss, test_acc = model.evaluate(batch[0], batch[1], verbose=False)\n acc += test_acc * len(batch[1])\n size += len(batch[1])\n preds.extend(model.predict(batch[0]))\n acc = acc / size\n pred_y = np.argmax(preds, axis=-1)\n print(pred_y.shape)\n return test_y, pred_y, acc\n\n\n##********** Matrix ranks *************##\ndef get_stable_rank(m):\n \"\"\"\n Compute stable rank of a matrix: frobenius norm (squared) / spectral norm (squared)\n \"\"\"\n return norm(m, ord=\"fro\") ** 2 / norm(m, ord=2) ** 2\n\n\ndef get_KF_Schatten_norms(m, num_k=5):\n \"\"\"\n Compute different matrix norms\n Input: m - 2d matrix (n by L)\n Return: 4 1D numpy arrays\n - First: Ky-Fan results [Un-normalized], where k-th element is the sum of top-k singular values\n - Second: Ky-Fan results [Normalized], where k-th element is the ratio of the variance explained by top-k singular values\n - Third: Ky-Fan results on m^T @ m, where k-th element is the sum of top-k eigenvalues of m^T @ m (i.e., singular values of (m) squared)\n - Fourth: Schatten results, where k-th element is the k-norm, (sum_i sigma^k)^{1/k}\n \"\"\"\n ss = np.linalg.svd(m, full_matrices=False, compute_uv=False)\n KFs_raw = np.array([ss[: i + 1].sum() for i in range(num_k)])\n total = ss.sum()\n KFs = KFs_raw / total\n evalues = ss ** 2\n KFs_kernel = np.array([evalues[: i + 1].sum() for i in range(num_k)])\n Schattens = [total]\n ss_pow = copy.deepcopy(ss)\n for i in range(2, num_k + 1):\n ss_pow = np.multiply(ss_pow, ss)\n Schattens.append(np.power(ss_pow.sum(), 1 / i))\n return KFs_raw, KFs, KFs_kernel, np.array(Schattens)\n\n\ndef graph_metrics(m):\n \"\"\"\n Input: internal representation, n by L\n Return: 2-tuple\n - clustering coefficients of a bipartite graph built from m, a measure of local density of the connectivity\n ref: https://networkx.org/documentation/stable//reference/algorithms/generated/networkx.algorithms.bipartite.cluster.clustering.html#networkx.algorithms.bipartite.cluster.clustering\n - modularity: relative density of edges inside communities with respect to edges outside communities.\n ref: https://python-louvain.readthedocs.io/en/latest/api.html#community.modularity\n \"\"\"\n sM = scipy.sparse.csr_matrix(m)\n G = bipartite.matrix.from_biadjacency_matrix(sM)\n avg_c = bipartite.average_clustering(G, mode=\"dot\")\n partition = community_louvain.best_partition(G)\n modularity = community.modularity(partition, G)\n\n return avg_c, modularity\n\n\ndef compute_complexity(L, k=5, from_evalues=False, from_gram=False):\n \"\"\"\n Computes a variety of internal representation complexity metrics at once.\n Parameters\n ----------\n L : numpy.ndarray, shape (n_samples, ...)\n internal representation matrix or precomputed eigenvalues\n k : int, default=5\n number of eigenvalues for KF and Schatten methods\n from_evalues : boolean, default=False\n If True, then L is assumed to be the precomputed eigenvalues\n from_gram : boolean, default=False\n If True, then L is assumed to be a square kernel (Gram) matrix.\n Otherwise an svd will be performed on L where the Gram matrix is LL^T\n which improves computational efficiency.\n Returns\n -------\n complexity_dict : dict\n dictionary of (metric_name, metric_value) pairs for L\n \"\"\"\n\n complexity_dict = {}\n\n # For efficiency across the multiple metrics\n if from_evalues:\n evalues = L\n elif from_gram:\n evalues = np.linalg.svd(L, compute_uv=False, hermitian=True)\n else:\n ss = np.linalg.svd(L, compute_uv=False)\n evalues = np.zeros(L.shape[0])\n evalues[:len(ss)] = ss**2\n\n KF_norms, KF_ratios, KF_kers, Schattens = get_KF_Schatten_norms(evalues, k, from_evalues=True)\n complexity_dict['KF-raw'] = KF_norms\n complexity_dict['KF-ratio'] = KF_ratios\n complexity_dict['KF-kernel'] = KF_kers\n complexity_dict['Schatten'] = Schattens\n\n h_star, h_argmin = get_local_rad_bound(evalues, normalize=True, from_evalues=True)\n complexity_dict['h*'] = h_star\n complexity_dict['h_argmin'] = h_argmin\n\n return complexity_dict\n\n\ndef compute_tau(gen_gap, metric, inverse=False):\n \"\"\"\n Input: array (generalization gap); array (metric computed for the model instance at such a generalization gap);\n - If inverse: first take inverse of the metric, and compute the kendall tau coefficient\n Return: kendall's tau coefficient, pvalue\n \"\"\"\n if inverse:\n metric = np.array([1 / elem for elem in metric])\n tau, p_value = stats.kendalltau(gen_gap, metric)\n return tau, p_value\n\n\ndef get_df_tau(plot_dict, gen_err):\n \"\"\"\n Return a dataframe of the kendall tau's coefficient for different methods\n \"\"\"\n # tau, p_value = compute_tau(result_dict[err], plot_dict['avg_clusters'], inverse=True)\n # taus, pvalues, names, inverses = [tau], [p_value], ['cc'], ['True']\n taus, pvalues, names, inverses = [], [], [], []\n for key, value in plot_dict.items():\n value = np.array(value)\n # if key in ['ranks', 'stable_ranks', 'avg_clusters', 'modularity']:\n # continue\n for i in range(value.shape[1]):\n if key == \"Schatten\":\n if i == 0: # Schatten 1-norm, no inversion\n inverse_flag = False\n elif i == 1:\n continue # skip trivial 2-norm\n else:\n inverse_flag = True\n else:\n inverse_flag = True\n tau, p_value = compute_tau(gen_err, value[:, i], inverse=inverse_flag)\n taus.append(tau)\n pvalues.append(p_value)\n names.append(key + \"_\" + str(i + 1))\n inverses.append(inverse_flag)\n\n kendal_cor = pd.DataFrame(\n {\"metric\": names, \"kendall_tau\": taus, \"pvalue\": pvalues, \"inverse\": inverses}\n )\n\n return kendal_cor"
] |
[
[
"torch.nn.Sequential",
"torch.nn.BatchNorm1d",
"torch.nn.ModuleList",
"torch.nn.Linear",
"torch.nn.BCEWithLogitsLoss",
"torch.nn.ReLU"
],
[
"numpy.linalg.svd",
"numpy.multiply",
"numpy.unique",
"numpy.linalg.norm",
"scipy.sparse.csr_matrix",
"pandas.DataFrame",
"numpy.argmax",
"scipy.stats.kendalltau",
"numpy.array",
"numpy.where",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
AIprogrammer/Detailed-virtual-try-on
|
[
"25691ef097a3e82d108a8dbf596ba635092a8301"
] |
[
"data/demo_dataset.py"
] |
[
"import os\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.dataset import Dataset\nimport os.path as osp\nfrom PIL import Image\nimport numpy as np\nfrom torchvision import transforms\nfrom torchvision import utils\nfrom utils import pose_utils\nfrom PIL import ImageDraw\nfrom utils.transforms import create_part\nimport time\nimport json\nimport random\nimport cv2\nfrom data.base_dataset import BaseDataset, get_transform\nnp.seterr(divide='ignore', invalid='ignore')\n\nclass DemoDataset(BaseDataset):\n def __init__(self, config, augment):\n self.opt = config\n self.transforms = augment\n self.isval = self.opt.isval\n self.isdemo = self.opt.isdemo\n self.train_mode = self.opt.train_mode \n self.fine_width = 192\n self.fine_height = 256\n self.size = (256, 192)\n \n if self.opt.warp_cloth:\n self.img_list =[i.strip() for i in open('dataset/data_pair.txt', 'r').readlines()]\n else:\n self.img_list =[i.strip() for i in open('demo/demo.txt', 'r').readlines()]\n\n\n def __getitem__(self, index):\n t0 = time.time()\n try:\n img_source = self.img_list[index].split('\\t')[0]\n target_pose = self.img_list[index].split('\\t')[1]\n cloth_img = self.img_list[index].split('\\t')[2]\n data_suffix = self.img_list[index].split('\\t')[3]\n except:\n img_source = self.img_list[index].split(' ')[0]\n target_pose = self.img_list[index].split(' ')[1]\n cloth_img = self.img_list[index].split(' ')[2]\n data_suffix = self.img_list[index].split(' ')[3]\n \n data_suffix = data_suffix if data_suffix == 'train' else 'val'\n source_splitext = os.path.splitext(img_source)[0]\n cloth_splitext = os.path.splitext(cloth_img)[0]\n\n if self.opt.warp_cloth:\n source_splitext = os.path.join(data_suffix, source_splitext)\n cloth_img = os.path.join(data_suffix, cloth_img)\n cloth_splitext = os.path.join(data_suffix, cloth_splitext)\n \n source_img_path = os.path.join('dataset/images', source_splitext + '.jpg')\n cloth_parse_path = os.path.join('dataset/cloth_mask', cloth_splitext + '_mask.png')\n \n if self.opt.warp_cloth:\n cloth_img_path = os.path.join('dataset/images', cloth_img)\n else:\n cloth_img_path = os.path.join('dataset/cloth_image', cloth_img)\n\n ### image\n source_img = self.open_transform(source_img_path, False)\n cloth_img = self.open_transform(cloth_img_path, False)\n cloth_parse = self.parse_cloth(cloth_parse_path)\n # parsing\n if self.opt.warp_cloth:\n source_splitext = os.path.join(source_splitext.split('/')[0], source_splitext.split('/')[2])\n \n source_parse_vis_path = os.path.join('dataset/parse_cihp', source_splitext + '_vis.png')\n source_parse_vis = self.transforms['3'](Image.open(source_parse_vis_path)) \n source_parse_path = os.path.join('dataset/parse_cihp', source_splitext + '.png')\n source_parse = pose_utils.parsing_embedding(source_parse_path)\n\n source_parse_shape = np.array(Image.open(source_parse_path))\n source_parse_shape = (source_parse_shape > 0).astype(np.float32)\n source_parse_shape = Image.fromarray((source_parse_shape*255).astype(np.uint8))\n source_parse_shape = source_parse_shape.resize((self.size[1]//16, self.size[0]//16), Image.BILINEAR) # downsample and then upsample\n source_parse_shape = source_parse_shape.resize((self.size[1], self.size[0]), Image.BILINEAR)\n source_parse_shape = self.transforms['1'](source_parse_shape) # [-1,1]\n\n source_parse_head = (np.array(Image.open(source_parse_path)) == 1).astype(np.float32) + \\\n (np.array(Image.open(source_parse_path)) == 2).astype(np.float32) + \\\n (np.array(Image.open(source_parse_path)) == 4).astype(np.float32) + \\\n (np.array(Image.open(source_parse_path)) == 13).astype(np.float32)\n\n\n # prepare for warped cloth\n phead = torch.from_numpy(source_parse_head) # [0,1]\n im_h = source_img * phead - (1 - phead) # [-1,1], fill -1 for other parts, thus become black visual\n \n # pose heatmap embedding\n source_pose_path = os.path.join('dataset/pose_coco', source_splitext +'_keypoints.json')\n with open(source_pose_path, 'r') as f:\n a = json.load(f)\n source_pose = a['people'][0]['pose_keypoints_2d']\n source_pose_loc = pose_utils.pose2loc(source_pose)\n source_pose_embedding = pose_utils.heatmap_embedding(self.size, source_pose_loc)\n \n if self.opt.warp_cloth:\n target_splitext = os.path.splitext(target_pose)[0]\n target_pose_path = os.path.join('dataset/pose_coco', data_suffix, target_splitext.split('/')[1] +'_keypoints.json')\n warped_cloth_name = source_splitext.split('/')[0] + '/' + \\\n source_splitext.split('/')[1] + '_' + \\\n target_splitext.split('/')[1] + '_' + \\\n cloth_splitext.split('/')[2] + '_warped_cloth.jpg' \n warped_cloth_name = warped_cloth_name.split('/')[0] + '/' + warped_cloth_name.split('/')[1].split('-')[0] + '/' + warped_cloth_name.split('/')[1]\n else:\n target_pose_path = os.path.join('dataset/pose_coco', target_pose)\n warped_cloth_name = cloth_splitext\n\n with open(target_pose_path, 'r') as f:\n a = json.load(f)\n target_pose = a['people'][0]['pose_keypoints_2d']\n target_pose_loc = pose_utils.pose2loc(target_pose)\n target_pose_embedding = pose_utils.heatmap_embedding(self.size, target_pose_loc)\n target_pose_img, _ = pose_utils.draw_pose_from_cords(target_pose_loc, (256, 192))\n result = {\n 'source_parse': source_parse,\n 'source_parse_vis': source_parse_vis,\n 'source_pose_embedding': source_pose_embedding,\n 'target_pose_embedding': target_pose_embedding,\n 'target_pose_loc': target_pose_loc,\n 'source_image': source_img, \n 'cloth_image' : cloth_img,\n 'cloth_parse' : cloth_parse,\n 'source_parse_shape': source_parse_shape,\n 'im_h': im_h, # source image head and hair\n 'source_image_name': source_splitext,\n 'cloth_image_name': cloth_splitext,\n 'source_img_path': source_img_path,\n 'target_pose_path': target_pose_path,\n 'source_parse_vis_path': source_parse_vis_path,\n 'target_pose_img': target_pose_img,\n 'warped_cloth_name': warped_cloth_name\n }\n\n return result\n\n def __len__(self):\n\n return len(self.img_list)\n \n def make_pair(self, pair_list, test_num, pair_num):\n\n test_list = list(filter(lambda p: p.split('\\t')[3] == 'test', pair_list))\n img_source = [i.split('\\t')[0] for i in test_list]\n img_target = [i.split('\\t')[1] for i in test_list]\n cloth_img = [i.split('\\t')[2] for i in test_list]\n\n selected_img = random.sample(img_source, test_num)\n selected_target = random.sample(img_target, pair_num)\n selected_cloth = random.sample(cloth_img, pair_num)\n\n pair_list = []\n\n with open('demo/uniform_test.txt', 'w') as f:\n for i in range(test_num):\n for j in range(pair_num):\n pair = selected_img[i] + '\\t' + selected_target[j] + '\\t' + selected_cloth[j] + '\\t' + 'test'\n f.write(pair + '\\n')\n pair_list.append(pair)\n return pair_list\n \n def open_transform(self, path, downsample=False):\n img = Image.open(path)\n if downsample:\n img = img.resize((96,128),Image.BICUBIC)\n img = self.transforms['3'](img)\n return img\n \n def parse_cloth(self, path, downsample=False): \n cloth_parse = Image.open(path)\n cloth_parse_array = np.array(cloth_parse)\n cloth_parse = (cloth_parse_array == 255).astype(np.float32) # 0 | 1\n cloth_parse = cloth_parse[np.newaxis, :]\n \n if downsample:\n [X, Y] = np.meshgrid(range(0,192,2),range(0,256,2)) \n cloth_parse = cloth_parse[:,Y,X]\n\n cloth_parse = torch.from_numpy(cloth_parse)\n\n return cloth_parse\n\nif __name__ == '__main__':\n pass\n"
] |
[
[
"numpy.seterr",
"numpy.array",
"torch.from_numpy"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
OvJat/LoadData
|
[
"2ed1d65b91c534ebf999e272cb067e60275a7318"
] |
[
"demo3.py"
] |
[
"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n\r\n\"\"\"\r\n Support Python 3.8\r\n @author: Lou Xiao([email protected])\r\n @maintainer: Lou Xiao([email protected])\r\n @copyright: Copyright 2018~2021\r\n @created time: 2021-10-17 19:26:32 CST\r\n @updated time: 2021-10-17 19:26:32 CST\r\n\"\"\"\r\n\r\nimport os\r\nimport time\r\nimport torch\r\nimport torch.utils.data as td\r\nimport h5py\r\n\r\n\r\ndef preprocess(data_dir: str, num_samples: int):\r\n data_file = os.path.join(data_dir, 'dataset.hdf5')\r\n os.makedirs(data_dir, exist_ok=True)\r\n with h5py.File(data_file, 'w') as f:\r\n for i in range(num_samples):\r\n xx = torch.rand(3, 128, 128, dtype=torch.float16)\r\n yy = torch.randint(0, 10, (1,), dtype=torch.long)\r\n\r\n index_name = 'sample_%010d' % i\r\n key_xx = '%s/xx' % index_name\r\n key_yy = '%s/yy' % index_name\r\n # compression\r\n # f.create_dataset(key_xx, data=xx, compression='gzip', compression_opts=9)\r\n # f.create_dataset(key_yy, data=yy, compression='gzip', compression_opts=9)\r\n f.create_dataset(key_xx, data=xx)\r\n f.create_dataset(key_yy, data=yy)\r\n\r\n\r\nclass MyData(td.Dataset):\r\n\r\n def __init__(self, data_file: str):\r\n self.data_file = data_file\r\n self.index_list = []\r\n # scan files\r\n with h5py.File(self.data_file, 'r') as f:\r\n for name in f.keys():\r\n if name.startswith('sample_'):\r\n self.index_list.append(name)\r\n\r\n def __len__(self):\r\n return len(self.index_list)\r\n\r\n def __getitem__(self, index: int):\r\n # load file for sample index\r\n index_name = self.index_list[index]\r\n with h5py.File(self.data_file, 'r') as f:\r\n dt = f[index_name]\r\n xx = dt['xx'][:]\r\n yy = dt['yy'][:]\r\n return xx, yy\r\n\r\n\r\ndef main():\r\n data_dir = './data/demo3'\r\n data_file = os.path.join(data_dir, 'dataset.hdf5')\r\n\r\n # preprocess(data_dir, 10000)\r\n\r\n batch_size = 32\r\n\r\n ds = MyData(data_file)\r\n dl = td.DataLoader(ds, shuffle=True, batch_size=batch_size, drop_last=True, num_workers=5)\r\n start = time.time()\r\n for i, (xx, yy) in enumerate(dl):\r\n pass\r\n total_time = time.time() - start\r\n print(\"total time: %5f\" % total_time)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n"
] |
[
[
"torch.utils.data.DataLoader",
"torch.rand",
"torch.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Sandeepa1995/cylon
|
[
"a42d04ad9a65b20c84a15d649f9d849f18676183"
] |
[
"python/test/test_frame.py"
] |
[
"##\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##\n\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport pycylon as cn\nimport pyarrow as pa\nfrom pycylon import Series\nfrom pycylon.frame import DataFrame\nfrom pycylon import Table\nfrom pycylon.io import CSVReadOptions\nfrom pycylon.io import read_csv\nfrom pycylon import CylonContext\nimport operator\n\n\ndef test_initialization_1():\n d1 = [[1, 2, 3], [4, 5, 6]]\n d2 = [np.array([1, 2, 3]), np.array([4, 5, 6])]\n d3 = {'0': [1, 2, 3], '1': [4, 5, 6]}\n d4 = pd.DataFrame(d3)\n d5 = pa.Table.from_pydict(d3)\n\n cdf1 = DataFrame(d1)\n cdf2 = DataFrame(d2)\n cdf3 = DataFrame(d3)\n cdf4 = DataFrame(d4)\n cdf5 = DataFrame(d5)\n\n assert cdf1.shape == cdf2.shape == cdf3.shape == cdf4.shape == cdf5.shape\n\n\ndef test_get_set_item():\n d1 = [[1, 2, 3], [4, 5, 6]]\n cdf1 = DataFrame(d1)\n print(cdf1)\n\n print(cdf1.columns)\n\n c1 = cdf1['0']\n print(c1.shape)\n d1 = DataFrame([[10, 20, 30]])\n\n print(d1.shape)\n print(cdf1)\n cdf1['0'] = d1\n\n print(cdf1)\n\n\ndef test_filter():\n ctx: CylonContext = CylonContext(config=None, distributed=False)\n table1_path = '/tmp/user_usage_tm_1.csv'\n table2_path = '/tmp/user_usage_tm_2.csv'\n\n assert os.path.exists(table1_path) and os.path.exists(table2_path)\n\n csv_read_options = CSVReadOptions().use_threads(True).block_size(1 << 30)\n\n tb: Table = read_csv(ctx, table1_path, csv_read_options)\n df: DataFrame = DataFrame(tb)\n\n column_name = 'monthly_mb'\n\n ops = [operator.__or__, operator.__and__]\n or_limits = [600, 5000, 15000]\n and_limits = [0, 5000, 1000]\n comp_op_or = [operator.__gt__, operator.__le__, operator.__gt__]\n comp_op_and = [operator.__gt__, operator.__le__, operator.__gt__]\n limits = [or_limits, and_limits]\n comp_ops = [comp_op_or, comp_op_and]\n\n for op, limit, comp_op in zip(ops, limits, comp_ops):\n print(\"Op \", op)\n tb_cond_1 = comp_op[0](df[column_name], limit[0])\n tb_cond_2 = comp_op[1](df[column_name], limit[1])\n tb_cond_3 = comp_op[2](df[column_name], limit[2])\n\n res_1_op = op(tb_cond_1, tb_cond_2)\n res_2_op = op(res_1_op, tb_cond_3)\n\n res_1 = df[res_1_op]\n res_2 = df[res_2_op]\n\n column_pdf_1 = res_1[column_name].to_pandas()\n column_pdf_2 = res_2[column_name].to_pandas()\n\n column_1 = column_pdf_1[column_name]\n for col in column_1:\n assert op(comp_op[0](col, limit[0]), comp_op[1](col, limit[1]))\n\n column_2 = column_pdf_2[column_name]\n for col in column_2:\n assert op(op(comp_op[0](col, limit[0]), comp_op[1](col, limit[1])),\n comp_op[2](col, limit[2]))\n\n\ndef test_invert():\n # Bool Invert Test\n\n data_list = [[False, True, False, True, True], [False, True, False, True, True]]\n pdf = pd.DataFrame(data_list)\n cdf = DataFrame(pdf)\n\n invert_cdf = ~cdf\n invert_pdf = ~pdf\n\n assert invert_cdf.to_pandas().values.tolist() == invert_pdf.values.tolist()\n\n\ndef test_neg():\n npr = np.array([[1, 2, 3, 4, 5, -6, -7], [-1, -2, -3, -4, -5, 6, 7]])\n pdf = pd.DataFrame(npr)\n cdf = DataFrame(pdf)\n neg_cdf = -cdf\n neg_pdf = -pdf\n assert neg_cdf.to_pandas().values.tolist() == neg_pdf.values.tolist()\n\n\ndef test_setitem():\n npr = np.array([[1, 2, 3, 4, 5], [-1, -2, -3, -4, -5]])\n pdf = pd.DataFrame(npr)\n\n cdf = DataFrame(pdf)\n # replacing an existing column\n cdf['0'] = cdf['4']\n assert cdf['0'].to_pandas().values.tolist() == cdf['4'].to_pandas().values.tolist()\n # adding a new column at the end\n cdf['5'] = cdf['4']\n assert cdf['5'].to_pandas().values.tolist() == cdf['4'].to_pandas().values.tolist()\n\n\ndef test_math_ops_for_scalar():\n npr = np.array([[20, 2, 3, 4, 5], [10, -20, -30, -40, -50], [10.2, 13.2, 16.4, 12.2, 10.8]])\n pdf = pd.DataFrame(npr)\n cdf = DataFrame(pdf)\n\n from operator import add, sub, mul, truediv\n ops = [add, sub, mul, truediv]\n\n for op in ops:\n cdf_1 = cdf\n pdf_1 = pdf\n # test column division\n cdf_1['0'] = op(cdf_1['0'], 2)\n pdf_1[0] = op(pdf_1[0], 2)\n\n assert pdf_1.values.tolist() == cdf_1.to_pandas().values.tolist()\n\n # test table division\n cdf_2 = cdf\n pdf_2 = pdf\n\n cdf_2 = op(cdf_2, 2)\n pdf_2 = op(pdf, 2)\n\n assert pdf_2.values.tolist() == cdf_2.to_pandas().values.tolist()\n\n\ndef test_i_bitwise_ops():\n # TODO: Improve test and functionality: https://github.com/cylondata/cylon/issues/229\n npr = np.array([[20, 2, 3, 4, 5], [10, -20, -30, -40, -50], [36.2, 13.2, 16.4, 12.2, 10.8]])\n pdf = pd.DataFrame(npr)\n cdf = DataFrame(pdf)\n\n a = cdf['0'] > 10\n b = cdf['1'] > 2\n a_pdf = pdf[0] > 10\n b_pdf = pdf[1] > 2\n\n d = a & b\n a &= b\n d_pdf = a_pdf & b_pdf\n a_pdf &= b_pdf\n\n assert d.to_pandas().values.tolist() == a.to_pandas().values.tolist()\n assert a.to_pandas().values.flatten().tolist() == a_pdf.values.tolist()\n\n ## OR\n\n a = cdf['0'] > 10\n b = cdf['1'] > 2\n a_pdf = pdf[0] > 10\n b_pdf = pdf[1] > 2\n\n d = a | b\n a |= b\n d_pdf = a_pdf | b_pdf\n a_pdf |= b_pdf\n\n assert d.to_pandas().values.tolist() == a.to_pandas().values.tolist()\n assert a.to_pandas().values.flatten().tolist() == a_pdf.values.tolist()\n\n\ndef test_math_i_ops_for_scalar():\n npr = np.array([[20, 2, 3, 4, 5], [10, -20, -30, -40, -50], [12.2, 13.2, 16.4, 12.2, 10.8]])\n pdf = pd.DataFrame(npr)\n cdf = DataFrame(pdf)\n\n cdf_1 = cdf\n pdf_1 = pdf\n # test column addition\n\n cdf_1['0'] += 2\n pdf_1[0] += 2\n\n assert pdf_1.values.tolist() == cdf_1.to_pandas().values.tolist()\n\n cdf_1['0'] -= 2\n pdf_1[0] -= 2\n\n assert pdf_1.values.tolist() == cdf_1.to_pandas().values.tolist()\n\n cdf_1['0'] *= 2\n pdf_1[0] *= 2\n\n assert pdf_1.values.tolist() == cdf_1.to_pandas().values.tolist()\n\n cdf_1['0'] /= 2\n pdf_1[0] /= 2\n\n assert pdf_1.values.tolist() == cdf_1.to_pandas().values.tolist()\n\n # test table division\n cdf_2 = cdf_1\n pdf_2 = pdf\n\n cdf_2 += 2\n pdf += 2\n\n assert pdf_2.values.tolist() == cdf_2.to_pandas().values.tolist()\n\n cdf_2 -= 2\n pdf -= 2\n\n assert pdf_2.values.tolist() == cdf_2.to_pandas().values.tolist()\n\n cdf_2 *= 2\n pdf *= 2\n\n assert pdf_2.values.tolist() == cdf_2.to_pandas().values.tolist()\n\n cdf_2 /= 2\n pdf /= 2\n\n assert pdf_2.values.tolist() == cdf_2.to_pandas().values.tolist()\n\n\ndef test_drop():\n ctx: CylonContext = CylonContext(config=None, distributed=False)\n\n table1_path = '/tmp/user_usage_tm_1.csv'\n\n assert os.path.exists(table1_path)\n\n csv_read_options = CSVReadOptions().use_threads(True).block_size(1 << 30)\n\n tb: Table = read_csv(ctx, table1_path, csv_read_options)\n cdf = DataFrame(tb)\n\n drop_column = 'outgoing_sms_per_month'\n\n cdf_new = cdf.drop([drop_column])\n\n assert not cdf_new.columns.__contains__(drop_column)\n\n\ndef test_fillna():\n data_list_numeric = [[1, 2, None, 4, 5], [6, 7, 8, 9, None]]\n fill_value = 0\n\n cdf_numeric = DataFrame(data_list_numeric)\n\n cn_tb_numeric_fillna = cdf_numeric.fillna(fill_value)\n\n data_list = list(cn_tb_numeric_fillna.to_dict().values())\n for col in data_list:\n assert not col.__contains__(None)\n assert col.__contains__(fill_value)\n\n\ndef test_notna():\n data = [[1, 2, 3, 4, 5, None], [None, 7, 8, 9, 10, 11]]\n cdf = DataFrame(data)\n df = cdf.to_pandas()\n\n assert df.notna().values.tolist() == cdf.notna().to_pandas().values.tolist()\n\n\ndef test_notnull():\n data = [[1, 2, 3, 4, 5, None], [None, 7, 8, 9, 10, 11]]\n cdf = DataFrame(data)\n df = cdf.to_pandas()\n\n assert df.notnull().values.tolist() == cdf.notnull().to_pandas().values.tolist()\n\n\ndef test_isin():\n pdf = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]})\n cdf = DataFrame(pdf)\n\n arr = [0, 2]\n assert (pdf.isin(arr).values.tolist() == cdf.isin(arr).to_pandas().values.tolist())\n\n\ndef test_isna():\n data = [[1, 2, 3, 4, 5, None], [None, 7, 8, 9, 10, 11]]\n cdf = DataFrame(data)\n df = cdf.to_pandas()\n\n assert df.isna().values.tolist() == cdf.isna().to_pandas().values.tolist()\n\n\ndef test_isnull():\n data = [[1, 2, 3, 4, 5, None], [None, 7, 8, 9, 10, 11]]\n cdf = DataFrame(data)\n df = cdf.to_pandas()\n\n assert df.isnull().values.tolist() == cdf.isnull().to_pandas().values.tolist()\n\n\ndef test_rename():\n col_names = ['col1', 'col2', 'col3', 'col4']\n data_list_numeric = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20]]\n ctx: CylonContext = CylonContext(config=None, distributed=False)\n index_values = [0, 1, 2, 3, 4]\n cn_tb = cn.Table.from_list(ctx, col_names, data_list_numeric)\n cn_tb.set_index(index_values)\n cdf = DataFrame(cn_tb)\n prev_col_names = cn_tb.column_names\n # with dictionary\n columns = {'col1': 'col-1', 'col3': 'col-3'}\n cdf.rename(columns)\n\n new_col_names = cdf.columns\n\n for key in columns:\n value = columns[key]\n assert prev_col_names.index(key) == new_col_names.index(value)\n\n # with list\n cn_tb_list = cn.Table.from_list(ctx, col_names, data_list_numeric)\n cn_tb_list.set_index(index_values)\n cdf_list = DataFrame(cn_tb_list)\n prev_col_names = cdf_list.columns\n new_column_names = ['col-1', 'col-2', 'col-3', 'col-4']\n cdf_list.rename(new_column_names)\n\n assert cdf_list.columns == new_column_names\n\n\ndef test_applymap():\n pdf = pd.DataFrame([[1, 2.12], [3.356, 4.567]])\n cdf = DataFrame(pdf)\n\n print(cdf.applymap(lambda x: len(str(x))))\n\n assert (pdf.applymap(lambda x: len(str(x))).values.tolist() == cdf.applymap(\n lambda x: len(str(x))).to_pandas().values.tolist())\n"
] |
[
[
"numpy.array",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
psmaAaron/keras-fcn
|
[
"90843ef7465e0ce289f0a45a62d2d176a932e7ab"
] |
[
"keras_fcn/encoders.py"
] |
[
"from __future__ import (\n absolute_import,\n unicode_literals\n)\nimport tensorflow.keras\nimport tensorflow.keras.backend as K\n\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.utils import get_file, convert_all_kernels_in_model\n\nfrom keras_fcn.blocks import (\n vgg_conv,\n vgg_fc\n)\n\ndef load_weights(model, weights_path):\n \"\"\"Load weights from Caffe models.\"\"\"\n print(\"Loading weights...\")\n if h5py is None:\n raise ImportError('`load_weights` requires h5py.')\n f = h5py.File(weights_path, mode='r')\n\n # New file format.\n layer_names = [n.decode('utf8') for n in f.attrs['layer_names']]\n\n # Reverse index of layer name to list of layers with name.\n index = {}\n for layer in model.layers:\n if layer.name:\n index.setdefault(layer.name, []).append(layer)\n\n # We batch weight value assignments in a single backend call\n # which provides a speedup in TensorFlow.\n weight_value_tuples = []\n for k, name in enumerate(layer_names):\n g = f[name]\n weight_names = [n.decode('utf8') for n in g.attrs['weight_names']]\n weight_values = [g[weight_name] for weight_name in weight_names]\n\n for layer in index.get(name, []):\n symbolic_weights = layer.weights\n # Set values.\n for i in range(len(weight_values)):\n weight_value_tuples.append((symbolic_weights[i],\n weight_values[i]))\n K.batch_set_value(weight_value_tuples)\n\n return layer_names\n\n\nclass Encoder(Model):\n \"\"\"Encoder for Fully Convolutional Networks.\n :param inputs: 4D Tensor, the input tensor\n :param blocks: 1D array, list of functional convolutional blocks\n\n :return A Keras Model with outputs including the output of\n each block except the final conv block (using the encoder's top instead)\n\n >>> from tensorflow.keras.layers import Input\n >>> from keras_fcn.encoders import Encoder\n >>> from keras_fcn.blocks import (vgg_conv, vgg_fc)\n >>> inputs = Input(shape=(224, 224, 3))\n >>> blocks = [vgg_conv(64, 2, 'block1'),\n >>> vgg_conv(128, 2, 'block2'),\n >>> vgg_conv(256, 3, 'block3'),\n >>> vgg_conv(512, 3, 'block4'),\n >>> vgg_conv(512, 3, 'block5'),\n >>> vgg_fc(4096)]\n >>> encoder = Encoder(inputs, blocks, weights='imagenet',\n >>> trainable=True)\n >>> feat_pyramid = encoder.outputs # A feature pyramid with 5 scales\n\n \"\"\"\n\n def __init__(self, inputs, blocks, weights=None,\n trainable=True, name='encoder'):\n inverse_pyramid = []\n\n # convolutional block\n conv_blocks = blocks[:-1]\n for i, block in enumerate(conv_blocks):\n if i == 0:\n x = block(inputs)\n inverse_pyramid.append(x)\n elif i < len(conv_blocks) - 1:\n x = block(x)\n inverse_pyramid.append(x)\n else:\n x = block(x)\n\n # fully convolutional block\n fc_block = blocks[-1]\n y = fc_block(x)\n inverse_pyramid.append(y)\n\n outputs = list(reversed(inverse_pyramid))\n\n super(Encoder, self).__init__(\n inputs=inputs, outputs=outputs)\n\n # load pre-trained weights\n if weights is not None:\n weights_path = get_file(\n '{}_weights_tf_dim_ordering_tf_kernels.h5'.format(name),\n weights,\n cache_subdir='models')\n layer_names = load_weights(self, weights_path)\n if K.image_data_format() == 'channels_first':\n convert_all_kernels_in_model(self)\n\n # Freezing basenet weights\n if trainable is False:\n for layer in self.layers:\n if layer.name in layer_names:\n layer.trainable = False\n\n\nclass VGGEncoder(Encoder):\n \"\"\"VGG VGGEncoder.\n\n :param inputs: 4D Tensor, the input tensor\n :param filters: 1D array, number of filters per block\n :param convs: 1D array, number of convolutional layers per block, with\n length the same as `filters`.\n\n :return A Keras Model with outputs including the output of\n each block except `pool5` (using drop7 from `pool5` instead)\n\n >>> from keras_fcn.encoders import VGGEncoder\n >>> from tensorflow.keras.layers import Input\n >>> x = Input(shape=(224, 224, 3))\n >>> encoder = VGGEncoder(Input(x),\n >>> filters=[64, 128, 256, 512, 512],\n >>> convs=[2, 2, 3, 3, 3])\n >>> feat_pyramid = encoder.outputs\n\n \"\"\"\n\n def __init__(self, inputs, filters, convs, weight_decay=0.,\n weights=None, trainable=True):\n blocks = []\n\n # Convolutional blocks\n for i, (fltr, conv) in enumerate(zip(filters, convs)):\n block_name = 'block{}'.format(i + 1)\n block = vgg_conv(filters=fltr, convs=conv, padding=False,\n weight_decay=weight_decay,\n block_name=block_name)\n blocks.append(block)\n\n # Fully Convolutional block\n fc_block = vgg_fc(filters=4096, weight_decay=weight_decay)\n blocks.append(fc_block)\n\n super(VGGEncoder, self).__init__(inputs=inputs, blocks=blocks,\n weights=weights, trainable=trainable)\n\n\nclass VGG16(VGGEncoder):\n \"\"\"A VGG16 feature encoder.\n\n >>> from keras_fcn.encoders import VGG16\n >>> from tensorflow.keras.layers import Input\n >>> x = Input(shape=(224, 224, 3))\n >>> encoder = VGG16(x)\n >>> feat_pyramid = encoder.outputs\n\n \"\"\"\n\n def __init__(self, inputs, weight_decay=0.,\n weights='imagenet', trainable=True):\n if weights == 'imagenet':\n weights = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5'\n else:\n weights = None\n\n super(VGG16, self).__init__(inputs,\n filters=[64, 128, 256, 512, 512],\n convs=[2, 2, 3, 3, 3],\n weight_decay=weight_decay,\n weights=weights,\n trainable=trainable)\n\n\nclass VGG19(VGGEncoder):\n \"\"\"VGG19 net.\n\n >>> from keras_fcn.encoders import VGG19\n >>> from tensorflow.keras.layers import Input\n >>> x = Input(shape=(224, 224, 3))\n >>> encoder = VGG19(x)\n >>> feat_pyramids = encoder.outputs\n\n \"\"\"\n\n def __init__(self, inputs, weight_decay=0.,\n weights='imagenet', trainable=True):\n if weights == 'imagenet':\n weights = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5'\n else:\n weights = None\n\n super(VGG19, self).__init__(inputs,\n filters=[64, 128, 256, 512, 512],\n convs=[2, 2, 4, 4, 4],\n weight_decay=weight_decay,\n weights=weights,\n trainable=trainable)\n"
] |
[
[
"tensorflow.keras.utils.convert_all_kernels_in_model",
"tensorflow.keras.backend.batch_set_value",
"tensorflow.keras.backend.image_data_format"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.2",
"2.3",
"1.10"
]
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.