Category Archives: Python

numpy.distutils.system_info.NotFoundError: no lapack/blas resources found problem solved

Operating environment

Python3.6 + Windows7

Problem phenomenon

  Using pip to automatically install the seaborn/numpy/scipy (pip install seaborn) module fails, prompting numpy.distutils.system_info.NotFoundError: no lapack/blas resources found error.

problem analysis

NA

problem solved

1. Click to enter the python package download address: http://www.lfd.uci.edu/~gohlke/pythonlibs/

2. The interface can directly search for the .whl file corresponding to the module to be installed. For example, seaborn, after obtaining it, choose to download according to your machine type (32-bit or 64-bit) and python version.

3. Use pip to install, with the absolute path of the file or place the file in the current path.

C:\Windows\system32>pip install C:\Users\linyfeng\Desktop\seaborn-0.8-py2.py3-none-any.whl

4. The import test is successful and the installation is over.

 other

If the xgboost installation fails, you can also obtain the .whl file from the above link. The installation is successful, and the installation method is the same. xgboost installation failed as described below

C:\Windows\system32> pip install xgboost
Collecting xgboost
  Downloading http: //pypi.doubanio.com/packages/34/85/456a1a8c762f646671043e446a59efbce02b5f408f522c4ef8793e860c5e/xgboost-0.6a2.tar.gz ( 1.2MB)
     100% |██████████████ █████████████████| 1.2MB 4.2MB/ s
 No files /directories in C:\Users\shiyanan\AppData\Local\Temp\pip-build-ujfe_1y7\xgboost\ pip-egg-info (from PKG-INFO)

No module named Crypto.Cipher [How to Solve]

1. PIP install Python often reports an error:

error: Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat). Get it from http://aka.ms/vcpython27

It seems to be troublesome, too

2. Use the compiled installation package. Download address:

  [pycropt](http://www.voidspace.org.uk/python/modules.shtml#pycrypto)

According to their own version of the corresponding installation can now

However, after installation, it may not be of any use, and the user still reports an error:

No module named Crypto.Cipher

After painstaking search, we finally found the answer on the stack over:
after opening the link, please pull to the last answer

I found the solution. Issue is probably in case sensitivity (on Windows).
Just change the name of the folder:
C:\Python27\Lib\site-packages\crypto
to: C:\Python27\Lib\site-packages\Crypto

The translation is:
rename the crypto folder to crypto

How to Solve Django Error: No such column: xxx

The operation before and after the model is as follows:

First migration:

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=True)
    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)

After change:

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=True)
    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
    owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
    highlighted = models.TextField()

There are three steps for Django to modify the database

1. Make changes to models.py (normal)

2. Creating migrations using makemigrations

3. Migration using migrate

Analysis: after the modified model, the code and highlighted fields cannot be empty when the database is synchronized for the second time. If you create the highlighted field the first time, there is no impact because the table does not have an existing row. If the data table has been created for the first time and data has been inserted into the table, a default value must be defined to fill in the existing row, otherwise the database will not accept the data table changes because of violating the integrity of the data

Solution: change to

code = models.TextField(default =”)

highlighted = models.TextField(default =”)

[Solved] pytorchImportError: numpy.core.multiarray failed to import

Project scenarios

Recently, I’m learning Python . First, I installed the following with the CONDA command provided on the official website:

conda install pytorch torchvision cudatoolkit=10.2 -c pytorch

Then test whether the installation is successful and whether it can be used normally according to the method of the official website

import torch
x = torch.rand(5, 3)
print(x)

If the value of x can be printed normally, it means that it can be used normally, otherwise it is the opposite

Problem description

Error in code operation: importerror: numpy.core.multiarray failed to import

D:\miniconda3\envs\pytorch\lib\site-packages\numpy\__init__.py:138: UserWarning: mkl-service package failed to import, therefore Intel(R) MKL 
initialization ensuring its correct out-of-the box operation under condition when Gnu OpenMP had already been loaded by Python process is not 
  from . import _distributor_init
Traceback (most recent call last):
  File "c:/Users/ghgxj/Desktop/pytorch/1_get_started.py", line 1, in <module>
    import torch
  File "D:\miniconda3\envs\pytorch\lib\site-packages\torch\__init__.py", line 189, in <module>
    from torch._C import *
ImportError: numpy.core.multiarray failed to import

Cause analysis

The Python environment comes with a numpy , which will conflict with the numpy version installed with Python

Solutions

Uninstall numpy first

conda uninstall numpy

reinstall numpy

conda install numpy

The final result

According to the above scheme, the values of x are printed normally

tensor([[0.8338, 0.1541, 0.0379],
        [0.4348, 0.0145, 0.3586],
        [0.4098, 0.2363, 0.5405],
        [0.7372, 0.7418, 0.3703],
        [0.5668, 0.9512, 0.8041]])

Let’s see if GPU driver and CUDA can be used:

import torch
print(torch.cuda.is_available())

If the console print shows true , it means it can be used normally

 

[Solved] TypeError Error: Cannot read property ‘0’ of undefined

Get a simple project from GitHub. I want to have a look at it, but there is an exception when running NPM start, that is, react scripts start

The general errors are as follows:

- ExternalModuleFactoryPlugin.js:19 
    [web]/[webpack]/lib/ExternalModuleFactoryPlugin.js:19:40
  
  - NormalModuleFactory.js:159 
    [web]/[react-scripts]/[webpack]/lib/NormalModuleFactory.js:159:3
  
  - Tapable.js:75 NormalModuleFactory.applyPluginsAsyncWaterfall
    [web]/[react-scripts]/[tapable]/lib/Tapable.js:75:69
  
  - NormalModuleFactory.js:144 NormalModuleFactory.create
    [web]/[react-scripts]/[webpack]/lib/NormalModuleFactory.js:144:8
  
  - Compilation.js:356 Compilation.process [as _addModuleChain]
    [web]/[react-scripts]/[webpack]/lib/Compilation.js:356:16
  
  - Compilation.js:424 Compilation.process [as addEntry]
    [web]/[react-scripts]/[webpack]/lib/Compilation.js:424:7
  
  - SingleEntryPlugin.js:24 Compiler.compiler.plugin
    [web]/[webpack]/lib/SingleEntryPlugin.js:24:16
  
  - Tapable.js:107 Compiler.applyPluginsParallel
    [web]/[react-scripts]/[tapable]/lib/Tapable.js:107:14
  
  - Compiler.js:394 Compiler.compile
    [web]/[react-scripts]/[webpack]/lib/Compiler.js:394:7
  
  - Compiler.js:203 Compiler.runAsChild
    [web]/[react-scripts]/[webpack]/lib/Compiler.js:203:7
  
  - compiler.js:70 
    [web]/[html-webpack-plugin]/lib/compiler.js:70:19
  
  - compiler.js:69 Object.compileTemplate
    [web]/[html-webpack-plugin]/lib/compiler.js:69:10
  
  - index.js:47 Compiler.<anonymous>
    [web]/[html-webpack-plugin]/index.js:47:40 Later, after much searching, it looked like the react-scripts version conflicted with the webpack version, so the react-scripts version was lowered from 0.9.5 to 0.7.0

[Solved] PythonTypeError: ‘<' not supported between instances of 'str' and 'int'

1 n = input()
2 if n>=100:print(int(n)/10)
3 else:print(int(n)*10)

Error:

Traceback (most recent call last):
  File "1.py", line 12, in <module>
    if n>=100:print(int(n)/10)
TypeError: '>=' not supported between instances of 'str' and 'int'

***Repl Closed***

analysis: the data type returned by input() is STR, which cannot be directly compared with integers. You must first replace STR with integers, and use the int() method

therefore, the input variable can be converted to int

1 n = input()
2 n = int(n)
3 if n>=100:print(int(n)/10)
4 else:print(int(n)*10)

Or

1 n = int(input("Input a number:"))
2 if n>=100:print(int(n)/10)
3 else:print(int(n)*10)

 

AttributeError: ‘NoneType’ object has no attribute ‘split’ [How to Solve]

Error reporting scenario

social_ Django component has better support for native Django, but because the verification in DRF is JWT mode, it is different from Django

Therefore, we need to make changes to support the addition of verification information in JWT mode

The following error occurs when the third party login is verified after the change

Detailed error report

[29/Apr/2019 15:12:02] "GET/HTTP/1.1" 200 6992
[29/Apr/2019 15:12:11] "GET /login/weibo/ HTTP/1.1" 302 0
[29/Apr/2019 15:12:13] "GET /complete/weibo/?state=cpNja8cxhyV9GPSKvjVfWnwogNskNjob&code=ba1e4f6fd32f32d0b57094eecd0e7d1b HTTP/1.1" 302 0
Traceback (most recent call last):
  File "C:\Python36\lib\wsgiref\handlers.py", line 138, in run
    self.finish_response()
  File "C:\Python36\lib\wsgiref\handlers.py", line 180, in finish_response
    self.write(data)
  File "C:\Python36\lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "C:\Python36\lib\wsgiref\handlers.py", line 333, in send_headers
    self._write(bytes(self.headers))
  File "C:\Python36\lib\wsgiref\headers.py", line 142, in __bytes__
    return str(self).encode('iso-8859-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 251-253: ordinal not in range(256)
[29/Apr/2019 15:12:13] "GET /complete/weibo/?state=cpNja8cxhyV9GPSKvjVfWnwogNskNjob&code=ba1e4f6fd32f32d0b57094eecd0e7d1b HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 11977)
Traceback (most recent call last):
  File "C:\Python36\lib\wsgiref\handlers.py", line 138, in run
    self.finish_response()
  File "C:\Python36\lib\wsgiref\handlers.py", line 180, in finish_response
    self.write(data)
  File "C:\Python36\lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "C:\Python36\lib\wsgiref\handlers.py", line 333, in send_headers
    self._write(bytes(self.headers))
  File "C:\Python36\lib\wsgiref\headers.py", line 142, in __bytes__
    return str(self).encode('iso-8859-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 251-253: ordinal not in range(256)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python36\lib\wsgiref\handlers.py", line 141, in run
    self.handle_error()
  File "C:\Python36\lib\site-packages\django\core\servers\basehttp.py", line 88, in handle_error
    super(ServerHandler, self).handle_error()
  File "C:\Python36\lib\wsgiref\handlers.py", line 368, in handle_error
    self.finish_response()
  File "C:\Python36\lib\wsgiref\handlers.py", line 180, in finish_response
    self.write(data)
  File "C:\Python36\lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "C:\Python36\lib\wsgiref\handlers.py", line 331, in send_headers
    if not self.origin_server or self.client_is_modern():
  File "C:\Python36\lib\wsgiref\handlers.py", line 344, in client_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python36\lib\socketserver.py", line 639, in process_request_thread
    self.finish_request(request, client_address)
  File "C:\Python36\lib\socketserver.py", line 361, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "C:\Python36\lib\socketserver.py", line 696, in __init__
    self.handle()
  File "C:\Python36\lib\site-packages\django\core\servers\basehttp.py", line 155, in handle
    handler.run(self.server.get_app())
  File "C:\Python36\lib\wsgiref\handlers.py", line 144, in run
    self.close()
  File "C:\Python36\lib\wsgiref\simple_server.py", line 35, in close
    self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
----------------------------------------

Solutions

For the time being, this can be solved, but I don’t know if it will have a bad impact

How to Solve Opencv error: assertion failed + error: (- 215)

When trying to write the ROS program of python2.7 and using the import CV2 statement, the program may automatically use the opencv3.3.1 – dev (path/opt/ROS/kinetic/lib/python2.7/dist packages/CV2. So) of ROS, rather than the higher version of OpenCV (path/usr/local/lib/python2.7/dist packages/CV2. So) installed by ourselves

Some of my programs use the face detection function provided by opencv’s DNN module

DNN = "CAFFE"
if DNN == "CAFFE":
    modelFile = "res10_300x300_ssd_iter_140000_fp16.caffemodel"
    configFile = "deploy.prototxt"
    net = cv2.dnn.readNetFromCaffe(configFile, modelFile)

When executing with ROS code, the program reports an error

[ INFO:0] Initialize OpenCL runtime...
OpenCV Error: Assertion failed (input.dims == 4 && (input.type() == 5 || input.type() == 6)) in finalize, file /tmp/binarydeb/ros-kinetic-opencv3-3.3.1/modules/dnn/src/layers/convolution_layer.cpp, line 78
Traceback (most recent call last):
  File "detect_faces.py", line 41, in <module>
    detections = net.forward()
cv2.error: /tmp/binarydeb/ros-kinetic-opencv3-3.3.1/modules/dnn/src/layers/convolution_layer.cpp:78: error: (-215) input.dims == 4 && (input.type() == 5 || input.type() == 6) in function finalize

Emmm… Tried several methods, the most effective one is to delete cv2.so in the ROS package and let the program use our own higher version of OpenCV. In order to prevent problems in the future, we just put the cv2.so of ROS into the trash instead of deleting it directly. The steps are as follows:

sudo easy_install trash-cli
# trash-cli is a software to move files into trash and recover them

sudo trash-put /opt/ros/kinetic/lib/python2.7/dist-packages/cv2.so
# This will work.

# If the python2.7 package also has a low version of opencv, the statement to install the specific version yourself is
sudo pip2 install opencv-python==3.4.0.12

Then run the program, no error will be reported

[Python Debug]Kernel Crash While Running Neural Network with Keras|Jupyter Notebook Run Keras Server Down

Recently, I did my machine learning assignment, and I want to build a neural network with keras on jupyter notebook. As a result, even the simplest layer of neural network couldn’t work. What’s more strange is that I ran the iris data set first, and there was no problem, but I used the fashion MNIST given by my teacher to prompt the server to hang up and restart as soon as I ran it. What’s more strange is that there’s no problem with the same code running on the students’ computers, which makes me think that my MacBook is too old and the configuration is too low, so I almost want to buy a new computer & gt_& lt;

After several times of debugging by ml teacher in class today, the problem has been solved perfectly, worthy of CMU God( Call Prof strongly here, though he doesn’t understand Chinese & gt& lt;) Because I haven’t learned Python for a long time and I’m not familiar with it. After this time, I’ve learned many new skills ✌️

The complete code of the problem is as follows, which is to use keras to realize logistic region. It is a simple one layer network, but every time it runs to the last line, the server will hang up, and then restart kernel

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA, FastICA
from sklearn.linear_model import LogisticRegression
from keras.models import Sequential
from keras.layers import Dense, Activation, Conv2D
from keras.utils import to_categorical
from keras.datasets import fashion_mnist

(x3_train, y_train), (x3_test, y_test) = fashion_mnist.load_data()
n_classes = np.max(y_train) + 1

# Vectorize image arrays, since most methods expect this format
x_train = x3_train.reshape(x3_train.shape[0], np.prod(x3_train.shape[1:]))
x_test = x3_test.reshape(x3_test.shape[0], np.prod(x3_test.shape[1:]))

# Binary vector representation of targets (for one-hot or multinomial output networks)
y3_train = to_categorical(y_train)
y3_test = to_categorical(y_test)

from sklearn import preprocessing
scaler = preprocessing.StandardScaler()
x_train_scaled = scaler.fit_transform(x_train)     
x_test_scaled = scaler.fit_transform(x_test) 

n_output = y3_train.shape[1]
n_input = x_train_scaled.shape[1]

nn_lr = Sequential() 
nn_lr.add(Dense(units=n_output, input_dim= n_input, activation = 'softmax'))
nn_lr.compile(optimizer = 'sgd', loss = 'categorical_crossentropy', metrics = ['accuracy'])

Since Jupyter Notebook just keeps restarting the kernel and there is no error message, so people can’t get started. But after the teacher prompted the original Jupyter Notebook automatically opened when the terminal will record information on the run (the first time a white person found.) The following is the detailed process of kerter abort and restart and the reasons for it.

[I 22:11:54.603 NotebookApp] Kernel interrupted: 7e7f6646-97b0-4ec7-951c-1dce783f60c4

[I 22:13:49.160 NotebookApp] Saving file at /Documents/[Rutgers]Study/2019Spring/MACHINE LEARNING W APPLCTN LARGE DATASET/hw/Untitled1.ipynb

2019-03-28 22:13:49.829246: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA

2019-03-28 22:13:49.829534: I tensorflow/core/common_runtime/process_util.cc:69] Creating new thread pool with default inter op setting: 4. Tune using inter_op_parallelism_threads for best performance.

OMP: Error #15: Initializing libiomp5.dylib, but found libiomp5.dylib already initialized.

OMP: Hint: This means that multiple copies of the OpenMP runtime have been linked into the program. That is dangerous, since it can degrade performance or cause incorrect results. The best thing to do is to ensure that only a single OpenMP runtime is linked into the process, e.g. by avoiding static linking of the OpenMP runtime in any library. As an unsafe, unsupported, undocumented workaround you can set the environment variable KMP_DUPLICATE_LIB_OK=TRUE to allow the program to continue to execute, but that may cause crashes or silently produce incorrect results. For more information, please see http://www.intel.com/software/products/support/.

[I 22:13:51.049 NotebookApp] KernelRestarter: restarting kernel (1/5), keep random ports

kernel c1114f5a-3829-432f-a26a-c2db6c330352 restarted

There is another way to get a similar message by copying the code into ipython, so the final error located is

OMP: Error #15: Initializing libiomp5.dylib, but found libiomp5.dylib already initialized.

Google it, there is a very detailed discussion post on github, but the owner was running XGBoost when he encountered this problem, which reminds me that the winter break installation of XGBoost did go through a very tortuous process, and may have accidentally downloaded a file to a different path repeatedly, so the program loaded the package when there was a conflict. The post provides several possible causes and solutions.

1. uninstall clang-omp

brew uninstall libiomp clang-omp

as long as u got gcc v5 from brew it come with openmp

follow steps in:
https://github.com/dmlc/xgboost/tree/master/python-package

Tried uninstalling xgboost and installing it again, then uninstalling clang-omp, got an error

No such keg: /usr/local/Cellar/libiomp

pip uninstall xbgoost
pip install xgboost
brew uninstall libiomp clang-omp

2. Run directly in jupyter notebook

# DANGER! DANGER!
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'

The teacher said that this command allows the system to ignore the problem of package conflict and choose a package to use. Try this method is really effective, but it is very dangerous, extremely not recommended

3. Find the duplicate libiomp5.dylib file and delete one of them

Two files are found in finder, which are in ~/⁨ anaconda3 ⁩/lib ⁩ and ~/anaconda3 ⁩/⁨ lib ⁩/⁨ Python 3.6 ⁩/⁨ site packages ⁩/⁨_ solib_ darwin⁩/⁨_ U@mkl_ Udarwin_ S_ S_ Cmkl_ Ulibs_ Udarwin___ Uexternal_ Smkl_ Udarwin_ Slib⁩ (????) But I’m not sure which one should be deleted. I think it’s dangerous. I can’t run if I delete the wrong one

4. OpenMP conflict

Hint: This means that multiple copies of the OpenMP runtime have been linked into the program

According to hint in the prompt message, I searched tensorflow OpenMP. OpenMP is a multi thread parallel programming platform, tensorflow seems to have its own parallel computing architecture, and can not use OpenMP (see) https://github.com/tensorflow/tensorflow/issues/12434 )

5. Unload nomkl

I had the same error on my Mac with a python program using numpy, keras, and matplotlib. I solved it with ‘conda install nomkl’.

This is the last effective way! The full name of nomkl is math kernel library (MKL) optimization. It is a module developed by Interl to speed up mathematical operations. MKL can be used automatically by installing package through CONDA. For more details, please refer to the official document of anaconda

To opt out, runcondainstallnomkland then usecondainstallto install packages that would normally include MKL or depend on packages that include MKL, such asscipy,numpy, andpandas.

Maybe there are some conflicts in the update of package such as numpy. After installing nomkl, it was solved miraculously. Later, it tried to unload MKL, and the program is still running normally.. The unload command is as follows:

conda remove mkl mkl-service

 

[Solved] Django Run Error: TypeError: object supporting the buffer API required

Type error: object supporting the buffer API required

Solution:

Change the password of database in settings.py to string format

Source code:

def scramble_caching_sha2(password, nonce):
    # (bytes, bytes) -> bytes
    """Scramble algorithm used in cached_sha2_password fast path.

    XOR(SHA256(password), SHA256(SHA256(SHA256(password)), nonce))
    """
    if not password:
        return b''

    p1 = hashlib.sha256(password).digest()

The password must be in the form of string