By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,814 Members | 1,111 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,814 IT Pros & Developers. It's quick & easy.

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

P: 25
Hey,

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

Expand|Select|Wrap|Line Numbers
  1. from numpy import array
  2. inputMeans =array([1, 2, 3])
  3. inputStds =array([4, 5, 6])
  4.  
  5. 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.
Jul 13 '11 #1
Share this Question
Share on Google+
4 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Where is inputs defined? I suspect inputs has different dimensions than the other objects.
Expand|Select|Wrap|Line Numbers
  1. >>> inputMeans =array([1., 2., 3.])
  2. >>> inputStds = array([4., 5., 6.])
  3. >>> inputs = array([7., 15., 5.67])
  4. >>> inputs = ((array(inputs)-inputMeans)/inputStds).tolist()
  5. >>> inputs
  6. [1.5, 2.6000000000000001, 0.44500000000000001]
  7. >>> 
Jul 13 '11 #2

P: 25
from numpy import array
inputMeans =array([1, 2, 3])
inputStds =array([4, 5, 6])
inputs=[]
inputs = ((array(inputs)-inputMeans)/inputStds).tolist()

// inputs is of array type
Jul 13 '11 #3

P: 25
sorry for inconvenience. Here is the code with good readability.

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/python
  2. from Scientific.IO import NetCDF
  3. from numpy import arange, array, vectorize, newaxis
  4. import netcdf_helpers
  5. from scipy import *
  6. from optparse import OptionParser
  7. import sys
  8. import os
  9. from xml.dom.minidom import parse
  10.  
  11. 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']
  12. inputMeans =array([0.03199977,102.7592,511.8343])
  13. inputStds =array([0.1758981,24.34094,134.0498])
  14.  
  15. #command line options
  16. parser = OptionParser()
  17. #parse command line options
  18. (options, args) = parser.parse_args()
  19. if (len(args)<2):
  20.     print "usage: -options input_filename output_filename"
  21.     print options
  22.     sys.exit(2)
  23.  
  24. inputFilename = args [0]
  25. ncFilename = args[1]
  26. print options
  27. print "input filename", inputFilename
  28. print "data filename", ncFilename
  29. seqDims = []
  30. seqLengths = []
  31. targetStrings = []
  32. wordTargetStrings = []
  33. seqTags = []
  34. inputs = []
  35. contain=[]
  36. new=[]
  37. print "reading data files"
  38. for l in file(inputFilename).readlines():
  39.     xmlfile = l.strip()
  40.     if len(xmlfile):
  41.         print xmlfile
  42.         seqTags.append(xmlfile)
  43.         upxfile = xmlfile.replace('xml', 'upx')
  44.         if os.path.exists(upxfile):
  45.             word = parse(upxfile).getElementsByTagName('hwData')[0].getElementsByTagName('label')[0].getElementsByTagName('alternate')[0].getAttribute('value').strip().replace(' ','*')
  46.             print word
  47.             wts = word.encode('spell')
  48.             print wts
  49.             wordTargetStrings.append(wts)    
  50.             ts = ""
  51.             for c in word:
  52.                 label = c.encode('spell')
  53.                 ts += label + ' '
  54.             ts = ts.strip()
  55.             print ts
  56.             targetStrings.append(ts)
  57.         else:
  58.             wordTargetStrings.append(' ')
  59.             targetStrings.append(' ')            
  60.         oldlen = len(inputs)
  61.         for trace in parse(xmlfile).getElementsByTagName('trace'):        
  62.             for coords in trace.firstChild.nodeValue.split(','):
  63.                 pt = coords.split()
  64.                 inputs.append([float(pt[0]), float(pt[1]), 0.0])
  65.             inputs[-1][-1] = 1
  66.         seqLengths.append(len(inputs) - oldlen)
  67.         seqDims.append([seqLengths[-1]])
  68.  
  69. inputs = ((array(inputs)- inputMeans)/inputStds).tolist()
  70. print len(labels), labels
  71. print labels
  72.  
  73. #create a new .nc file
  74. file = netcdf_helpers.NetCDFFile(ncFilename, 'w')
  75.  
  76. #create the dimensions
  77. netcdf_helpers.createNcDim(file,'numSeqs',len(seqLengths))
  78. netcdf_helpers.createNcDim(file,'numTimesteps',len(inputs))
  79. #netcdf_helpers.createNcDim(file,'inputPattSize',len(inputs[0]))
  80. netcdf_helpers.createNcDim(file,'numDims',1)
  81. netcdf_helpers.createNcDim(file,'numLabels',len(labels))
  82.  
  83. #create the variables
  84. netcdf_helpers.createNcStrings(file,'seqTags',seqTags,('numSeqs','maxSeqTagLength'),'sequence tags')
  85. netcdf_helpers.createNcStrings(file,'labels',labels,('numLabels','maxLabelLength'),'labels')
  86. netcdf_helpers.createNcStrings(file,'targetStrings',targetStrings,('numSeqs','maxTargStringLength'),'target strings')
  87. netcdf_helpers.createNcStrings(file,'wordTargetStrings',wordTargetStrings,('numSeqs','maxWordTargStringLength'),'word target strings')
  88. netcdf_helpers.createNcVar(file,'seqLengths',seqLengths,'i',('numSeqs',),'sequence lengths')
  89. netcdf_helpers.createNcVar(file,'seqDims',seqDims,'i',('numSeqs','numDims'),'sequence dimensions')
  90. #netcdf_helpers.createNcVar(file,'inputs',inputs,'f',('numTimesteps','inputPattSize'),'input patterns')
  91.  
  92. #write the data to disk
  93. print "closing file", ncFilename
  94. file.close()
If I give .inkml file then it works fine but it gives an error when I give .xml file
Jul 14 '11 #4

bvdet
Expert Mod 2.5K+
P: 2,851
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:
Expand|Select|Wrap|Line Numbers
  1. import sys, traceback
  2.  
  3. def formatExceptionInfo(level=3):
  4.     error_type, error_value, trbk = sys.exc_info()
  5.     info_list = ["Error: %s \nDescription: %s \nTraceback:\n" % (error_type.__name__, error_value), ]
  6.     info_list.extend(traceback.format_tb(trbk, level))
  7.     return ''.join(info_list)
Example:
Expand|Select|Wrap|Line Numbers
  1.     def test_formatExceptionInfo():
  2.         try:
  3.             # Code to be executed here
  4.         except Exception, e:
  5.             print formatExceptionInfo()
Jul 15 '11 #5

Post your reply

Sign in to post your reply or Sign up for a free account.