基于python的理论与实践

基于python的理论与实践(前两章)

chapter1

# NumPy 计算数值的库 数组和矩阵
# MatplotLib 画图的库
# 使用Anaconda来安装python3,因为anaconda集成了很多库
# 查看python版本命令:python --version
# 对话模式: python

'''
1.数据类型:整型、布尔型、字符串型,用type()来查看数据的类型,bool的运算符有and or not,字符串拼接可以用“+”
2.python3中的整数/整数得到的是浮点数
3.变量 variable,用变量进行计算或赋值
4.python属于动态类型语言的编程语言,所谓动态就是变量的类型根据情况自己决定的
5.列表:list 中有slicing,list[-1]是最后一个元素,list[:-1]到倒数第二个元素
6.词典dict 集合set 元组tuple
7.各种数据类型的操作
'''

'''
1. if语句 if else
2. for语句 for in
3. 函数 def 函数名(参数)
4. python脚本文件,即将程序保存在文件中,集中运行这个文件, 使用命令:python 文件名
5. 类:定义新的数据类型,实例变量是存储在各个实例中的变量
    class 类型:
        def __init__(self,para): # 构造函数constructor
            xxx
        def functionname(self, para):
            xxx

'''

'''
1. numpy:生成数组的代码:np.array([[],[]])
2. 数组之间的运算需要两个数组的元素个数一致,乘法就是element-wise product
3. 数组可以和单一的数值进行计算,即标量
4. numpy也可以生成多维的数组,查看元素的类型.dtype,查看矩阵形状:.shape,矩阵的算术运算也可以在相同形状的矩阵之间以对应元素的方式进行
5. 一维数组是向量,二维数组是矩阵,三维及以上是张量或多维数组,广播是指不同形状的数组之间也可以进行计算.
6. 创建数组的方式: np.zeros([2,2], dtype=int),2*2维的数组,元素是int类型 ,np.ones([3,5], dtype=int),b.flatten()转成一维数组,np.arange(10,30,5, dtype=int) 每间隔5个取值

'''

'''
1. matplotlib:import matplotlib.pyplot as plt
2. matplotlib:用于读入图片的命令 from matplot.image import imread
3. vscode不知道为什么不能显示图片,只能save之后才看到
'''
# coding: utf-8
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import imread
import matplotlib

'''
# 生成数据
x = np.arange(0, 6, 0.1)
y1 = np.cos(x)
y2 = np.sin(x)
 
# 绘制图形
plt.plot(x, y1, label="cos")
plt.plot(x, y2, linestyle="--", label="sin")
plt.xlabel("x")
plt.ylabel("y")
plt.title("cos & sin")
plt.legend() # 使文字说明,图例出现
plt.show()
plt.savefig("firstone.jpg")

'''
os.system('export disPLAY=:0.0')
matplotlib.use('Agg')
img = imread("firstone.jpg")
plt.imshow(img)
plt.show()

chapter2

'''
感知机 perceptron 是一种算法 Frank Rosenblatt在1957年提出来的,是deep learning 起源的算法
感知机可以接收多个信号,输出一个信号,这里的信号是类似电流或河流具备流动性的东西。和实际的流不同,感知机的信号只有流和不流两个取值(1/0)
每个神经元用于计算传过来的信号,如果信号大于某个阈值神经元就被激活了,每个信号都有各自的权重,例如图perception.jpg
简单逻辑电路:与门,与非门,或门,
感知机的局限是不能实现异或门,单纯的直线不能将四个点(0,1)(1,0)和(0,0)(1,1)分开;它的局限在于它只能表示由一条直线分割的空间
由曲线分割而成的空间称为非线性空间,由直线分割而成的空间称为线性空间
叠加层可以实现异或,异或门是一种多层结构的神经网络

'''

# -*-coding:utf-8-*-
import encodings
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import imread
from matplotlib.patches import Circle

def get_perceptron():
    a = [[5,8], [5,8]]
    b = [[3,7], [10,8]]
    ti = np.arange(0, 15+1)
    fig, ax = plt.subplots() # 返回一个包含figure和axes对象的元组
    plt.xlim(0,15)# 设定绘制范围
    plt.ylim(0,15)
    plt.xticks(ti) # 设置刻度
    plt.yticks(ti)
    plt.text(3,3, "x1") # 在某个坐标写文字
    plt.text(10,8, "y")
    plt.text(3,10, "x2")
    plt.text(7,5, "w1")
    plt.text(7,10, "w2")
    draw_circle1 = plt.Circle((3,3), 2) # 画圆 圆心坐标和半径
    draw_circle2 = plt.Circle((10,8), 2) # 画圆 圆心坐标和半径
    draw_circle3 = plt.Circle((3,10), 2) # 画圆 圆心坐标和半径
    ax.set_aspect(1) # x y 等比例
    ax.add_artist(draw_circle1)
    ax.add_artist(draw_circle2)
    ax.add_artist(draw_circle3)
    ax.annotate('', xy=(8,7), xytext=(5,3), arrowprops=dict(arrowstyle="->", color="r", hatch='*',))
    ax.annotate('', xy=(8,8), xytext=(5,10), arrowprops=dict(arrowstyle="->", color="r", hatch='*',))

    # for i in range(len(a)): 
    #     ax.plot(a[i], b[i], color='r')
        # ax.scatter(a[i], b[i], color='b')
    plt.title("Perceptron")
    plt.show()
    plt.savefig("perceptron.jpg")

def get_andgate(x1, x2):
    # 与门
    print("与门:")
    w1, w2, theta = 0.5, 0.5, 0.7
    temp = x1*w1 + x2*w2
    if temp <= theta:
        return 0
    else:
        return 1

def get_NANDgate(x1, x2):
    # 与非门
    print("与非门:")
    w1, w2, theta = -0.5, -0.5, -0.7
    temp = x1*w1 + x2*w2
    if temp <= theta:
        return 0
    else:
        return 1

def get_ORgate(x1, x2):
    # 或门
    print("或门:")
    w1, w2, theta = 0.5, 0.5, 0.3
    temp = x1*w1 + x2*w2
    if temp <= theta:
        return 0
    else:
        return 1

def get_Andgate2(x):
    w = np.array([0.5, 0.5])
    b = -0.7
    temp = np.sum(w*x)+b
    if temp <= 0 :
        return 0
    else:
        return 1

def get_NAndgate2(x):
    w = np.array([-0.5, -0.5])
    b = 0.7
    temp = np.sum(w*x)+b
    if temp <= 0 :
        return 0
    else:
        return 1

def get_Orgate2(x):
    w = np.array([0.5, 0.5])
    b = -0.3
    temp = np.sum(w*x)+b
    if temp <= 0 :
        return 0
    else:
        return 1

def XOR(x):
    s1 = get_NAndgate2(x)
    s2 = get_Orgate2(x)
    return get_andgate(s1, s2)

if __name__ == "__main__":
    # 画感知机图
    # get_perceptron()
    
    # 实现 与、与非、或门
    temp = [[0,0],[0,1],[1,0],[1,1]]

    # for t in temp:
    #     print(get_andgate(t[0],t[1]))
    #     print(get_NANDgate(t[0],t[1]))
    #     print(get_ORgate(t[0],t[1]))

    # 实现与、与非、或门 version2,将阈值改称为偏置
    x = np.array([[0,0], [0,1], [1,0], [1,1]])
    for t in x:
        # print(get_Andgate2(t))
        # print(get_NAndgate2(t))
        # print(get_Orgate2(t))
        print(XOR(t))


相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...