Category Archives: Python

[Solved] Pytoch nn.CrossEntropyLoss Error: RuntimeError: expected scalar type Long but found Float

When I want to test, NN. Crossentropyloss() is an error, as follows:

>>> x = torch.rand(64, 4)
>>> y = torch.rand(64)
>>> criterion(x, y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/rogn/opt/anaconda3/envs/deeplearning/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "/Users/rogn/opt/anaconda3/envs/deeplearning/lib/python3.8/site-packages/torch/nn/modules/loss.py", line 1120, in forward
    return F.cross_entropy(input, target, weight=self.weight,
  File "/Users/rogn/opt/anaconda3/envs/deeplearning/lib/python3.8/site-packages/torch/nn/functional.py", line 2824, in cross_entropy
    return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: expected scalar type Long but found Float

Reference resources: https://stackoverflow.com/questions/60440292/runtimeerror-expected-scalar-type-long-but-found-float

The reason is that the category target cannot be a floating-point type, but can only be an integer. For example, it belongs to a certain class

So, change the target to an integer

>>> x = torch.rand(64, 4)
>>> y = torch.randint(0,4, (64,))
>>> criterion(x, y)
tensor(1.4477)

TypeError: __init__() takes 1 positional argument but 2 were given [How to Solve]

class conv_try(nn.Module):
    def __init__(self):
        super(conv_try, self).__init__()
        # self.conv1 = nn.Conv1d(1, 32, kernel_size=3, stride=2, padding=1)
        # self.conv2 = nn.Conv2d(1, 32, kernel_size=3, stride=2, padding=1)
        self.encoder = nn.Sequential(
            nn.Conv1d(96, 192, kernel_size=3, stride=2, padding=1),
            nn.ReLU()
        )

    def forward(self,x):
        x2 = self.encoder(x)
        return x2

if __name__ == '__main__':
    x =torch.rand(16,96,512)
    # print('x1:',x.size())
    conv = conv_try(x)

Error Message:
Traceback (most recent call last):
File "C:/Users/12051/Desktop/vae+a/conv2.py", line 23, in <module>
conv = conv_try(x)
TypeError: __init__() takes 1 positional argument but 2 were given

 

Modified:

if __name__ == '__main__':
    x =torch.rand(16,96,512)
    # print('x1:',x.size())
    conv = conv_try() ####Define a custom class
    a = conv(x) ##### and then call
    print(a.size())

[Solved] Pdfplumber Parsing PDF error: ValueError: not enough values to unpack (expected 2, got 1)

Question:

Environment: Ubuntu 18.04, electronic invoice PDF document

Cause: the cause of the problem is not clear. The error can only be determined after pdfminer recompiled and installed for Chinese fonts (if any God knows, please let us know)

Solution: modifying the source code is actually a layer of error filtering

Python: How to Modify AD Password

Prerequisite: AD has started certificate service (the most important sentence).

import ldap3

SERVER = 'adserver'
BASEDN = "DC=example,DC=com"
USER = "[email protected]"
CURREENTPWD = "adcvQ.SAD"
NEWPWD = "adcv.Q.SAD"

SEARCHFILTER = '(&(userPrincipalName='+USER+')(objectClass=person))'

USER_DN = ""
USER_CN = ""

ldap_server = ldap3.Server(SERVER, get_info=ldap3.ALL, use_ssl=True)
conn = ldap3.Connection(ldap_server, USER, CURREENTPWD, auto_bind=True)
conn.start_tls()

conn.search(search_base=BASEDN, search_filter=SEARCHFILTER, search_scope=ldap3.SUBTREE, attributes=['cn', 'givenName', 'userPrincipalName'], paged_size=5)

# print(conn.response)
for entry in conn.response:
    if entry.get("dn") and entry.get("attributes"):
        if entry.get("attributes").get("userPrincipalName"):
            if entry.get("attributes").get("userPrincipalName") == USER:
                USER_DN = entry.get("dn")
                USER_CN = entry.get("attributes").get("cn")


if USER_DN:
    res = ldap3.extend.microsoft.modifyPassword.ad_modify_password(conn, USER_DN, NEWPWD, CURREENTPWD,  controls=None)
    if res:
        print('user %s change password Success.' % USER_CN)
    else:
        print('user %s change password Failed.' % USER_CN)
else:
    print("User DN is missing!")

Python Via get-pip.py Install pip Error: zipimport.ZipImportError: can‘t decompress data; zlib not availabl

How to Solve error: zipimport.ZipImportError: can‘t decompress data; zlib not availablwget https://bootstrap.pypa.io/pip/2.7/get-pip.py  # python2.7
wget https://bootstrap.pypa.io/get-pip.py  # python3
error:

[[email protected] ~]$ https://bootstrap.pypa.io/get-pip.py
[[email protected] ~]$ sudo python get-pip.py

The error message “zipimport.ZipImportError: can’t decompress data; zlib not available”
It seems that the zlib library is missing and needs to be installed before execution.
Problem solved

1 [[email protected] ~]$ sudo yum install zlib

After the installation was completed, we found that it still reported an error, and a Google search revealed that we needed to install zlib-dev
So we install the zlib library again

1 [[email protected] ~]$ sudo yum install zlib*

This time the installation should be OK, but the result is disappointing, it still gives the same error.
But we have already installed the zlib library, why does it still give us an error?

We need to recompile and install python
Before recompiling, we need to modify the Modules/Setup.dist file in the installation source file to change the

1 #zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz

The comment on this line is removed and becomes

1 zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz

Then compile and install it again (execute the following command in Python’s installation source directory)

1 [[email protected] ~]$ make && make install

Reinstallation completed
Execute.

1 [[email protected] ~]$ sudo python get-pip.py

Install pip successfully!

[Solved] Python import _ SSL DLL load fail error the module problem could not be found

Solution:

Add the following three items to the windows environment variable:

C:\Users\username\Anaconda3
C:\Users\username\Anaconda3\Scripts
C:\Users\username\Anaconda3\Library\bin

Note: if anaconda is not installed in the default directory, you need to replace the C:\Users\username path with the path where you installed anaconda

PS: for Windows environment variable configuration, please refer to: open file explorer, right-click this computer – properties – advanced system settings – environment variables – system variables – path on the left, and add the above three items. If any item is not added, a question will appear

If it still hasn’t been solved

Set anaconda3\library\bin

-   libcrypto-1_1-x64.dll
-   libssl-1_1-x64.dll 
Copy to anaconda3/DLLs

Docker Django: underlying buffer has been detached [How to Solve]

#error:underlying buffer has been detached
#Envirment: Docker, Django3.2.5, pyhton3.6

Scenario: the above error occurs every time I execute Python 3 manage.py runserver 0.0.0.0:8000

Finally, the problem was that I introduced the following code into some Python files

sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())  # System current default encoding format

​However, this code is a habitual way of writing the default output code in Python 2.

Solution: delete all sys.stdout in the .Py file

Reference: https://stackoverflow.com/questions/53533860/valueerror-underlying-buffer-has-been-detached-when-i-run-python-manager-py-mak