神经网络基础
神经网络是一种模拟人脑神经元工作方式的计算模型,它由多个层次的节点(神经元)组成,每个神经元接收输入、进行加权求和并经过非线性激活函数转换后输出到下一层或作为最终输出。
昇思模型中的mindspore.nn提供了常见神经网络层的实现,在MindSpore中,Cell类是构建所有网络的基类,也是网络的基本单元。一个神经网络模型表示为一个Cell
,它由不同的子Cell
构成。使用这样的嵌套结构,可以简单地使用面向对象编程的思维,对神经网络结构进行构建和管理。
import mindspore
from mindspore import nn, ops
import time
class Network(nn.Cell):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
self.dense_relu_sequential = nn.SequentialCell(
nn.Dense(28*28, 512, weight_init="normal", bias_init="zeros"),
nn.ReLU(),
nn.Dense(512, 512, weight_init="normal", bias_init="zeros"),
nn.ReLU(),
nn.Dense(512, 10, weight_init="normal", bias_init="zeros")
)
def construct(self, x):
x = self.flatten(x)
logits = self.dense_relu_sequential(x)
return logits
model = Network()
print(model)
X = ops.ones((1, 28, 28), mindspore.float32)
logits = model(X)
# print logits
logits
pred_probab = nn.Softmax(axis=1)(logits)
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {y_pred}")
input_image = ops.ones((3, 28, 28), mindspore.float32)
print(input_image.shape)
flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.shape)
layer1 = nn.Dense(in_channels=28*28, out_channels=20)
hidden1 = layer1(flat_image)
print(hidden1.shape)
print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")
seq_modules = nn.SequentialCell(
flatten,
layer1,
nn.ReLU(),
nn.Dense(20, 10)
)
logits = seq_modules(input_image)
print(logits.shape)
softmax = nn.Softmax(axis=1)
pred_probab = softmax(logits)
print(f"Model structure: {model}\n\n")
for name, param in model.parameters_and_names():
print(f"Layer: {name}\nSize: {param.shape}\nValues : {param[:2]} \n")
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),'skywp')