“深度学习”学习日记。多维数组的运算、三层神经网络的实现

2022.12.23

昨天冬至给自己放纵一天,没有学习

今天学习python二维数组的建立学习了很久,才知道pyhton并没有内置的数组类型,只有tuple、list、dict、set等内置类型。我们也可以通过numpy去建立二维数组

# 多维数组的运算

import numpy as np

# 多维数组

A = np.arange(-10, 10, 1)
print(A, '\n')
print(np.ndim(A), '\n')  # np.ndim() 获取数组的维度
print(A.shape, '\n')  # (20,) (第0维的元素数量,第1维的元素数量,......)

# python 二维数组的创建
# list遍历法
a = [[] for i in range(3)]
for i in range(2):
    tmp1 = np.random.randint(0, 100)
    a[0].append(tmp1)

for i in range(2):
    tmp2 = np.random.randint(0, 100)
    a[1].append(tmp2)

for i in range(2):
    tmp3 = np.random.randint(0, 100)
    a[2].append(tmp3)

print(a, '\n')  # [[0, 56], [39, 44], [17, 5]]

# 表列推导式
b = [[(row + 1) * (col + 1) for col in range(4)] for row in range(3)]
print(b, '\n')  # [[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12]]

B = np.array([[1, 2], [3, 4], [5, 6]])
print(B, '\n', np.ndim(B), '\n', B.shape)

# 矩阵乘法

a1 = np.array([[1, 2], [3, 4]])
b1 = np.array([[5, 6], [7, 8]])
a2 = np.array([[1], [2]])
c1 = np.dot(a1, b1)  # np.dot(a1,a2)是矩阵相乘
c2 = np.dot(b1, a1)  # 这里与线性代数同理,c1与c2的结果可能不一样 矩阵运算要符合线性代数计算规则
print(c1, '\n', c2, '\n')
print(np.dot(a1, a2), '\n')

今天试着写了一下3层神经网络,过程算顺利没有太多报错

import numpy as np


def sigmoid(x):
    return 1 / (1 + np.exp(-x))


def identity(x):
    return x


def forward(network, x):
    w1, w2, w3 = network['w1'], network['w2'], network['w3']
    b1, b2, b3 = network['b1'], network['b2'], network['b3']

    a1 = np.dot(x, w1) + b1
    z1 = sigmoid(a1)
    a2 = np.dot(z1, w2) + b2
    z2 = sigmoid(a2)
    a3 = np.dot(z2, w3) + b3
    y = identity(a3)

    return y


def init_network():
    network = {}
    network['w1'] = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])
    network['w2'] = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]])
    network['w3'] = np.array([[0.1, 0.3], [0.2, 0.4]])
    network['b1'] = np.array([0.1, 0.2, 0.3])
    network['b2'] = np.array([0.1, 0.2])
    network['b3'] = np.array([0.1, 0.2])

    return network


network = init_network()
parameter_a = float(input())  # 1
parameter_b = float(input())  # 0.5
x = np.array([parameter_a, parameter_b])
y = forward(network, x)
print(y)  # [0.31682708 0.69627909]

你可能感兴趣的:(python,神经网络,numpy)