Хорошо, мне это показалось странным.
Я создаю классификатор текста. Я использовал word2vec gensim с агрегацией, когда я пытаюсь запустить его через классификатор sklearn, он выдает мне ValueError: установка элемента массива с последовательностью.
Вот мой код KNN
Вот мой код KNN р>
def check_inconsistencies(values):
# Check if it's a sequence (like a list of lists)
if isinstance(values, (list, tuple)):
# 1. Check for inconsistent types
types = set(type(v) for v in values)
if len(types) > 1:
print(f"Inconsistent types detected: {types}")
else:
print(f"Consistent type: {list(types)[0]}")
# 2. Check if all elements are also sequences (to verify shapes)
if all(isinstance(v, (list, tuple, np.ndarray)) for v in values):
# Check for shape inconsistencies
lengths = [len(v) for v in values]
if len(set(lengths)) > 1:
print(f"Inconsistent lengths detected: {lengths}")
else:
print(f"Consistent shape: All sub-lists/arrays have length {lengths[0]}")
else:
print("Not all elements are sequences; some may be single values.")
# If the input is a NumPy array, check its dtype consistency
if isinstance(values, np.ndarray):
print(f"NumPy array detected with dtype: {values.dtype}")
print(f"Shape: {values.shape}")
# Try to convert to NumPy array and catch potential errors
try:
arr = np.asarray(values)
print("Array created successfully:", arr)
except ValueError as e:
print(f"Error encountered: {e}")
Кроме того, я сам написал следующую проверку согласованности кода
for x in vec_pooled:
count1 += 1
if (type(x) != type(prev1)) or (len(x) != len(prev1)):
print(f"\nMismatch1: {type(x)} not {type(prev1)} {len(x)} not {len(prev1)} {count1}")
print(f" {x} \n {prev1} \n\n\n\n")
prev1 = x
for y in x:
count2 += 1
if (type(y) != type(prev2)) or (len(y) != len(prev2)):
print(f"\nMismatch2: {type(y)} not {type(prev2)} {len(y)} not {len(prev2)} {count2}")
print(f" {x} \n {prev1} \n\n\n\n")
prev2 = y
for z in y:
count3 += 1
if type(z) != type(prev3):
print(f"Mismatch3:{type(z)} not {type(prev3)} {count3}")
prev3 = z
count3 = 0
count2 = 0
print("Loop Completed")
print (f"Type of prev1: {type(prev1)}")
print (f"Type of prev2: {type(prev2)}")
print (f"Type of prev3: {type(prev3)}")
return vec_pooled
Оба работают нормально, поэтому я знаю, что массив не является неровным и не имеет противоречивых типов. Но при обычном запуске кода возникает следующая проблема
Хорошо, мне это показалось странным. Я создаю классификатор текста. Я использовал word2vec gensim с агрегацией, когда я пытаюсь запустить его через классификатор sklearn, он выдает мне ValueError: установка элемента массива с последовательностью. Вот мой код KNN Вот мой код KNN р> [code]def knn(X_train, y_train, k): start = time.time() knn = KNeighborsClassifier(n_neighbors=k) X_train, y_train = X_train.reset_index(drop=True), y_train.reset_index(drop=True) check_inconsistencies(values=X_train) check_inconsistencies(values=y_train) # X_train, y_train = np.asarray(X_train, dtype=np.dtype), np.asarray(y_train, dtype=np.dtype) print(f"KNN") knn.fit(X=X_train, y=y_train) net_time = time.time()-start return knn, net_time [/code] где check_inconsistency записывается Chatgpt, чтобы проверить, не является ли тип данных или длина несовместимыми [code]def check_inconsistencies(values): # Check if it's a sequence (like a list of lists) if isinstance(values, (list, tuple)): # 1. Check for inconsistent types types = set(type(v) for v in values) if len(types) > 1: print(f"Inconsistent types detected: {types}") else: print(f"Consistent type: {list(types)[0]}")
# 2. Check if all elements are also sequences (to verify shapes) if all(isinstance(v, (list, tuple, np.ndarray)) for v in values): # Check for shape inconsistencies lengths = [len(v) for v in values] if len(set(lengths)) > 1: print(f"Inconsistent lengths detected: {lengths}") else: print(f"Consistent shape: All sub-lists/arrays have length {lengths[0]}") else: print("Not all elements are sequences; some may be single values.")
# If the input is a NumPy array, check its dtype consistency if isinstance(values, np.ndarray): print(f"NumPy array detected with dtype: {values.dtype}") print(f"Shape: {values.shape}")
# Try to convert to NumPy array and catch potential errors try: arr = np.asarray(values) print("Array created successfully:", arr) except ValueError as e: print(f"Error encountered: {e}") [/code] Кроме того, я сам написал следующую проверку согласованности кода [code] for x in vec_pooled: count1 += 1 if (type(x) != type(prev1)) or (len(x) != len(prev1)): print(f"\nMismatch1: {type(x)} not {type(prev1)} {len(x)} not {len(prev1)} {count1}") print(f" {x} \n {prev1} \n\n\n\n") prev1 = x for y in x: count2 += 1 if (type(y) != type(prev2)) or (len(y) != len(prev2)): print(f"\nMismatch2: {type(y)} not {type(prev2)} {len(y)} not {len(prev2)} {count2}") print(f" {x} \n {prev1} \n\n\n\n") prev2 = y for z in y: count3 += 1 if type(z) != type(prev3): print(f"Mismatch3:{type(z)} not {type(prev3)} {count3}") prev3 = z count3 = 0 count2 = 0 print("Loop Completed") print (f"Type of prev1: {type(prev1)}") print (f"Type of prev2: {type(prev2)}") print (f"Type of prev3: {type(prev3)}") return vec_pooled [/code] Оба работают нормально, поэтому я знаю, что массив не является неровным и не имеет противоречивых типов. Но при обычном запуске кода возникает следующая проблема [code]--------------------------------------------------------------------------- TypeError Traceback (most recent call last) TypeError: only length-1 arrays can be converted to Python scalars
The above exception was the direct cause of the following exception:
Cell In[24], line 4 1 def model_training_master(X_train, X_test, y_train, y_test): 2 training_result = [] ----> 4 model, time = knn(X_train, y_train, max(y_train)) 5 accuracy, recall, f1 = model_performance(model, y_train, y_test) 6 training_result.append("KNN", False, 0, time, accuracy, recall, f1) ... -> 1022 arr = np.asarray(values, dtype=dtype) 1023 if using_copy_on_write() and astype_is_view(values.dtype, arr.dtype): 1024 arr = arr.view()
ValueError: setting an array element with a sequence. [/code] Между тем, если я раскомментирую строку KNN, произойдет следующая ошибка [code]--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[30], line 2 1 bakara = [3, ["./bakara.xlsx"], "text", "label"] ----> 2 df = pd.DataFrame(master_function(bakara))
Я запускаю файл Python «data_prep.py», в котором он подготавливает и загружает данные изображения для использования в модели машинного обучения, особенно для задач классификации, включающих изображения разных категорий. Однако каждый раз, когда я...
Создайте неровный массив целых чисел. Этот массив должен состоять из двух двумерных массивов. Первый двумерный массив должен содержать 3 строки длиной 4, 3 и 2 соответственно. Второй двумерный массив должен содержать 2 строки длиной 3 и 4...
Мне нужно вернуть неровный массив из функции-члена. Массив инициализируется следующим образом: float *domain ;, где SIZE равен, скажем, 2, и некоторые массивы присваиваются ему в ctor следующим образом:
for (unsigned int i=0; i. Объект вызывается в...
Мне нужно вернуть неровный массив из функции-члена. Массив инициализируется следующим образом: float *domain ;, где SIZE равен, скажем, 2, и некоторые массивы присваиваются ему в ctor следующим образом:
for (unsigned int i=0; i. Объект вызывается в...