簡體   English   中英

TypeError:數組dtype('float64')和格式說明符之間不匹配

[英]TypeError: Mismatch between array dtype ('float64') and format specifier

我有一個尺寸為1000 * 30 * 150的numpy數組。 我試圖將其保存為txt文件。 到目前為止,我已經嘗試過了

np.savetxt("test.txt", mydata, fmt='%.5f', delimiter=",")
#and 
with open('test.txt', 'w') as f:
    for row in mydata:
        np.savetxt(f, row, delimiter=',', fmt='%.5f')

這兩種方法都給我錯誤

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py", line 1254, in savetxt
    fh.write(asbytes(format % tuple(row) + newline))
TypeError: only length-1 arrays can be converted to Python scalars

During handling of the above exception, another exception occurred:

Traceback (most recent call last):


        np.savetxt("test.txt", train, fmt='%.5f', delimiter=",")
      File "/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py", line 1258, in savetxt
        % (str(X.dtype), format))
    TypeError: Mismatch between array dtype ('float64') and format specifier ('%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f')

問題是你的數組是3維的,不能以二維格式保存。 要么重塑它,所以它是2d:

mydata = mydata.reshape(mydata.shape[0],mydata.shape[1]*mydata.shape[2])
np.savetxt('text.txt',mydata,fmt='%.5f',delimiter=',')

或者如果您不需要將其作為文本文件讀取,並希望稍后在python使用中重新加載它:

np.save('text.npy',mydata)

您沒有提到將三維數組寫入文本文件的目的是什么,將來是否會將其讀回來,以及您要查找的格式,但這是一種可能性:

import json
print(json.dumps(mydata, default=lambda x: list(x), indent=4))

如果您澄清目的,人們將能夠提出更合適的解決方案。

告訴我們mydata 特別是它的dtypeshape

要以%.5f格式保存,它需要是一個二維數組。

savetxt大致:

 for row in arr:
   print(format % tuple(row))

其中format是根據您的fmt參數構造的,以及數組中的數字列。 看起來您的數組有大量列,因此format'%.5f,%.5f,%.5f,%.5f,%.5f,%... string。

需要使用tuple將該1d數組row轉換為使用format%()的元組。

如果數組是更高的維度或對象數組,則會出現問題。


編輯 - 所以你說數組是1000 * 30 * 150。 所以它試圖迭代1000行,30看起來像那個format的大小。 但它不能應用於(30,150)陣列。

使用openrow迭代,你會得到同樣的錯誤嗎? 在Py3中,您可能需要使用'wb'. Iterating yourself on the first dimension means each打開'wb'. Iterating yourself on the first dimension means each 'wb'. Iterating yourself on the first dimension means each savetxt call works with a 30x150 array. It will iterate on the 30, and try to format rows of 150. The would create a larger call works with a 30x150 array. It will iterate on the 30, and try to format rows of 150. The would create a larger格式`,但我認為這將運行。

無論如何, savetxt是為2d數字數組設計的。 3d需要某種軟糖。 請記住, csv閱讀器也不是為3d陣列設計的。 他們期望具有一致列的行由簡單的分隔符分隔。


In [260]: arr = np.arange(24).reshape(4,3,2)

它可以使用3d - 如果允許使用%s格式化每個子行:

In [261]: np.savetxt('test',arr, fmt='%s')
In [262]: cat test
[0 1] [2 3] [4 5]
[6 7] [8 9] [10 11]
[12 13] [14 15] [16 17]
[18 19] [20 21] [22 23]

3d數字格式 - 錯誤

In [263]: np.savetxt('test',arr, fmt='%d')
....
TypeError: Mismatch between array dtype ('int32') and format specifier ('%d %d %d')

重塑3d到2d - 保存工作:

In [264]: np.savetxt('test',arr.reshape(-1,2), fmt='%d')
In [265]: cat test
0 1
2 3
4 5
6 7
8 9
...
22 23

通過額外的迭代; 可以在塊之間添加一個空行

In [267]: with open('test','wb') as f:
     ...:     for row in arr:
     ...:         np.savetxt(f, row, '%d',delimiter=', ')
     ...:         
In [268]: cat test
0, 1
2, 3
4, 5
6, 7
...
22, 23

np.savetxt()的替代方法可能是使用csv模塊:

with open("filename.","w+") as my_csv:            # writing the file as my_csv
    csvWriter = csv.writer(my_csv,delimiter=',')  # using the csv module to write the file
    csvWriter.writerows(array_2d)                 # write every row in the matrix

我遇到了與numpy類似的TypeError問題,但CSV方法似乎工作正常。

如果您希望在mydata[i,:,:]的軸上以格式化的行和列寫出數據,目的是以更易讀的表格格式生成內容,請參閱以下答案: 如何編寫多維數組到文本文件? 由@JoeKington。 我的代碼在每個切片的行和列中添加了一個循環,因為我找不到我在實現原始代碼時得到的TypeError的任何其他解析:

    with open('test.txt', 'w') as outfile:
        # Add header giving shape of array
        # Any line starting with "#" will be ignored by numpy.loadtxt
        outfile.write('# Array shape: {0}\n'.format(x_train.shape))

        # Iterating through a ndimensional array produces slices along
        # the last axis. This is equivalent to data[i,:,:] in this case
        sliceCount = 0
        for data_slice in x_train:
            # Keep track of the slice numbers
            outfile.write('# New slice %d\n'%sliceCount)

            # Work through each row and column of the 2d numpy array inside the 
            # slice, writing each column number to file in format of your choosing
            for row in data_slice:
                for col in row:
                    itemStr = "%8.6f,"%col
                    outfile.write(itemStr)
                outfile.write("\n")

            sliceCount += 1

TypeError: 數組 dtype (' <u32') and format specifier ('%.18e')< div><div id="text_translate"><p> 我第一次使用np.savetxt ,我試圖將兩個變量(一個字符串和一個浮點數)保存在一個名為“trial.csv”的文件中,如下所示:</p><pre> import numpy as np RT = 2.76197329736740 key_name = 'space' print(RT,key_name) # Save data in a CSV file named subj_data_file np.savetxt("trial.csv", (RT,key_name), delimiter=',', header="RTs,Key_Name")</pre><p> 我收到以下錯誤:</p><pre> TypeError: Mismatch between array dtype ('&lt;U32') and format specifier ('%.18e')</pre><p> 我不明白('&lt;U32')和('%.18e')的含義。 事實上,當我有浮點數、整數和字符串時,我不明白如何使用fmt ......</p><p> 這是一個簡化的示例,但具體而言,我會將 RT 值(浮點數)放在一列“RTs”中,將 key_name(浮點數)值放在另一列“Key_Name”中。 稍后我將創建更多列,雖然我在此示例中為 RT 提供了一個值,為 key_name 提供了一個值,但在“RTs”列中將有更多 RT 值以及在“Key_Name”列中的鍵名。</p></div></u32')>

[英]TypeError: Mismatch between array dtype ('<U32') and format specifier ('%.18e')

TypeError:無法將數組數據從 dtype('float64) 轉換為 dtype(' <u32') according to safe rule< div><div id="text_translate"><pre> class SigmoidNeuron: def __init__(self): self.w=None self.b=None def perceptron(self,x): return np.dot(x,self.wT)+self.b def sigmoid(self,x): return 1.0/(1.0+np.exp(-x)) def grad_w(self,x,y): y_pred = self.sigmoid(self.perceptron(x)) return (y_pred-y)*y_pred*(1-y_pred)*x def grad_b(self,x,y): y_pred = self.sigmoid(self.perceptron(x)) return (y_pred-y)*y_pred*(1-y_pred) def fit(self,x,y,epochs=1,learning_rate=1,initialise=True): #initialise w,b if initialise: self.w=np.random.randn(1,X.shape[1]) self.b=0 for i in range(epochs): dw=0 db=0 for x,y in zip(X,Y): dw+=self.grad_w(x,y) db+=self.grad_b(x,y) self.w -= learning_rate*dw self.b -= learning_rate*db</pre><pre> `</pre><p> 我正在運行一個 sigmoid 神經網絡代碼,並且在使用數據運行此 class 時出現錯誤</p><pre>X_scaled_train.astype(float) array([[ 1.29929126, -0.90185206, 0.03173306, ..., -0.14142136, -0.15523011, 0.21232515], [-1.16225208, -0.86697607, 1.03451971, ..., -0.14142136, -0.15523011, 0.21232515], [ 1.77523922, 0.65594214, 0.03173306, ..., -0.14142136, -0.15523011, 0.21232515], ..., [ 1.44058831, -0.58796815, -0.66464655, ..., -0.14142136, -0.15523011, 0.21232515], [-1.42253612, 0.50481285, 1.54984063, ..., -0.14142136, -0.15523011, 0.21232515], [ 1.06875397, 0.6791928, 0.97880934, ..., -0.14142136, -0.15523011, 0.21232515]])</pre><pre> Y_scaled_train.astype(float) array([[0.68], [0.72], [0.72], [0.6 ], [0.8 ], [0.64], [0.68],</pre><p> 這些是我在運行這條線時訓練集的數據 sn.fit(X_scaled_train,Y_scaled_train,epochs=10,learning_rate=0.2) 我收到了那個類型錯誤我應該怎么做才能刪除它</p><p>錯誤顯示</p><pre>TypeError Traceback (most recent call last) &lt;ipython-input-167-51016d58d1f5&gt; in &lt;module&gt;() ----&gt; 1 sn.fit(X_scaled_train,Y_scaled_train,epochs=10,learning_rate=0.2) 2 frames &lt;ipython-input-25-2e09637c6d09&gt; in perceptron(self, x) 4 self.b=None 5 def perceptron(self,x): ----&gt; 6 return np.dot(x,self.wT)+self.b 7 def sigmoid(self,x): 8 return 1.0/(1.0+np.exp(-x)) &lt;__array_function__ internals&gt; in dot(*args, **kwargs) TypeError: Cannot cast array data from dtype('float64') to dtype('&lt;U32') according to the rule 'safe'</pre></div></u32')>

[英]TypeError: cannot cast array data from dtype('float64) to dtype('<U32') according to safe rule

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

相關問題 TypeError:數組 dtype 和格式說明符不匹配。 如何將具有不同值類型的 dataframe 保存為 txt 文件? 類型錯誤:數組 dtype(&#39;object&#39;)和格式說明符(&#39;%.18e&#39;)不匹配 TypeError:將熊貓文件保存到文本時,數組dtype(&#39;object&#39;)與格式說明符(&#39;%d%d&#39;)`之間不匹配 TypeError: 數組 dtype (' <u32') and format specifier ('%.18e')< div><div id="text_translate"><p> 我第一次使用np.savetxt ,我試圖將兩個變量(一個字符串和一個浮點數)保存在一個名為“trial.csv”的文件中,如下所示:</p><pre> import numpy as np RT = 2.76197329736740 key_name = 'space' print(RT,key_name) # Save data in a CSV file named subj_data_file np.savetxt("trial.csv", (RT,key_name), delimiter=',', header="RTs,Key_Name")</pre><p> 我收到以下錯誤:</p><pre> TypeError: Mismatch between array dtype ('&lt;U32') and format specifier ('%.18e')</pre><p> 我不明白('&lt;U32')和('%.18e')的含義。 事實上,當我有浮點數、整數和字符串時,我不明白如何使用fmt ......</p><p> 這是一個簡化的示例,但具體而言,我會將 RT 值(浮點數)放在一列“RTs”中,將 key_name(浮點數)值放在另一列“Key_Name”中。 稍后我將創建更多列,雖然我在此示例中為 RT 提供了一個值,為 key_name 提供了一個值,但在“RTs”列中將有更多 RT 值以及在“Key_Name”列中的鍵名。</p></div></u32')> 類型錯誤:無法根據規則“安全”將數組數據從 dtype(&#39;O&#39;) 轉換為 dtype(&#39;float64&#39;) TypeError:無法從dtype(&#39; TypeError: 數組 dtype ('|S32') 和格式說明符 ('%.7f %.7f %.7f %s') 不匹配 Numpy.dot TypeError:根據規則&#39;safe&#39;,無法將數組數據從dtype(&#39;float64&#39;)轉換為dtype(&#39;S32&#39;) TypeError:無法將數組數據從 dtype('float64) 轉換為 dtype(' <u32') according to safe rule< div><div id="text_translate"><pre> class SigmoidNeuron: def __init__(self): self.w=None self.b=None def perceptron(self,x): return np.dot(x,self.wT)+self.b def sigmoid(self,x): return 1.0/(1.0+np.exp(-x)) def grad_w(self,x,y): y_pred = self.sigmoid(self.perceptron(x)) return (y_pred-y)*y_pred*(1-y_pred)*x def grad_b(self,x,y): y_pred = self.sigmoid(self.perceptron(x)) return (y_pred-y)*y_pred*(1-y_pred) def fit(self,x,y,epochs=1,learning_rate=1,initialise=True): #initialise w,b if initialise: self.w=np.random.randn(1,X.shape[1]) self.b=0 for i in range(epochs): dw=0 db=0 for x,y in zip(X,Y): dw+=self.grad_w(x,y) db+=self.grad_b(x,y) self.w -= learning_rate*dw self.b -= learning_rate*db</pre><pre> `</pre><p> 我正在運行一個 sigmoid 神經網絡代碼,並且在使用數據運行此 class 時出現錯誤</p><pre>X_scaled_train.astype(float) array([[ 1.29929126, -0.90185206, 0.03173306, ..., -0.14142136, -0.15523011, 0.21232515], [-1.16225208, -0.86697607, 1.03451971, ..., -0.14142136, -0.15523011, 0.21232515], [ 1.77523922, 0.65594214, 0.03173306, ..., -0.14142136, -0.15523011, 0.21232515], ..., [ 1.44058831, -0.58796815, -0.66464655, ..., -0.14142136, -0.15523011, 0.21232515], [-1.42253612, 0.50481285, 1.54984063, ..., -0.14142136, -0.15523011, 0.21232515], [ 1.06875397, 0.6791928, 0.97880934, ..., -0.14142136, -0.15523011, 0.21232515]])</pre><pre> Y_scaled_train.astype(float) array([[0.68], [0.72], [0.72], [0.6 ], [0.8 ], [0.64], [0.68],</pre><p> 這些是我在運行這條線時訓練集的數據 sn.fit(X_scaled_train,Y_scaled_train,epochs=10,learning_rate=0.2) 我收到了那個類型錯誤我應該怎么做才能刪除它</p><p>錯誤顯示</p><pre>TypeError Traceback (most recent call last) &lt;ipython-input-167-51016d58d1f5&gt; in &lt;module&gt;() ----&gt; 1 sn.fit(X_scaled_train,Y_scaled_train,epochs=10,learning_rate=0.2) 2 frames &lt;ipython-input-25-2e09637c6d09&gt; in perceptron(self, x) 4 self.b=None 5 def perceptron(self,x): ----&gt; 6 return np.dot(x,self.wT)+self.b 7 def sigmoid(self,x): 8 return 1.0/(1.0+np.exp(-x)) &lt;__array_function__ internals&gt; in dot(*args, **kwargs) TypeError: Cannot cast array data from dtype('float64') to dtype('&lt;U32') according to the rule 'safe'</pre></div></u32')> Matplotlib錯誤TypeError:無法將數組數據從dtype(&#39;float64&#39;)轉換為dtype(&#39;
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM