_id
stringlengths
5
9
text
stringlengths
5
385k
title
stringclasses
1 value
doc_27700
Scalar method identical to the corresponding array attribute. Please see ndarray.diagonal.
doc_27701
stop the music playback stop() -> None Stops the music playback if it is currently playing. It Won't Unload the music.
doc_27702
os.spawn* Information about how the subprocess module can be used to replace these modules and functions can be found in the following sections. See also PEP 324 – PEP proposing the subprocess module Using the subprocess Module The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly. The run() function was added in Python 3.5; if you need to retain compatibility with older versions, see the Older high-level API section. subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs) Run the command described by args. Wait for command to complete, then return a CompletedProcess instance. The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the Popen constructor - most of the arguments to this function are passed through to that interface. (timeout, input, check, and capture_output are not.) If capture_output is true, stdout and stderr will be captured. When used, the internal Popen object is automatically created with stdout=PIPE and stderr=PIPE. The stdout and stderr arguments may not be supplied at the same time as capture_output. If you wish to capture and combine both streams into one, use stdout=PIPE and stderr=STDOUT instead of capture_output. The timeout argument is passed to Popen.communicate(). If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated. The input argument is passed to Popen.communicate() and thus to the subprocess’s stdin. If used it must be a byte sequence, or a string if encoding or errors is specified or text is true. When used, the internal Popen object is automatically created with stdin=PIPE, and the stdin argument may not be used as well. If check is true, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured. If encoding or errors are specified, or text is true, file objects for stdin, stdout and stderr are opened in text mode using the specified encoding and errors or the io.TextIOWrapper default. The universal_newlines argument is equivalent to text and is provided for backwards compatibility. By default, file objects are opened in binary mode. If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of the default behavior of inheriting the current process’ environment. It is passed directly to Popen. Examples: >>> subprocess.run(["ls", "-l"]) # doesn't capture output CompletedProcess(args=['ls', '-l'], returncode=0) >>> subprocess.run("exit 1", shell=True, check=True) Traceback (most recent call last): ... subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1 >>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True) CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0, stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'') New in version 3.5. Changed in version 3.6: Added encoding and errors parameters Changed in version 3.7: Added the text parameter, as a more understandable alias of universal_newlines. Added the capture_output parameter. class subprocess.CompletedProcess The return value from run(), representing a process that has finished. args The arguments used to launch the process. This may be a list or a string. returncode Exit status of the child process. Typically, an exit status of 0 indicates that it ran successfully. A negative value -N indicates that the child was terminated by signal N (POSIX only). stdout Captured stdout from the child process. A bytes sequence, or a string if run() was called with an encoding, errors, or text=True. None if stdout was not captured. If you ran the process with stderr=subprocess.STDOUT, stdout and stderr will be combined in this attribute, and stderr will be None. stderr Captured stderr from the child process. A bytes sequence, or a string if run() was called with an encoding, errors, or text=True. None if stderr was not captured. check_returncode() If returncode is non-zero, raise a CalledProcessError. New in version 3.5. subprocess.DEVNULL Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that the special file os.devnull will be used. New in version 3.3. subprocess.PIPE Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that a pipe to the standard stream should be opened. Most useful with Popen.communicate(). subprocess.STDOUT Special value that can be used as the stderr argument to Popen and indicates that standard error should go into the same handle as standard output. exception subprocess.SubprocessError Base class for all other exceptions from this module. New in version 3.3. exception subprocess.TimeoutExpired Subclass of SubprocessError, raised when a timeout expires while waiting for a child process. cmd Command that was used to spawn the child process. timeout Timeout in seconds. output Output of the child process if it was captured by run() or check_output(). Otherwise, None. stdout Alias for output, for symmetry with stderr. stderr Stderr output of the child process if it was captured by run(). Otherwise, None. New in version 3.3. Changed in version 3.5: stdout and stderr attributes added exception subprocess.CalledProcessError Subclass of SubprocessError, raised when a process run by check_call() or check_output() returns a non-zero exit status. returncode Exit status of the child process. If the process exited due to a signal, this will be the negative signal number. cmd Command that was used to spawn the child process. output Output of the child process if it was captured by run() or check_output(). Otherwise, None. stdout Alias for output, for symmetry with stderr. stderr Stderr output of the child process if it was captured by run(). Otherwise, None. Changed in version 3.5: stdout and stderr attributes added Frequently Used Arguments To support a wide variety of use cases, the Popen constructor (and the convenience functions) accept a large number of optional arguments. For most typical use cases, many of these arguments can be safely left at their default values. The arguments that are most commonly needed are: args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments. stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, DEVNULL, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. DEVNULL indicates that the special file os.devnull will be used. With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout. If encoding or errors are specified, or text (also known as universal_newlines) is true, the file objects stdin, stdout and stderr will be opened in text mode using the encoding and errors specified in the call or the defaults for io.TextIOWrapper. For stdin, line ending characters '\n' in the input will be converted to the default line separator os.linesep. For stdout and stderr, all line endings in the output will be converted to '\n'. For more information see the documentation of the io.TextIOWrapper class when the newline argument to its constructor is None. If text mode is not used, stdin, stdout and stderr will be opened as binary streams. No encoding or line ending conversion is performed. New in version 3.6: Added encoding and errors parameters. New in version 3.7: Added the text parameter as an alias for universal_newlines. Note The newlines attribute of the file objects Popen.stdin, Popen.stdout and Popen.stderr are not updated by the Popen.communicate() method. If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory. However, note that Python itself offers implementations of many shell-like features (in particular, glob, fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser(), and shutil). Changed in version 3.3: When universal_newlines is True, the class uses the encoding locale.getpreferredencoding(False) instead of locale.getpreferredencoding(). See the io.TextIOWrapper class for more information on this change. Note Read the Security Considerations section before using shell=True. These options, along with all of the other options, are described in more detail in the Popen constructor documentation. Popen Constructor The underlying process creation and management in this module is handled by the Popen class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions. class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=-1, encoding=None, errors=None, text=None) Execute a child program in a new process. On POSIX, the class uses os.execvp()-like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess() function. The arguments to Popen are as follows. args should be a sequence of program arguments or else a single string or path-like object. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence. An example of passing some arguments to an external program as a sequence is: Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."]) On POSIX, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program. Note It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split() can illustrate how to determine the correct tokenization for args: >>> import shlex, subprocess >>> command_line = input() /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" >>> args = shlex.split(command_line) >>> print(args) ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] >>> p = subprocess.Popen(args) # Success! Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the echo command shown above) are single list elements. On Windows, if args is a sequence, it will be converted to a string in a manner described in Converting an argument sequence to a string on Windows. This is because the underlying CreateProcess() operates on strings. Changed in version 3.6: args parameter accepts a path-like object if shell is False and a sequence containing path-like objects on POSIX. Changed in version 3.8: args parameter accepts a path-like object if shell is False and a sequence containing bytes and path-like objects on Windows. The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence. On POSIX with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say, Popen does the equivalent of: Popen(['/bin/sh', '-c', args[0], args[1], ...]) On Windows with shell=True, the COMSPEC environment variable specifies the default shell. The only time you need to specify shell=True on Windows is when the command you wish to execute is built into the shell (e.g. dir or copy). You do not need shell=True to run a batch file or console-based executable. Note Read the Security Considerations section before using shell=True. bufsize will be supplied as the corresponding argument to the open() function when creating the stdin/stdout/stderr pipe file objects: 0 means unbuffered (read and write are one system call and can return short) 1 means line buffered (only usable if universal_newlines=True i.e., in a text mode) any other positive value means use a buffer of approximately that size negative bufsize (the default) means the system default of io.DEFAULT_BUFFER_SIZE will be used. Changed in version 3.3.1: bufsize now defaults to -1 to enable buffering by default to match the behavior that most code expects. In versions prior to Python 3.2.4 and 3.3.1 it incorrectly defaulted to 0 which was unbuffered and allowed short reads. This was unintentional and did not match the behavior of Python 2 as most code expected. The executable argument specifies a replacement program to execute. It is very seldom needed. When shell=False, executable replaces the program to execute specified by args. However, the original args is still passed to the program. Most programs treat the program specified by args as the command name, which can then be different from the program actually executed. On POSIX, the args name becomes the display name for the executable in utilities such as ps. If shell=True, on POSIX the executable argument specifies a replacement shell for the default /bin/sh. Changed in version 3.6: executable parameter accepts a path-like object on POSIX. Changed in version 3.8: executable parameter accepts a bytes and path-like object on Windows. stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, DEVNULL, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. DEVNULL indicates that the special file os.devnull will be used. With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout. If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed. (POSIX only) Warning The preexec_fn parameter is not safe to use in the presence of threads in your application. The child process could deadlock before exec is called. If you must use it, keep it trivial! Minimize the number of libraries you call into. Note If you need to modify the environment for the child use the env parameter rather than doing it in a preexec_fn. The start_new_session parameter can take the place of a previously common use of preexec_fn to call os.setsid() in the child. Changed in version 3.8: The preexec_fn parameter is no longer supported in subinterpreters. The use of the parameter in a subinterpreter raises RuntimeError. The new restriction may affect applications that are deployed in mod_wsgi, uWSGI, and other embedded environments. If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. Otherwise when close_fds is false, file descriptors obey their inheritable flag as described in Inheritance of File Descriptors. On Windows, if close_fds is true then no handles will be inherited by the child process unless explicitly passed in the handle_list element of STARTUPINFO.lpAttributeList, or by standard handle redirection. Changed in version 3.2: The default for close_fds was changed from False to what is described above. Changed in version 3.7: On Windows the default for close_fds was changed from False to True when redirecting the standard handles. It’s now possible to set close_fds to True when redirecting the standard handles. pass_fds is an optional sequence of file descriptors to keep open between the parent and child. Providing any pass_fds forces close_fds to be True. (POSIX only) Changed in version 3.2: The pass_fds parameter was added. If cwd is not None, the function changes the working directory to cwd before executing the child. cwd can be a string, bytes or path-like object. In particular, the function looks for executable (or for the first item in args) relative to cwd if the executable path is a relative path. Changed in version 3.6: cwd parameter accepts a path-like object on POSIX. Changed in version 3.7: cwd parameter accepts a path-like object on Windows. Changed in version 3.8: cwd parameter accepts a bytes object on Windows. If restore_signals is true (the default) all signals that Python has set to SIG_IGN are restored to SIG_DFL in the child process before the exec. Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals. (POSIX only) Changed in version 3.2: restore_signals was added. If start_new_session is true the setsid() system call will be made in the child process prior to the execution of the subprocess. (POSIX only) Changed in version 3.2: start_new_session was added. If group is not None, the setregid() system call will be made in the child process prior to the execution of the subprocess. If the provided value is a string, it will be looked up via grp.getgrnam() and the value in gr_gid will be used. If the value is an integer, it will be passed verbatim. (POSIX only) Availability: POSIX New in version 3.9. If extra_groups is not None, the setgroups() system call will be made in the child process prior to the execution of the subprocess. Strings provided in extra_groups will be looked up via grp.getgrnam() and the values in gr_gid will be used. Integer values will be passed verbatim. (POSIX only) Availability: POSIX New in version 3.9. If user is not None, the setreuid() system call will be made in the child process prior to the execution of the subprocess. If the provided value is a string, it will be looked up via pwd.getpwnam() and the value in pw_uid will be used. If the value is an integer, it will be passed verbatim. (POSIX only) Availability: POSIX New in version 3.9. If umask is not negative, the umask() system call will be made in the child process prior to the execution of the subprocess. Availability: POSIX New in version 3.9. If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of the default behavior of inheriting the current process’ environment. Note If specified, env must provide any variables required for the program to execute. On Windows, in order to run a side-by-side assembly the specified env must include a valid SystemRoot. If encoding or errors are specified, or text is true, the file objects stdin, stdout and stderr are opened in text mode with the specified encoding and errors, as described above in Frequently Used Arguments. The universal_newlines argument is equivalent to text and is provided for backwards compatibility. By default, file objects are opened in binary mode. New in version 3.6: encoding and errors were added. New in version 3.7: text was added as a more readable alias for universal_newlines. If given, startupinfo will be a STARTUPINFO object, which is passed to the underlying CreateProcess function. creationflags, if given, can be one or more of the following flags: CREATE_NEW_CONSOLE CREATE_NEW_PROCESS_GROUP ABOVE_NORMAL_PRIORITY_CLASS BELOW_NORMAL_PRIORITY_CLASS HIGH_PRIORITY_CLASS IDLE_PRIORITY_CLASS NORMAL_PRIORITY_CLASS REALTIME_PRIORITY_CLASS CREATE_NO_WINDOW DETACHED_PROCESS CREATE_DEFAULT_ERROR_MODE CREATE_BREAKAWAY_FROM_JOB Popen objects are supported as context managers via the with statement: on exit, standard file descriptors are closed, and the process is waited for. with Popen(["ifconfig"], stdout=PIPE) as proc: log.write(proc.stdout.read()) Popen and the other functions in this module that use it raise an auditing event subprocess.Popen with arguments executable, args, cwd, and env. The value for args may be a single string or a list of strings, depending on platform. Changed in version 3.2: Added context manager support. Changed in version 3.6: Popen destructor now emits a ResourceWarning warning if the child process is still running. Changed in version 3.8: Popen can use os.posix_spawn() in some cases for better performance. On Windows Subsystem for Linux and QEMU User Emulation, Popen constructor using os.posix_spawn() no longer raise an exception on errors like missing program, but the child process fails with a non-zero returncode. Exceptions Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. The most common exception raised is OSError. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSError exceptions. A ValueError will be raised if Popen is called with invalid arguments. check_call() and check_output() will raise CalledProcessError if the called process returns a non-zero return code. All of the functions and methods that accept a timeout parameter, such as call() and Popen.communicate() will raise TimeoutExpired if the timeout expires before the process exits. Exceptions defined in this module all inherit from SubprocessError. New in version 3.3: The SubprocessError base class was added. Security Considerations Unlike some other popen functions, this implementation will never implicitly call a system shell. This means that all characters, including shell metacharacters, can safely be passed to child processes. If the shell is invoked explicitly, via shell=True, it is the application’s responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid shell injection vulnerabilities. When using shell=True, the shlex.quote() function can be used to properly escape whitespace and shell metacharacters in strings that are going to be used to construct shell commands. Popen Objects Instances of the Popen class have the following methods: Popen.poll() Check if child process has terminated. Set and return returncode attribute. Otherwise, returns None. Popen.wait(timeout=None) Wait for child process to terminate. Set and return returncode attribute. If the process does not terminate after timeout seconds, raise a TimeoutExpired exception. It is safe to catch this exception and retry the wait. Note This will deadlock when using stdout=PIPE or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use Popen.communicate() when using pipes to avoid that. Note The function is implemented using a busy loop (non-blocking call and short sleeps). Use the asyncio module for an asynchronous wait: see asyncio.create_subprocess_exec. Changed in version 3.3: timeout was added. Popen.communicate(input=None, timeout=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate and set the returncode attribute. The optional input argument should be data to be sent to the child process, or None, if no data should be sent to the child. If streams were opened in text mode, input must be a string. Otherwise, it must be bytes. communicate() returns a tuple (stdout_data, stderr_data). The data will be strings if streams were opened in text mode; otherwise, bytes. Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too. If the process does not terminate after timeout seconds, a TimeoutExpired exception will be raised. Catching this exception and retrying communication will not lose any output. The child process is not killed if the timeout expires, so in order to cleanup properly a well-behaved application should kill the child process and finish communication: proc = subprocess.Popen(...) try: outs, errs = proc.communicate(timeout=15) except TimeoutExpired: proc.kill() outs, errs = proc.communicate() Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited. Changed in version 3.3: timeout was added. Popen.send_signal(signal) Sends the signal signal to the child. Do nothing if the process completed. Note On Windows, SIGTERM is an alias for terminate(). CTRL_C_EVENT and CTRL_BREAK_EVENT can be sent to processes started with a creationflags parameter which includes CREATE_NEW_PROCESS_GROUP. Popen.terminate() Stop the child. On POSIX OSs the method sends SIGTERM to the child. On Windows the Win32 API function TerminateProcess() is called to stop the child. Popen.kill() Kills the child. On POSIX OSs the function sends SIGKILL to the child. On Windows kill() is an alias for terminate(). The following attributes are also available: Popen.args The args argument as it was passed to Popen – a sequence of program arguments or else a single string. New in version 3.3. Popen.stdin If the stdin argument was PIPE, this attribute is a writeable stream object as returned by open(). If the encoding or errors arguments were specified or the universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stdin argument was not PIPE, this attribute is None. Popen.stdout If the stdout argument was PIPE, this attribute is a readable stream object as returned by open(). Reading from the stream provides output from the child process. If the encoding or errors arguments were specified or the universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stdout argument was not PIPE, this attribute is None. Popen.stderr If the stderr argument was PIPE, this attribute is a readable stream object as returned by open(). Reading from the stream provides error output from the child process. If the encoding or errors arguments were specified or the universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stderr argument was not PIPE, this attribute is None. Warning Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process. Popen.pid The process ID of the child process. Note that if you set the shell argument to True, this is the process ID of the spawned shell. Popen.returncode The child return code, set by poll() and wait() (and indirectly by communicate()). A None value indicates that the process hasn’t terminated yet. A negative value -N indicates that the child was terminated by signal N (POSIX only). Windows Popen Helpers The STARTUPINFO class and following constants are only available on Windows. class subprocess.STARTUPINFO(*, dwFlags=0, hStdInput=None, hStdOutput=None, hStdError=None, wShowWindow=0, lpAttributeList=None) Partial support of the Windows STARTUPINFO structure is used for Popen creation. The following attributes can be set by passing them as keyword-only arguments. Changed in version 3.7: Keyword-only argument support was added. dwFlags A bit field that determines whether certain STARTUPINFO attributes are used when the process creates a window. si = subprocess.STARTUPINFO() si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW hStdInput If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard input handle for the process. If STARTF_USESTDHANDLES is not specified, the default for standard input is the keyboard buffer. hStdOutput If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard output handle for the process. Otherwise, this attribute is ignored and the default for standard output is the console window’s buffer. hStdError If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard error handle for the process. Otherwise, this attribute is ignored and the default for standard error is the console window’s buffer. wShowWindow If dwFlags specifies STARTF_USESHOWWINDOW, this attribute can be any of the values that can be specified in the nCmdShow parameter for the ShowWindow function, except for SW_SHOWDEFAULT. Otherwise, this attribute is ignored. SW_HIDE is provided for this attribute. It is used when Popen is called with shell=True. lpAttributeList A dictionary of additional attributes for process creation as given in STARTUPINFOEX, see UpdateProcThreadAttribute. Supported attributes: handle_list Sequence of handles that will be inherited. close_fds must be true if non-empty. The handles must be temporarily made inheritable by os.set_handle_inheritable() when passed to the Popen constructor, else OSError will be raised with Windows error ERROR_INVALID_PARAMETER (87). Warning In a multithreaded process, use caution to avoid leaking handles that are marked inheritable when combining this feature with concurrent calls to other process creation functions that inherit all handles such as os.system(). This also applies to standard handle redirection, which temporarily creates inheritable handles. New in version 3.7. Windows Constants The subprocess module exposes the following constants. subprocess.STD_INPUT_HANDLE The standard input device. Initially, this is the console input buffer, CONIN$. subprocess.STD_OUTPUT_HANDLE The standard output device. Initially, this is the active console screen buffer, CONOUT$. subprocess.STD_ERROR_HANDLE The standard error device. Initially, this is the active console screen buffer, CONOUT$. subprocess.SW_HIDE Hides the window. Another window will be activated. subprocess.STARTF_USESTDHANDLES Specifies that the STARTUPINFO.hStdInput, STARTUPINFO.hStdOutput, and STARTUPINFO.hStdError attributes contain additional information. subprocess.STARTF_USESHOWWINDOW Specifies that the STARTUPINFO.wShowWindow attribute contains additional information. subprocess.CREATE_NEW_CONSOLE The new process has a new console, instead of inheriting its parent’s console (the default). subprocess.CREATE_NEW_PROCESS_GROUP A Popen creationflags parameter to specify that a new process group will be created. This flag is necessary for using os.kill() on the subprocess. This flag is ignored if CREATE_NEW_CONSOLE is specified. subprocess.ABOVE_NORMAL_PRIORITY_CLASS A Popen creationflags parameter to specify that a new process will have an above average priority. New in version 3.7. subprocess.BELOW_NORMAL_PRIORITY_CLASS A Popen creationflags parameter to specify that a new process will have a below average priority. New in version 3.7. subprocess.HIGH_PRIORITY_CLASS A Popen creationflags parameter to specify that a new process will have a high priority. New in version 3.7. subprocess.IDLE_PRIORITY_CLASS A Popen creationflags parameter to specify that a new process will have an idle (lowest) priority. New in version 3.7. subprocess.NORMAL_PRIORITY_CLASS A Popen creationflags parameter to specify that a new process will have an normal priority. (default) New in version 3.7. subprocess.REALTIME_PRIORITY_CLASS A Popen creationflags parameter to specify that a new process will have realtime priority. You should almost never use REALTIME_PRIORITY_CLASS, because this interrupts system threads that manage mouse input, keyboard input, and background disk flushing. This class can be appropriate for applications that “talk” directly to hardware or that perform brief tasks that should have limited interruptions. New in version 3.7. subprocess.CREATE_NO_WINDOW A Popen creationflags parameter to specify that a new process will not create a window. New in version 3.7. subprocess.DETACHED_PROCESS A Popen creationflags parameter to specify that a new process will not inherit its parent’s console. This value cannot be used with CREATE_NEW_CONSOLE. New in version 3.7. subprocess.CREATE_DEFAULT_ERROR_MODE A Popen creationflags parameter to specify that a new process does not inherit the error mode of the calling process. Instead, the new process gets the default error mode. This feature is particularly useful for multithreaded shell applications that run with hard errors disabled. New in version 3.7. subprocess.CREATE_BREAKAWAY_FROM_JOB A Popen creationflags parameter to specify that a new process is not associated with the job. New in version 3.7. Older high-level API Prior to Python 3.5, these three functions comprised the high level API to subprocess. You can now use run() in many cases, but lots of existing code calls these functions. subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs) Run the command described by args. Wait for command to complete, then return the returncode attribute. Code needing to capture stdout or stderr should use run() instead: run(...).returncode To suppress stdout or stderr, supply a value of DEVNULL. The arguments shown above are merely some common ones. The full function signature is the same as that of the Popen constructor - this function passes all supplied arguments other than timeout directly through to that interface. Note Do not use stdout=PIPE or stderr=PIPE with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from. Changed in version 3.3: timeout was added. subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs) Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. Code needing to capture stdout or stderr should use run() instead: run(..., check=True) To suppress stdout or stderr, supply a value of DEVNULL. The arguments shown above are merely some common ones. The full function signature is the same as that of the Popen constructor - this function passes all supplied arguments other than timeout directly through to that interface. Note Do not use stdout=PIPE or stderr=PIPE with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from. Changed in version 3.3: timeout was added. subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs) Run command with arguments and return its output. If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute. This is equivalent to: run(..., check=True, stdout=PIPE).stdout The arguments shown above are merely some common ones. The full function signature is largely the same as that of run() - most arguments are passed directly through to that interface. One API deviation from run() behavior exists: passing input=None will behave the same as input=b'' (or input='', depending on other arguments) rather than using the parent’s standard input file handle. By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level. This behaviour may be overridden by setting text, encoding, errors, or universal_newlines to True as described in Frequently Used Arguments and run(). To also capture standard error in the result, use stderr=subprocess.STDOUT: >>> subprocess.check_output( ... "ls non_existent_file; exit 0", ... stderr=subprocess.STDOUT, ... shell=True) 'ls: non_existent_file: No such file or directory\n' New in version 3.1. Changed in version 3.3: timeout was added. Changed in version 3.4: Support for the input keyword argument was added. Changed in version 3.6: encoding and errors were added. See run() for details. New in version 3.7: text was added as a more readable alias for universal_newlines. Replacing Older Functions with the subprocess Module In this section, “a becomes b” means that b can be used as a replacement for a. Note All “a” functions in this section fail (more or less) silently if the executed program cannot be found; the “b” replacements raise OSError instead. In addition, the replacements using check_output() will fail with a CalledProcessError if the requested operation produces a non-zero return code. The output is still available as the output attribute of the raised exception. In the following examples, we assume that the relevant functions have already been imported from the subprocess module. Replacing /bin/sh shell command substitution output=$(mycmd myarg) becomes: output = check_output(["mycmd", "myarg"]) Replacing shell pipeline output=$(dmesg | grep hda) becomes: p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0] The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1. Alternatively, for trusted input, the shell’s own pipeline support may still be used directly: output=$(dmesg | grep hda) becomes: output=check_output("dmesg | grep hda", shell=True) Replacing os.system() sts = os.system("mycmd" + " myarg") # becomes sts = call("mycmd" + " myarg", shell=True) Notes: Calling the program through the shell is usually not required. A more realistic example would look like this: try: retcode = call("mycmd" + " myarg", shell=True) if retcode < 0: print("Child was terminated by signal", -retcode, file=sys.stderr) else: print("Child returned", retcode, file=sys.stderr) except OSError as e: print("Execution failed:", e, file=sys.stderr) Replacing the os.spawn family P_NOWAIT example: pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") ==> pid = Popen(["/bin/mycmd", "myarg"]).pid P_WAIT example: retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") ==> retcode = call(["/bin/mycmd", "myarg"]) Vector example: os.spawnvp(os.P_NOWAIT, path, args) ==> Popen([path] + args[1:]) Environment example: os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) ==> Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) Replacing os.popen(), os.popen2(), os.popen3() (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdin, child_stdout) = (p.stdin, p.stdout) (child_stdin, child_stdout, child_stderr) = os.popen3(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) (child_stdin, child_stdout, child_stderr) = (p.stdin, p.stdout, p.stderr) (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) Return code handling translates as follows: pipe = os.popen(cmd, 'w') ... rc = pipe.close() if rc is not None and rc >> 8: print("There were some errors") ==> process = Popen(cmd, stdin=PIPE) ... process.stdin.close() if process.wait() != 0: print("There were some errors") Replacing functions from the popen2 module Note If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. If it is a list, the command is directly executed. (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) ==> p = Popen("somestring", shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) ==> p = Popen(["mycmd", "myarg"], bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) popen2.Popen3 and popen2.Popen4 basically work as subprocess.Popen, except that: Popen raises an exception if the execution fails. The capturestderr argument is replaced with the stderr argument. stdin=PIPE and stdout=PIPE must be specified. popen2 closes all file descriptors by default, but you have to specify close_fds=True with Popen to guarantee this behavior on all platforms or past Python versions. Legacy Shell Invocation Functions This module also provides the following legacy functions from the 2.x commands module. These operations implicitly invoke the system shell and none of the guarantees described above regarding security and exception handling consistency are valid for these functions. subprocess.getstatusoutput(cmd) Return (exitcode, output) of executing cmd in a shell. Execute the string cmd in a shell with Popen.check_output() and return a 2-tuple (exitcode, output). The locale encoding is used; see the notes on Frequently Used Arguments for more details. A trailing newline is stripped from the output. The exit code for the command can be interpreted as the return code of subprocess. Example: >>> subprocess.getstatusoutput('ls /bin/ls') (0, '/bin/ls') >>> subprocess.getstatusoutput('cat /bin/junk') (1, 'cat: /bin/junk: No such file or directory') >>> subprocess.getstatusoutput('/bin/junk') (127, 'sh: /bin/junk: not found') >>> subprocess.getstatusoutput('/bin/kill $$') (-15, '') Availability: POSIX & Windows. Changed in version 3.3.4: Windows support was added. The function now returns (exitcode, output) instead of (status, output) as it did in Python 3.3.3 and earlier. exitcode has the same value as returncode. subprocess.getoutput(cmd) Return output (stdout and stderr) of executing cmd in a shell. Like getstatusoutput(), except the exit code is ignored and the return value is a string containing the command’s output. Example: >>> subprocess.getoutput('ls /bin/ls') '/bin/ls' Availability: POSIX & Windows. Changed in version 3.3.4: Windows support added Notes Converting an argument sequence to a string on Windows On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime): Arguments are delimited by white space, which is either a space or a tab. A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark. Backslashes are interpreted literally, unless they immediately precede a double quotation mark. If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3. See also shlex Module which provides function to parse and escape command lines.
doc_27703
This specifies the HTTP protocol version used in responses. If set to 'HTTP/1.1', the server will permit HTTP persistent connections; however, your server must then include an accurate Content-Length header (using send_header()) in all of its responses to clients. For backwards compatibility, the setting defaults to 'HTTP/1.0'.
doc_27704
Turn off the standout attribute. On some terminals this has the side effect of turning off all attributes.
doc_27705
See Migration guide for more details. tf.compat.v1.math.special.bessel_k0 tf.math.special.bessel_k0( x, name=None ) Modified Bessel function of order 0. It is preferable to use the numerically stabler function k0e(x) instead. tf.math.special.bessel_k0([0.5, 1., 2., 4.]).numpy() array([0.92441907, 0.42102444, 0.11389387, 0.01115968], dtype=float32) Args x A Tensor or SparseTensor. Must be one of the following types: half, float32, float64. name A name for the operation (optional). Returns A Tensor or SparseTensor, respectively. Has the same type as x. Scipy Compatibility Equivalent to scipy.special.k0
doc_27706
See Migration guide for more details. tf.compat.v1.raw_ops.MaxPoolGradWithArgmax tf.raw_ops.MaxPoolGradWithArgmax( input, grad, argmax, ksize, strides, padding, include_batch_in_index=False, name=None ) Args input A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64. The original input. grad A Tensor. Must have the same type as input. 4-D with shape [batch, height, width, channels]. Gradients w.r.t. the output of max_pool. argmax A Tensor. Must be one of the following types: int32, int64. The indices of the maximum values chosen for each output of max_pool. ksize A list of ints that has length >= 4. The size of the window for each dimension of the input tensor. strides A list of ints that has length >= 4. The stride of the sliding window for each dimension of the input tensor. padding A string from: "SAME", "VALID". The type of padding algorithm to use. include_batch_in_index An optional bool. Defaults to False. Whether to include batch dimension in flattened index of argmax. name A name for the operation (optional). Returns A Tensor. Has the same type as input.
doc_27707
Search for files *.py and add the corresponding file to the archive. If the optimize parameter to PyZipFile was not given or -1, the corresponding file is a *.pyc file, compiling if necessary. If the optimize parameter to PyZipFile was 0, 1 or 2, only files with that optimization level (see compile()) are added to the archive, compiling if necessary. If pathname is a file, the filename must end with .py, and just the (corresponding *.pyc) file is added at the top level (no path information). If pathname is a file that does not end with .py, a RuntimeError will be raised. If it is a directory, and the directory is not a package directory, then all the files *.pyc are added at the top level. If the directory is a package directory, then all *.pyc are added under the package name as a file path, and if any subdirectories are package directories, all of these are added recursively in sorted order. basename is intended for internal use only. filterfunc, if given, must be a function taking a single string argument. It will be passed each path (including each individual full file path) before it is added to the archive. If filterfunc returns a false value, the path will not be added, and if it is a directory its contents will be ignored. For example, if our test files are all either in test directories or start with the string test_, we can use a filterfunc to exclude them: >>> zf = PyZipFile('myprog.zip') >>> def notests(s): ... fn = os.path.basename(s) ... return (not (fn == 'test' or fn.startswith('test_'))) >>> zf.writepy('myprog', filterfunc=notests) The writepy() method makes archives with file names like this: string.pyc # Top level name test/__init__.pyc # Package directory test/testall.pyc # Module test.testall test/bogus/__init__.pyc # Subpackage directory test/bogus/myfile.pyc # Submodule test.bogus.myfile New in version 3.4: The filterfunc parameter. Changed in version 3.6.2: The pathname parameter accepts a path-like object. Changed in version 3.7: Recursion sorts directory entries.
doc_27708
Standardize features by removing the mean and scaling to unit variance The standard score of a sample x is calculated as: z = (x - u) / s where u is the mean of the training samples or zero if with_mean=False, and s is the standard deviation of the training samples or one if with_std=False. Centering and scaling happen independently on each feature by computing the relevant statistics on the samples in the training set. Mean and standard deviation are then stored to be used on later data using transform. Standardization of a dataset is a common requirement for many machine learning estimators: they might behave badly if the individual features do not more or less look like standard normally distributed data (e.g. Gaussian with 0 mean and unit variance). For instance many elements used in the objective function of a learning algorithm (such as the RBF kernel of Support Vector Machines or the L1 and L2 regularizers of linear models) assume that all features are centered around 0 and have variance in the same order. If a feature has a variance that is orders of magnitude larger that others, it might dominate the objective function and make the estimator unable to learn from other features correctly as expected. This scaler can also be applied to sparse CSR or CSC matrices by passing with_mean=False to avoid breaking the sparsity structure of the data. Read more in the User Guide. Parameters copybool, default=True If False, try to avoid a copy and do inplace scaling instead. This is not guaranteed to always work inplace; e.g. if the data is not a NumPy array or scipy.sparse CSR matrix, a copy may still be returned. with_meanbool, default=True If True, center the data before scaling. This does not work (and will raise an exception) when attempted on sparse matrices, because centering them entails building a dense matrix which in common use cases is likely to be too large to fit in memory. with_stdbool, default=True If True, scale the data to unit variance (or equivalently, unit standard deviation). Attributes scale_ndarray of shape (n_features,) or None Per feature relative scaling of the data to achieve zero mean and unit variance. Generally this is calculated using np.sqrt(var_). If a variance is zero, we can’t achieve unit variance, and the data is left as-is, giving a scaling factor of 1. scale_ is equal to None when with_std=False. New in version 0.17: scale_ mean_ndarray of shape (n_features,) or None The mean value for each feature in the training set. Equal to None when with_mean=False. var_ndarray of shape (n_features,) or None The variance for each feature in the training set. Used to compute scale_. Equal to None when with_std=False. n_samples_seen_int or ndarray of shape (n_features,) The number of samples processed by the estimator for each feature. If there are no missing samples, the n_samples_seen will be an integer, otherwise it will be an array of dtype int. If sample_weights are used it will be a float (if no missing data) or an array of dtype float that sums the weights seen so far. Will be reset on new calls to fit, but increments across partial_fit calls. See also scale Equivalent function without the estimator API. PCA Further removes the linear correlation across features with ‘whiten=True’. Notes NaNs are treated as missing values: disregarded in fit, and maintained in transform. We use a biased estimator for the standard deviation, equivalent to numpy.std(x, ddof=0). Note that the choice of ddof is unlikely to affect model performance. For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py. Examples >>> from sklearn.preprocessing import StandardScaler >>> data = [[0, 0], [0, 0], [1, 1], [1, 1]] >>> scaler = StandardScaler() >>> print(scaler.fit(data)) StandardScaler() >>> print(scaler.mean_) [0.5 0.5] >>> print(scaler.transform(data)) [[-1. -1.] [-1. -1.] [ 1. 1.] [ 1. 1.]] >>> print(scaler.transform([[2, 2]])) [[3. 3.]] Methods fit(X[, y, sample_weight]) Compute the mean and std to be used for later scaling. fit_transform(X[, y]) Fit to data, then transform it. get_params([deep]) Get parameters for this estimator. inverse_transform(X[, copy]) Scale back the data to the original representation partial_fit(X[, y, sample_weight]) Online computation of mean and std on X for later scaling. set_params(**params) Set the parameters of this estimator. transform(X[, copy]) Perform standardization by centering and scaling fit(X, y=None, sample_weight=None) [source] Compute the mean and std to be used for later scaling. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The data used to compute the mean and standard deviation used for later scaling along the features axis. yNone Ignored. sample_weightarray-like of shape (n_samples,), default=None Individual weights for each sample. New in version 0.24: parameter sample_weight support to StandardScaler. Returns selfobject Fitted scaler. fit_transform(X, y=None, **fit_params) [source] Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters Xarray-like of shape (n_samples, n_features) Input samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None Target values (None for unsupervised transformations). **fit_paramsdict Additional fit parameters. Returns X_newndarray array of shape (n_samples, n_features_new) Transformed array. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. inverse_transform(X, copy=None) [source] Scale back the data to the original representation Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The data used to scale along the features axis. copybool, default=None Copy the input X or not. Returns X_tr{ndarray, sparse matrix} of shape (n_samples, n_features) Transformed array. partial_fit(X, y=None, sample_weight=None) [source] Online computation of mean and std on X for later scaling. All of X is processed as a single batch. This is intended for cases when fit is not feasible due to very large number of n_samples or because X is read from a continuous stream. The algorithm for incremental mean and std is given in Equation 1.5a,b in Chan, Tony F., Gene H. Golub, and Randall J. LeVeque. “Algorithms for computing the sample variance: Analysis and recommendations.” The American Statistician 37.3 (1983): 242-247: Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The data used to compute the mean and standard deviation used for later scaling along the features axis. yNone Ignored. sample_weightarray-like of shape (n_samples,), default=None Individual weights for each sample. New in version 0.24: parameter sample_weight support to StandardScaler. Returns selfobject Fitted scaler. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance. transform(X, copy=None) [source] Perform standardization by centering and scaling Parameters X{array-like, sparse matrix of shape (n_samples, n_features) The data used to scale along the features axis. copybool, default=None Copy the input X or not. Returns X_tr{ndarray, sparse matrix} of shape (n_samples, n_features) Transformed array.
doc_27709
sklearn.metrics.mean_absolute_error(y_true, y_pred, *, sample_weight=None, multioutput='uniform_average') [source] Mean absolute error regression loss. Read more in the User Guide. Parameters y_truearray-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_predarray-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weightarray-like of shape (n_samples,), default=None Sample weights. multioutput{‘raw_values’, ‘uniform_average’} or array-like of shape (n_outputs,), default=’uniform_average’ Defines aggregating of multiple output values. Array-like value defines weights used to average errors. ‘raw_values’ : Returns a full set of errors in case of multioutput input. ‘uniform_average’ : Errors of all outputs are averaged with uniform weight. Returns lossfloat or ndarray of floats If multioutput is ‘raw_values’, then mean absolute error is returned for each output separately. If multioutput is ‘uniform_average’ or an ndarray of weights, then the weighted average of all output errors is returned. MAE output is non-negative floating point. The best value is 0.0. Examples >>> from sklearn.metrics import mean_absolute_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> mean_absolute_error(y_true, y_pred) 0.5 >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> mean_absolute_error(y_true, y_pred) 0.75 >>> mean_absolute_error(y_true, y_pred, multioutput='raw_values') array([0.5, 1. ]) >>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.85... Examples using sklearn.metrics.mean_absolute_error Poisson regression and non-normal loss Tweedie regression on insurance claims
doc_27710
Load dataset from multiple files in SVMlight format This function is equivalent to mapping load_svmlight_file over a list of files, except that the results are concatenated into a single, flat list and the samples vectors are constrained to all have the same number of features. In case the file contains a pairwise preference constraint (known as “qid” in the svmlight format) these are ignored unless the query_id parameter is set to True. These pairwise preference constraints can be used to constraint the combination of samples when using pairwise loss functions (as is the case in some learning to rank problems) so that only pairs with the same query_id value are considered. Parameters filesarray-like, dtype=str, file-like or int (Paths of) files to load. If a path ends in “.gz” or “.bz2”, it will be uncompressed on the fly. If an integer is passed, it is assumed to be a file descriptor. File-likes and file descriptors will not be closed by this function. File-like objects must be opened in binary mode. n_featuresint, default=None The number of features to use. If None, it will be inferred from the maximum column index occurring in any of the files. This can be set to a higher value than the actual number of features in any of the input files, but setting it to a lower value will cause an exception to be raised. dtypenumpy data type, default=np.float64 Data type of dataset to be loaded. This will be the data type of the output numpy arrays X and y. multilabelbool, default=False Samples may have several labels each (see https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multilabel.html) zero_basedbool or “auto”, default=”auto” Whether column indices in f are zero-based (True) or one-based (False). If column indices are one-based, they are transformed to zero-based to match Python/NumPy conventions. If set to “auto”, a heuristic check is applied to determine this from the file contents. Both kinds of files occur “in the wild”, but they are unfortunately not self-identifying. Using “auto” or True should always be safe when no offset or length is passed. If offset or length are passed, the “auto” mode falls back to zero_based=True to avoid having the heuristic check yield inconsistent results on different segments of the file. query_idbool, default=False If True, will return the query_id array for each file. offsetint, default=0 Ignore the offset first bytes by seeking forward, then discarding the following bytes up until the next new line character. lengthint, default=-1 If strictly positive, stop reading any new line of data once the position in the file has reached the (offset + length) bytes threshold. Returns [X1, y1, …, Xn, yn] where each (Xi, yi) pair is the result from load_svmlight_file(files[i]). If query_id is set to True, this will return instead [X1, y1, q1, …, Xn, yn, qn] where (Xi, yi, qi) is the result from load_svmlight_file(files[i]) See also load_svmlight_file Notes When fitting a model to a matrix X_train and evaluating it against a matrix X_test, it is essential that X_train and X_test have the same number of features (X_train.shape[1] == X_test.shape[1]). This may not be the case if you load the files individually with load_svmlight_file.
doc_27711
Send a SLAVE command. Return the server’s response.
doc_27712
Set the height of the box. Parameters heightfloat
doc_27713
""" May be applied as a `default=...` value on a serializer field. Returns the current user. """ requires_context = True def __call__(self, serializer_field): return serializer_field.context['request'].user When serializing the instance, default will be used if the object attribute or dictionary key is not present in the instance. Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error. allow_null Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value. Note that, without an explicit default, setting this argument to True will imply a default value of null for serialization output, but does not imply a default for input deserialization. Defaults to False source The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url'), or may use dotted notation to traverse attributes, such as EmailField(source='user.email'). When serializing fields with dotted notation, it may be necessary to provide a default value if any object is not present or is empty during attribute traversal. The value source='*' has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. Defaults to the name of the field. validators A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise serializers.ValidationError, but Django's built-in ValidationError is also supported for compatibility with validators defined in the Django codebase or third party Django packages. error_messages A dictionary of error codes to error messages. label A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. help_text A text string that may be used as a description of the field in HTML form fields or other descriptive elements. initial A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as you may do with any regular Django Field: import datetime from rest_framework import serializers class ExampleSerializer(serializers.Serializer): day = serializers.DateField(initial=datetime.date.today) style A dictionary of key-value pairs that can be used to control how renderers should render the field. Two examples here are 'input_type' and 'base_template': # Use <input type="password"> for the input. password = serializers.CharField( style={'input_type': 'password'} ) # Use a radio input instead of a select input. color_channel = serializers.ChoiceField( choices=['red', 'green', 'blue'], style={'base_template': 'radio.html'} ) For more details see the HTML & Forms documentation. Boolean fields BooleanField A boolean representation. When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to False, even if it has a default=True option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input. Note that Django 2.1 removed the blank kwarg from models.BooleanField. Prior to Django 2.1 models.BooleanField fields were always blank=True. Thus since Django 2.1 default serializers.BooleanField instances will be generated without the required kwarg (i.e. equivalent to required=True) whereas with previous versions of Django, default BooleanField instances will be generated with a required=False option. If you want to control this behaviour manually, explicitly declare the BooleanField on the serializer class, or use the extra_kwargs option to set the required flag. Corresponds to django.db.models.fields.BooleanField. Signature: BooleanField() NullBooleanField A boolean representation that also accepts None as a valid value. Corresponds to django.db.models.fields.NullBooleanField. Signature: NullBooleanField() String fields CharField A text representation. Optionally validates the text to be shorter than max_length and longer than min_length. Corresponds to django.db.models.fields.CharField or django.db.models.fields.TextField. Signature: CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True) max_length - Validates that the input contains no more than this number of characters. min_length - Validates that the input contains no fewer than this number of characters. allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False. trim_whitespace - If set to True then leading and trailing whitespace is trimmed. Defaults to True. The allow_null option is also available for string fields, although its usage is discouraged in favor of allow_blank. It is valid to set both allow_blank=True and allow_null=True, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs. EmailField A text representation, validates the text to be a valid e-mail address. Corresponds to django.db.models.fields.EmailField Signature: EmailField(max_length=None, min_length=None, allow_blank=False) RegexField A text representation, that validates the given value matches against a certain regular expression. Corresponds to django.forms.fields.RegexField. Signature: RegexField(regex, max_length=None, min_length=None, allow_blank=False) The mandatory regex argument may either be a string, or a compiled python regular expression object. Uses Django's django.core.validators.RegexValidator for validation. SlugField A RegexField that validates the input against the pattern [a-zA-Z0-9_-]+. Corresponds to django.db.models.fields.SlugField. Signature: SlugField(max_length=50, min_length=None, allow_blank=False) URLField A RegexField that validates the input against a URL matching pattern. Expects fully qualified URLs of the form http://<host>/<path>. Corresponds to django.db.models.fields.URLField. Uses Django's django.core.validators.URLValidator for validation. Signature: URLField(max_length=200, min_length=None, allow_blank=False) UUIDField A field that ensures the input is a valid UUID string. The to_internal_value method will return a uuid.UUID instance. On output the field will return a string in the canonical hyphenated format, for example: "de305d54-75b4-431b-adb2-eb6b9e546013" Signature: UUIDField(format='hex_verbose') format: Determines the representation format of the uuid value 'hex_verbose' - The canonical hex representation, including hyphens: "5ce0e9a5-5ffa-654b-cee0-1238041fb31a" 'hex' - The compact hex representation of the UUID, not including hyphens: "5ce0e9a55ffa654bcee01238041fb31a" 'int' - A 128 bit integer representation of the UUID: "123456789012312313134124512351145145114" 'urn' - RFC 4122 URN representation of the UUID: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a" Changing the format parameters only affects representation values. All formats are accepted by to_internal_value FilePathField A field whose choices are limited to the filenames in a certain directory on the filesystem Corresponds to django.forms.fields.FilePathField. Signature: FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs) path - The absolute filesystem path to a directory from which this FilePathField should get its choice. match - A regular expression, as a string, that FilePathField will use to filter filenames. recursive - Specifies whether all subdirectories of path should be included. Default is False. allow_files - Specifies whether files in the specified location should be included. Default is True. Either this or allow_folders must be True. allow_folders - Specifies whether folders in the specified location should be included. Default is False. Either this or allow_files must be True. IPAddressField A field that ensures the input is a valid IPv4 or IPv6 string. Corresponds to django.forms.fields.IPAddressField and django.forms.fields.GenericIPAddressField. Signature: IPAddressField(protocol='both', unpack_ipv4=False, **options) protocol Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive. unpack_ipv4 Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'. Numeric fields IntegerField An integer representation. Corresponds to django.db.models.fields.IntegerField, django.db.models.fields.SmallIntegerField, django.db.models.fields.PositiveIntegerField and django.db.models.fields.PositiveSmallIntegerField. Signature: IntegerField(max_value=None, min_value=None) max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value. FloatField A floating point representation. Corresponds to django.db.models.fields.FloatField. Signature: FloatField(max_value=None, min_value=None) max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value. DecimalField A decimal representation, represented in Python by a Decimal instance. Corresponds to django.db.models.fields.DecimalField. Signature: DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits The maximum number of digits allowed in the number. It must be either None or an integer greater than or equal to decimal_places. decimal_places The number of decimal places to store with the number. coerce_to_string Set to True if string values should be returned for the representation, or False if Decimal objects should be returned. Defaults to the same value as the COERCE_DECIMAL_TO_STRING settings key, which will be True unless overridden. If Decimal objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting localize will force the value to True. max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value. localize Set to True to enable localization of input and output based on the current locale. This will also force coerce_to_string to True. Defaults to False. Note that data formatting is enabled if you have set USE_L10N=True in your settings file. rounding Sets the rounding mode used when quantising to the configured precision. Valid values are decimal module rounding modes. Defaults to None. Example usage To validate numbers up to 999 with a resolution of 2 decimal places, you would use: serializers.DecimalField(max_digits=5, decimal_places=2) And to validate numbers up to anything less than one billion with a resolution of 10 decimal places: serializers.DecimalField(max_digits=19, decimal_places=10) This field also takes an optional argument, coerce_to_string. If set to True the representation will be output as a string. If set to False the representation will be left as a Decimal instance and the final representation will be determined by the renderer. If unset, this will default to the same value as the COERCE_DECIMAL_TO_STRING setting, which is True unless set otherwise. Date and time fields DateTimeField A date and time representation. Corresponds to django.db.models.fields.DateTimeField. Signature: DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None, default_timezone=None) format - A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation. In this case the datetime encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601']. default_timezone - A pytz.timezone representing the timezone. If not specified and the USE_TZ setting is enabled, this defaults to the current timezone. If USE_TZ is disabled, then datetime objects will be naive. DateTimeField format strings. Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z') When a value of None is used for the format datetime objects will be returned by to_representation and the final output representation will determined by the renderer class. auto_now and auto_now_add model fields. When using ModelSerializer or HyperlinkedModelSerializer, note that any model fields with auto_now=True or auto_now_add=True will use serializer fields that are read_only=True by default. If you want to override this behavior, you'll need to declare the DateTimeField explicitly on the serializer. For example: class CommentSerializer(serializers.ModelSerializer): created = serializers.DateTimeField() class Meta: model = Comment DateField A date representation. Corresponds to django.db.models.fields.DateField Signature: DateField(format=api_settings.DATE_FORMAT, input_formats=None) format - A string representing the output format. If not specified, this defaults to the same value as the DATE_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python date objects should be returned by to_representation. In this case the date encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATE_INPUT_FORMATS setting will be used, which defaults to ['iso-8601']. DateField format strings Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style dates should be used. (eg '2013-01-29') TimeField A time representation. Corresponds to django.db.models.fields.TimeField Signature: TimeField(format=api_settings.TIME_FORMAT, input_formats=None) format - A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python time objects should be returned by to_representation. In this case the time encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601']. TimeField format strings Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style times should be used. (eg '12:34:56.000000') DurationField A Duration representation. Corresponds to django.db.models.fields.DurationField The validated_data for these fields will contain a datetime.timedelta instance. The representation is a string following this format '[DD] [HH:[MM:]]ss[.uuuuuu]'. Signature: DurationField(max_value=None, min_value=None) max_value Validate that the duration provided is no greater than this value. min_value Validate that the duration provided is no less than this value. Choice selection fields ChoiceField A field that can accept a value out of a limited set of choices. Used by ModelSerializer to automatically generate fields if the corresponding model field includes a choices=… argument. Signature: ChoiceField(choices) choices - A list of valid values, or a list of (key, display_name) tuples. allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False. html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None. html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to "More than {count} items…" Both the allow_blank and allow_null are valid options on ChoiceField, although it is highly recommended that you only use one and not both. allow_blank should be preferred for textual choices, and allow_null should be preferred for numeric or other non-textual choices. MultipleChoiceField A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. to_internal_value returns a set containing the selected values. Signature: MultipleChoiceField(choices) choices - A list of valid values, or a list of (key, display_name) tuples. allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False. html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None. html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to "More than {count} items…" As with ChoiceField, both the allow_blank and allow_null options are valid, although it is highly recommended that you only use one and not both. allow_blank should be preferred for textual choices, and allow_null should be preferred for numeric or other non-textual choices. File upload fields Parsers and file uploads. The FileField and ImageField classes are only suitable for use with MultiPartParser or FileUploadParser. Most parsers, such as e.g. JSON don't support file uploads. Django's regular FILE_UPLOAD_HANDLERS are used for handling uploaded files. FileField A file representation. Performs Django's standard FileField validation. Corresponds to django.forms.fields.FileField. Signature: FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) max_length - Designates the maximum length for the file name. allow_empty_file - Designates if empty files are allowed. use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise. ImageField An image representation. Validates the uploaded file content as matching a known image format. Corresponds to django.forms.fields.ImageField. Signature: ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) max_length - Designates the maximum length for the file name. allow_empty_file - Designates if empty files are allowed. use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise. Requires either the Pillow package or PIL package. The Pillow package is recommended, as PIL is no longer actively maintained. Composite fields ListField A field class that validates a list of objects. Signature: ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None) child - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated. allow_empty - Designates if empty lists are allowed. min_length - Validates that the list contains no fewer than this number of elements. max_length - Validates that the list contains no more than this number of elements. For example, to validate a list of integers you might use something like the following: scores = serializers.ListField( child=serializers.IntegerField(min_value=0, max_value=100) ) The ListField class also supports a declarative style that allows you to write reusable list field classes. class StringListField(serializers.ListField): child = serializers.CharField() We can now reuse our custom StringListField class throughout our application, without having to provide a child argument to it. DictField A field class that validates a dictionary of objects. The keys in DictField are always assumed to be string values. Signature: DictField(child=<A_FIELD_INSTANCE>, allow_empty=True) child - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated. allow_empty - Designates if empty dictionaries are allowed. For example, to create a field that validates a mapping of strings to strings, you would write something like this: document = DictField(child=CharField()) You can also use the declarative style, as with ListField. For example: class DocumentField(DictField): child = CharField() HStoreField A preconfigured DictField that is compatible with Django's postgres HStoreField. Signature: HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True) child - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values. allow_empty - Designates if empty dictionaries are allowed. Note that the child field must be an instance of CharField, as the hstore extension stores values as strings. JSONField A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings. Signature: JSONField(binary, encoder) binary - If set to True then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to False. encoder - Use this JSON encoder to serialize input object. Defaults to None. Miscellaneous fields ReadOnlyField A field class that simply returns the value of the field without modification. This field is used by default with ModelSerializer when including field names that relate to an attribute rather than a model field. Signature: ReadOnlyField() For example, if has_expired was a property on the Account model, then the following serializer would automatically generate it as a ReadOnlyField: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'has_expired'] HiddenField A field class that does not take a value based on user input, but instead takes its value from a default value or callable. Signature: HiddenField() For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following: modified = serializers.HiddenField(default=timezone.now) The HiddenField class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user. For further examples on HiddenField see the validators documentation. ModelField A generic field that can be tied to any arbitrary model field. The ModelField class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field. This field is used by ModelSerializer to correspond to custom model field classes. Signature: ModelField(model_field=<Django ModelField instance>) The ModelField class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a ModelField, it must be passed a field that is attached to an instantiated model. For example: ModelField(model_field=MyModel()._meta.get_field('custom_field')) SerializerMethodField This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. Signature: SerializerMethodField(method_name=None) method_name - The name of the method on the serializer to be called. If not included this defaults to get_<field_name>. The serializer method referred to by the method_name argument should accept a single argument (in addition to self), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example: from django.contrib.auth.models import User from django.utils.timezone import now from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): days_since_joined = serializers.SerializerMethodField() class Meta: model = User fields = '__all__' def get_days_since_joined(self, obj): return (now() - obj.date_joined).days Custom fields If you want to create a custom field, you'll need to subclass Field and then override either one or both of the .to_representation() and .to_internal_value() methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using. The .to_representation() method is called to convert the initial datatype into a primitive, serializable datatype. The .to_internal_value() method is called to restore a primitive datatype into its internal python representation. This method should raise a serializers.ValidationError if the data is invalid. Examples A Basic Custom Field Let's look at an example of serializing a class that represents an RGB color value: class Color: """ A color represented in the RGB colorspace. """ def __init__(self, red, green, blue): assert(red >= 0 and green >= 0 and blue >= 0) assert(red < 256 and green < 256 and blue < 256) self.red, self.green, self.blue = red, green, blue class ColorField(serializers.Field): """ Color objects are serialized into 'rgb(#, #, #)' notation. """ def to_representation(self, value): return "rgb(%d, %d, %d)" % (value.red, value.green, value.blue) def to_internal_value(self, data): data = data.strip('rgb(').rstrip(')') red, green, blue = [int(col) for col in data.split(',')] return Color(red, green, blue) By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override .get_attribute() and/or .get_value(). As an example, let's create a field that can be used to represent the class name of the object being serialized: class ClassNameField(serializers.Field): def get_attribute(self, instance): # We pass the object instance onto `to_representation`, # not just the field attribute. return instance def to_representation(self, value): """ Serialize the value's class name. """ return value.__class__.__name__ Raising validation errors Our ColorField class above currently does not perform any data validation. To indicate invalid data, we should raise a serializers.ValidationError, like so: def to_internal_value(self, data): if not isinstance(data, str): msg = 'Incorrect type. Expected a string, but got %s' raise ValidationError(msg % type(data).__name__) if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data): raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.') data = data.strip('rgb(').rstrip(')') red, green, blue = [int(col) for col in data.split(',')] if any([col > 255 or col < 0 for col in (red, green, blue)]): raise ValidationError('Value out of range. Must be between 0 and 255.') return Color(red, green, blue) The .fail() method is a shortcut for raising ValidationError that takes a message string from the error_messages dictionary. For example: default_error_messages = { 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}', 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.', 'out_of_range': 'Value out of range. Must be between 0 and 255.' } def to_internal_value(self, data): if not isinstance(data, str): self.fail('incorrect_type', input_type=type(data).__name__) if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data): self.fail('incorrect_format') data = data.strip('rgb(').rstrip(')') red, green, blue = [int(col) for col in data.split(',')] if any([col > 255 or col < 0 for col in (red, green, blue)]): self.fail('out_of_range') return Color(red, green, blue) This style keeps your error messages cleaner and more separated from your code, and should be preferred. Using source='*' Here we'll take an example of a flat DataPoint model with x_coordinate and y_coordinate attributes. class DataPoint(models.Model): label = models.CharField(max_length=50) x_coordinate = models.SmallIntegerField() y_coordinate = models.SmallIntegerField() Using a custom field and source='*' we can provide a nested representation of the coordinate pair: class CoordinateField(serializers.Field): def to_representation(self, value): ret = { "x": value.x_coordinate, "y": value.y_coordinate } return ret def to_internal_value(self, data): ret = { "x_coordinate": data["x"], "y_coordinate": data["y"], } return ret class DataPointSerializer(serializers.ModelSerializer): coordinates = CoordinateField(source='*') class Meta: model = DataPoint fields = ['label', 'coordinates'] Note that this example doesn't handle validation. Partly for that reason, in a real project, the coordinate nesting might be better handled with a nested serializer using source='*', with two IntegerField instances, each with their own source pointing to the relevant field. The key points from the example, though, are: to_representation is passed the entire DataPoint object and must map from that to the desired output. >>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2) >>> out_serializer = DataPointSerializer(instance) >>> out_serializer.data ReturnDict([('label', 'Example'), ('coordinates', {'x': 1, 'y': 2})]) Unless our field is to be read-only, to_internal_value must map back to a dict suitable for updating our target object. With source='*', the return from to_internal_value will update the root validated data dictionary, rather than a single key. >>> data = { ... "label": "Second Example", ... "coordinates": { ... "x": 3, ... "y": 4, ... } ... } >>> in_serializer = DataPointSerializer(data=data) >>> in_serializer.is_valid() True >>> in_serializer.validated_data OrderedDict([('label', 'Second Example'), ('y_coordinate', 4), ('x_coordinate', 3)]) For completeness lets do the same thing again but with the nested serializer approach suggested above: class NestedCoordinateSerializer(serializers.Serializer): x = serializers.IntegerField(source='x_coordinate') y = serializers.IntegerField(source='y_coordinate') class DataPointSerializer(serializers.ModelSerializer): coordinates = NestedCoordinateSerializer(source='*') class Meta: model = DataPoint fields = ['label', 'coordinates'] Here the mapping between the target and source attribute pairs (x and x_coordinate, y and y_coordinate) is handled in the IntegerField declarations. It's our NestedCoordinateSerializer that takes source='*'. Our new DataPointSerializer exhibits the same behaviour as the custom field approach. Serializing: >>> out_serializer = DataPointSerializer(instance) >>> out_serializer.data ReturnDict([('label', 'testing'), ('coordinates', OrderedDict([('x', 1), ('y', 2)]))]) Deserializing: >>> in_serializer = DataPointSerializer(data=data) >>> in_serializer.is_valid() True >>> in_serializer.validated_data OrderedDict([('label', 'still testing'), ('x_coordinate', 3), ('y_coordinate', 4)]) But we also get the built-in validation for free: >>> invalid_data = { ... "label": "still testing", ... "coordinates": { ... "x": 'a', ... "y": 'b', ... } ... } >>> invalid_serializer = DataPointSerializer(data=invalid_data) >>> invalid_serializer.is_valid() False >>> invalid_serializer.errors ReturnDict([('coordinates', {'x': ['A valid integer is required.'], 'y': ['A valid integer is required.']})]) For this reason, the nested serializer approach would be the first to try. You would use the custom field approach when the nested serializer becomes infeasible or overly complex. Third party packages The following third party packages are also available. DRF Compound Fields The drf-compound-fields package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the many=True option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type. DRF Extra Fields The drf-extra-fields package provides extra serializer fields for REST framework, including Base64ImageField and PointField classes. djangorestframework-recursive the djangorestframework-recursive package provides a RecursiveField for serializing and deserializing recursive structures django-rest-framework-gis The django-rest-framework-gis package provides geographic addons for django rest framework like a GeometryField field and a GeoJSON serializer. django-rest-framework-hstore The django-rest-framework-hstore package provides an HStoreField to support django-hstore DictionaryField model field. fields.py
doc_27714
Return the total number of headers, including duplicates.
doc_27715
See Migration guide for more details. tf.compat.v1.raw_ops.CompressElement tf.raw_ops.CompressElement( components, name=None ) Args components A list of Tensor objects. name A name for the operation (optional). Returns A Tensor of type variant.
doc_27716
Set the artist's clip Bbox. Parameters clipboxBbox
doc_27717
Returns the content length if available or None otherwise. Return type Optional[int]
doc_27718
Returns True if self tensor is contiguous in memory in the order specified by memory format. Parameters memory_format (torch.memory_format, optional) – Specifies memory allocation order. Default: torch.contiguous_format.
doc_27719
Computes the Mean Squared Error between two covariance estimators. (In the sense of the Frobenius norm). Parameters comp_covarray-like of shape (n_features, n_features) The covariance to compare with. norm{“frobenius”, “spectral”}, default=”frobenius” The type of norm used to compute the error. Available error types: - ‘frobenius’ (default): sqrt(tr(A^t.A)) - ‘spectral’: sqrt(max(eigenvalues(A^t.A)) where A is the error (comp_cov - self.covariance_). scalingbool, default=True If True (default), the squared error norm is divided by n_features. If False, the squared error norm is not rescaled. squaredbool, default=True Whether to compute the squared error norm or the error norm. If True (default), the squared error norm is returned. If False, the error norm is returned. Returns resultfloat The Mean Squared Error (in the sense of the Frobenius norm) between self and comp_cov covariance estimators.
doc_27720
Return a proxy to object which uses a weak reference. This supports use of the proxy in most contexts instead of requiring the explicit dereferencing used with weak reference objects. The returned object will have a type of either ProxyType or CallableProxyType, depending on whether object is callable. Proxy objects are not hashable regardless of the referent; this avoids a number of problems related to their fundamentally mutable nature, and prevent their use as dictionary keys. callback is the same as the parameter of the same name to the ref() function. Changed in version 3.8: Extended the operator support on proxy objects to include the matrix multiplication operators @ and @=.
doc_27721
The latest representable date, date(MAXYEAR, 12, 31).
doc_27722
Returns a dictionary mapping MIME types to a list of mailcap file entries. This dictionary must be passed to the findmatch() function. An entry is stored as a list of dictionaries, but it shouldn’t be necessary to know the details of this representation. The information is derived from all of the mailcap files found on the system. Settings in the user’s mailcap file $HOME/.mailcap will override settings in the system mailcap files /etc/mailcap, /usr/etc/mailcap, and /usr/local/etc/mailcap.
doc_27723
bytearray.rsplit(sep=None, maxsplit=-1) Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.
doc_27724
Set multiple properties at once. Supported properties are Property Description agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha scalar or None animated bool backgroundcolor color bbox dict with properties for patches.FancyBboxPatch clip_box unknown clip_on unknown clip_path unknown color color figure Figure fontfamily {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'} fontproperties font_manager.FontProperties or str or pathlib.Path fontsize float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'} fontstretch {a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'} fontstyle {'normal', 'italic', 'oblique'} fontvariant {'normal', 'small-caps'} fontweight {a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'} gid str horizontalalignment {'center', 'right', 'left'} in_layout bool label object linespacing float (multiple of font size) math_fontfamily str multialignment {'left', 'right', 'center'} parse_math bool path_effects AbstractPathEffect picker None or bool or float or callable position (float, float) rasterized bool rotation float or {'vertical', 'horizontal'} rotation_mode {None, 'default', 'anchor'} sketch_params (scale: float, length: float, randomness: float) snap bool or None text object transform Transform transform_rotates_text bool url str usetex bool or None verticalalignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'} visible bool wrap bool x float y float zorder float
doc_27725
Return the first value for the key if it is in the headers, otherwise set the header to the value given by default and return that. Parameters key – The header key to get. default – The value to set for the key if it is not in the headers.
doc_27726
Alias for output, for symmetry with stderr.
doc_27727
alias of ConvTranspose3d
doc_27728
Return the longest common sub-path of each pathname in the sequence paths. Raise ValueError if paths contain both absolute and relative pathnames, the paths are on the different drives or if paths is empty. Unlike commonprefix(), this returns a valid path. Availability: Unix, Windows. New in version 3.5. Changed in version 3.6: Accepts a sequence of path-like objects.
doc_27729
Set the path effects. Parameters path_effectsAbstractPathEffect
doc_27730
Adds a buffer to the module. This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s running_mean is not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by setting persistent to False. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’s state_dict. Buffers can be accessed as attributes using given names. Parameters name (string) – name of the buffer. The buffer can be accessed from this module using the given name tensor (Tensor) – buffer to be registered. persistent (bool) – whether the buffer is part of this module’s state_dict. Example: >>> self.register_buffer('running_mean', torch.zeros(num_features))
doc_27731
Bases: object
doc_27732
Sets up a new event loop to run the test, collecting the result into the TestResult object passed as result. If result is omitted or None, a temporary result object is created (by calling the defaultTestResult() method) and used. The result object is returned to run()’s caller. At the end of the test all the tasks in the event loop are cancelled.
doc_27733
The constant string used by the operating system to refer to the parent directory. This is '..' for Windows and POSIX. Also available via os.path.
doc_27734
Dump FontManager data as JSON to the file named filename. See also json_load Notes File paths that are children of the Matplotlib data path (typically, fonts shipped with Matplotlib) are stored relative to that data path (to remain valid across virtualenvs). This function temporarily locks the output file to prevent multiple processes from overwriting one another's output.
doc_27735
Alias for get_facecolor.
doc_27736
Set the colormap for luminance data. Parameters cmapColormap or str or None
doc_27737
-self
doc_27738
Applies a 3D average pooling over an input signal composed of several input planes. In the simplest case, the output value of the layer with input size (N,C,D,H,W)(N, C, D, H, W) , output (N,C,Dout,Hout,Wout)(N, C, D_{out}, H_{out}, W_{out}) and kernel_size (kD,kH,kW)(kD, kH, kW) can be precisely described as: out(Ni,Cj,d,h,w)=∑k=0kD−1∑m=0kH−1∑n=0kW−1input(Ni,Cj,stride[0]×d+k,stride[1]×h+m,stride[2]×w+n)kD×kH×kW\begin{aligned} \text{out}(N_i, C_j, d, h, w) ={} & \sum_{k=0}^{kD-1} \sum_{m=0}^{kH-1} \sum_{n=0}^{kW-1} \\ & \frac{\text{input}(N_i, C_j, \text{stride}[0] \times d + k, \text{stride}[1] \times h + m, \text{stride}[2] \times w + n)} {kD \times kH \times kW} \end{aligned} If padding is non-zero, then the input is implicitly zero-padded on all three sides for padding number of points. Note When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding or the input. Sliding windows that would start in the right padded region are ignored. The parameters kernel_size, stride can either be: a single int – in which case the same value is used for the depth, height and width dimension a tuple of three ints – in which case, the first int is used for the depth dimension, the second int for the height dimension and the third int for the width dimension Parameters kernel_size – the size of the window stride – the stride of the window. Default value is kernel_size padding – implicit zero padding to be added on all three sides ceil_mode – when True, will use ceil instead of floor to compute the output shape count_include_pad – when True, will include the zero-padding in the averaging calculation divisor_override – if specified, it will be used as divisor, otherwise kernel_size will be used Shape: Input: (N,C,Din,Hin,Win)(N, C, D_{in}, H_{in}, W_{in}) Output: (N,C,Dout,Hout,Wout)(N, C, D_{out}, H_{out}, W_{out}) , where Dout=⌊Din+2×padding[0]−kernel_size[0]stride[0]+1⌋D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] - \text{kernel\_size}[0]}{\text{stride}[0]} + 1\right\rfloor Hout=⌊Hin+2×padding[1]−kernel_size[1]stride[1]+1⌋H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] - \text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor Wout=⌊Win+2×padding[2]−kernel_size[2]stride[2]+1⌋W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] - \text{kernel\_size}[2]}{\text{stride}[2]} + 1\right\rfloor Examples: >>> # pool of square window of size=3, stride=2 >>> m = nn.AvgPool3d(3, stride=2) >>> # pool of non-square window >>> m = nn.AvgPool3d((3, 2, 2), stride=(2, 1, 2)) >>> input = torch.randn(20, 16, 50,44, 31) >>> output = m(input)
doc_27739
New in Django 3.2. An optional string of a field name (with an optional "-" prefix which indicates descending order) or an expression (or a tuple or list of strings and/or expressions) that specifies the ordering of the elements in the result list. Examples are the same as for ArrayAgg.ordering.
doc_27740
Return string-valued system configuration values. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given as the keys of the confstr_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted. If the configuration value specified by name isn’t defined, None is returned. If name is a string and is not known, ValueError is raised. If a specific value for name is not supported by the host system, even if it is included in confstr_names, an OSError is raised with errno.EINVAL for the error number. Availability: Unix.
doc_27741
Create a numpy array from a ctypes array or POINTER. The numpy array shares the memory with the ctypes object. The shape parameter must be given if converting from a ctypes POINTER. The shape parameter is ignored if converting from a ctypes array numpy.ctypeslib.as_ctypes(obj)[source] Create and return a ctypes object from a numpy array. Actually anything that exposes the __array_interface__ is accepted. numpy.ctypeslib.as_ctypes_type(dtype)[source] Convert a dtype into a ctypes type. Parameters dtypedtype The dtype to convert Returns ctype A ctype scalar, union, array, or struct Raises NotImplementedError If the conversion is not possible Notes This function does not losslessly round-trip in either direction. np.dtype(as_ctypes_type(dt)) will: insert padding fields reorder fields to be sorted by offset discard field titles as_ctypes_type(np.dtype(ctype)) will: discard the class names of ctypes.Structures and ctypes.Unions convert single-element ctypes.Unions into single-element ctypes.Structures insert padding fields numpy.ctypeslib.load_library(libname, loader_path)[source] It is possible to load a library using >>> lib = ctypes.cdll[<full_path_name>] But there are cross-platform considerations, such as library file extensions, plus the fact Windows will just load the first library it finds with that name. NumPy supplies the load_library function as a convenience. Changed in version 1.20.0: Allow libname and loader_path to take any path-like object. Parameters libnamepath-like Name of the library, which can have ‘lib’ as a prefix, but without an extension. loader_pathpath-like Where the library can be found. Returns ctypes.cdll[libpath]library object A ctypes library object Raises OSError If there is no library with the expected extension, or the library is defective and cannot be loaded. numpy.ctypeslib.ndpointer(dtype=None, ndim=None, shape=None, flags=None)[source] Array-checking restype/argtypes. An ndpointer instance is used to describe an ndarray in restypes and argtypes specifications. This approach is more flexible than using, for example, POINTER(c_double), since several restrictions can be specified, which are verified upon calling the ctypes function. These include data type, number of dimensions, shape and flags. If a given array does not satisfy the specified restrictions, a TypeError is raised. Parameters dtypedata-type, optional Array data-type. ndimint, optional Number of array dimensions. shapetuple of ints, optional Array shape. flagsstr or tuple of str Array flags; may be one or more of: C_CONTIGUOUS / C / CONTIGUOUS F_CONTIGUOUS / F / FORTRAN OWNDATA / O WRITEABLE / W ALIGNED / A WRITEBACKIFCOPY / X UPDATEIFCOPY / U Returns klassndpointer type object A type object, which is an _ndtpr instance containing dtype, ndim, shape and flags information. Raises TypeError If a given array does not satisfy the specified restrictions. Examples >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64, ... ndim=1, ... flags='C_CONTIGUOUS')] ... >>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64)) ... class numpy.ctypeslib.c_intp A ctypes signed integer type of the same size as numpy.intp. Depending on the platform, it can be an alias for either c_int, c_long or c_longlong.
doc_27742
By default, AuthenticationForm rejects users whose is_active flag is set to False. You may override this behavior with a custom policy to determine which users can log in. Do this with a custom form that subclasses AuthenticationForm and overrides the confirm_login_allowed() method. This method should raise a ValidationError if the given user may not log in. For example, to allow all users to log in regardless of “active” status: from django.contrib.auth.forms import AuthenticationForm class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm): def confirm_login_allowed(self, user): pass (In this case, you’ll also need to use an authentication backend that allows inactive users, such as AllowAllUsersModelBackend.) Or to allow only some active users to log in: class PickyAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: raise ValidationError( _("This account is inactive."), code='inactive', ) if user.username.startswith('b'): raise ValidationError( _("Sorry, accounts starting with 'b' aren't welcome here."), code='no_b_users', )
doc_27743
Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced. waitstatus_to_exitcode() can be used to convert the exit status into an exit code. Availability: Unix. See also waitpid() can be used to wait for the completion of a specific child process and has more options.
doc_27744
A class used to check the whether the actual output from a doctest example matches the expected output. OutputChecker defines two methods: check_output(), which compares a given pair of outputs, and returns True if they match; and output_difference(), which returns a string describing the differences between two outputs. OutputChecker defines the following methods: check_output(want, got, optionflags) Return True iff the actual output from an example (got) matches the expected output (want). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See section Option Flags for more information about option flags. output_difference(example, got, optionflags) Return a string describing the differences between the expected output for a given example (example) and the actual output (got). optionflags is the set of option flags used to compare want and got.
doc_27745
lookup_name = 'month'
doc_27746
Set the path effects. Parameters path_effectsAbstractPathEffect
doc_27747
Return class labels or probabilities for each estimator. Return predictions for X for each estimator. Parameters X{array-like, sparse matrix, dataframe} of shape (n_samples, n_features) Input samples yndarray of shape (n_samples,), default=None Target values (None for unsupervised transformations). **fit_paramsdict Additional fit parameters. Returns X_newndarray array of shape (n_samples, n_features_new) Transformed array.
doc_27748
Load the Labeled Faces in the Wild (LFW) pairs dataset (classification). Download it if necessary. Classes 2 Samples total 13233 Dimensionality 5828 Features real, between 0 and 255 In the official README.txt this task is described as the “Restricted” task. As I am not sure as to implement the “Unrestricted” variant correctly, I left it as unsupported for now. The original images are 250 x 250 pixels, but the default slice and resize arguments reduce them to 62 x 47. Read more in the User Guide. Parameters subset{‘train’, ‘test’, ‘10_folds’}, default=’train’ Select the dataset to load: ‘train’ for the development training set, ‘test’ for the development test set, and ‘10_folds’ for the official evaluation set that is meant to be used with a 10-folds cross validation. data_homestr, default=None Specify another download and cache folder for the datasets. By default all scikit-learn data is stored in ‘~/scikit_learn_data’ subfolders. funneledbool, default=True Download and use the funneled variant of the dataset. resizefloat, default=0.5 Ratio used to resize the each face picture. colorbool, default=False Keep the 3 RGB channels instead of averaging them to a single gray level channel. If color is True the shape of the data has one more dimension than the shape with color = False. slice_tuple of slice, default=(slice(70, 195), slice(78, 172)) Provide a custom 2D slice (height, width) to extract the ‘interesting’ part of the jpeg files and avoid use statistical correlation from the background download_if_missingbool, default=True If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. Returns dataBunch Dictionary-like object, with the following attributes. datandarray of shape (2200, 5828). Shape depends on subset. Each row corresponds to 2 ravel’d face images of original size 62 x 47 pixels. Changing the slice_, resize or subset parameters will change the shape of the output. pairsndarray of shape (2200, 2, 62, 47). Shape depends on subset Each row has 2 face images corresponding to same or different person from the dataset containing 5749 people. Changing the slice_, resize or subset parameters will change the shape of the output. targetnumpy array of shape (2200,). Shape depends on subset. Labels associated to each pair of images. The two label values being different persons or the same person. DESCRstring Description of the Labeled Faces in the Wild (LFW) dataset.
doc_27749
Return a list of all the top-level nodes. Each node returned is not a pandas storage object. Returns list List of objects.
doc_27750
Return a tuple containing event and the current node as xml.dom.minidom.Document if event equals START_DOCUMENT, xml.dom.minidom.Element if event equals START_ELEMENT or END_ELEMENT or xml.dom.minidom.Text if event equals CHARACTERS. The current node does not contain information about its children, unless expandNode() is called.
doc_27751
The reverse operation to url_parse(). This accepts arbitrary as well as URL tuples and returns a URL as a string. Parameters components (Tuple[str, str, str, str, str]) – the parsed URL as tuple which should be converted into a URL string. Return type str
doc_27752
Return the positions of the grid cells in figure coordinates. Parameters figFigure The figure the grid should be applied to. The subplot parameters (margins and spacing between subplots) are taken from fig. rawbool, default: False If True, the subplot parameters of the figure are not taken into account. The grid spans the range [0, 1] in both directions without margins and there is no space between grid cells. This is used for constrained_layout. Returns bottoms, tops, lefts, rightsarray The bottom, top, left, right positions of the grid cells in figure coordinates.
doc_27753
Return a copy of the Bbox, shrunk by the factor mx in the x direction and the factor my in the y direction. The lower left corner of the box remains unchanged. Normally mx and my will be less than 1, but this is not enforced.
doc_27754
Copy properties from other to self.
doc_27755
Register a user signal: install a handler for the signum signal to dump the traceback of all threads, or of the current thread if all_threads is False, into file. Call the previous handler if chain is True. The file must be kept open until the signal is unregistered by unregister(): see issue with file descriptors. Not available on Windows. Changed in version 3.5: Added support for passing file descriptor to this function.
doc_27756
Set the first sequence to be compared. The second sequence to be compared is not changed.
doc_27757
See Migration guide for more details. tf.compat.v1.raw_ops.Relu6Grad tf.raw_ops.Relu6Grad( gradients, features, name=None ) Args gradients A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64. The backpropagated gradients to the corresponding Relu6 operation. features A Tensor. Must have the same type as gradients. The features passed as input to the corresponding Relu6 operation, or its output; using either one produces the same result. name A name for the operation (optional). Returns A Tensor. Has the same type as gradients.
doc_27758
See Migration guide for more details. tf.compat.v1.estimator.export.TensorServingInputReceiver tf.estimator.export.TensorServingInputReceiver( features, receiver_tensors, receiver_tensors_alternatives=None ) This is for use with models that expect a single Tensor or SparseTensor as an input feature, as opposed to a dict of features. The normal ServingInputReceiver always returns a feature dict, even if it contains only one entry, and so can be used only with models that accept such a dict. For models that accept only a single raw feature, the serving_input_receiver_fn provided to Estimator.export_saved_model() should return this TensorServingInputReceiver instead. See: https://github.com/tensorflow/tensorflow/issues/11674 Note that the receiver_tensors and receiver_tensor_alternatives arguments will be automatically converted to the dict representation in either case, because the SavedModel format requires each input Tensor to have a name (provided by the dict key). Attributes features A single Tensor or SparseTensor, representing the feature to be passed to the model. receiver_tensors A Tensor, SparseTensor, or dict of string to Tensor or SparseTensor, specifying input nodes where this receiver expects to be fed by default. Typically, this is a single placeholder expecting serialized tf.Example protos. receiver_tensors_alternatives a dict of string to additional groups of receiver tensors, each of which may be a Tensor, SparseTensor, or dict of string to Tensor orSparseTensor. These named receiver tensor alternatives generate additional serving signatures, which may be used to feed inputs at different points within the input receiver subgraph. A typical usage is to allow feeding raw feature Tensors downstream of the tf.parse_example() op. Defaults to None.
doc_27759
Return self==value.
doc_27760
Set one or more properties on an Artist, or list allowed values. Parameters objArtist or list of Artist The artist(s) whose properties are being set or queried. When setting properties, all artists are affected; when querying the allowed values, only the first instance in the sequence is queried. For example, two lines can be made thicker and red with a single call: >>> x = arange(0, 1, 0.01) >>> lines = plot(x, sin(2*pi*x), x, sin(4*pi*x)) >>> setp(lines, linewidth=2, color='r') filefile-like, default: sys.stdout Where setp writes its output when asked to list allowed values. >>> with open('output.log') as file: ... setp(line, file=file) The default, None, means sys.stdout. *args, **kwargs The properties to set. The following combinations are supported: Set the linestyle of a line to be dashed: >>> line, = plot([1, 2, 3]) >>> setp(line, linestyle='--') Set multiple properties at once: >>> setp(line, linewidth=2, color='r') List allowed values for a line's linestyle: >>> setp(line, 'linestyle') linestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} List all properties that can be set, and their allowed values: >>> setp(line) agg_filter: a filter function, ... [long output listing omitted] setp also supports MATLAB style string/value pairs. For example, the following are equivalent: >>> setp(lines, 'linewidth', 2, 'color', 'r') # MATLAB style >>> setp(lines, linewidth=2, color='r') # Python style See also getp Examples using matplotlib.pyplot.setp Creating a timeline with lines, dates, and text Contouring the solution space of optimizations Creating annotated heatmaps Boxplots Pie Demo2 Labeling a pie and a donut Patheffect Demo Set and get properties TickedStroke patheffect Topographic hillshading Evans test The Lifecycle of a Plot
doc_27761
Decodes the query part of the URL. Ths is a shortcut for calling url_decode() on the query argument. The arguments and keyword arguments are forwarded to url_decode() unchanged. Parameters args (Any) – kwargs (Any) – Return type ds.MultiDict[str, str]
doc_27762
Return the value of an Artist's property, or print all of them. Parameters objArtist The queried artist; e.g., a Line2D, a Text, or an Axes. propertystr or None, default: None If property is 'somename', this function returns obj.get_somename(). If it's None (or unset), it prints all gettable properties from obj. Many properties have aliases for shorter typing, e.g. 'lw' is an alias for 'linewidth'. In the output, aliases and full property names will be listed as: property or alias = value e.g.: linewidth or lw = 2 See also setp
doc_27763
Regression based on k-nearest neighbors. The target is predicted by local interpolation of the targets associated of the nearest neighbors in the training set. Read more in the User Guide. New in version 0.9. Parameters n_neighborsint, default=5 Number of neighbors to use by default for kneighbors queries. weights{‘uniform’, ‘distance’} or callable, default=’uniform’ weight function used in prediction. Possible values: ‘uniform’ : uniform weights. All points in each neighborhood are weighted equally. ‘distance’ : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. Uniform weights are used by default. algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’ Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree ‘kd_tree’ will use KDTree ‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_sizeint, default=30 Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. pint, default=2 Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metricstr or callable, default=’minkowski’ the distance metric to use for the tree. The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. See the documentation of DistanceMetric for a list of available metrics. If metric is “precomputed”, X is assumed to be a distance matrix and must be square during fit. X may be a sparse graph, in which case only “nonzero” elements may be considered neighbors. metric_paramsdict, default=None Additional keyword arguments for the metric function. n_jobsint, default=None The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Doesn’t affect fit method. Attributes effective_metric_str or callable The distance metric to use. It will be same as the metric parameter or a synonym of it, e.g. ‘euclidean’ if the metric parameter set to ‘minkowski’ and p parameter set to 2. effective_metric_params_dict Additional keyword arguments for the metric function. For most metrics will be same with metric_params parameter, but may also contain the p parameter value if the effective_metric_ attribute is set to ‘minkowski’. n_samples_fit_int Number of samples in the fitted data. See also NearestNeighbors RadiusNeighborsRegressor KNeighborsClassifier RadiusNeighborsClassifier Notes See Nearest Neighbors in the online documentation for a discussion of the choice of algorithm and leaf_size. Warning Regarding the Nearest Neighbors algorithms, if it is found that two neighbors, neighbor k+1 and k, have identical distances but different labels, the results will depend on the ordering of the training data. https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm Examples >>> X = [[0], [1], [2], [3]] >>> y = [0, 0, 1, 1] >>> from sklearn.neighbors import KNeighborsRegressor >>> neigh = KNeighborsRegressor(n_neighbors=2) >>> neigh.fit(X, y) KNeighborsRegressor(...) >>> print(neigh.predict([[1.5]])) [0.5] Methods fit(X, y) Fit the k-nearest neighbors regressor from the training dataset. get_params([deep]) Get parameters for this estimator. kneighbors([X, n_neighbors, return_distance]) Finds the K-neighbors of a point. kneighbors_graph([X, n_neighbors, mode]) Computes the (weighted) graph of k-Neighbors for points in X predict(X) Predict the target for the provided data score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction. set_params(**params) Set the parameters of this estimator. fit(X, y) [source] Fit the k-nearest neighbors regressor from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs) Target values. Returns selfKNeighborsRegressor The fitted k-nearest neighbors regressor. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...) kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]]) predict(X) [source] Predict the target for the provided data Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’ Test samples. Returns yndarray of shape (n_queries,) or (n_queries, n_outputs), dtype=int Target values. score(X, y, sample_weight=None) [source] Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred) ** 2).sum() and \(v\) is the total sum of squares ((y_true - y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters Xarray-like of shape (n_samples, n_features) Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True values for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat \(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor). set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
doc_27764
Initialize vertices with path codes.
doc_27765
Return a copy of the vertices used in this patch. If the patch contains Bezier curves, the curves will be interpolated by line segments. To access the curves as curves, use get_path.
doc_27766
Segments image using k-means clustering in Color-(x,y,z) space. Parameters image2D, 3D or 4D ndarray Input image, which can be 2D or 3D, and grayscale or multichannel (see multichannel parameter). Input image must either be NaN-free or the NaN’s must be masked out n_segmentsint, optional The (approximate) number of labels in the segmented output image. compactnessfloat, optional Balances color proximity and space proximity. Higher values give more weight to space proximity, making superpixel shapes more square/cubic. In SLICO mode, this is the initial compactness. This parameter depends strongly on image contrast and on the shapes of objects in the image. We recommend exploring possible values on a log scale, e.g., 0.01, 0.1, 1, 10, 100, before refining around a chosen value. max_iterint, optional Maximum number of iterations of k-means. sigmafloat or (3,) array-like of floats, optional Width of Gaussian smoothing kernel for pre-processing for each dimension of the image. The same sigma is applied to each dimension in case of a scalar value. Zero means no smoothing. Note, that sigma is automatically scaled if it is scalar and a manual voxel spacing is provided (see Notes section). spacing(3,) array-like of floats, optional The voxel spacing along each image dimension. By default, slic assumes uniform spacing (same voxel resolution along z, y and x). This parameter controls the weights of the distances along z, y, and x during k-means clustering. multichannelbool, optional Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension. convert2labbool, optional Whether the input should be converted to Lab colorspace prior to segmentation. The input image must be RGB. Highly recommended. This option defaults to True when multichannel=True and image.shape[-1] == 3. enforce_connectivitybool, optional Whether the generated segments are connected or not min_size_factorfloat, optional Proportion of the minimum segment size to be removed with respect to the supposed segment size `depth*width*height/n_segments` max_size_factorfloat, optional Proportion of the maximum connected segment size. A value of 3 works in most of the cases. slic_zerobool, optional Run SLIC-zero, the zero-parameter mode of SLIC. [2] start_label: int, optional The labels’ index start. Should be 0 or 1. New in version 0.17: start_label was introduced in 0.17 mask2D ndarray, optional If provided, superpixels are computed only where mask is True, and seed points are homogeneously distributed over the mask using a K-means clustering strategy. New in version 0.17: mask was introduced in 0.17 Returns labels2D or 3D array Integer mask indicating segment labels. Raises ValueError If convert2lab is set to True but the last array dimension is not of length 3. ValueError If start_label is not 0 or 1. Notes If sigma > 0, the image is smoothed using a Gaussian kernel prior to segmentation. If sigma is scalar and spacing is provided, the kernel width is divided along each dimension by the spacing. For example, if sigma=1 and spacing=[5, 1, 1], the effective sigma is [0.2, 1, 1]. This ensures sensible smoothing for anisotropic images. The image is rescaled to be in [0, 1] prior to processing. Images of shape (M, N, 3) are interpreted as 2D RGB images by default. To interpret them as 3D with the last dimension having length 3, use multichannel=False. start_label is introduced to handle the issue [4]. The labels indexing starting at 0 will be deprecated in future versions. If mask is not None labels indexing starts at 1 and masked area is set to 0. References 1 Radhakrishna Achanta, Appu Shaji, Kevin Smith, Aurelien Lucchi, Pascal Fua, and Sabine Süsstrunk, SLIC Superpixels Compared to State-of-the-art Superpixel Methods, TPAMI, May 2012. DOI:10.1109/TPAMI.2012.120 2 https://www.epfl.ch/labs/ivrl/research/slic-superpixels/#SLICO 3 Irving, Benjamin. “maskSLIC: regional superpixel generation with application to local pathology characterisation in medical images.”, 2016, arXiv:1606.09518 4 https://github.com/scikit-image/scikit-image/issues/3722 Examples >>> from skimage.segmentation import slic >>> from skimage.data import astronaut >>> img = astronaut() >>> segments = slic(img, n_segments=100, compactness=10) Increasing the compactness parameter yields more square regions: >>> segments = slic(img, n_segments=100, compactness=20)
doc_27767
Output of the child process if it was captured by run() or check_output(). Otherwise, None.
doc_27768
See Migration guide for more details. tf.compat.v1.raw_ops.QuantizedConv2DWithBiasSumAndRelu tf.raw_ops.QuantizedConv2DWithBiasSumAndRelu( input, filter, bias, min_input, max_input, min_filter, max_filter, summand, strides, padding, out_type=tf.dtypes.qint32, dilations=[1, 1, 1, 1], padding_list=[], name=None ) Args input A Tensor. Must be one of the following types: qint8, quint8, qint32, qint16, quint16. filter A Tensor. Must be one of the following types: qint8, quint8, qint32, qint16, quint16. bias A Tensor of type float32. min_input A Tensor of type float32. max_input A Tensor of type float32. min_filter A Tensor of type float32. max_filter A Tensor of type float32. summand A Tensor of type float32. strides A list of ints. padding A string from: "SAME", "VALID". out_type An optional tf.DType from: tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16. Defaults to tf.qint32. dilations An optional list of ints. Defaults to [1, 1, 1, 1]. padding_list An optional list of ints. Defaults to []. name A name for the operation (optional). Returns A tuple of Tensor objects (output, min_output, max_output). output A Tensor of type out_type. min_output A Tensor of type float32. max_output A Tensor of type float32.
doc_27769
Decorator to require that a view only accepts the POST method.
doc_27770
Based on DateTimeField and translates its input into DateTimeTZRange. Default for DateTimeRangeField.
doc_27771
Add a SubFigure to the figure as part of a subplot arrangement. Parameters subplotspecgridspec.SubplotSpec Defines the region in a parent gridspec where the subfigure will be placed. Returns figure.SubFigure Other Parameters **kwargs Are passed to the SubFigure object. See also Figure.subfigures
doc_27772
Alias for torch.transpose(). This function is equivalent to NumPy’s swapaxes function. Examples: >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) >>> x tensor([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> torch.swapdims(x, 0, 1) tensor([[[0, 1], [4, 5]], [[2, 3], [6, 7]]]) >>> torch.swapdims(x, 0, 2) tensor([[[0, 4], [2, 6]], [[1, 5], [3, 7]]])
doc_27773
Bases: matplotlib.backend_bases.FigureCanvasBase draw()[source] Render the Figure. It is important that this method actually walk the artist tree even if not output is produced because this will trigger deferred work (like computing limits auto-limits and tick values) that users may want access to before saving to disk. filetypes={'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics'} fixed_dpi=72 get_default_filetype()[source] Return the default savefig file format as specified in rcParams["savefig.format"] (default: 'png'). The returned string does not include a period. This method is overridden in backends that only support a single file type. print_svg(filename, *args, dpi=<deprecated parameter>, bbox_inches_restore=None, metadata=None)[source] Parameters filenamestr or path-like or file-like Output target; if a string, a file will be opened for writing. metadatadict[str, Any], optional Metadata in the SVG file defined as key-value pairs of strings, datetimes, or lists of strings, e.g., {'Creator': 'My software', 'Contributor': ['Me', 'My Friend'], 'Title': 'Awesome'}. The standard keys and their value types are: str: 'Coverage', 'Description', 'Format', 'Identifier', 'Language', 'Relation', 'Source', 'Title', and 'Type'. str or list of str: 'Contributor', 'Creator', 'Keywords', 'Publisher', and 'Rights'. str, date, datetime, or tuple of same: 'Date'. If a non-str, then it will be formatted as ISO 8601. Values have been predefined for 'Creator', 'Date', 'Format', and 'Type'. They can be removed by setting them to None. Information is encoded as Dublin Core Metadata. print_svgz(filename, *args, **kwargs)[source]
doc_27774
list of weak references to the object (if defined)
doc_27775
Computes the squared Mahalanobis distances of given observations. Parameters Xarray-like of shape (n_samples, n_features) The observations, the Mahalanobis distances of the which we compute. Observations are assumed to be drawn from the same distribution than the data used in fit. Returns distndarray of shape (n_samples,) Squared Mahalanobis distances of the observations.
doc_27776
See Migration guide for more details. tf.compat.v1.raw_ops.CudnnRNNParamsToCanonicalV2 tf.raw_ops.CudnnRNNParamsToCanonicalV2( num_layers, num_units, input_size, params, num_params_weights, num_params_biases, rnn_mode='lstm', input_mode='linear_input', direction='unidirectional', dropout=0, seed=0, seed2=0, num_proj=0, name=None ) Retrieves a set of weights from the opaque params buffer that can be saved and restored in a way compatible with future runs. Note that the params buffer may not be compatible across different GPUs. So any save and restoration should be converted to and from the canonical weights and biases. num_layers: Specifies the number of layers in the RNN model. num_units: Specifies the size of the hidden state. input_size: Specifies the size of the input state. num_params_weights: number of weight parameter matrix for all layers. num_params_biases: number of bias parameter vector for all layers. weights: the canonical form of weights that can be used for saving and restoration. They are more likely to be compatible across different generations. biases: the canonical form of biases that can be used for saving and restoration. They are more likely to be compatible across different generations. rnn_mode: Indicates the type of the RNN model. input_mode: Indicate whether there is a linear projection between the input and The actual computation before the first layer. 'skip_input' is only allowed when input_size == num_units; 'auto_select' implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. direction: Indicates whether a bidirectional model will be used. dir = (direction == bidirectional) ? 2 : 1 dropout: dropout probability. When set to 0., dropout is disabled. seed: the 1st part of a seed to initialize dropout. seed2: the 2nd part of a seed to initialize dropout. num_proj: The output dimensionality for the projection matrices. If None or 0, no projection is performed. Args num_layers A Tensor of type int32. num_units A Tensor of type int32. input_size A Tensor of type int32. params A Tensor. Must be one of the following types: half, float32, float64. num_params_weights An int that is >= 1. num_params_biases An int that is >= 1. rnn_mode An optional string from: "rnn_relu", "rnn_tanh", "lstm", "gru". Defaults to "lstm". input_mode An optional string from: "linear_input", "skip_input", "auto_select". Defaults to "linear_input". direction An optional string from: "unidirectional", "bidirectional". Defaults to "unidirectional". dropout An optional float. Defaults to 0. seed An optional int. Defaults to 0. seed2 An optional int. Defaults to 0. num_proj An optional int. Defaults to 0. name A name for the operation (optional). Returns A tuple of Tensor objects (weights, biases). weights A list of num_params_weights Tensor objects with the same type as params. biases A list of num_params_biases Tensor objects with the same type as params.
doc_27777
A dictionary mapping names to descriptors for nested functions and classes. New in version 3.7.
doc_27778
Predict using GLM with feature matrix X. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Samples. Returns y_predarray of shape (n_samples,) Returns predicted values.
doc_27779
Register the factory function with the name name. The factory function should return an object which implements the DOMImplementation interface. The factory function can return the same object every time, or a new one for each call, as appropriate for the specific implementation (e.g. if that implementation supports some customization).
doc_27780
Get the matrix for the affine part of this transform.
doc_27781
The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the io.IOBase.readline() method of file objects. Each call to the function should return one line of input as bytes. The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed (the last tuple item) is the physical line. The 5 tuple is returned as a named tuple with the field names: type string start end line. The returned named tuple has an additional property named exact_type that contains the exact operator type for OP tokens. For all other token types exact_type equals the named tuple type field. Changed in version 3.1: Added support for named tuples. Changed in version 3.3: Added support for exact_type. tokenize() determines the source encoding of the file by looking for a UTF-8 BOM or encoding cookie, according to PEP 263.
doc_27782
Bases: matplotlib.patches.Patch An elliptical annulus. Parameters xy(float, float) xy coordinates of annulus centre. rfloat or (float, float) The radius, or semi-axes: If float: radius of the outer circle. If two floats: semi-major and -minor axes of outer ellipse. widthfloat Width (thickness) of the annular ring. The width is measured inward from the outer ellipse so that for the inner ellipse the semi-axes are given by r - width. width must be less than or equal to the semi-minor axis. anglefloat, default: 0 Rotation angle in degrees (anti-clockwise from the positive x-axis). Ignored for circular annuli (i.e., if r is a scalar). **kwargs Keyword arguments control the Patch properties: Property Description agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha unknown animated bool antialiased or aa bool or None capstyle CapStyle or {'butt', 'projecting', 'round'} clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None color color edgecolor or ec color or None facecolor or fc color or None figure Figure fill bool gid str hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'} in_layout bool joinstyle JoinStyle or {'miter', 'round', 'bevel'} label object linestyle or ls {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw float or None path_effects AbstractPathEffect picker None or bool or float or callable rasterized bool sketch_params (scale: float, length: float, randomness: float) snap bool or None transform Transform url str visible bool zorder float propertyangle Return the angle of the annulus. propertycenter Return the center of the annulus. get_angle()[source] Return the angle of the annulus. get_center()[source] Return the center of the annulus. get_path()[source] Return the path of this patch. get_radii()[source] Return the semi-major and semi-minor radii of the annulus. get_width()[source] Return the width (thickness) of the annulus ring. propertyradii Return the semi-major and semi-minor radii of the annulus. set(*, agg_filter=<UNSET>, alpha=<UNSET>, angle=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, capstyle=<UNSET>, center=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, color=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, fill=<UNSET>, gid=<UNSET>, hatch=<UNSET>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, radii=<UNSET>, rasterized=<UNSET>, semimajor=<UNSET>, semiminor=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, width=<UNSET>, zorder=<UNSET>)[source] Set multiple properties at once. Supported properties are Property Description agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha scalar or None angle float animated bool antialiased or aa bool or None capstyle CapStyle or {'butt', 'projecting', 'round'} center (float, float) clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None color color edgecolor or ec color or None facecolor or fc color or None figure Figure fill bool gid str hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'} in_layout bool joinstyle JoinStyle or {'miter', 'round', 'bevel'} label object linestyle or ls {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw float or None path_effects AbstractPathEffect picker None or bool or float or callable radii float or (float, float) rasterized bool semimajor float semiminor float sketch_params (scale: float, length: float, randomness: float) snap bool or None transform Transform url str visible bool width float zorder float set_angle(angle)[source] Set the tilt angle of the annulus. Parameters anglefloat set_center(xy)[source] Set the center of the annulus. Parameters xy(float, float) set_radii(r)[source] Set the semi-major (a) and semi-minor radii (b) of the annulus. Parameters rfloat or (float, float) The radius, or semi-axes: If float: radius of the outer circle. If two floats: semi-major and -minor axes of outer ellipse. set_semimajor(a)[source] Set the semi-major axis a of the annulus. Parameters afloat set_semiminor(b)[source] Set the semi-minor axis b of the annulus. Parameters bfloat set_width(width)[source] Set the width (thickness) of the annulus ring. The width is measured inwards from the outer ellipse. Parameters widthfloat propertywidth Return the width (thickness) of the annulus ring.
doc_27783
Bases: matplotlib.backend_bases.Event An event that has a screen location. A LocationEvent has a number of special attributes in addition to those defined by the parent Event class. Attributes x, yint or None Event location in pixels from bottom left of canvas. inaxesAxes or None The Axes instance over which the mouse is, if any. xdata, ydatafloat or None Data coordinates of the mouse within inaxes, or None if the mouse is not over an Axes. lastevent=None
doc_27784
Predict class probabilities of the input samples X. The predicted class probability is the fraction of samples of the same class in a leaf. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. check_inputbool, default=True Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns probandarray of shape (n_samples, n_classes) or list of n_outputs such arrays if n_outputs > 1 The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
doc_27785
Return the axes padding. Returns hpad, vpad Padding (horizontal pad, vertical pad) in inches.
doc_27786
class ast.Sub class ast.Mult class ast.Div class ast.FloorDiv class ast.Mod class ast.Pow class ast.LShift class ast.RShift class ast.BitOr class ast.BitXor class ast.BitAnd class ast.MatMult Binary operator tokens.
doc_27787
Casts all floating point parameters and buffers to half datatype. Returns self Return type Module
doc_27788
Plot horizontal lines at each y from xmin to xmax. Parameters yfloat or array-like y-indexes where to plot the lines. xmin, xmaxfloat or array-like Respective beginning and end of each line. If scalars are provided, all lines will have same length. colorslist of colors, default: rcParams["lines.color"] (default: 'C0') linestyles{'solid', 'dashed', 'dashdot', 'dotted'}, optional labelstr, default: '' Returns LineCollection Other Parameters dataindexable object, optional If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception): y, xmin, xmax, colors **kwargsLineCollection properties. See also vlines vertical lines axhline horizontal line across the Axes Examples using matplotlib.axes.Axes.hlines hlines and vlines Specifying Colors
doc_27789
Display data as an image, i.e., on a 2D regular raster. The input may either be actual RGB(A) data, or 2D scalar data, which will be rendered as a pseudocolor image. For displaying a grayscale image set up the colormapping using the parameters cmap='gray', vmin=0, vmax=255. The number of pixels used to render an image is set by the Axes size and the dpi of the figure. This can lead to aliasing artifacts when the image is resampled because the displayed image size will usually not match the size of X (see Image antialiasing). The resampling can be controlled via the interpolation parameter and/or rcParams["image.interpolation"] (default: 'antialiased'). Parameters Xarray-like or PIL image The image data. Supported array shapes are: (M, N): an image with scalar data. The values are mapped to colors using normalization and a colormap. See parameters norm, cmap, vmin, vmax. (M, N, 3): an image with RGB values (0-1 float or 0-255 int). (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency. The first two dimensions (M, N) define the rows and columns of the image. Out-of-range RGB(A) values are clipped. cmapstr or Colormap, default: rcParams["image.cmap"] (default: 'viridis') The Colormap instance or registered colormap name used to map scalar data to colors. This parameter is ignored for RGB(A) data. normNormalize, optional The Normalize instance used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling mapping the lowest value to 0 and the highest to 1 is used. This parameter is ignored for RGB(A) data. aspect{'equal', 'auto'} or float, default: rcParams["image.aspect"] (default: 'equal') The aspect ratio of the Axes. This parameter is particularly relevant for images since it determines whether data pixels are square. This parameter is a shortcut for explicitly calling Axes.set_aspect. See there for further details. 'equal': Ensures an aspect ratio of 1. Pixels will be square (unless pixel sizes are explicitly made non-square in data coordinates using extent). 'auto': The Axes is kept fixed and the aspect is adjusted so that the data fit in the Axes. In general, this will result in non-square pixels. interpolationstr, default: rcParams["image.interpolation"] (default: 'antialiased') The interpolation method used. Supported values are 'none', 'antialiased', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'blackman'. If interpolation is 'none', then no interpolation is performed on the Agg, ps, pdf and svg backends. Other backends will fall back to 'nearest'. Note that most SVG renderers perform interpolation at rendering and that the default interpolation method they implement may differ. If interpolation is the default 'antialiased', then 'nearest' interpolation is used if the image is upsampled by more than a factor of three (i.e. the number of display pixels is at least three times the size of the data array). If the upsampling rate is smaller than 3, or the image is downsampled, then 'hanning' interpolation is used to act as an anti-aliasing filter, unless the image happens to be upsampled by exactly a factor of two or one. See Interpolations for imshow for an overview of the supported interpolation methods, and Image antialiasing for a discussion of image antialiasing. Some interpolation methods require an additional radius parameter, which can be set by filterrad. Additionally, the antigrain image resize filter is controlled by the parameter filternorm. interpolation_stage{'data', 'rgba'}, default: 'data' If 'data', interpolation is carried out on the data provided by the user. If 'rgba', the interpolation is carried out after the colormapping has been applied (visual interpolation). alphafloat or array-like, optional The alpha blending value, between 0 (transparent) and 1 (opaque). If alpha is an array, the alpha blending values are applied pixel by pixel, and alpha must have the same shape as X. vmin, vmaxfloat, optional When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when norm is given. When using RGB(A) data, parameters vmin/vmax are ignored. origin{'upper', 'lower'}, default: rcParams["image.origin"] (default: 'upper') Place the [0, 0] index of the array in the upper left or lower left corner of the Axes. The convention (the default) 'upper' is typically used for matrices and images. Note that the vertical axis points upward for 'lower' but downward for 'upper'. See the origin and extent in imshow tutorial for examples and a more detailed description. extentfloats (left, right, bottom, top), optional The bounding box in data coordinates that the image will fill. The image is stretched individually along x and y to fill the box. The default extent is determined by the following conditions. Pixels have unit size in data coordinates. Their centers are on integer coordinates, and their center coordinates range from 0 to columns-1 horizontally and from 0 to rows-1 vertically. Note that the direction of the vertical axis and thus the default values for top and bottom depend on origin: For origin == 'upper' the default is (-0.5, numcols-0.5, numrows-0.5, -0.5). For origin == 'lower' the default is (-0.5, numcols-0.5, -0.5, numrows-0.5). See the origin and extent in imshow tutorial for examples and a more detailed description. filternormbool, default: True A parameter for the antigrain image resize filter (see the antigrain documentation). If filternorm is set, the filter normalizes integer values and corrects the rounding errors. It doesn't do anything with the source floating point values, it corrects only integers according to the rule of 1.0 which means that any sum of pixel weights must be equal to 1.0. So, the filter function must produce a graph of the proper shape. filterradfloat > 0, default: 4.0 The filter radius for filters that have a radius parameter, i.e. when interpolation is one of: 'sinc', 'lanczos' or 'blackman'. resamplebool, default: rcParams["image.resample"] (default: True) When True, use a full resampling method. When False, only resample when the output image is larger than the input image. urlstr, optional Set the url of the created AxesImage. See Artist.set_url. Returns AxesImage Other Parameters dataindexable object, optional If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception). **kwargsArtist properties These parameters are passed on to the constructor of the AxesImage artist. See also matshow Plot a matrix or an array as an image. Notes Unless extent is used, pixel centers will be located at integer coordinates. In other words: the origin will coincide with the center of pixel (0, 0). There are two common representations for RGB images with an alpha channel: Straight (unassociated) alpha: R, G, and B channels represent the color of the pixel, disregarding its opacity. Premultiplied (associated) alpha: R, G, and B channels represent the color of the pixel, adjusted for its opacity by multiplication. imshow expects RGB images adopting the straight (unassociated) alpha representation. Examples using matplotlib.pyplot.imshow Layer Images Subplots spacings and margins Dolphins Hyperlinks Image tutorial Tight Layout guide
doc_27790
Set the font properties that control the text. Parameters fpfont_manager.FontProperties or str or pathlib.Path If a str, it is interpreted as a fontconfig pattern parsed by FontProperties. If a pathlib.Path, it is interpreted as the absolute path to a font file.
doc_27791
Return the average log-likelihood of all samples. See. “Pattern Recognition and Machine Learning” by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf Parameters Xarray-like of shape (n_samples, n_features) The data. yIgnored Returns llfloat Average log-likelihood of the samples under the current model.
doc_27792
Animation using a fixed set of Artist objects. Before creating an instance, all plotting should have taken place and the relevant artists saved. Note You must store the created Animation in a variable that lives as long as the animation should run. Otherwise, the Animation object will be garbage-collected and the animation stops. Parameters figFigure The figure object used to get needed events, such as draw or resize. artistslist Each list entry is a collection of Artist objects that are made visible on the corresponding frame. Other artists are made invisible. intervalint, default: 200 Delay between frames in milliseconds. repeat_delayint, default: 0 The delay in milliseconds between consecutive animation runs, if repeat is True. repeatbool, default: True Whether the animation repeats when the sequence of frames is completed. blitbool, default: False Whether blitting is used to optimize drawing. __init__(fig, artists, *args, **kwargs)[source] Methods __init__(fig, artists, *args, **kwargs) new_frame_seq() Return a new sequence of frame information. new_saved_frame_seq() Return a new sequence of saved/cached frame information. pause() Pause the animation. resume() Resume the animation. save(filename[, writer, fps, dpi, codec, ...]) Save the animation as a movie file by drawing every frame. to_html5_video([embed_limit]) Convert the animation to an HTML5 <video> tag. to_jshtml([fps, embed_frames, default_mode]) Generate HTML representation of the animation.
doc_27793
Check whether iterations are left, and perform a single internal iteration without returning the result. Used in the C-style pattern do-while pattern. For an example, see nditer. Returns iternextbool Whether or not there are iterations left.
doc_27794
get the name of a key identifier name(key) -> string Get the descriptive name of the button from a keyboard button id constant.
doc_27795
See Migration guide for more details. tf.compat.v1.raw_ops.BoostedTreesTrainingPredict tf.raw_ops.BoostedTreesTrainingPredict( tree_ensemble_handle, cached_tree_ids, cached_node_ids, bucketized_features, logits_dimension, name=None ) computes the update to cached logits. It is designed to be used during training. It traverses the trees starting from cached tree id and cached node id and calculates the updates to be pushed to the cache. Args tree_ensemble_handle A Tensor of type resource. cached_tree_ids A Tensor of type int32. Rank 1 Tensor containing cached tree ids which is the starting tree of prediction. cached_node_ids A Tensor of type int32. Rank 1 Tensor containing cached node id which is the starting node of prediction. bucketized_features A list of at least 1 Tensor objects with type int32. A list of rank 1 Tensors containing bucket id for each feature. logits_dimension An int. scalar, dimension of the logits, to be used for partial logits shape. name A name for the operation (optional). Returns A tuple of Tensor objects (partial_logits, tree_ids, node_ids). partial_logits A Tensor of type float32. tree_ids A Tensor of type int32. node_ids A Tensor of type int32.
doc_27796
See Migration guide for more details. tf.compat.v1.raw_ops.DestroyResourceOp tf.raw_ops.DestroyResourceOp( resource, ignore_lookup_error=True, name=None ) All subsequent operations using the resource will result in a NotFound error status. Args resource A Tensor of type resource. handle to the resource to delete. ignore_lookup_error An optional bool. Defaults to True. whether to ignore the error when the resource doesn't exist. name A name for the operation (optional). Returns The created Operation.
doc_27797
The name of the ContentType foreign key field on the model. Defaults to content_type.
doc_27798
joins two rectangles into one union(Rect) -> Rect Returns a new rectangle that completely covers the area of the two provided rectangles. There may be area inside the new Rect that is not covered by the originals.
doc_27799
tf.debugging.assert_non_positive( x, message=None, summarize=None, name=None ) This Op checks that x[i] <= 0 holds for every element of x. If x is empty, this is trivially satisfied. If x is not <= 0 everywhere, message, as well as the first summarize entries of x are printed, and InvalidArgumentError is raised. Args x Numeric Tensor. message A string to prefix to the default message. summarize Print this many entries of each tensor. name A name for this operation (optional). Defaults to "assert_non_positive". Returns Op raising InvalidArgumentError unless x is all non-positive. This can be used with tf.control_dependencies inside of tf.functions to block followup computation until the check has executed. Raises InvalidArgumentError if the check can be performed immediately and x[i] <= 0 is False. The check can be performed immediately during eager execution or if x is statically known. Eager Compatibility returns None