【问题标题】:ValueError: could not convert string to float: matrix fileValueError:无法将字符串转换为浮点数:矩阵文件
【发布时间】:2019-08-03 02:41:58
【问题描述】:

问候我有一个文件 matrix.txt,具有以下矩阵 3x3 dtype float32...

-----------------matrix.txt------------

[[ 2.94795074e+00  3.15288849e-02 -8.67170450e+02]
 [-2.21123258e-17  2.94877180e+00 -5.95651904e+02]
 [ 1.49601560e-04  1.52843706e-04  1.00000000e+00]]

p_homo = np.array([[1], [1], [1]])    
file = open('matrix.txt', 'r')
matrix_file_l =list()
matrix_file_l = file.read()
matrix_file = np.array(matrix_file_l,  dtype="float32")

def mult_matrix(matrix1, matrix2):
    matrixx = np.empty([len(matrix1), len(matrix2[0])])
    for i in range(len(matrix1)):
        for j in range(len(matrix2[0])):
            for k in range(len(matrix2)):
                matrixx[i][j] += matrix1[i][k] * matrix2[k][j]
    return matrixx

matrix = mult_matrix(matrix_file, p_homo)

matrix_file 是一个字符串,我无法转换为 float32 我尝试通过多种方式进行转换

matrix_file = np.array(matrix_file_l,  dtype="float32")
ValueError: could not convert string to float: '[[-5.62093010e+01... 

【问题讨论】:

  • 如果该文件不包含方括号,它会更容易阅读。只是数字,每行的列数相等,并带有一些明确定义的分隔符(空格或逗号)。所谓的csv 格式。
  • 是的,这是真的,但我需要括号以便稍后将矩阵相乘 @hpaulj.. 谢谢
  • 文本文件中不需要括号。从技术上讲,括号也不是数组的一部分——它们只是数组漂亮显示格式的一部分。 csvnp.genfromtxt 等读者从 csv 文件创建一个数组。
  • 如果出于某种原因我想不出文本文件已经带有括号,请尝试使用eval:matrix_file = np.array(eval(matrix_file_l))。仅供参考,numpy 还具有矩阵乘法的功能(np.matmulnp.dot
  • @Mstaino 我尝试使用 eval: 但同样的错误.. matrix_file = np.array(matrix_file_l, dtype="float32") ValueError: could not convert string to float: '[[ 1.82278459e+00 1.91872062e-02 -8.78831607e+02]\n'

标签: python-3.x string file numpy matrix-multiplication


【解决方案1】:

这对我有用...我使用 numpy np.savenp.load 代替文件 file = open('matrix.txt', 'w') file.write(matrix) matrix_value = file.read() 将我的矩阵保存在 matrix.npy 之后很容易进行操作,因为 numpy 保存值作为 numpy.ndarray 而不是字符串 ....

--------------- script1 ------

...

np.save('matrix', matrix_value)

...

--------- 脚本2 ---------------

p_homo = np.array([[1], [1], [1]])    
a= np.load('matrix.npy')

...

matrix = mult_matrix(a, p_homo)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-23
    • 2018-06-13
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    相关资源
    最近更新 更多