将一个请求有不均匀形状的数组的一个元素设置为一个序列后,该错误出现在1维后。检测到的形状为(2,)+不均匀部分。

19
import os
import numpy as np
from scipy.signal import *
import csv
import matplotlib.pyplot as plt

from scipy import signal
from brainflow.board_shim import BoardShim, BrainFlowInputParams, LogLevels, BoardIds
from brainflow.data_filter import DataFilter, FilterTypes, AggOperations, WindowFunctions, DetrendOperations
from sklearn.cluster import KMeans

#Options to read: 'EEG-IO', 'EEG-VV', 'EEG-VR', 'EEG-MB'
data_folder = 'EEG-IO' 

# Parameters and bandpass filtering
fs = 250.0

# Reading data files
file_idx = 0
list_of_files = [f for f in os.listdir(data_folder) if os.path.isfile(os.path.join(data_folder, f)) and '_data' in f] #List of all the files, Lists are randomized, its only looking for file with _data in it
print(list_of_files)
file_sig = list_of_files[file_idx] # Data File
file_stim = list_of_files[file_idx].replace('_data','_labels') #Label File, Replacing _data with _labels
print ("Reading: ", file_sig, file_stim)

# Loading data
if data_folder == 'EEG-IO' or data_folder == 'EEG-MB':
    data_sig = np.loadtxt(open(os.path.join(data_folder,file_sig), "rb"), delimiter=";", skiprows=1, usecols=(0,1,2)) #data_sig would be a buffer
elif data_folder == 'EEG-VR' or data_folder == 'EEG-VV':
    data_sig = np.loadtxt(open(os.path.join(data_folder,file_sig), "rb"), delimiter=",", skiprows=5, usecols=(0,1,2)) 
    data_sig = data_sig[0:(int(200*fs)+1),:] # getting data ready -- not needed for previous 2 datasets
    data_sig = data_sig[:,0:3] #
    data_sig[:,0] = np.array(range(0,len(data_sig)))/fs


############ Calculating PSD ############
index, ch = data_sig.shape[0], data_sig.shape[1]
# print(index)
feature_vectors = [[], []]
feature_vectorsa = [[], []]
feature_vectorsb = [[], []]
feature_vectorsc = [[], []]
#for x in range(ch):
#for x in range(1,3):
#while x < 
#while x>0:
x=1
while x>0 and x<3:
    if x==1:
        data_sig[:,1] = lowpass(data_sig[:,1], 10, fs, 4)

    elif x==2:
        data_sig[:,2] = lowpass(data_sig[:,2], 10, fs, 4)

    for y in range(500, 19328 ,500):
        #print(ch)
        if x==1:
            DataFilter.detrend(data_sig[y-500:y, 1], DetrendOperations.LINEAR.value)

            psd = DataFilter.get_psd_welch(data_sig[y-500:y, 1], nfft, nfft//2, 250,
                                       WindowFunctions.BLACKMAN_HARRIS.value)

            band_power_delta = DataFilter.get_band_power(psd, 1.0, 4.0)
            
            # Theta 4-8
            band_power_theta = DataFilter.get_band_power(psd, 4.0, 8.0)
            
            #Alpha 8-12
            band_power_alpha = DataFilter.get_band_power(psd, 8.0, 12.0)
             
            #Beta 12-30
            band_power_beta = DataFilter.get_band_power(psd, 12.0, 30.0)
            # print(feature_vectors.shape)

            feature_vectors[x].insert(y, [band_power_delta, band_power_theta, band_power_alpha, band_power_beta])
            feature_vectorsa[x].insert(y, [band_power_delta, band_power_theta])

        elif x==2:
            DataFilter.detrend(data_sig[y-500:y, 2], DetrendOperations.LINEAR.value)

            psd = DataFilter.get_psd_welch(data_sig[y-500:y, 2], nfft, nfft//2, 250,
                                       WindowFunctions.BLACKMAN_HARRIS.value)

            band_power_delta = DataFilter.get_band_power(psd, 1.0, 4.0)
            
            # Theta 4-8
            band_power_theta = DataFilter.get_band_power(psd, 4.0, 8.0)
            
            #Alpha 8-12
            band_power_alpha = DataFilter.get_band_power(psd, 8.0, 12.0)
             
            #Beta 12-30
            band_power_beta = DataFilter.get_band_power(psd, 12.0, 30.0)
            # print(feature_vectors.shape)

            # feature_vectorsc[x].insert(y, [band_power_delta, band_power_theta, band_power_alpha, band_power_beta])
            # feature_vectorsd[x].insert(y, [band_power_delta, band_power_theta])

    x = x+1

print(feature_vectorsa)
powers = np.log10(np.asarray(feature_vectors, dtype=float))
powers1 = np.log10(np.asarray(feature_vectorsa, dtype=float))
# powers2 = np.log10(np.asarray(feature_vectorsb))
# powers3 = np.log10(np.asarray(feature_vectorsc))
print(powers.shape)
print(powers1.shape)

非常困惑。当我运行代码时,一直出现以下错误:
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.
回溯信息:
File "/Users/mikaelhaji/Downloads/EEG-EyeBlinks/read_data.py", line 170, in powers = np.log10(np.asarray(feature_vectors, dtype=float)) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/numpy/core/_asarray.py", line 102, in asarray return array(a, dtype, copy=False, order=order) ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.
如果您对为什么会发生这种情况有任何想法或答案,请告诉我。
提前感谢您的回复。

1
首先,请发布带有行号的完整回溯。否则,我们只能猜测哪一行代码引发了“ValueError”。其次,请不要在此处粘贴整个代码。尝试创建一个最小可重现示例 - jjramsey
1
抱歉,我现在会立即处理。 - ILovePhysics
@jjramsey 我刚刚让代码更加简洁,并添加了回溯。 - ILovePhysics
无法从“feature_vectors”创建数字数组,可能是由于列表大小混合。 - hpaulj
2
我遇到了类似的问题,而且在我的情况下,内部数组的大小是不同的。一旦我通过确保数组大小一致来纠正这个问题,问题就得到了解决。这可能不是解决这个问题的唯一方法,但对于像我这样花了几个小时解决问题的人可能会有所帮助 :D。 - vipin
8个回答

17

你尝试过降级 numpy 吗?当我将它从 1.24.1 降级到 1.21.6 时,错误消失了,只剩下了 UserWarning 和 FutureWarning。

!pip install numpy==1.21.6

对我没用:我已经安装了numpy==1.21.6,但仍然出现错误。 - xdola
如果你运行 pip uninstall numpy 然后 pip install numpy=1.21.1 如果版本不对,你会收到一个错误提示,告诉你应该安装哪个版本的 numpy错误:pip 的依赖解析器目前未考虑所有已安装的软件包。这种行为是以下依赖冲突的根源。 pandas 2.1.0 需要 numpy>=1.22.4; python_version < "3.11",但你安装的是不兼容的 numpy 1.21.2。 - undefined

5

带有 dtype="object" 对我有效。

variable2 = np.asarray(variable1, dtype="object")

你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

3
这里有一个产生错误信息的简单案例:

以下是需要翻译的内容:

In [19]: np.asarray([[1,2,3],[4,5]],float)
Traceback (most recent call last):
  File "<ipython-input-19-72fd80bc7856>", line 1, in <module>
    np.asarray([[1,2,3],[4,5]],float)
  File "/usr/local/lib/python3.8/dist-packages/numpy/core/_asarray.py", line 102, in asarray
    return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.

如果我省略 float,它会生成一个对象类型的数组 - 伴随着警告。
In [20]: np.asarray([[1,2,3],[4,5]])
/usr/local/lib/python3.8/dist-packages/numpy/core/_asarray.py:102: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  return array(a, dtype, copy=False, order=order)
Out[20]: array([list([1, 2, 3]), list([4, 5])], dtype=object)

1

我尝试了上面提到的所有方法,但都没有解决我的问题。

实际问题是numpy版本不对。

尝试使用 pip install numpy==1.21.1,这对我起作用了。


1

当我们遇到Numpy版本问题时,就会出现这个错误。

我正在使用Python3.9,所以我按照以下方式安装:

pip install numpy==1.21.2

并且对我有用。


1

我遇到了同样的错误。 我正在打开一个包含值表的txt文件,并将其保存到NumPy数组中,定义dtype为float,否则数字将是字符串。

with open(dirfile) as fh:
    next(fh)
    header = next(fh)[2:]
    next(fh)
    data = np.array([line.strip().split() for line in fh], float)

对于之前的文件,它完美地工作了,但是对于最后一个文件却没有: 请求的数组在1维后具有不均匀的形状。检测到的形状为(35351,) + 不均匀部分。

然而,当我运行data = nploadtxt(fh)时,出现了一个新的错误:第35351行列数错误

所以,我的问题是文件的最后一行缺少最后两列的值。我在txt文件中进行了更正,因为我想要一个numpy.array(dtype=float)的相同结构,一切都正常工作了。


0
在我的情况下,我试图将一组对象设置为数据框。
pd.DataFrame(list_of_objects)

并且收到了相同的错误。
我能够使用@Chris上面的答案来解决它。
np_array_of_objects = np.asarray(list_of_objects, dtype="object")

pd.DataFrame(np_array_of_objects)

我想我应该加上这个答案,以防万一有人像我一样通过谷歌来使用pandas,而这个解决方案并不明显。

-1

你可能会遇到这样的问题:[1, np.array[0,1,2], 3, np.array[8,9,10]]

你可以做的一个简单的事情是:

  1. 在错误出现的地方设置断点
  2. 以调试模式运行IDE
  3. 打印特定的变量或代码行
  4. 避免使用嵌套数组的情况,它就能正常工作!

目前你的回答不够清晰,请[编辑]以添加更多细节,帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接