Category Archives: Python

[Solved] RuntimeError: scatter(): Expected dtype int64 for index


RuntimeError: scatter(): Expected dtype int64 for index

1. Error reporting reason:

Scatter requires the data to be of type Int64, and I wrote torch when defining tensor Tensor (x) should be written as torch Longtensor (x), specified as Int64 type.

2. Solutions

Find the definition method of the original data and change it
generally, dtype = NP int64; dtype=np.
in float32 (most definition functions have dtype attribute)
it is better to have the same number of bits of int and float

import numpy as np
a = np.random.randint(100, size=(10**6), dtype="int64")
print(a)
print(type(a[0]))

[Solved] cv2.error: OpenCV(4.5.1) XXX\shapedescr.cpp:315: error: (-215:Assertion failed) npoints >= 0 &&……

Error resolution

Error reproduction

Traceback (most recent call last):
  File "D:/pythonProjects/Object_movement/object_movement.py", line 88, in <module>
    c = max(cnts, key=cv2.contourArea)
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-i1s8y2i1\opencv\modules\imgproc\src\shapedescr.cpp:315: error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function 'cv::contourArea'

source code

cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
                            cv2.CHAIN_APPROX_SIMPLE)
cnts=cnts[1]

Modified code

cnts, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
                                       cv2.CHAIN_APPROX_SIMPLE)

Error reporting reason

New CV2 Findcontours returns two values. The result of [0] is contour instead of [1]

BlazingSQL Error: AttributeError: module ‘cio‘ has no attribute ‘RunQueryError‘

When using blazingsql, the following error was encountered:

Exception:
java.lang.IllegalStateException: Unable to instantiate java compiler
at org.apache.calcite.rel.metadata.JaninoRelMetadataProvider.compile(JaninoRelMetadataProvider.java:433)
at org.apache.calcite.rel.metadata.JaninoRelMetadataProvider.load3(JaninoRelMetadataProvider.java:374)
at org.apache.calcite.rel.metadata.JaninoRelMetadataProvider.lambda$static$0(JaninoRelMetadataProvider.java:109)
at com.google.common.cache.CacheLoader$FunctionToCacheLoader.load(CacheLoader.java:151)
·····

File "/root/bsqlserver/gce_app/libs/bsql_util.py", line 22, in jsonstr_bsql_exec
gdf = bc.sql(sql)
File "/usr/local/envs/bsql/lib/python3.7/site-packages/pyblazing/apiv2/context.py", line 2880, in sql
except cio.RunQueryError as e:
AttributeError: module 'cio' has no attribute 'RunQueryError'

Possible causes: blazingsql modules are imported in multiple places
keep a from blazingsql import blazingcontext to restore normal operation

[Solved] Networkx Error: Attributeerror: ‘graph’ object has no attribute ‘node’

When learning Networkx, you encounter an error when viewing node attributes:
attributeerror: ‘graph’ object has no attribute ‘node’

G= nx.Graph(name='undirected graph',data=2022) # Create undirected graph
G.add_nodes_from([1,2,3,4,5]) # Add nodes to the graph using the list
G.add_node(6,name='F',weight=12)
print(G.node[6]['name']) # Check the other attributes of the node according to its ID

The reason is that the lower version of Networkx has the node attribute, while the higher version does not use the node attribute
correction method 1: just change the node attribute to nodes
the correct code is as follows:

G= nx.Graph(name='undirected graph',data=2022) # Create undirected graph
G.add_nodes_from([1,2,3,4,5]) # Add nodes to the graph using the list
G.add_node(6,name='F',weight=12)
print(G.nodes[6]['name']) # Check the other attributes of the node based on its ID

Correction 2: reinstall the lower version of Networkx
PIP install: PIP install Networkx = = 2.3

[Solved] AttributeError: module ‘setuptools._distutils‘ has no attribute ‘version‘

AttributeError: module ‘setuptools._distutils’ has no attribute ‘version’
pytorch tensorboard error: AttributeError: module ‘setuptools._distutils’ has no attribute ‘version’

from torch.utils.tensorboard import SummaryWriter

writer=SummaryWriter("logs")

# writer.add_image()  
#y=x
for i in range(100):

    writer.add_scalar("y=x",i,i)  

writer.close()

Cause of problem:

Setuptools version too high

Solution:

Install lower version setuptools
Enter:
PIP uninstall setuptools
PIP install setuptools = = 59.5.0// it needs to be lower than your previous version

[Solved] Python Keras Error: AttributeError: ‘Sequential‘ object has no attribute ‘predict_classes‘

This article is about using Keras in Python to execute yhat_classes = model.predict_classes(X_test) code with an error: AttributeError: ‘Sequential’ object has no attribute ‘predict_classes’ solution.

model = Sequential()
model.add(Dense(24, input_dim=13, activation='relu'))
model.add(Dense(18, activation='relu'))
model.add(Dense(6, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
-
history = model.fit(X_train, y_train, batch_size = 256, epochs = 10, verbose = 2, validation_split = 0.2)
-
score, acc = model.evaluate(X_test, y_test,verbose=2, batch_size= 256)
print('test accuracy:', acc)
-
yhat_classes = model.predict_classes(X_test)

Cause of problem:

This predict was removed in tensorflow version 2.6_ Classes function.

Reference documents: https://keras.rstudio.com/reference/predict_proba.html#details

The following codes can be used:

predict_x=model.predict(X_test) 
classes_x=np.argmax(predict_x,axis=1)

Or

You can also try tensorflow 2.5 or other versions to solve this problem.

Using tensorflow version 2.5, there may be the following warning messages:

tensorflow\python\keras\engine\sequential.py:455: UserWarning: model.predict_classes() is deprecated and will be removed after 2021-01-01. Please use instead:* np.argmax(model.predict(x), axis=-1), if your model does multi-class classification (e.g. if it uses a softmax last-layer activation).* (model.predict(x) > 0.5).astype("int32"), if your model does binary classification (e.g. if it uses a sigmoid last-layer activation).

[Solved] ERROR: No matching distribution found for torch-cluster==x.x.x

Refer to the configuration of others and configure py36 in CONDA virtual environment

conda create -n py36 python=3.6

The default is Python 3 6.0. Later, pytorch = 1.8.0 and cudatoolkit = 11.1.1 are installed successfully, and then pip is used to install
– torch cluster = = 1.5.9
– torch scatter = = 2.0.6
– torch spark = = 0.6.9
– torch spline conv = = 1.2.1

ERROR: No matching distribution found for torch-cluster==1.5.9

After trying various methods on the Internet, it still doesn’t work. Even if you remove the version limit, you still report an error
later, I checked the environment configuration of others I referred to. It was the wrong version of Python I used. I should use Python 3 6.10
then execute in this virtual environment:

conda install python=3.6.10=hcf32534_1

Then execute it

pip install torch-xxxx==x.x.x

You can install it successfully

[Solved] lto1: fatal error: bytecode stream..generated with LTO version 6.2 instead of the expected 8.1 compi

ubuntu Compile libxml2-2.9.1
./configure & make & make install
Error Messages:

lto1: fatal error: bytecode stream in file ‘/home/…/anaconda3/envs/rasa/lib/python3.6/config-3.6m-x86_64-linux-gnu/libpython3.6m.a’ generated with LTO version 6.2 instead of the expected 8.1
compilation terminated.
lto-wrapper: fatal error: gcc returned 1 exit status
compilation terminated.
/usr/bin/ld: error: lto-wrapper failed
collect2: error: ld returned 1 exit status
make[4]: *** [Makefile:519: libxml2mod.la] Error 1
make[4]: Leaving directory ‘/home/…/libxml2-2.9.1/python’
make[3]: *** [Makefile:607: all-recursive] Error 1
make[3]: Leaving directory ‘/home/…/libxml2-2.9.1/python’
make[2]: *** [Makefile:450: all] Error 2
make[2]: Leaving directory ‘/home/…/libxml2-2.9.1/python’
make[1]: *** [Makefile:1304: all-recursive] Error 1
make[1]: Leaving directory ‘/home/…/libxml2-2.9.1’
make: *** [Makefile:777: all] Error 2

 

Solution:
conda install -c anaconda gcc_linux-64

[Solved] cv2.xfeatures2d.SIFT_create() Error: module ‘cv2.cv2’ has no attribute ‘xfeatures2d’

Problem Description:

In the experiment of digital image processing course, SIFT algorithm is used in the feature matching experiment, and opencv4 is used for the first time with vscode 4 and python 3 8. An error is reported

module 'cv2.cv2' has no attribute 'xfeatures2d'

Then install the opencv Python 3.4.2.16 command in Anaconda prompt as follows, and an error occurs that the relevant version cannot be found

pip install opencv-python==3.4.2.16

And report an error as

cv2.error: OpenCV(3.4.8) C:\projects\opencv-python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1207: error: (-213:The function/feature is not implemented) This algorithm is patented and is excluded in this configuration; Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library in function 'cv::xfeatures2d::SIFT::create'

Cause analysis

The reason for the first error is opencv4 Version 4 cannot be used due to sift patent; The second error is due to opencv4 2 and python 3 8 mismatch, need to be reduced to 3.6; This error is still a problem with the opencv version

Solution:

If it’s Python 3.6. You only need to install the package of the relevant version of OpenCV. Execute the following command in Anaconda prompt

pip install opencv-python==3.4.2.16
pip install opencv-contrib-python==3.4.2.16

Because I’m Python 3.8. Therefore, a virtual environment py36 is created for related configuration. For creating a virtual environment and activating a virtual environment, please refer to the creating a virtual environment – brief book in Anaconda blog, and then execute the above command in the activated virtual environment

Finally, run the PY file in the vs Code terminal

[Solved] Django project locally Open Error: importerror: couldn’t import Django

There is a mature Django project. After it is opened locally, an error is reported: importerror: couldn’t import Django Are you sure it’s installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
solution step 1: because this Django project uses python2.7. My local configuration environment variable is 3.7.7. After importing the Django project locally, the python compiler has been modified to 2.7

but an error is still reported after execution
solution step 2: open the teminal terminal of pycharm

execute the command: source venv/bin/activate
start the Django project: Python manage Py runserver

the Django project was started successfully and the problem was solved perfectly.