鸣叫 鸣叫 分享 分享
最后更新于2021年12月29日
运行你的Python脚本是开发过程中的一个重要步骤,因为正是通过这种方式,你可以发现你的代码是否按照你的意图运行。另外,我们经常需要向Python脚本传递信息以使其发挥作用。
在本教程中,你将发现运行和传递信息给Python脚本的各种方法。
完成本教程后,你将知道。
- 如何使用命令行界面、Jupyter 笔记本或集成开发环境 (IDE) 运行一个 Python 脚本。
- 如何使用sys.argv命令,通过在 Jupyter Notebook 中硬编码输入变量,或通过交互式使用input()函数,向 Python 脚本传递信息。
让我们开始吧。
运行并向Python脚本传递信息
照片:Andrea Leopardi,保留部分权利。
教程概述
本教程分为两部分;它们是。
- 运行一个Python脚本
- 使用命令行界面
- 使用Jupyter笔记本
- 使用集成开发环境 (IDE)
- Python输入
运行一个Python脚本。
使用命令行界面
命令行界面被广泛地用于运行Python代码。
让我们来测试几个命令,首先打开一个命令提示符或终端窗口,这取决于你正在使用的操作系统。
在你的命令行界面中输入python命令将启动一个Python交互式会话。你会看到一条信息出现,告知你正在使用的Python版本。
Python 3.7.4 (default, Aug 13 2019, 15:17:50)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
在交互式会话中,你在命令行界面中写的任何语句都会立即执行。例如,输入 2 + 3 会返回一个 5 的值。
2 + 3
5
以这种方式使用交互式会话有它的优势,因为你可以轻松而快速地测试出Python代码行。然而,如果我们对编写较长的程序更感兴趣的话,这并不是一个理想的选择,比如我们正在开发一个机器学习算法。一旦交互式会话结束,代码也会消失。
另一个选择是运行一个Python脚本。首先让我们从一个简单的例子开始。
在一个文本编辑器中(比如,Notepad++、Visual Studio Code或Sublime Text),输入print("Hello World!")语句,并将文件保存为test_script.py,或者任何其他你选择的名字,只要你包含一个*.py*扩展名。
现在回到你的命令行界面,输入python命令,然后再输入你的脚本文件的名称。在这样做之前,你可能需要改变路径,使之指向包含脚本文件的目录。运行该脚本文件应该会产生以下输出。
python test_script.py
Hello World!
现在让我们写一个脚本文件,加载一个预先训练好的Keras模型,并对这个狗的图像进行预测输出。通常情况下,我们还需要以命令行参数的形式向Python脚本传递信息。为此,我们将使用sys.argv命令向脚本传递图像路径和要返回的顶部猜测的数量。我们可以根据代码的要求有尽可能多的输入参数,在这种情况下,我们将不断地从参数列表中读取输入。
我们现在要运行的脚本文件包含以下代码。
import sys
import numpy as np
from tensorflow.keras.applications import vgg16
from tensorflow.keras.applications.vgg16 import preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
# Load the VGG16 model pre-trained on the ImageNet dataset
vgg16_model = vgg16.VGG16(weights='imagenet')
# Read the command-line argument passed to the interpreter when invoking the script
image_path = sys.argv[1]
top_guesses = sys.argv[2]
# Load the image, resized according to the model target size
img_resized = image.load_img(image_path, target_size=(224, 224))
# Convert the image into an array
img = image.img_to_array(img_resized)
# Add in a dimension
img = np.expand_dims(img, axis=0)
# Scale the pixel intensity values
img = preprocess_input(img)
# Generate a prediction for the test image
pred_vgg = vgg16_model.predict(img)
# Decode and print the top 3 predictions
print('Prediction:', decode_predictions(pred_vgg, top=int(top_guesses)))
在上面的代码中,我们用sys.argv[1]
和sys.argv[2]
来读取前两个参数的命令行参数。我们可以通过使用python
命令和脚本文件的名称来运行该脚本,并进一步将图像路径(在图像被保存到磁盘后)和我们想要预测的顶级猜测的数量作为参数传给它。
python pretrained_model.py dog.jpg 3
其中pretrained_model.py是脚本文件的名称,而dog.jpg图像已被保存在包含Python脚本的同一目录中。
生成的前三个猜测是以下几个。
Prediction: [[('n02088364', 'beagle', 0.6751468), ('n02089867', 'Walker_hound', 0.1394801), ('n02089973', 'English_foxhound', 0.057901423)]]
但在命令行中可以有更多的内容。例如,下面的命令行将以 "优化 "模式运行脚本,其中调试变量__debug__
被设置为False
,assert
语句被跳过。
python -O test_script.py
而下面的命令是用Python模块启动脚本,例如调试器。
python -m pdb test_script.py
我们将有另一篇关于使用调试器和剖析器的文章。
使用Jupyter笔记本
如果你的代码只产生一个字符串输出,而没有其他的东西,从命令行界面运行一个Python脚本是一个直接的选择。
然而,当我们在处理图像时,往往也需要生成一个可视化的输出:我们可能要检查在将图像送入神经网络之前应用于输入图像的任何预处理的正确性,或者可视化神经网络产生的结果。Jupyter笔记本提供了一个交互式计算环境,可以帮助我们实现这一目标。
通过Jupyter笔记本界面运行Python脚本的一种方法是简单地将代码添加到笔记本的一个 "单元 "中。但这意味着你的代码停留在Jupyter笔记本内,不能在其他地方访问,比如像上面那样使用命令行。另一种方法是使用runmagic命令,以%字符为前缀。试着在Jupyter笔记本的一个单元格中输入以下代码。
%run pretrained_model.py dog.jpg 3
在这里,我们再次指定Python脚本文件的名称,如pretrained_model.py,然后是图像路径和顶级猜测的数量作为输入参数。你会看到,在产生这一结果的单元格下面,打印出了前三名的预测结果。
现在,假设我们想显示输入的图像,以便检查它是否已经按照模型的目标尺寸加载。为此,我们将对代码稍作修改,并保存到一个新的Python脚本,pretrained_model_image.py。
import sys
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.applications import vgg16
from tensorflow.keras.applications.vgg16 import preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
# Load the VGG16 model pre-trained on the ImageNet dataset
vgg16_model = vgg16.VGG16(weights='imagenet')
# Read the arguments passed to the interpreter when invoking the script
image_path = sys.argv[1]
top_guesses = sys.argv[2]
# Load the image, resized according to the model target size
img_resized = image.load_img(image_path, target_size=(224, 224))
# Convert the image into an array
img = image.img_to_array(img_resized)
# Display the image to check that it has been correctly resized
plt.imshow(img.astype(np.uint8))
# Add in a dimension
img = np.expand_dims(img, axis=0)
# Scale the pixel intensity values
img = preprocess_input(img)
# Generate a prediction for the test image
pred_vgg = vgg16_model.predict(img)
# Decode and print the top 3 predictions
print('Prediction:', decode_predictions(pred_vgg, top=int(top_guesses)))
通过Jupyter笔记本界面运行新保存的Python脚本,现在除了打印出前三名的预测结果外,还显示出调整后的224美元/times 224美元像素的图像。
%run pretrained_model_image.py dog.jpg 3
在Jupyter笔记本中运行一个Python脚本
另外,我们可以将代码缩减为以下内容(并将其保存在另一个Python脚本中,pretrained_model_inputs.py)。
# Load the VGG16 model pre-trained on the ImageNet dataset
vgg16_model = vgg16.VGG16(weights='imagenet')
# Load the image, resized according to the model target size
img_resized = image.load_img(image_path, target_size=(224, 224))
# Convert the image into an array
img = image.img_to_array(img_resized)
# Display the image to check that it has been correctly resized
plt.imshow(img.astype(np.uint8))
# Add in a dimension
img = np.expand_dims(img, axis=0)
# Scale the pixel intensity values
img = preprocess_input(img)
# Generate a prediction for the test image
pred_vgg = vgg16_model.predict(img)
# Decode and print the top 3 predictions
print('Prediction:', decode_predictions(pred_vgg, top=top_guesses))
并在Jupyter笔记本本身的一个单元中定义输入变量。以这种方式运行Python脚本,需要我们在%run魔法之后也使用-i选项。
%run -i pretrained_model_inputs.py
在Jupyter Notebook中运行一个Python脚本
这样做的好处是可以更容易地访问Python脚本中可以交互定义的变量。
随着你的代码的增长,结合使用文本编辑器和Jupyter Notebook可以提供一个方便的前进方式:文本编辑器可以用来创建Python脚本,它存储了可以重复使用的代码,而Jupyter Notebook提供了一个交互式的计算环境,可以更容易地探索数据。
使用集成开发环境(IDE)
另一个选择是在一个集成开发环境中运行Python脚本。这需要先创建一个项目,并将扩展名为*.py*的Python脚本添加到其中。
如果我们不得不考虑选择 PyCharm 或 Visual Studio Code 作为 IDE,这就要求我们创建一个新的项目,然后选择我们想使用的 Python 解释器的版本。在将Python脚本添加到新创建的项目中后,可以运行它来生成输出。下面是在macOS上运行Visual Studio Code的屏幕截图。根据IDE的情况,应该有一个选项可以在有或没有调试器的情况下运行代码。
Python输入
到目前为止,我们已经考虑了通过sys.argv命令向Python脚本传递信息,或者在运行脚本之前在Jupyter Notebook中硬编码输入变量的选项。
另一个选择是通过input()函数从用户那里获取输入。
请看下面的代码。
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.applications import vgg16
from tensorflow.keras.applications.vgg16 import preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
# Load the VGG16 model pre-trained on the ImageNet dataset
vgg16_model = vgg16.VGG16(weights='imagenet')
# Ask the user for manual inputs
image_path = input("Enter image path: ")
top_guesses = input("Enter number of top guesses: ")
# Load the image, resized according to the model target size
img_resized = image.load_img(image_path, target_size=(224, 224))
# Convert the image into an array
img = image.img_to_array(img_resized)
# Add in a dimension
img = np.expand_dims(img, axis=0)
# Scale the pixel intensity values
img = preprocess_input(img)
# Generate a prediction for the test image
pred_vgg = vgg16_model.predict(img)
# Decode and print the top 3 predictions
print('Prediction:', decode_predictions(pred_vgg, top=int(top_guesses)))
这里提示用户手动输入图片路径(图片已经被保存在包含Python脚本的同一目录中,因此,指定图片名称就足够了),以及要生成的顶级猜测的数量。这两个输入值都是字符串类型,但是在使用时,顶级猜测的数量会被转换为整数。
无论这段代码是在命令行界面、Jupyter Notebook还是Python IDE中运行,它都会提示用户所需的输入,并随后生成用户要求的预测数。
进一步阅读
如果你想深入了解,本节提供了更多关于该主题的资源。
书籍
- Python Fundamentals, 2018.
- Python Machine Learning Blueprints, 2019.
总结
在本教程中,你发现了运行和传递信息给Python脚本的各种方法。
具体来说,你学会了。
- 如何使用命令行界面、Jupyter笔记本或集成开发环境(IDE)来运行Python脚本。
- 如何使用sys.argv命令,通过在Jupyter Notebook中硬编码输入变量,或通过input()函数的交互式使用,向Python脚本传递信息。
你有什么问题吗?
请在下面的评论中提出你的问题,我将尽力回答。
鸣叫 鸣叫 分享 分享
The postRunning and Passing Information to a Python Scriptappeared first onMachine Learning Mastery.