Why do I get "TypeError: expected np.ndarray (got numpy.ndarray)" when I use torch.from_numpy() function?

username: yxchng
cooked: <p>Why do I get “TypeError: expected np.ndarray (got numpy.ndarray)”  when I use torch.from_numpy() function? Isn’t np.ndarray equivalent to numpy.ndarray? Also, there doesn’t seem to be any np.ndarray type, but only numpy.ndarray type.</p>
<p><code>Traceback (most recent call last): File "test_opencv.py", line 31, in &lt;module&gt; bounding_boxes, landmarks = detect_faces(img, pnet, rnet, onet) File "/home/xxx/git/project/src/detector.py", line 67, in detect_faces boxes = run_first_stage(image, pnet, scale=s, threshold=thresholds[0]) File "/home/xxx/git/project/src/first_stage.py", line 73, in run_first_stage img = torch.from_numpy(img).unsqueeze(0).permute(0,3,1,2).cuda().float() TypeError: expected np.ndarray (got numpy.ndarray)</code></p>

username: Kushaj
cooked: <p>Can you share some debugging info like printing type(img) and img.dtype I wrote the same line of code and it worked for me.<br>
There has to be some bug in the data loading process of the image.</p>

username: raghavendragaleppa
cooked: <p>Hello It seems you are getting the error because the argument to from_numpy function is a single value rather than array.<br>
In numpy, there is difference between np.array(1) and np.array([1]) and both are completely different data types.<br>
Try torch.from_numpy(np.asarray(x)).</p>

username: yangfeifei02
cooked: <p>Hello, I have encountered the same problem. Do you have any solutions?Thank you</p>

username: Deepak_Agrawal
cooked: <p>Try<br>
<code>torch.as_tensor(np.array(pil_img).astype('float'))</code></p>
<p>It worked for me.</p>

username: Eric_K
cooked: <p>Have you fix this problem? I encounter this problem too…</p>

username: ptrblck
cooked: <p>Could you post a minimal code snippet to reproduce this error?</p>

username: Eric_K
cooked: <p>I found it is because of the version of numpy…</p>
<p><a href="https://maas.mail.163.com/dashi-web-extend/html/proSignature.html?iconUrl=http%3A%2F%2Fmail-online.nosdn.127.net%2Fa74f0bc6760ea9d1d8b5a113be800853.jpg&amp;name=%E4%BF%A1%E5%B7%A5%20%E5%88%98%E8%93%AC%E5%8D%9A&amp;uid=example%40163.com&amp;ftlId=3&amp;items=%5B%22%E9%82%AE%E7%AE%B1%EF%BC%9Apengbo18555%40163.com%22%5D" rel="nofollow noopener"><br>
</a><br>
<img width="38" height="38" src="http://mail-online.nosdn.127.net/a74f0bc6760ea9d1d8b5a113be800853.jpg"><br>
信工 刘蓬博</p>
<p>邮箱：pengbo18555@163.com</p>
<p>签名由 <a href="https://mail.163.com/dashi/dlpro.html?from=mail88" rel="nofollow noopener">网易邮箱大师</a> 定制</p>

username: rilut
cooked: <p>It’s also happening to me on numpy 1.17.4, my own solution is to downgrade to 1.16.4</p>

username: Anonymous_For_Justic
cooked: <p>thanks! it worked for me.<br>
Numpy version -  1.19.5</p>

username: codenigma1
cooked: <p>It worked for me. Thank you <a class="mention" href="/u/raghavendragaleppa">@raghavendragaleppa</a></p>

username: shyamgupta196
cooked: <p>I was working with tabular MNIST data !!<br>
one possible solution that worked for me was,</p>
<p>x_train.reset_index(drop=True,inplace=True)<br>
x_test.reset_index(drop=True,inplace=True)<br>
y_train.reset_index(drop=True,inplace=True)<br>
y_test.reset_index(drop=True,inplace=True)</p>
<p>hope it helps for those using TABULAR dataset</p>

username: 19IT043_KABILAN_D
cooked: <p>iam trying to run a simple dqn code for cartpole environment in my computer.                                                        This is my code updated as you said;</p>
<pre data-code-wrap="def"><code class="lang-plaintext">    env = gym.make('CartPole-v1')
    q = Qnet()
    q_target = Qnet()
    q_target.load_state_dict(q.state_dict())
    memory = ReplayBuffer()

    print_interval = 20
    score = 0.0  
    optimizer = optim.Adam(q.parameters(), lr=learning_rate)

    for n_epi in range(10000):
        epsilon = max(0.01, 0.08 - 0.01*(n_epi/200)) #Linear annealing from 8% to 1%
        s = env.reset()
        done = False
        while not done:
            **a = q.sample_action(torch.from_numpy(np.asarray(s)).float(), epsilon)**      
            s_prime, r, done, info = env.step(a)
            done_mask = 0.0 if done else 1.0
            memory.put((s,a,r/100.0,s_prime, done_mask))
            s = s_prime
</code></pre>
<p>but iam getting the following error again where everything is fine<br>
Traceback (most recent call last):<br>
File “d:\college\final yr\project\rl-series\dqn\simpledqn.py”, line 114, in <br>
main()<br>
File “d:\college\final yr\project\rl-series\dqn\simpledqn.py”, line 93, in main<br>
a = q.sample_action(torch.from_numpy(np.asarray(s)), epsilon)<br>
<strong>ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.</strong></p>

username: Rupasree_Dey
cooked: <p>Thanks! This solved my issue.</p>

username: shipshipliucixin1
cooked: <p>I think this problem may arise from torch.from_numpy(array)'s mismatching with numpy version or dtype,and use other way of generating a tensor from numpy is a solution.</p>