I work on a Python 3.11 program and I have this error:
Traceback (most recent call last):
File "\Égalisation\Python Version\Wiener Filter\main.py", line 14, in <module>
symb = [random.choice(A) for _ in range(nbsymb)]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "\Égalisation\Python Version\Wiener Filter\main.py", line 14, in <listcomp>
symb = [random.choice(A) for _ in range(nbsymb)]
^^^^^^^^^^^^^^^^
File "\Programs\Python\Python311\Lib\random.py", line 369, in choice
if not seq:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
When I run this simple code:
import numpy as np
import random
nbsymb = 8
M = 16
A = np.arange(-np.sqrt(M)+1, np.sqrt(M), 2)
symb = [random.choice(A) for _ in range(8)]
Sounds like this is due to a regression in Python 3.11 which was later fixed. Upgrade to Python >=3.11.2
Numpy has its own random stuff, perhaps you should use that instead: https://numpy.org/doc/stable/reference/random/
If for some reason you can't upgrade, choose random elements from a list instead of a numpy array:
A = list(np.arange(-np.sqrt(M)+1, np.sqrt(M), 2))
symb = [random.choice(A) for _ in range(nbsymb)]
Related
I wanted to compare faces in the line "matches = face_recognition.compare_faces(pessoas[c], original_face_encodings[b])" , if using the pessoas array works, if I use pessoas[c] to compare one at a time, I have the following error message:
Traceback (most recent call last):
File "face.py", line 43, in <module>
matches = face_recognition.compare_faces(pessoas[c], original_face_encodings[b])
File "C:\face-recognition\course\face_recognition\api.py", line 226, in compare_faces
return list(face_distance(known_face_encodings, face_encoding_to_check) <= tolerance)
File "C:\face-recognition\course\face_recognition\api.py", line 75, in face_distance
return np.linalg.norm(face_encodings - face_to_compare, axis=1)
File "C:\Users\user\Anaconda3\lib\site-packages\numpy\linalg\linalg.py", line 2481, in norm
return sqrt(add.reduce(s, axis=axis, keepdims=keepdims)) numpy.AxisError: axis 1 is out of bounds for array of dimension 1
How can I solve it?
a = 110
pessoas = []
photos = []
b = 0
c = 0
r = 0
for i in range(100,a):
test_image = cv2.imread('test1/' + str(i) + '.jpeg')
all_face_locations = face_recognition.face_locations(test_image, model='CNN')
original_face_encodings = face_recognition.face_encodings(test_image, all_face_locations)
print(i)
for b in range(len(all_face_locations)):
if not pessoas:
for r in range(len(all_face_locations)):
pessoas.insert(r, original_face_encodings[r])
else:
for c in range(len(pessoas)):
matches = face_recognition.compare_faces(pessoas[c], original_face_encodings[b])
if(matches):
photos.insert(i, i)
else:
pessoas.insert(i, original_face_encodings[b])
print(pessoas)
print(photos)
You should make sure that pessoas[c] array and original_face_encodings[b] have the same shape. Currently, it seems that pessoas[c] has 1D shape and original_face_encodings[b] has 2D shape.
Try to wrap it in a list, for example:
pessoas.insert(r, [original_face_encodings[r]])
matches = face_recognition.compare_faces(pessoas[c], [original_face_encodings[b]]
pessoas.insert(i, [original_face_encodings[b]])
I want to create random integers and convert them in binary format via NumPy matrix. I wrote the following code:
def toBinary(C):
l = []
for x in C:
b = [int(i) for i in bin(x)[2:]]
l = np.vstack((l, np.array(b)))
return l
list_vectors = [random.randint(0, 2 ** 64) for _ in range(2)]
print(toBinary(list_vectors))
But I still don't know how to solve this error:
Traceback (most recent call last):
File "test.py", line 31, in <module>
print(toBinary(list_vectors))
File "test.py", line 27, in toBinary
l = np.vstack((l, np.array(b)))
File "/anaconda3/lib/python3.6/site-packages/numpy/core/shape_base.py", line 234, in vstack
return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
ValueError: all the input array dimensions except for the concatenation axis must match exactly
Any suggestion is highly appreciated.
The issue here is that the conversion to binary does not always return a binary number of same length.
If the first integer in C is, let's say 3, it'll give '0b11'. Stack this in the array, then try to convert 17. Oops, you're trying to concatenate '11' and '1001' together, it won't work.
What I did here then, is forcing the converted binary number length to 10 using the format() function (Convert to binary and keep leading zeros in Python).
import numpy as np
import numpy.random as random
def toBinary(C):
binaries_length = 10
bin_format = f'#0{binaries_length+2}b'
array_rows = len(C)
l = np.empty((array_rows, binaries_length))
for i, x in enumerate(C):
l[i,:] = np.array([int(i) for i in format(x, bin_format)[2:]])
return l
list_vectors = [random.randint(0, 2 * 64) for _ in range(10)]
print(toBinary(list_vectors))
Also, the returned array is pre-allocated, since you now perfectly know what size it will be :
binaries_length = 10
bin_format = f'#0{10+2}b'
array_rows = len(C)
l = np.empty((array_rows, binaries_length))
By the way, the call random.randint(0, 2 ** 64) also triggers an exception because 2 ** 64 is insanely too high so I changed it to 2*64 here.
To go further, you can find the optimal binary length by finding the maximum of C.
Try this, it will return a list instead of array, so make the necessary adjustments if you like:
def toBinary(C):
l = []
for x in C:
b = [i for i in bin(x)[2:]]
a="".join(b)
a=int(a)
l.append(a)
return l
I've currently got the following, but it won't iterate over i. I don't understand why it isn't working. Bwavelength and throughput are lists. It appears that i starts at 0, but won't increase to 1.
ABconstant=[]
c=3e18
for i in range(0, ((len(Bwavelength))-1)):
ABconstant1=(((3e18/((Bwavelength[i])**2))*throughput[i]))
ABconstant.append(ABconstant1)
i+=1
a=Bwavelength[0]
b=Bwavelength[-1]
h=((b-a)/len(Bwavelength))
ABflux = numpy.trapz(Bwavelength, ABconstant, h)
return ABflux
The error I get is:
Traceback (most recent call last):
File "Rewrite17.11.2014.py", line 196, in <module>
ABflux1 = ABconversion(Bwavelength, throughput)
File "Rewrite17.11.2014.py", line 186, in ABconversion
ABflux = numpy.trapz(Bwavelength, ABconstant, h)
File "C:\Python27\lib\site-packages\numpy\lib\function_base.py, line 3234, in trapz
ret = add.reduce(d * (y[slice1]+y[slice2]/2.0, axis)
ValueError: Operands could not be broadcast together with shapes (0,) (444,)
Bwavelength and throughput are of equal length.
I have no idea what that actually means, despite having looked it up.
Thanks in advance.
The loop can be substituted by vector calculations:
c=3e18
ABconstant = c / numpy.array(Bwavelength) ** 2 * throughput
ABflux = numpy.trapz(ABconstant, Bwavelength)
return ABflux
import math
import pylab
from matplotlib.pylab import *
import numpy as np
import scipy.fftpack
from scipy.io.wavfile import read
w = read('c:/users/ggg.wav')
a=np.array(w[1])
l=len(a)
#from __future__ import division
#b=(l/w[0])
b=(float(l)/w[0])
c=b*1000
d=int(c/40)
print d
print l/d
e=l/d
for i in range(0,d):
k[9]=np.array(a[(i*e)+1:((i+1)*e)])
print k
this is a python code to frame an audio signal. But when i executed this code,i got an error "ValueError: setting an array element with a sequence.". How can i avoid this error?
There is another problem with your code I can at least help you with:
You can't assign k[9] without k being undefined. E.g:
>>> k[9] = 'test'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined
'k' needs to be defined as an array and needs to get the 'proper' index. You can't assign the index on it straight after.
See the following examples:
>>> k[9]='test'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
and
>>> k = [None]*10
>>> k[9]='test'
>>> k
[None, None, None, None, None, None, None, None, None, 'test']
This works fine with a sample .wav
w = read('ggg.wav')
a = w[1] # already an array
l=len(a)
b=(float(l)/w[0])
c=b*1000
d=int(c/40)
e=l/d
k = a[:e*d].reshape(d,e)
print k.shape
print k
print ''
k = [[] for i in range(d)] # initialize python list
for i in range(0,d):
k[i] = a[(i*e)+1:((i+1)*e)]
for i in k:
print i
# or
k = np.zeros((d,e-1),dtype='int') # initialize np.array
for i in range(d):
k[i,:] = a[(i*e)+1:((i+1)*e)]
print k
w[1] is already an np.array. I think what you want to break a into blocks e long. To do that, I truncated a and reshaped it, producing my k. Your indexing misses a[0], a[e], etc.
I'm trying to make a 2^n x 2^n numpy array of all possible dot product permutations of a very large set of vectors. My test array, "data", is a (129L, 222L) numpy array. My function seems (in my novice opinion) to be pretty straightforward. It's just the fact that I have too much data to process. How do programmers typically get around this issue? Any suggestions?
My data:
>>> data
array([[ 1.36339199e-07, 6.71355407e-09, 2.13336419e-07, ...,
8.44471296e-10, 6.02566662e-10, 3.38577178e-10],
[ 7.19224620e-08, 5.64739121e-08, 1.49689547e-07, ...,
3.85361972e-10, 3.17756751e-10, 1.68563023e-10],
[ 1.93443482e-10, 1.11626853e-08, 2.66691759e-09, ...,
2.20938084e-11, 2.56114420e-11, 1.31865060e-11],
...,
[ 7.12584509e-13, 7.70844451e-13, 1.09718565e-12, ...,
2.08390730e-13, 3.05264153e-13, 1.62286818e-13],
[ 2.57153616e-13, 6.08747557e-13, 2.00768488e-12, ...,
6.29901984e-13, 1.19631816e-14, 1.05109078e-13],
[ 1.74618064e-13, 5.03695393e-13, 1.29632351e-14, ...,
7.60145676e-13, 3.19648911e-14, 8.72102078e-15]])`
My function:
import numpy as np
from itertools import product, count
def myFunction(data):
S = np.array([])
num = 2**len(data)
y = product(data, repeat = 2)
for x in count():
while x <= num:
z = y.next()
i, j = z
s = np.dot(i, j)
S = np.insert(S, x, s)
break #for the 'StopIteration' issue
return np.reshape(S, (num,num))
My error:
>>> theMatrix = myFunction(data)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2721, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "", line 1, in <module>
matrix = myFunction(data)
File "E:\Folder1\Folder2\src\myFunction.py", line 16, in myFunction
return np.reshape(S, (num,num))
File "C:\Python27\lib\site-packages\numpy\core\fromnumeric.py", line 171, in reshape
return reshape(newshape, order=order)
ValueError: Maximum allowed dimension exceeded
Why are you passing num,num to reshape, but not the actual thing you're reshaping?
Perhaps you want something like return np.reshape(S, (num, num)) instead?
As for the actual error, 2^129 is a pretty darn large number - even your regular 64-bit integer can only index up to 2^64. The memory of your machine probably can't contain a 2^129 x 2^129 matrix.
Are you sure you really want to be processing quite that much? Even with a GHz processor, that's still ~2^100 seconds worth of processing if you can operate on an element in a single cpu cycle (which you probably can't).
The cartesian product is O(n^2) not O(2^n), (lucky for you). Probably that's also the cause of your "StopIteration" issue
S = np.array([])
num = len(data) ** 2 # This is not the same as 2 ** len(data) !!
y = product(data, repeat=2)
for x in count():
while x <= num:
z = y.next()
i, j = z
s = np.dot(i, j)
S = np.insert(S, x, s)
break #for the 'StopIteration' issue
return np.reshape(S, (num, num))