运行numpy代码报错TypeError: order must be str, not int如何解决?
报错原因
错误触发自代码最后一行的np.reshape(tempSmall,120,1)调用。
numpy的reshape函数语法为np.reshape(a, newshape, order='C'),其中第三个参数order是控制元素排列顺序的可选字符串参数,仅接受'C'/'F'/'A'三类字符串取值。你此处将整数1作为第三个参数传入,被函数识别为order参数的取值,因此触发TypeError: order must be str, not int报错。
解决方案
你需要将目标维度统一放在第二个参数的元组中传递。如果是要把10×12的tempSmall转为长度为120的一维数组(匹配Theta[:,k]的维度要求),可以选择以下任意一种写法替换最后一行:
- 写法1:将目标形状作为元组传入
Theta[:,k] = np.reshape(tempSmall, (120,)) - 写法2:直接用flatten方法拉平数组
Theta[:,k] = tempSmall.flatten()
如果确实需要先生成(120,1)的二维列向量再赋值,可以调整为:
Theta[:,k] = np.reshape(tempSmall, (120,1))[:,0]
修复后完整代码
M = Train.shape[1] Theta = np.zeros((120,M)) for k in range(M): temp = np.reshape(np.copy(Train[:,k]),(m,n)) tempSmall = resize(temp, (10, 12), anti_aliasing=True) Theta[:,k] = np.reshape(tempSmall, (120,))
内容的提问来源于stack exchange,提问作者Rohit thingbaijam
相关产品推荐
相关产品推荐

