
class定义类
class 类名:
def __init__(self, 参数, …): # 构造函数 ...
def 方法名1(self, 参数, …): # 方法1 ...
def 方法名2(self, 参数, …): # 方法2...
1.这里有一个特殊的__init__方法,这是进行初始化的方法,也称为构造 函数(constructor),只在生成类的实例时被调用一次。
2.在方法的第一 个参数中明确地写入表示自身(自身的实例)的self是Python的一个特点
Python中可 以像self.name这样,通过在self后面添加属性名来生成或访问实例变量。
例:创建一个类man.py
class Man:
def __init__(self, name):
self.name = name
print("Initialized!")
def hello(self):
print("Hello " + self.name + "!")
def goodbye(self):
print("Good-bye " + self.name + "!")
m = Man("David")
m.hello()
m.goodbye()
从终端运行man.py
$ python man.py
Initialized!
Hello David!
Good-bye David!
NumPy
1.需先导入NumPy库 >>> import numpy as np(NumPy相关的方法均可通过np来调用。)
2.生成NumPy数组
>>> x = np.array([1.0, 2.0, 3.0])
>>> print(x)
[ 1. 2. 3.]
>>> type(x)
3. NumPy 的算术运算
>>> x = np.array([1.0, 2.0, 3.0])
>>> y = np.array([2.0, 4.0, 6.0])
>>> x + y # 对应元素的加法
array([ 3., 6., 9.])
>>> x - y
array([ -1., -2., -3.])
>>> x * y # element-wise product
array([ 2., 8., 18.])
>>> x / y
array([ 0.5, 0.5, 0.5])
注意:数组x和数组y的元素个数是相同的
4.NumPy的N维数组
NumPy不仅可以生成一维数组(排成一列的数组),也可以生成多维数组。 比如,可以生成如下的二维数组(矩阵)。
>>> A = np.array([[1, 2], [3, 4]])
>>> print(A)
[[1 2]
[3 4]]
>>> A.shape
(2, 2)
>>> A.dtype
dtype('int64')
广播
因为NumPy有广播功能,所以不同形状的数组之间也可以顺利 地进行运算
>>> A = np.array([[1, 2], [3, 4]])
>>> B = np.array([10, 20])
>>> A * B
访问元素
>>> X = np.array([[51, 55], [14, 19], [0, 4]])
>>> print(X)
[[51 55]
[14 19]
[ 0 4]]
>>> X[0]
Matplotlib
1.用matplotlib的pyplot模块绘制图形
import numpy as np
import matplotlib.pyplot as plt
# 生成数据
x = np.arange(0, 6, 0.1) # 以0.1为单位,生成0到6的数据
y = np.sin(x)
# 绘制图形
1.6 Matplotlib 17
plt.plot(x, y)
plt.show()
感知机
使用权重和偏置的实现
与门 或门 非门
def AND(x1, x2):
x = np.array([x1, x2])
w = np.array([0.5, 0.5])
b = -0.7
tmp = np.sum(w*x) + b
if tmp <= 0:
return 0
else:
return 1
def NAND(x1, x2):
x = np.array([x1, x2])
w = np.array([-0.5, -0.5]) # 仅权重和偏置与AND不同!
b = 0.7
tmp = np.sum(w*x) + b
if tmp <= 0:
return 0
else:
return 1
def OR(x1, x2):
x = np.array([x1, x2])
w = np.array([0.5, 0.5]) # 仅权重和偏置与AND不同!
b = -0.2
tmp = np.sum(w*x) + b
if tmp <= 0:
return 0
else:
return 1
异或门
def XOR(x1, x2):
s1 = NAND(x1, x2)
s2 = OR(x1, x2)
y = AND(s1, s2)
return y
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)