Tag Archives: python

cannot import name ‘_validate_lengths’ from ‘numpy.lib.arraypad’

Error in importing skimage:

>>> import skimage
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/AI/AN/lib/python3.7/site-packages/skimage/__init__.py", line 157, in <module>
    from .util.dtype import *
  File "/opt/AI/AN/lib/python3.7/site-packages/skimage/util/__init__.py", line 8, in <module>
    from .arraycrop import crop
  File "/opt/AI/AN/lib/python3.7/site-packages/skimage/util/arraycrop.py", line 8, in <module>
    from numpy.lib.arraypad import _validate_lengths
ImportError: cannot import name '_validate_lengths' from 'numpy.lib.arraypad' (/opt/AI/AN/lib/python3.7/site-packages/numpy/lib

Because it doesn’t match the numpy version, my numpy is 1.16

The version of numpy can be reduced or the version of skimage can be improved. When I finally use the latter, the former will report an error

ValueError: numpy.ufunc has the wrong size, try recompiling. Expected 192, got 216

resolvent:

1) View version:

[root@localhost datasets]# pip install scikit-image==9999
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
ERROR: Could not find a version that satisfies the requirement scikit-image==9999 (from versions: 0.7.2, 0.8.0, 0.8.1, 0.8.2, 0.9.0, 0.9.1, 0.9.3, 0.10.0, 0.10.1, 0.11.2, 0.11.3, 0.12.0, 0.12.1, 0.12.2, 0.12.3, 0.13.0, 0.13.1, 0.14.0, 0.14.1, 0.14.2, 0.14.3, 0.14.4, 0.14.5, 0.15.0, 0.16.1, 0.16.2)
ERROR: No matching distribution found for scikit-image==9999

2) Install the latest

[root@localhost datasets]# pip install scikit-image==0.16.2
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting scikit-image==0.16.2
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/dc/48/454bf836d302465475e02bc0468b879302145b07a005174c409a5b5869c7/scikit_image-0.16.2-cp37-cp37m-manylinux1_x86_64.whl (26.5MB)
     |████████████████████████████████| 26.5MB 1.8MB/s 
Requirement already satisfied: matplotlib!=3.0.0,>=2.0.0 in /opt/AI/AN/lib/python3.7/site-packages (from scikit-image==0.16.2) (2.2.3)
Requirement already satisfied: scipy>=0.19.0 in /opt/AI/AN/lib/python3.7/site-packages (from scikit-image==0.16.2) (1.1.0)
Requirement already satisfied: networkx>=2.0 in /opt/AI/AN/lib/python3.7/site-packages (from scikit-image==0.16.2) (2.1)
Requirement already satisfied: imageio>=2.3.0 in /opt/AI/AN/lib/python3.7/site-packages (from scikit-image==0.16.2) (2.4.1)
Requirement already satisfied: PyWavelets>=0.4.0 in /opt/AI/AN/lib/python3.7/site-packages (from scikit-image==0.16.2) (1.0.0)
Requirement already satisfied: pillow>=4.3.0 in /opt/AI/AN/lib/python3.7/site-packages (from scikit-image==0.16.2) (5.2.0)
Requirement already satisfied: numpy>=1.7.1 in /opt/AI/AN/lib/python3.7/site-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.16.2) (1.16.0)
Requirement already satisfied: cycler>=0.10 in /opt/AI/AN/lib/python3.7/site-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.16.2) (0.10.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/AI/AN/lib/python3.7/site-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.16.2) (2.4.5)
Requirement already satisfied: python-dateutil>=2.1 in /opt/AI/AN/lib/python3.7/site-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.16.2) (2.7.3)
Requirement already satisfied: pytz in /opt/AI/AN/lib/python3.7/site-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.16.2) (2018.5)
Requirement already satisfied: six>=1.10 in /opt/AI/AN/lib/python3.7/site-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.16.2) (1.13.0)
Requirement already satisfied: kiwisolver>=1.0.1 in /opt/AI/AN/lib/python3.7/site-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.16.2) (1.0.1)
Requirement already satisfied: decorator>=4.1.0 in /opt/AI/AN/lib/python3.7/site-packages (from networkx>=2.0->scikit-image==0.16.2) (4.3.0)
Requirement already satisfied: setuptools in /opt/AI/AN/lib/python3.7/site-packages (from kiwisolver>=1.0.1->matplotlib!=3.0.0,>=2.0.0->scikit-image==0.16.2) (41.0.0)
Installing collected packages: scikit-image
  Found existing installation: scikit-image 0.14.0
    Uninstalling scikit-image-0.14.0:
      Successfully uninstalled scikit-image-0.14.0
Successfully installed scikit-image-0.16.2

3) Try:

[root@localhost datasets]# python
Python 3.7.0 (default, Jun 28 2018, 13:15:42) 
[GCC 7.2.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import skimage
>>> 

Absolutely OK

ERROR: pygame-1.9.2-cp35-cp35m-win32.whl is not a supported wheel on this platform.

Why?

The downloaded pyGame is not compatible with the python version.

How do you do it?

Go to the website and download the pyGame installation related to your Python version.
(check your Python version: if you enter Python in CMD, you will be prompted for the python version.)

Process:

When installing pyGame last night, I went to the website: link according to the process in the textbook “Python Programming: from introduction to practice”, and downloaded the corresponding pyGame. However, the above errors occurred during the installation.
Looking all over the network, there is no suitable solution for me.
Then I look at the error report carefully:
pygame-1.9.2-cp35-cp35m-win32.whl is not supported by this platform (wheel, please point out what it is). The previous file is used to install pyGame.
1.9.2 refers to PIP version.
Cp35 refers to Python version 3.5, while mine is 3.7.
So far, the event is clear. Each pyGame corresponds to a different version of Python. The version is incompatible and an error is reported.
After downloading, the installation is successful!
(no screenshots here: I forgot to cut them last night)

File “manage.py“, line 17 ) from exc ^ SyntaxError: invalid syntax

The newly created Django project will run directly after entering

python manage.py runserver

The mistakes are as follows:

user@UserdeMacBook-Pro djangoProject % python manage.py runserver
  File "manage.py", line 17
    ) from exc
         ^
SyntaxError: invalid syntax

I feel a little puzzled. Later, I found that there was a problem with the specification of the python version. I should specify the python 3 version

python3 manage.py runserver

That’s it.

Python error type error: ‘range’ object does not support item assignment, solution

1. Examples are as follows:

from math import sqrt
if __name__ == '__main__':
    N = 100
    a = range(0,N)
    for i in range(2,int(sqrt(N))):
        for j in range(i + 1,N):
            if (a[i] != 0) and (a[j] != 0):
                if a[j] % a[i] == 0:
                        a[j]= 0

    for i in range(2,N):
        if a[i] != 0:
            print ("%5d" % a[i])
            if (i - 2) % 10 == 0:
                print         

Error after execution: typeerror: ‘range’ object does not support item assignment

2. The reasons for the error are as follows:

Try to use range()
to create an integer list (leading to “typeerror: ‘range’ object does not support item assignment”). Sometimes you want to get an ordered integer list, so range() seems to be a good way to generate this list. However, you need to remember that range () returns the “range object” instead of the actual list value.

3. Solutions:

Just change the code of the above example: a = range (0, n) to a = list (range (0, n))!

data argument can’t be an iterator

 b = map(ct,data.as_matrix())

data = pd.DataFrame(b).fillna(0)
Traceback (most recent call last):

  File "<ipython-input-47-48b397cc2c53>", line 1, in <module>
    data = pd.DataFrame(b).fillna(0)

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py", line 389, in __init__
    raise TypeError("data argument can't be an iterator")

TypeError: data argument can't be an iterator

Reason: Elements in a dataframe cannot be iterative.

b = map(ct,data.as_matrix())
c = list(b)
data = pd.DataFrame(c).fillna(0)

pyspark : NameError: name ‘spark’ is not defined

This is because there is no default in Python program pyspark.sql.session . sparksession , so we just need to import the relevant modules and then convert them to sparksession .
Related codes:

from pyspark.context import SparkContext
from pyspark.sql.session import SparkSession
sc = SparkContext('local')
spark = SparkSession(sc)
print(type(spark))

Print out its type and solve it successfully:
& lt; class' pyspark.sql.session .SparkSession'>

ImportError: No module named indexes.base

The problem recurred

When I use pickle to reload data, all the errors are as follows:

Traceback (most recent call last):
  File "segment.py", line 17, in <module>
    word2id = pickle.load(pk)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 858, in load
    dispatch[key](self)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1090, in load_global
    klass = self.find_class(module, name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1124, in find_class
    __import__(module)
ImportError: No module named indexes.base

The reason for this

The same code and data run on two different machines. At first, I thought the wrong machine was missing some Python packages. But there are too many packages to install, so I can’t try them one by one. Fortunately, I use virsualenv to copy the environment from another machine to this machine directly. After running, there is no problem. But in order to find out which Python installation package is missing, I use the original compilation environment, reuse pickle to generate the original data to be loaded, and then reload it At this time, there was no error.

summary

To sum up, the reason is that the original version of panda used in the generation of pickle file is different from the current version of load pickle file. So whether it is to write code in Python or other languages, the compiling environment is very important. Once the version of a package is different, it may also lead to program errors.

TypeError: ‘numpy.int64′ object is not iterable ,’int’ object is not iterable

If you want to use a list to dynamically add numpy type data, as shown in the following code, you will find that the error type error is: ‘ numpy.int64 ‘ object is not iterable 

a = []
b = np.array([1,2,3])
a.extend(b[0])
a.extend(b[1])
a.extend(b[2])
print(a)

The numpy data is converted to the list type, as follows:

a = []
b = np.array([1,2,3])
a.extend(b[0].tolist())
a.extend(b[1].tolist())
a.extend(b[2].tolist())
print(a)

Error found: typeerror: ‘Int’ object is not Iterable

By printing the type of ‘B [0]. Tolist ()’, we find that the type of ‘B [0]. Tolist ()’ is’ Int ‘, that is, it does not convert’ B [0]. Tolist () ‘to list type

Then modify the code as follows, change ‘B [0]. Tolist ()’ to list type by adding a bracket []

a = []
b = np.array([1,2,3])
a.extend([b[0].tolist()])
a.extend([b[1].tolist()])
a.extend([b[2].tolist()])
print(a) #[1, 2, 3]

————————————————————————-Dividing line————————————————————————————————–

Later, I found that the following code can also be used directly:

a = []
b = np.array([1,2,3])
a.extend([b[0]])
a.extend([b[1]])
a.extend([b[2]])
print(a) #[1, 2, 3]

This is because the ‘B [0]’ is changed from numpy data type to list type by adding a bracket []

Pychar appears“ PEP:8 expected 2 blank lines ,found 1″

When using pychar to write python, the above problem always appears in the line def function() .
“PEP 8: expected 2 blank lines, found 1”

The specific reason is that there must be two empty lines above the line that declares the function, otherwise this will happen.
The annotation of function can be integrated with function

# coding: utf-8
# fun1
def func1():
    return 0
# fun2


def func2():
    return 1

 

Type error: the JSON object must be STR, bytes or byte array, not ‘textiowrapper’

When using JSON in Python to read a JSON file, an error is reported because the corresponding method is used incorrectly: typeerror: the JSON object must be STR, bytes or byte array, not ‘textiowrapper’.

Solution: first of all, we need to understand that there are four methods for JSON: dumps and loads, dump and load. Among them, dumps and loads are converted in memory (the conversion between Python objects and JSON strings), while dump and load are the processing corresponding to files.

The reason for this error is that I used the loads method to convert the JSON file into a python object, and the correct way is to use the load method.

Solve the problem of flag error valueerror: View function did not return a response

Today, we use Python to implement the restful interface of Flask, and then call it wrong.

ValueError: View function did not return a response

The code is as follows:

@app.route('/xxxx/yyyy_zzzzz', methods=['POST', 'GET'])

def receive():

      param = request.json

      print(param)

The reason for the error is that the restful interface of flag must have a return value.

Therefore, modify the code to add the return value:

Add: return XXXX

For example:

@app.route('/xxxx/yyyy_zzzzz', methods=['POST', 'GET'])

def receive():

    try:

        if not request.json:

            return jsonify({'code': -1, 'message': 'request is not json'})

        param = request.json

        return jsonify({'code': 0, 'status': 'running'})

    except Exception as e:

        print(e)

        return jsonify({'code': -1, 'error_message':e})

 

Summary of solutions to open flash back problem after Python packaging

Recently, I wrote a python project, but I found no response after packing it today. I checked some information and said that adding a input input statement at the end of the program can stay here to see the cause of the error.

After I add the input statement, I execute the following command to package

pyinstaller -F --hidden-import babel.numbers start_trade.py

Pay attention not to add the - W parameter, so that the terminal window cannot be displayed and the saved information cannot be seen.
--hidden-import babel.numbers represents the hidden module of packaging

The error message displayed during operation is

No module named 'talib.stream' name 'UI' is not defined

Now the program can’t find the package.

resolvent

Introduce into the files using the module talib.stream

The same is true for the missing module. The missing module is introduced in the file that references the module

However, it should be noted that what it prompts should be introduced according to the name it prompts, such as

import talib.stream