ValueError: shape mismatch: objects cannot be broadcast to a single shape

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Saad Bin Ahmed
    New Member
    • Jul 2011
    • 25

    ValueError: shape mismatch: objects cannot be broadcast to a single shape

    Hey,

    I got the following error in python program. If anybody knows about this error then please share the solution.

    Code:
    from numpy import array
    inputMeans =array([1, 2, 3])
    inputStds =array([4, 5, 6])
    
    inputs = ((array(inputs)-inputMeans)/inputStds).tolist()
    ---------------------------------------------------------------------------
    ValueError Traceback (most recent call last)

    /home/saad/<ipython console> in <module>()

    ValueError: shape mismatch: objects cannot be broadcast to a single shape

    This is the error message which shows to me when I try to execute program. Your timely help would be highly appreciated.
    Last edited by bvdet; Jul 13 '11, 11:24 PM. Reason: Add code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Where is inputs defined? I suspect inputs has different dimensions than the other objects.
    Code:
    >>> inputMeans =array([1., 2., 3.])
    >>> inputStds = array([4., 5., 6.])
    >>> inputs = array([7., 15., 5.67])
    >>> inputs = ((array(inputs)-inputMeans)/inputStds).tolist()
    >>> inputs
    [1.5, 2.6000000000000001, 0.44500000000000001]
    >>>
    Last edited by Niheel; Jul 18 '11, 10:00 PM.

    Comment

    • Saad Bin Ahmed
      New Member
      • Jul 2011
      • 25

      #3
      from numpy import array
      inputMeans =array([1, 2, 3])
      inputStds =array([4, 5, 6])
      inputs=[]
      inputs = ((array(inputs)-inputMeans)/inputStds).toli st()

      // inputs is of array type

      Comment

      • Saad Bin Ahmed
        New Member
        • Jul 2011
        • 25

        #4
        sorry for inconvenience. Here is the code with good readability.

        Code:
        #!/usr/bin/python
        from Scientific.IO import NetCDF
        from numpy import arange, array, vectorize, newaxis
        import netcdf_helpers
        from scipy import *
        from optparse import OptionParser
        import sys
        import os
        from xml.dom.minidom import parse
        
        labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g','ga', 'h', 'i', 'j', 'k', 'km', 'l', 'm', 'n', 'o', 'p', 'pt', 'q','r','s','sc','sp','t','u','v','w','x','y','z']
        inputMeans =array([0.03199977,102.7592,511.8343])
        inputStds =array([0.1758981,24.34094,134.0498])
        
        #command line options
        parser = OptionParser()
        #parse command line options
        (options, args) = parser.parse_args()
        if (len(args)<2):
        	print "usage: -options input_filename output_filename"
        	print options
        	sys.exit(2)
        
        inputFilename = args [0]
        ncFilename = args[1]
        print options
        print "input filename", inputFilename
        print "data filename", ncFilename
        seqDims = []
        seqLengths = []
        targetStrings = []
        wordTargetStrings = []
        seqTags = []
        inputs = []
        contain=[]
        new=[]
        print "reading data files"
        for l in file(inputFilename).readlines():
        	xmlfile = l.strip()
        	if len(xmlfile):
        		print xmlfile
        		seqTags.append(xmlfile)
        		upxfile = xmlfile.replace('xml', 'upx')
        		if os.path.exists(upxfile):
        			word = parse(upxfile).getElementsByTagName('hwData')[0].getElementsByTagName('label')[0].getElementsByTagName('alternate')[0].getAttribute('value').strip().replace(' ','*')
        			print word
        			wts = word.encode('spell')
        			print wts
        			wordTargetStrings.append(wts)	
        			ts = ""
        			for c in word:
        				label = c.encode('spell')
        				ts += label + ' '
        			ts = ts.strip()
        			print ts
        			targetStrings.append(ts)
        		else:
        			wordTargetStrings.append(' ')
        			targetStrings.append(' ')			
        		oldlen = len(inputs)
        		for trace in parse(xmlfile).getElementsByTagName('trace'):		
        			for coords in trace.firstChild.nodeValue.split(','):
        				pt = coords.split()
        				inputs.append([float(pt[0]), float(pt[1]), 0.0])
        			inputs[-1][-1] = 1
        		seqLengths.append(len(inputs) - oldlen)
        		seqDims.append([seqLengths[-1]])
        
        [B]inputs = ((array(inputs)- inputMeans)/inputStds).tolist()[/B]
        print len(labels), labels
        print labels
        
        #create a new .nc file
        file = netcdf_helpers.NetCDFFile(ncFilename, 'w')
        
        #create the dimensions
        netcdf_helpers.createNcDim(file,'numSeqs',len(seqLengths))
        netcdf_helpers.createNcDim(file,'numTimesteps',len(inputs))
        #netcdf_helpers.createNcDim(file,'inputPattSize',len(inputs[0]))
        netcdf_helpers.createNcDim(file,'numDims',1)
        netcdf_helpers.createNcDim(file,'numLabels',len(labels))
        
        #create the variables
        netcdf_helpers.createNcStrings(file,'seqTags',seqTags,('numSeqs','maxSeqTagLength'),'sequence tags')
        netcdf_helpers.createNcStrings(file,'labels',labels,('numLabels','maxLabelLength'),'labels')
        netcdf_helpers.createNcStrings(file,'targetStrings',targetStrings,('numSeqs','maxTargStringLength'),'target strings')
        netcdf_helpers.createNcStrings(file,'wordTargetStrings',wordTargetStrings,('numSeqs','maxWordTargStringLength'),'word target strings')
        netcdf_helpers.createNcVar(file,'seqLengths',seqLengths,'i',('numSeqs',),'sequence lengths')
        netcdf_helpers.createNcVar(file,'seqDims',seqDims,'i',('numSeqs','numDims'),'sequence dimensions')
        #netcdf_helpers.createNcVar(file,'inputs',inputs,'f',('numTimesteps','inputPattSize'),'input patterns')
        
        #write the data to disk
        print "closing file", ncFilename
        file.close()
        If I give .inkml file then it works fine but it gives an error when I give .xml file

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          It would help immensely if you would post the error message and full traceback. Here's some code that you can call to trap the error and print the traceback:
          Code:
          import sys, traceback
          
          def formatExceptionInfo(level=3):
              error_type, error_value, trbk = sys.exc_info()
              info_list = ["Error: %s \nDescription: %s \nTraceback:\n" % (error_type.__name__, error_value), ]
              info_list.extend(traceback.format_tb(trbk, level))
              return ''.join(info_list)
          Example:
          Code:
              def test_formatExceptionInfo():
                  try:
                      # Code to be executed here
                  except Exception, e:
                      print formatExceptionInfo()

          Comment

          Working...