# 7- 深度学习之神经网络核心原理与算法-模型的保存与加载

## 模型的保存与加载

• 网络训练完毕你需要保存，以便在产品上使用。(手写识别模型要识别新的图片)
• 保存网络的结构，权重，偏置，使用的损失函数。
• 使用别人的模型或者对已有模型进行微调。

### 添加模型保存的相关代码

``` # 保存模型
def save(self, filename):
data = {"sizes": self.sizes,
"weights": [w.tolist() for w in self.weights],
"biases": [b.tolist() for b in self.biases],
"cost": str(self.cost.__name__)
}
f = open(filename, "w")
json.dump(data, f)
f.close()```

size是一个列表，定义了一共有多少层，每层有多少个神经元。保存模型权重。

w是numpy的array类型，调用它的tolist方法，把它转换成python的列表类型。

### 加载文件

```# 加载模型
f = open(filename, "r")
f.close()
cost = getattr(sys.modules[__name__], data["cost"])
net = Network(data["sizes"], cost=cost)
net.weights = [np.array(w) for w in data["weights"]]
net.biases = [np.array(b) for b in data["biases"]]
return net```

## 应用案例—-进阶版本的前馈神经网络代码的手写数字识别

mark

`            print("Epoch %s training complete" % j)`

```            cost = self.total_cost(training_data, lmbda)
print("Cost on training data: {}".format(cost))```

```            accuracy = self.accuracy(training_data, convert=True)
print("Accuracy on training data: {} / {}".format(accuracy, n))```

```            if test_data:
cost = self.total_cost(test_data, lmbda, convert=True)
print("Cost on test data: {}".format(cost))
accuracy = self.accuracy(test_data)
print("Accuracy on test data: {} / {}".format(accuracy, len(test_data)))```

### 实现两个函数 total_cost 和 accuracy

```    def accuracy(self, data, convert=False):
if convert:
results = [(np.argmax(self.feedforward(x)), np.argmax(y))
for (x, y) in data]
else:
# 预测结果[0,1,2,3...]中最大的。然后再把真实值保存下来成为一对。
results = [(np.argmax(self.feedforward(x)), y)
for (x, y) in data]
return sum(int(x == y) for (x, y) in results)```

``` def total_cost(self, data, lmbda, convert=False):
cost = 0.0
for x, y in data:
a = self.feedforward(x)
if convert: y = vectorized_result(y)
cost += self.cost.fn(a, y)/len(data)
cost += 0.5*(lmbda/len(data))*sum(
np.linalg.norm(w)**2 for w in self.weights)
return cost```

```def vectorized_result(j):
"""Return a 10-dimensional unit vector with a 1.0 in the j'th position
and zeroes elsewhere.  This is used to convert a digit (0...9)
into a corresponding desired output from the neural network.

"""
e = np.zeros((10, 1))
e[j] = 1.0
return e```
```if __name__ == '__main__':

# net = Network([784, 30, 10])
# net.SGD(traning_data, 30, 10, 0.5, test_data=test_data)

net = Network([784, 60, 10])
net.SGD(traning_data, 30, 10, 0.5, 5.0, test_data=test_data)```

mark

mark

0 篇文章106 人订阅

## 相关文章

2526

841

4505

3364

2304

1202

4145

21510

### 机器学习之线性代数

完整内容已上传到github：https://github.com/ZingP/machine-learning/tree/master/linear_al...

1961