在学习的过程中我也翻阅了一些书籍,最近在看《深度学习之pytorch实战计算机视觉》,记录一下笔记。这篇笔记主要是第5章的内容,介绍一些python中的类,以及常用的库Numpy和Matplotlib。
目录
5.3.8 Python中的类
5.4 Python中的Numpy
5.4.1 安装
5.4.2 多维数组
5.4.3 多维数组的基本操作
5.5 Python中的Matplotlib
5.5.1 Matplotlib的安装
5.5.2 创建图
python是面向对象的程序语言。
1.类的创建
看一下例子。
class Student:
student_Count = 0
def __init__(self,name,age):
self.name = name
self.age = age
Student.student_Count += 1
def dis_student(self):
print("Student name:",self.name,"Student age:",self.age)
#创建对象
student1 = Student("TANG","20")
student2 = Student("WU","22")
student1.dis_student()
student2.dis_student()
print("Total Student:",Student.student_Count)
输出结果:
Student name: TANG Student age: 20
Student name: WU Student age: 22
Total Student: 2
2.类的继承
我们可以将继承理解为:定义一个类,通过继承获得另一个类的所有方法,被继承的类叫作父类,进行继承的类叫作子类,这样可以有效地解决代码的重用问题,在提升了代码的效率和利用率的基础上还增加了可扩展性。
不过需要注意的是,当一个类被继承时,这个类中的初始化方法是不会被自动调用的,所以我们需要在子类中重新定义类的初始化方法。
另外,我们在使用 Python 代码去调用某个方法时,默认会先在所在类中进行查找,如果没有找到,则判断所在的类是否为子类,若为子类,就继续到父类中查找。下面通过一个具体的实例来看看如何创建和使用子类。
class People():
def __init__ (self,name,age):
self.name= name
self.age= age
def dis_name(self):
print ("name is :", self.name)
def set_age(self, age):
self.age = age
def dis_age(self):
print ("age is: ", self.age)
class Student(People):
def __init__(self,name,age,school_name):
# People.__init__(self,name,age)
# super(Student,self).__init__(self,name,age,school_name)
self.name=name
self.age=age
self.school_name=school_name
def dis_student(self):
print("school name is:",self.school_name)
stu = Student("Wu","20","GLDZ")
stu.dis_student()#调用子类的方法
stu.dis_name()#调用父类的方法
stu.dis_age() #调用父类的方法
stu.set_age(22) #调用父类的方法
stu.dis_age() #调用父类的方法
输出:
school name is: GLDZ
name is : Wu
age is: 20
age is: 22
或者
class People():
def __init__(self,name,age):
self.name = name
self.age = age
def dis_name(self):
print ("name is :", self.name)
def set_age(self, age):
self.age = age
def dis_age(self):
print ("age is: ", self.age)
class Student(People):
def __init__(self,name,age):
#super().__init__(self,restaurant_name,cuisine_type)
super().__init__(name,age)
self.school_name="abc"
def dis_student(self):
print("school name is:",self.school_name)
stu = Student("Wu","20")
stu.dis_name()
stu.dis_age()
stu.dis_student()
输出:
name is : Wu
age is: 20
school name is: abc
再看一个例子:
class Father(object):
def __init__(self, name):
self.name=name
print ( "name: %s" %( self.name) )
def getName(self):
return 'Father ' + self.name
class Son(Father):
def __init__(self, name,age):
print ( "hi" )
self.name = name
self.age = age
def getName(self):
return 'Son '+ self.name + " is " + self.age
if __name__=='__main__':
son=Son('runoob','20')
print ( son.getName() )
输出:
hi
Son runoob is 20
3. 类的重写
在继承一个类后,父类中的很多方法也许就不能满足我们现有的需求了,这时我们就要对类进行重写。下面通过一个实例来看看如何对类中的内容进行重写。
#定义父类
class Parent:
def __init__(self):
pass
def print_info(self):
print("This is Parent.")
#定义子类
class Child(Parent):
def __init__(self):
pass
#重写父类的方法
def print_info(self):
print("This is Child.")
child = Child()
child.print_info()#This is Child.
pip install numpy
1.创建多维数组
常用的方法是array。
import numpy as np
np.array([1,2,3])
np.array([[1,2,3],[4,5,6]])
(1)使用 NumPy 中的 ones 可以创建维度指定且元素全为1的数组。
(2)使用 NumPy 中的 zeros 可以创建维度指定且元素全为0的数组。
(3)使用 NumPy 中的 empty 可以创建维度指定且元素全为随机数的数组。
2.多维数组的常用属性
import numpy as np
a = np.empty([3,3])
a.dim #2
a.shape #(3,3)
a.size #9
a.dtype #dtype('float64')
a.itemsize #8
3.数组的打印
在数组中的元素太多时,若全部进行打印输出,则会占用大面积的显示空间,而且不易查看,所以在打印输出元素过多的数组时,输出显示的内容会自动跳过中间的部分,只打印首尾的一小部分,对中间的部分用省略号(...)来代替。
b = np.arange(2000)
print(b) #[ 0 1 2 ... 1997 1998 1999]
这些操作包括数组的算术运算、索引、切片、迭代等。
1.数组的算术运算
加法、减法、乘法和除法,分别为+、-、*和/。
2.数组自身的运算
3.随机数组
生成随机数在我们平时的应用中是很有用的,有很多方法:
np.random.seed(42)
print(np.random.rand(2,3))
print(np.random.randn(2,3))
print(np.random.randint(1,10))
print(np.random.binomial(6,1))
print(np.random.beta(2,3))
print(np.random.normal(2,3))
输出:
[[0.37454012 0.95071431 0.73199394]
[0.59865848 0.15601864 0.15599452]]
[[ 1.57921282 0.76743473 -0.46947439]
[ 0.54256004 -0.46341769 -0.46572975]]
6
6
0.45543839870822056
2.666236704694229
pip install Matplotlib
1.线型图
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
x = np.random.randn(30)
plt.plot(x,"r--o")
输出图像:
2.线条颜色、标记形状和线型
用于设置线型图中线条颜色的常用参数如下:
用于设置线型图中标记参数点形状的常用参数如下:
用于设置线型图中连接参数点线条形状的常用参数如下:
3.标签和图例
我们可以增加一些绘制图像的说明,一般是添加图像的轴标签和图例。看一个例子。
np.random.seed(42)
x = np.random.randn(30)
y = np.random.randn(30)
plt.title("Example")
plt.xlabel("X")
plt.ylabel("Y")
X, = plt.plot(x,"r--o")
Y, = plt.plot(y,"b-*")
plt.legend([X,Y],["X","Y"])
输出内容如下:
4.子图(Subplot)
可以将多个图像同时在不同的位置显示。代码如下:
a = np.random.randn(30)
b = np.random.randn(30)
c = np.random.randn(30)
d = np.random.randn(30)
fig = plt.figure() #首先定义一个实例
#添加子图
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)
A, = ax1.plot(a,"r--o")
ax1.legend([A],["A"])
B, = ax2.plot(b,"b-*")
ax2.legend([B],["B"])
C, = ax3.plot(c,"g-.+")
ax3.legend([C],["C"])
D, = ax4.plot(d,"m:x")
ax4.legend([D],["D"])
输出图像:
除了绘制线型图,Matplotlib还能绘制散点图、直方图和饼图等。
5.散点图(Scatter)
如果有一批散点数据,绘制散点图能更清晰地展示所有数据的分布和布局。
np.random.seed(42)
x = np.random.randn(30)
y = np.random.randn(30)
plt.scatter(x,y,c="g",marker="o",label="(X,Y)")
plt.title("Example")
plt.xlabel("X")
plt.ylabel("Y")
plt.legend(loc = 1)
plt.show()
图像输出如下:
上述的核心代码为:plt.scatter(x,y,c="g",marker="o",label="(X,Y)"),其中有三个需要注意的参数:
通过plt.legend(loc=1)对图例的位置进行设定,一般采用这几种:
6.直方图
直方图(Histogram)又称质量分布图,是一种统计报告图,通过使用一系列高度不等的纵向条纹或直方表示数据分布的情况,一般用横轴表示数据类型,用纵轴表示分布情况,下面看具体的实例。
np.random.seed(42)
x = np.random.randn(100)
plt.hist(x,bins=20,color='g')#bins指定直方图条纹的数量
plt.title("Example")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
输出图像:
7.饼图
饼图用于显示一个数据系列(理解为一类数据),而每个数据系列都应当拥有自己唯一的颜色。在同一个饼图中可以绘制多个系列的数据,并根据每个系列的数据量的不同来分配它们在饼图中的占比。代码如下:
import matplotlib.pyplot as plt
import numpy as np
labels = ['dog','cat','bird']
sizes = [15,50,35]
plt.pie(sizes,explode=(0,0,0.1),labels= labels,autopct='%1.1f%%',startangle = 90)
plt.axis('equal')#必须有,保证x轴和y轴刻度一致,得到的饼图是圆形
plt.show()
图像如下:
核心代码为plt.pie(sizes,explode=(0,0,0.1),labels= labels,autopct='%1.1f%%',startangle = 90),其中几个参数理解为:
plt.axis('equal')是必须有的,用于保证x轴和y轴刻度一致,最后得到的饼图才是圆形。
说明:记录学习笔记,如果错误欢迎指正!写文章不易,转载请联系我。