Category Archives: Python

Plt.acorr() Function Error: ValueError: object too deep for desired array

sketch

Note that the input data needs to be one-dimensional. Otherwise, it’s strange to report an error( Don’t ask me why I know)

Correct code:

import matplotlib.pyplot as plt
import numpy as np
data = np.random.random(100)
plt.acorr(data)
plt.show()

Error code:

import matplotlib.pyplot as plt
import numpy as np
data = np.random.random((1, 100))
plt.acorr(data)
plt.show()

Python TypeError: not all arguments converted during string formatting [Solved]

For example:

 strs=(1,2,3,4)  #Create a collection
 strs
 (1, 2, 3,4)
 >>> print 'strs= %s ' % strs
 Traceback (most recent call last):
   File "<pyshell#43>", line 1, in <module>
     print 'strs= %s ' % str
 TypeError: not all arguments converted during string formatting

Reason: the 1% operator can only be used directly for string (‘123 ‘). If it is a list ([1,2,3]) or tuple, it needs to match operators one by one.

To put it bluntly, it’s written in parentheses with commas (STRs,)

Solution:

print 'strs= %s' % (strs,)
strs= (1, 2, 3,4)
or
print 'strs= %s,%s,%s,%s' % sstr
strs= 1,2,3,4 

# simple explanation
the% before and after explanation does not correspond to the number of parameters after explanation, such as

File "<pyshell#37>", line 1, in <module>
print '%f meters is the same as &f km' % (meters, kilometers)
TypeError: not all arguments converted during string formatting

There are two parameters of miles and kilometer in the back, only one% F in the front, and one & amp; with wrong print;, The former is inconsistent with the latter; If you change it to

print '%f miles is the same as %f km' % (miles, kilometers)

That’s all

[Solved] TypeError: not all arguments converted during string formatting

When formatting the output of a string, one of the methods is as follows:

for value in ['A', 'B', 'C']:
    print('output: %s' % value)

When I print the running status of the sub process, print() I found several strings in the list, but the error is as follows:

TypeError: not all arguments converted during string formatting

Not all the parameters are converted during the string formatting period. I looked at the location of the error. It turned out that % was wrongly typed, and it became $, and I didn’t know the reason at first. I saw this error for the first time and sent this information to everyone for reference. This is a low-level mistake

Supplement: several ways of string output

Direct print() output

print('str1', 'str2', 'str3', '...')

'%s' % value Placeholder output

# 1. Single
>>> name = 'Jason'
>>> print('name: %s' % name)
name: Jason
# 2.Multiple
>>> name1, name2 = 'Jason', 'Bob'
>>> print('name1: %s; name2: %s' % (name1, name2))
name1:, Jason; name2: Bob
# Output order can also be customized
>>> print('name1: %s; name2: %s' % (name2, name1))
name1: Bob; name2: Jason

When outputting multiple string variables, multiple variables after % need to be enclosed in parentheses, otherwise the error of insufficient parameters will be reported

TypeError: not enough arguments for format string

format() format output

# 1. Single
>>> '{}'.format('world')
'world'
# 2. Multiple
>>> word1, word2 = 'hello', 'world'
>>> hello_world = '{}, {}'.format(word1, word2)
>>> hello_world
'hello, world'
# Output order can also be customized
>>> hello_world = '{1}, {1}'.format(word1, word2)
>>> hello_world
'world, world'

When output at specified position, all {} must have subscripts of parameters, otherwise it will not be able to convert from manual field number to automatic field number valueerror error:

ValueError: cannot switch from manual field specification to automatic field numbering

It must also be within the subscript range, otherwise an overrun indexerror error will be reported

IndexError: Replacement index 2 out of range for positional args tuple

[Solved] Python Error: TypeError: write() argument must be str, not bytes

In the chapter “decision tree” of “machine learning in action”, the error typeerror: write() argument must be STR, not bytes is first prompted in the stored procedure of learning decision tree. The error message is that the parameter of write() function must be STR, not byte. I don’t understand. Look at the source code. There is an error. There is an error in compiling the sentence pickle. Dump (inputtree, FW). Let’s first look at the usage of pickle. Dump()

From the penultimate sentence, we can see that our problem lies in the variable FW, that is, the statement FW = open (file name, ‘W’). That is to say, the type of the variable FW should be bytes, so you can change ‘W’ to ‘WB’ and compile it successfully after modification. The same principle prompts Unicode decodeerror: ‘GBK’ codec can’t decode byte 0x80 in position 0: illegal multibyte sequence error, because the previously saved TXT file is written in binary, so binary should also be used when reading, Fr = open (filename) in the read file should be changed to fr = open (filename, ‘RB’). OK, problem solved! Under the test:

success!

[Solved] SystemError: Parent module ” not loaded, cannot perform relative import

The problem that peer modules can’t be called directly has not been solved by the relative import path solution on the Internet
finally, just put the file. Py in the new folder. By the way__ init__. Py related import statement
and then run
it’s strange that I used to associate. Py with__ init__. Py is put back under the same level file of import, or run
later I found that I changed two places, the root cause is not the same level or not the same level file!

Instead, the package calling the parent module should declare the upper folder of the folder where the file is located!

The final investigation is correct! It turns out that in the final analysis:

Python Import Error: SystemError: Parent module ‘‘ not loaded, cannot perform relative import

System error: parent module “not loaded, can not perform relative import when importing Python package

When using flash for web development, the structure of the project is reset as follows:
write the picture description here
when running the project again, the system error: parent module “not loaded, cannot perform relative import will appear. Through the error location, it is found that the problem is caused by the packet guidance.

from .app import create_ app

The “parent module” is not loaded and cannot be imported. Why is there such a problem
by viewing the project structure, use

from web_ flask.app import create_ app

At this time, there are more package guiding problems
write the picture description here
first locate yourself in views.py and delete the package guiding statement

from .models import Users

Then, use the local guide
from web_ Flash. App. Models import users
User = users (1 ‘sun’)
so far, the problem has been solved
or you can add the corresponding Python path with sys.path.append
to solve the problem———————

urllib.error.HTTPError: HTTP Error 403: Forbidden [How to Solve]

problem:

 The urllib.request.urlopen() method is often used to open the source code of a webpage, and then analyze the source code of the page, but for some websites when using this method, an “HTTP Error 403: Forbidden” exception will be thrown
For example, when the following statement is executed
[python] 
<span style=”font-size:14px;”> urllib.request.urlopen(“http://blog.csdn.net/eric_sunah/article/details/11099295”)</span>  
The following exception will occur:
[python]  
<span style=”color:#FF0000;”> File “D:\Python32\lib\urllib\request.py”, line 475, in open  
    response = meth(req, response)  
  File “D:\Python32\lib\urllib\request.py”, line 587, in http_response  
    ‘http’, request, response, code, msg, hdrs)  
  File “D:\Python32\lib\urllib\request.py”, line 513, in error  
    return self._call_chain(*args)  
  File “D:\Python32\lib\urllib\request.py”, line 447, in _call_chain  
    result = func(*args)  
  File “D:\Python32\lib\urllib\request.py”, line 595, in http_error_default  
    raise HTTPError(req.full_url, code, msg, hdrs, fp)  
urllib.error.HTTPError: HTTP Error 403: Forbidden</span>  
analysis:
The reason for the above exception is that if you open a URL with urllib.request.urlopen, the server will only receive a simple request for access to the page, but the server does not know the browser used to send this request . Operating system, hardware platform and other information, and requests for missing this information are often abnormal access, such as crawlers.
In order to prevent such abnormal access, some websites will verify the UserAgent in the request information (its information includes hardware platform, system software, application software, and user personal preferences). If the UserAgent is abnormal or does not exist, then this request Will be rejected (as shown in the error message above)
So you can try to include UserAgent information in the request
Program:
For Python  3.x, it is very simple to add UserAgent information in the request, the code is as follows
[python]  
#If you do not add the following line, urllib2.HTTPError: HTTP Error 403: Forbidden error will appear  
    #It is mainly caused by the prohibition of crawlers on this website. You can add header information to the request and pretend to be a browser to access User-Agent. The specific information can be queried through the FireBug plug-in of Firefox  
    headers = {‘User-Agent’:’Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0′}  
    req = urllib.request.Request(url=chaper_url, headers=headers)  
    urllib.request.urlopen(req).read()  
After replacing urllib.request.urlopen.read() with the above code, the page with the problem can be accessed normally

Solve pytorch multiprocess valueerror: error initializing torch.distributed using env: //rendezvou… Error

error message: ValueError: Error initializing torch.distributed using env:// rendezvous: environment variable MASTER_ADDR expected, but not set
Solution 1:
Use in the code

import os

os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '5678'

Solution 2:

If you are running the command line, you can use:

export MASTER_ADDR=localhost
export MASTER_PORT=5678

[Solved] ImportError: cannot import name ‘delayed‘ from ‘sklearn.utils.fixes‘

Problem Description:

Call imbalanced today_ An error is reported when the module is enabled:
importerror: cannot import name ‘delayed’ from ‘sklearn. Utils. Fixes’

Cause analysis:

Sklearn library, not updated in time. As a result, the sklearn.utils.fixes.py file does not have a delayed module.


Solution:

Update the sklearn library with the following command

conda update scikit-learn