PythonistGit
@PythonistGit
Програміст-самоучка

Что это за неясная ошибка в Дискорд боте?

Прив всем. Суть в том, что я разрабатываю бота в Дискорде. Вот его код:

import discord
from discord.ext import commands
from math import *
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
import random as rn
import numpy as np

client = commands.Bot (command_prefix="'")

@client.event
async def on_ready():
    print("hi")

@client.command(pass_context=True)
async def hello(ctx):
    author = ctx.message.author
    await ctx.send(f"{author.mention} Hello!")

@client.command(pass_context=True)
async def hi(ctx):
    author = ctx.message.author
    await ctx.send(f"{author.mention} Hello!")

@client.command(pass_context=True)
async def smile(ctx):
    author = ctx.message.author
    smiles_massive = [":)", ";)", "%)", "=)", ":}", ";}", "%}", "=}", ":]", ";]", "%]", "=]", ":D", ";D", "%D", "=D"]
    smile_index = rn.randint(0, len(smiles_massive)-1)
    smile = smiles_massive[smile_index]
    await ctx.send(f"{author.mention} " + smile)

@client.command(pass_context=True)
async def math(ctx, arg):
    author = ctx.message.author
    pi = 3.1415926535897932384626433  
    e = 2.7182818284590452353602874
    if (arg == "euler"):
        await ctx.send(f"""{author.mention} ```
           (тут пасхалка для математиков, да)```""")
    else:
        result = eval(arg)
        await ctx.send(f"{author.mention} Result: " + str(result))

@client.command(pass_context=True)
async def machlearn(ctx, feature_data, target_data, new_data):
    X = np.array(feature_data).reshape(-1,1)
    y = np.array(target_data).reshape(-1,1)
    classify_method = rn.randint(0, 1)
    if classify_method == 0:
        clf = DecisionTreeClassifier()
    if classify_method == 1:
        clf = KNeighborsClassifier()
    clf.fit(X, y)
    pred = clf.predict(np.array(new_data).reshape(-1,1))
    metr = accuracy_score(y, pred)
    await ctx.send(f"{author.mention} Result: " + str(metr))

client.run("токен")


Идет разработка команды machlearn. С ним полная жесть. Что я только не перепробовал, все идет коту под хвост.
При вводе команды:
'machlearn "[[140, 1], [130, 1], [150, 0], [170, 0]]" "[0, 0, 1, 1]" "[[150,0]]"

у меня срабатывает ошибка:
Ignoring exception in command machlearn:
Traceback (most recent call last):
File "C:\Users\Nik\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 57, in machlearn
clf.fit(X, y)
File "C:\Users\Nik\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\sklearn\tree\_classes.py", line 890, in fit
super().fit(
File "C:\Users\Nik\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\sklearn\tree\_classes.py", line 156, in fit
X, y = self._validate_data(X, y,
File "C:\Users\Nik\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\sklearn\base.py", line 429, in _validate_data
X = check_array(X, **check_X_params)
File "C:\Users\Nik\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\sklearn\utils\validation.py", line 73, in inner_f
return f(**kwargs)
File "C:\Users\Nik\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\sklearn\utils\validation.py", line 599, in check_array
array = np.asarray(array, order=order, dtype=dtype)
File "C:\Users\Nik\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\numpy\core\_asarray.py", line 85, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: could not convert string to float: '[[140, 1], [130, 1], [150, 0], [
170, 0]]'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\Nik\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Nik\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Nik\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Val
ueError: could not convert string to float: '[[140, 1], [130, 1], [150, 0], [170
, 0]]'


Вопрос: в чем дело? Как это можно исправить? И в коде это как будет выглядеть?
  • Вопрос задан
  • 135 просмотров
Решения вопроса 1
SoreMix
@SoreMix Куратор тега Python
yellow
Не эксперт, но

  1. Вы в np.array() передаете строку '[[140, 1], [130, 1], [150, 0], [170, 0]]'. В X и y надо передать список
  2. Дальше возникнет ошибка, связнная с разным размером матрицы, т.к. X - 8, y - 4
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
Noizefan
@Noizefan
could not convert string to float: '[[140, 1], [130, 1], [150, 0], [170, 0]]'

с последнего вверх поднимайся и поймёшь в чём дело на будущее
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
16 мая 2024, в 23:36
200000 руб./за проект
16 мая 2024, в 23:10
12000 руб./за проект