官术网_书友最值得收藏!

Creating array views and copies

In the example about ravel(), views were brought up. Views should not be confused with the construct of database views. Views in the NumPy universe are not read-only and you don't have the possibility to protect the underlying information. It is crucial to know when we are handling a shared array view and when we have a replica of the array data. A slice of an array, for example, will produce a view. This entails that if you assign the slice to a variable and then alter the underlying array, the value of this variable will change. We will create an array from the face picture in the SciPy package, and then create a view and alter it at the final stage:

  1. Get the face image:
            face = scipy.misc.face() 
    
  2. Create a copy of the face array:
            acopy = face.copy() 
    
  3. Create a view of the array:
            aview = face.view() 
    
  4. Set all the values in the view to 0 with a flat iterator:
            aview.flat = 0 
    

The final outcome is that only one of the pictures depicts the model. The other ones are censored altogether, as shown in the following screenshot:

Refer to the following code of this tutorial, which shows the behavior of array views and copies:

import scipy.misc 
import matplotlib.pyplot as plt 
 
face = scipy.misc.face() 
acopy = face.copy() 
aview = face.view() 
aview.flat = 0 
plt.subplot(221) 
plt.imshow(face) 
plt.subplot(222) 
plt.imshow(acopy) 
plt.subplot(223) 
plt.imshow(aview) 
plt.show() 

As you can see, by altering the view at the end of the program, we modified the original Lena array. This resulted in three blue (or black if you are reading the print version of this book) pictures. The copied array was unchanged. It is crucial to remember that views are not read-only.

主站蜘蛛池模板: 公主岭市| 阿尔山市| 株洲市| 长治县| 嘉黎县| 清水河县| 荆门市| 德阳市| 曲阜市| 鄢陵县| 当涂县| 东兰县| 牙克石市| 三台县| 克什克腾旗| 伊吾县| 富蕴县| 宁远县| 金昌市| 筠连县| 阿瓦提县| 武夷山市| 象州县| 西华县| 民权县| 同德县| 天水市| 平塘县| 盈江县| 休宁县| 镇巴县| 临高县| 金沙县| 西乌珠穆沁旗| 巴马| 温泉县| 左权县| 成武县| 临江市| 龙游县| 宁晋县|