Я создаю классификатор текста. Я использовал word2vec gensim с агрегацией, когда я пытаюсь запустить его через классификатор sklearn, он выдает мне ValueError: установка элемента массива с последовательностью.
Вот мой код KNN
Вот мой код KNN р>
Код: Выделить всё
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
Код: Выделить всё
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
Код: Выделить всё
---------------------------------------------------------------------------
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:
ValueError Traceback (most recent call last)
Cell In[28], line 2
1 bakara = [3, ["./bakara.xlsx"], "text", "label"]
----> 2 df = pd.DataFrame(master_function(bakara))
Cell In[25], line 40
38 temp_df['vec_text'] = vectorization(temp_df["prep_text"], vec ,agg_type, avg, None)
39 X_train, X_test, y_train, y_test = train_test_split(temp_df['vec_text'], df[data[3]], test_size=0.2, random_state=42)
---> 40 train_result = model_training_master(X_train, X_test, y_train, y_test)
41 print(f"{Agg_type} | {avg} | {vec}")
42 for result in train_results:
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.
Код: Выделить всё
---------------------------------------------------------------------------
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))
Cell In[25], line 40
38 temp_df['vec_text'] = vectorization(temp_df["prep_text"], vec ,agg_type, avg, None)
39 X_train, X_test, y_train, y_test = train_test_split(temp_df['vec_text'], df[data[3]], test_size=0.2, random_state=42)
---> 40 train_result = model_training_master(X_train, X_test, y_train, y_test)
41 print(f"{Agg_type} | {avg} | {vec}")
42 for result in train_results:
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)
Cell In[29], line 7
5 check_inconsistencies(values=X_train)
6 check_inconsistencies(values=y_train)
----> 7 X_train, y_train = np.asarray(X_train, dtype=np.dtype), np.asarray(y_train, dtype=np.dtype)
8 print(f"KNN")
9 knn.fit(X=X_train, y=y_train)
TypeError: Cannot convert np.dtype into a dtype.
Подробнее здесь: https://stackoverflow.com/questions/790 ... atype-or-j