Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?
You're getting the error message
ValueError: setting an array element with a sequence.
because you're trying to set an array element with a sequence. I'm not trying to be cute, there -- the error message is trying to tell you exactly what the problem is. Don't think of it as a cryptic error, it's simply a phrase. What line is giving the problem?
kOUT[i]=func(TempLake[i],Z)
This line tries to set the ith
element of kOUT
to whatever func(TempLAke[i], Z)
returns. Looking at the i=0
case:
In [39]: kOUT[0]
Out[39]: 0.0
In [40]: func(TempLake[0], Z)
Out[40]: array([ 0., 0., 0., 0.])
You're trying to load a 4-element array into kOUT[0]
which only has a float. Hence, you're trying to set an array element (the left hand side, kOUT[i]
) with a sequence (the right hand side, func(TempLake[i], Z)
).
Probably func
isn't doing what you want, but I'm not sure what you really wanted it to do (and don't forget you can usually use vectorized operations like A*B rather than looping in numpy.) That should explain the problem, anyway.
Problem: ValueError: setting an array element with a sequence
The ValueError arises due to the fact that you are trying to perform dot product of a tuple with a vector (input vector).
I also noted that you are passing learning_rate = 0,3
, whereas you are expecting learning rate to be an integer or float in the body of the class. This made me think that probably the dots(.) in the book you're reading have been misprinted as commas(,). This could be a probable issue.
Once you fix the three commas with dots, you can see your code run.
Here's the complete code below:
import numpy
import scipy
from scipy import special
class neuralNetwork:
def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
self.inodes = inputnodes
self.hnodes = hiddennodes
self.onodes = outputnodes
self.wih = (numpy.random.rand(self.hnodes, self.inodes)-0.5)
self.who = (numpy.random.rand(self.onodes, self.hnodes)-0.5)
self.lr = learningrate
self.activation_function= lambda x: scipy.special.expit(x)
pass
def train():
pass
def query(self, inputs_list):
inputs = numpy.array(inputs_list, ndmin=2).T
print(self.wih[0].shape)
hidden_inputs = numpy.dot(self.wih, inputs)
hidden_outputs = self.activation_function(hidden_inputs)
final_inputs = numpy.dot(self.who, hidden_outputs)
final_outputs = self.activation_function(final_inputs)
return final_outputs
pass
input_nodes = 3
hidden_nodes = 3
output_nodes = 3
learning_rate = 0.3
n = neuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate)
n.query([1,1,1])
Moreover, please add some context when posting a question to SO. This would help us to understand what you're trying to achieve rather than just fixing the compile-time errors.
Hope it helps.
Python numpy ValueError: setting an array element with a sequence
I can reproduce the error message with this code:
import numpy as np
def rotate_by_90_deg(im):
new_mat=np.zeros((im.shape[1],im.shape[0]), dtype=np.uint8)
n = im.shape[0]
for x in range(im.shape[0]):
for y in range(im.shape[1]):
new_mat[y,n-1-x]=im[x,y]
return new_mat
im = np.arange(27).reshape(3,3,3)
rotate_by_90_deg(im)
The problem here is that im
is 3-dimensional, not 2-dimensional. That might happen if your image is in RGB format, for example.
So im[x,y]
is an array of shape (3,). new_mat[y, n-1-x]
expects a np.uint8
value, but instead is getting assigned to an array.
To fix rotate_by_90_deg
, make new_mat
have the same number of axes as im
:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
def rotate_by_90_deg(im):
H, W, V = im.shape[0], im.shape[1], im.shape[2:]
new_mat = np.empty((W, H)+V, dtype=im.dtype)
n = im.shape[0]
for x in range(im.shape[0]):
for y in range(im.shape[1]):
new_mat[y,n-1-x]=im[x,y]
return new_mat
im = np.random.random((3,3,3))
arr = rotate_by_90_deg(im)
fig, ax = plt.subplots(ncols=2)
ax[0].imshow(10*im, interpolation='nearest')
ax[0].set_title('orig')
ax[1].imshow(10*arr, interpolation='nearest')
ax[1].set_title('rot90')
plt.show()
Or, you could use np.rot90
:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
im = np.random.random((3,3,3))
arr = np.rot90(im, 3)
fig, ax = plt.subplots(ncols=2)
ax[0].imshow(10*im, interpolation='nearest')
ax[0].set_title('orig')
ax[1].imshow(10*arr, interpolation='nearest')
ax[1].set_title('rot90')
plt.show()
ODES: ValueError: setting an array element with a sequence
Obviously, your state P has 2 components. Thus also the expressions you compute from P will have two components. Then you try to assign these tuples to a single cell in the array dP
, which is not possible and results in that error message.
You might want to replace P
with its first element P[0]
in these expressions. Or use
def rhs(t, u):
P,phi = u
dP = ...
dphi = ...
return [dP, dphi]
Convert numpy array dtype. ValueError: setting an array element with a sequence
Make an object array and fill it with lists:
In [410]: arr = np.zeros(6,object)
In [411]: for i in range(6): arr[i]=[1,2,3]
In [413]: arr=arr.reshape(2,3)
In [414]: arr
Out[414]:
array([[[1, 2, 3], [1, 2, 3], [1, 2, 3]],
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]], dtype=object)
astype
does not work
In [415]: arr.astype(float)
but a list intermediary does:
In [416]: np.array(arr.tolist())
Out[416]:
array([[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]],
[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]])
The object array contains pointers to lists (else where in memory). So astype
and view
cannot convert that to a float array. Instead we have to make a whole new, fresh, array from the equivalent nested list.
tolist
also works when one or more of the elements is an array, as long as sizes match
In [417]: arr[0,0]=np.arange(3)
In [418]: arr
Out[418]:
array([[array([0, 1, 2]), [1, 2, 3], [1, 2, 3]],
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]], dtype=object)
In [419]: arr.tolist()
Out[419]: [[array([0, 1, 2]), [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]
In [420]: np.array(arr.tolist())
Out[420]:
array([[[0, 1, 2],
[1, 2, 3],
[1, 2, 3]],
[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]])
Related Topics
Time Complexity of Accessing a Python Dict
Multiple Ping Script in Python
Why Does Pyplot.Contour() Require Z to Be a 2D Array
How to Remove Duplicate Words in a String with Python
How to Call Setattr() on the Current Module
How to Call Python Functions Dynamically
How to Stop Numpy from Multithreading
How to Stack Vectors of Different Lengths in Numpy
Pandas - Explanation on Apply Function Being Slow
Opencv - Apply Mask to a Color Image
Converting List of Tuples into a Dictionary
Access to Table Objects on Webpage Using Python Selenium
Python: How to Send Mail with To, Cc and Bcc
Does Tkinter Have a Table Widget
How to Edit a Seaborn Legend Title and Labels for Figure-Level Functions