'TypeError: only size-1 arrays can be converted to Python scalars, problem with float

I don't know what the problem is, maybe I used np.asfarray wrong? It is noted that the error is in line 6.

for i in training_data_list:
    all_values = i.split(',') 
    inputs_x = np.asfarray(all_values[1:])
    outputs = n.query(inputs_x)
    print(int(all_values[1]), 'or', int(all_values[2]), '=' ,  float(outputs), '\n')

Full Error:

TypeError                                 Traceback (most recent call last)
/var/folders/7x/q0gw9knx0klf7ngkgvd95wj40000gn/T/ipykernel_62654/1155902910.py in <module>
      3     inputs_x = np.asfarray(all_values[1:])
      4     outputs = n.query(inputs_x)
----> 5     print(int(all_values[1]), 'or', int(all_values[2]), '=' ,  float(outputs), '\n')

TypeError: only size-1 arrays can be converted to Python scalars

The result should be:

0 OR 0 = 0.0015221568573919875 

1 OR 0 = 0.9999989042032791 

0 OR 1 = 0.9999985457530554 

1 OR 1 = 1.000000835153846 


Solution 1:[1]

Here are some valid uses of float

In [18]: float('1.23')
Out[18]: 1.23
In [19]: float(np.array(2.34))
Out[19]: 2.34
In [20]: float(np.array([2.34]))
Out[20]: 2.34

and invalid ones:

In [21]: float('1.23 2.32')
Traceback (most recent call last):
  Input In [21] in <cell line: 1>
    float('1.23 2.32')
ValueError: could not convert string to float: '1.23 2.32'

In [22]: float(np.array([1.23, 3.34]))
Traceback (most recent call last):
  Input In [22] in <cell line: 1>
    float(np.array([1.23, 3.34]))
TypeError: only size-1 arrays can be converted to Python scalars

float is Python function that tries to return one float value.

I don't know what n.query does or is, but the error suggests that `outputs is a numpy array with more than one element

outputs = n.query(inputs_x)

Have you examined outputs? What is it - type, shape, dtype, etc? Does it even need conversion to floats.

edit

Try this print:

print(all_values[1], 'or', all_values[2], '=' ,  outputs)

It may not be the prettiest, but at least is should work. Or

print(f'{all_values[1]} or {all_values[2]} = {outputs}')

for example:

In [45]: all_values = [0, 2, 3]; outputs = np.array([1.23, 2.12])

In [46]: print(all_values[1], 'or', all_values[2], '=' ,  outputs)
2 or 3 = [1.23 2.12]
In [47]: print(f'{all_values[1]} or {all_values[2]} = {outputs}')
2 or 3 = [1.23 2.12]

Once you get some working output, you can go on to worry about fine points of formatting. Throwing int() and float() into the display without understanding what you are doing is not going to help.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1