git 项目大瘦身

This commit is contained in:
jiangzhonglian
2019-10-11 16:48:36 +08:00
commit 81abcb3f3a
169 changed files with 35021 additions and 0 deletions

View File

@@ -0,0 +1,400 @@
# Keras 快速入门
* 安装: `pip install keras`
> Keras 发展生态支持
* 1.Keras 的开发主要由谷歌支持Keras API 以 tf.keras 的形式包装在 TensorFlow 中。
* 2.微软维护着 Keras 的 CNTK 后端。
* 3.亚马逊 AWS 正在开发 MXNet 支持。
* 4.其他提供支持的公司包括 NVIDIA、优步、苹果通过 CoreML等。
## Keras dataset 生产数据
```py
# With Numpy arrays
data = np.random.random((1000, 32))
labels = np.random.random((1000, 10))
model.evaluate(data, labels, batch_size=32)
# With a Dataset
dataset = tf.data.Dataset.from_tensor_slices((data, labels))
dataset = dataset.batch(32)
model.evaluate(dataset)
```
## Keras Sequential 顺序模型
顺序模型是多个网络层的线性堆叠目前支持2中方式
### 构造模型
> 1.构造器: 构建 Sequential 模型
```py
from keras.models import Sequential
from keras.layers import Dense, Activation
model = Sequential([
Dense(32, input_shape=(784,)),
Activation('relu'),
Dense(10),
Activation('softmax'),
])
```
> 2.add(): 构建 Sequential 模型
```py
from keras.models import Sequential
from keras.layers import Dense, Activation
model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
model.add(Dense(10)
model.add(Activation('softmax'))
```
### Dense: <https://keras.io/zh/layers/core>
Dense 指的是配置全连接层
```py
keras.layers.Dense(units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None)
# 参数
* units: 正整数输出空间维度
* activation: 激活函数 (详见 activations) 若不指定则不使用激活函数 (线性激活: a(x) = x)
* use_bias: 布尔值该层是否使用偏置向量
* kernel_initializer: kernel 权值矩阵的初始化器 (详见 initializers)
* bias_initializer: 偏置向量的初始化器 (see initializers).
* kernel_regularizer: 运用到 kernel 权值矩阵的正则化函数 (详见 regularizer)
* bias_regularizer: 运用到偏置向的的正则化函数 (详见 regularizer)
* activity_regularizer: 运用到层的输出的正则化函数 (它的 "activation") (详见 regularizer)
* kernel_constraint: 运用到 kernel 权值矩阵的约束函数 (详见 constraints)
* bias_constraint: 运用到偏置向量的约束函数 (详见 constraints)
```
例如:
```py
# 作为 Sequential 模型的第一层
model = Sequential()
# 现在模型就会以尺寸为 (*, 16) 的数组作为输入,
# 其输出数组的尺寸为 (*, 32)
model.add(Dense(32, input_shape=(16,)))
# 在第一层之后,你就不再需要指定输入的尺寸了:
model.add(Dense(32))
```
### Activation 激活函数: <https://keras-cn.readthedocs.io/en/latest/other/activations>
> 激活函数: 将线性问题变成非线性(回归问题变为分类问题),简单计算难度和复杂性。
sigmoid
hard_sigmoid
tanh
relu
softmax: 对输入数据的最后一维进行softmax输入数据应形如(nb_samples, nb_timesteps, nb_dims)或(nb_samples,nb_dims)
elu
selu: 可伸缩的指数线性单元Scaled Exponential Linear Unit参考Self-Normalizing Neural Networks
softplus
softsign
linear
## Keras compile 过程
```py
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test, verbose=2)
```
### 优化器 optimizer: <https://keras.io/optimizers>
> SGD
```py
keras.optimizers.SGD(learning_rate=0.01, momentum=0.0, nesterov=False)
```
例如:
```py
from keras import optimizers
sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='mean_squared_error', optimizer=sgd)
```
> RMSprop
```py
keras.optimizers.RMSprop(learning_rate=0.001, rho=0.9)
```
> Adagrad
```py
keras.optimizers.Adagrad(learning_rate=0.01)
```
> Adadelta
```py
keras.optimizers.Adadelta(learning_rate=1.0, rho=0.95)
```
> Adam
```py
keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False)
```
> Adamax
```py
keras.optimizers.Adamax(learning_rate=0.002, beta_1=0.9, beta_2=0.999)
```
> Nadam
```py
keras.optimizers.Nadam(learning_rate=0.002, beta_1=0.9, beta_2=0.999)
```
### 损失函数 loss: <https://keras.io/losses>
#### 回归
> mean_squared_error
```py
keras.losses.mean_squared_error(y_true, y_pred)
```
#### 二分类
> binary_crossentropy
```py
keras.losses.binary_crossentropy(y_true, y_pred, from_logits=False, label_smoothing=0)
```
#### 多分类
> categorical_crossentropy
```py
keras.losses.categorical_crossentropy(y_true, y_pred, from_logits=False, label_smoothing=0)
```
### 评价函数 metrics: <https://keras.io/zh/metrics>
评价函数: 用来衡量`真实值``预测值`的差异
> binary_accuracy
对二分类问题,计算在所有预测值上的平均正确率
```py
binary_accuracy(y_true, y_pred)
```
> categorical_accuracy
对多分类问题,计算再所有预测值上的平均正确率
```py
categorical_accuracy(y_true, y_pred)
```
> sparse_categorical_accuracy
与categorical_accuracy相同,在对稀疏的目标值预测时有用
```py
sparse_categorical_accuracy(y_true, y_pred)
```
> top_k_categorical_accuracy
计算top-k正确率,当预测值的前k个值中存在目标类别即认为预测正确
```py
top_k_categorical_accuracy(y_true, y_pred, k=5)
```
> sparse_top_k_categorical_accuracy
与top_k_categorical_accracy作用相同但适用于稀疏情况
```py
sparse_top_k_categorical_accuracy(y_true, y_pred, k=5)
```
## Keras load/save 模型持久化
> 保存模型
```py
import tensorflow as tf
# Save entire model to a HDF5 file
model.save('my_model.h5')
# Recreate the exact same model, including weights and optimizer.
model = tf.keras.models.load_model('my_model.h5')
```
> 仅保存权重值
```py
import tensorflow as tf
# Save weights to a TensorFlow Checkpoint file
model.save_weights('./weights/my_model')
# Restore the model's state,
# this requires a model with the same architecture.
model.load_weights('./weights/my_model')
# Save weights to a HDF5 file
model.save_weights('my_model.h5', save_format='h5')
# Restore the model's state
model.load_weights('my_model.h5')
```
> 仅保存模型配置
```py
import tensorflow as tf
# Serialize a model to json format
json_string = model.to_json()
fresh_model = tf.keras.models.model_from_json(json_string)
# Serialize a model to yaml format
yaml_string = model.to_yaml()
fresh_model = tf.keras.models.model_from_yaml(yaml_string)
```
---
补充损失函数
> mean_absolute_error
```py
keras.losses.mean_absolute_error(y_true, y_pred)
```
> mean_absolute_percentage_error
```py
keras.losses.mean_absolute_percentage_error(y_true, y_pred)
```
> mean_squared_logarithmic_error
```py
keras.losses.mean_squared_logarithmic_error(y_true, y_pred)
```
> squared_hinge
```
keras.losses.squared_hinge(y_true, y_pred)
```
> hinge
```py
keras.losses.hinge(y_true, y_pred)
```
> categorical_hinge
```py
keras.losses.categorical_hinge(y_true, y_pred)
```
> logcosh
```py
keras.losses.logcosh(y_true, y_pred)
```
> huber_loss
```py
keras.losses.huber_loss(y_true, y_pred, delta=1.0)
```
> sparse_categorical_crossentropy
```py
keras.losses.sparse_categorical_crossentropy(y_true, y_pred, from_logits=False, axis=-1)
```
> kullback_leibler_divergence
```py
keras.losses.kullback_leibler_divergence(y_true, y_pred)
```
> poisson
```py
keras.losses.poisson(y_true, y_pred)
```
> cosine_proximity
```py
keras.losses.cosine_proximity(y_true, y_pred, axis=-1)
```
> is_categorical_crossentropy
```py
keras.losses.is_categorical_crossentropy(loss)
```

View File

View File

@@ -0,0 +1,185 @@
# Ubuntu16.04安装TensorFlow2.x CPU和GPU必备指南
* CPU安装: `pip install tensorflow`
* GPU安装: `pip install tensorflow-gpu` 【**`别慌GPU需要先安装以下内容`**】
* 注意: 不要同时安装
> 硬件要求
支持以下启用GPU的设备
* 具有CUDA®Compute Capability 3.5或更高版本的NVIDIA®GPU卡。请参阅[支持CUDA的GPU卡](https://developer.nvidia.com/cuda-gpus)列表 。
> 软件需求
您的系统上必须安装以下NVIDIA®软件
* NVIDIA®GPU [驱动程序](https://www.nvidia.com/drivers) CUDA 10.0需要410.x或更高版本。
* [CUDA®工具包](https://developer.nvidia.com/cuda-toolkit-archive) - TensorFlow支持CUDA 10.0TensorFlow> = 1.13.0
* [CUPTI](http://docs.nvidia.com/cuda/cupti/)随附CUDA工具包。
* [cuDNN SDK](https://developer.nvidia.com/cudnn)> = 7.4.1
* *(可选)* [TensorRT 5.0](https://docs.nvidia.com/deeplearning/sdk/tensorrt-install-guide/index.html) 可以改善延迟和吞吐量,以在某些模型上进行推断。
## 1.安装 NVIDIA 驱动
```shell
$ wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/nvidia-machine-learning-repo-ubuntu1604_1.0.0-1_amd64.deb
$ sudo apt install ./nvidia-machine-learning-repo-ubuntu1604_1.0.0-1_amd64.deb
$ sudo apt-get update
$ ubuntu-drivers devices # 查看推荐的版本安装
== /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0 ==
modalias : pci:v000010DEd000017C8sv00001458sd000036B6bc03sc00i00
vendor : NVIDIA Corporation
model : GM200 [GeForce GTX 980 Ti]
driver : nvidia-387 - third-party non-free
driver : nvidia-410 - third-party non-free
driver : nvidia-384 - third-party non-free
driver : nvidia-430 - third-party free recommended # 推荐安装
driver : xserver-xorg-video-nouveau - distro free builtin
driver : nvidia-396 - third-party non-free
driver : nvidia-390 - third-party non-free
driver : nvidia-418 - third-party non-free
driver : nvidia-415 - third-party free
# no-install-recommends参数来避免安装非必须的文件从而减小镜像的体积
$ sudo apt-get install --no-install-recommends nvidia-430 -y
正在读取软件包列表... 完成
正在分析软件包的依赖关系树
正在读取状态信息... 完成
将会同时安装下列软件:
lib32gcc1 libc-dev-bin libc6 libc6-dbg libc6-dev libc6-i386
建议安装:
glibc-doc
推荐安装:
libcuda1-430 nvidia-opencl-icd-430
下列【新】软件包将被安装:
lib32gcc1 libc6-i386 nvidia-430
下列软件包将被升级:
libc-dev-bin libc6 libc6-dbg libc6-dev
升级了 4 个软件包,新安装了 3 个软件包,要卸载 0 个软件包,有 260 个软件包未被升级。
需要下载 99.7 MB/111 MB 的归档。
解压缩后会消耗 429 MB 的额外空间。
您希望继续执行吗? [Y/n] Y
获取:1 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu xenial/main amd64 nvidia-430 amd64 430.26-0ubuntu0~gpu16.04.1 [99.7 MB]
25% [1 nvidia-430 492 kB/99.7 MB 0%] 563 B/s 2天 0小时 58分 14秒58秒
...
92% [1 nvidia-430 93.0 MB/99.7 MB 93%] 4,111 B/s 27分 28秒
已下载 7,180 kB耗时 4分 26秒 (26.9 kB/s)
Running module version sanity check.
- Original module
- No original module exists within this kernel
- Installation
- Installing to /lib/modules/4.10.0-28-generic/updates/dkms/
depmod....
DKMS: install completed.
正在处理用于 libc-bin (2.23-0ubuntu10) 的触发器 ...
正在处理用于 initramfs-tools (0.122ubuntu8.14) 的触发器 ...
update-initramfs: Generating /boot/initrd.img-4.10.0-28-generic
# $ sudo reboot # 安装完需要重启电脑
$ sudo nvidia-smi
```
这里面大家需要注意的是: 采用在终端输入 `ubuntu-drivers devices` 会提示推荐你用什么版本我的设备显示不出来所以安装的是418.43这个型号的驱动。(目前最新版本)
注意事项一:官网下载地址
推荐网址:(https://www.geforce.cn/drivers)只有这个GeForce型号的别的型号推荐去其对应的网址查询。
注意事项二:不要在下面这个网址下载,不是不能,最直接的官网,对应的东西最新,也最详细
网址如下(https://www.nvidia.com/Download/index.aspx?lang=cn)
理由:
* 1上面的网址选择驱动型号点进去可以看到许多详细的信息尤其是它支持什么样的显卡都有特别详细。
* 2这个网址在我写博客2019.3.6为止还没有GTX1660Ti的Ubuntu驱动
注意事项三:具体操作见网上别人写好的。
## 2.安装 CUDA 1.0 + cuDNN 7
> CUDA
下面这个网址是tensorflow各环境参数对应版本图(https://tensorflow.google.cn/install/source)可供参考。cuda和cudnn对应关系应该没问题但是tensorflow版本不能过高否则会出错。
注意事项一:下载地址
cuda下载网址为(https://developer.nvidia.com/)右上角搜索“CUDA Toolkit Archive”点击第一个最新的的进去里面有许多版本可供选择切记切记!切记目前网友的说法是tensorflow只能支持cuda9.0及以下版本。
注意事项二选择run下载而不选择del
这个具体是什么原因没搞明白网友也强烈推荐run,我之前试过del的失败了所以大家尽量采用run这种方法。可能有人没明白说明意思你在选择的时候多留个心眼就注意到了。
> cuDNN
官网网址如下
网址:<https://developer.nvidia.com/cudnn>
需要注册,我是从别人那直接过来的,就没注册,大家需要的自己去,这个安装相对简单。
同样有验证的过程,这个相对来说是简单的,没什么需要太注意的,跟着网上的走就好了。
> 执行命令
```shell
$ sudo apt-get install gnupg-curl
$ wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/cuda-repo-ubuntu1604_10.0.130-1_amd64.deb
$ sudo dpkg -i cuda-repo-ubuntu1604_10.0.130-1_amd64.deb
$ sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/7fa2af80.pub
$ sudo apt-get update -y
# sudo apt-get install cuda
$ sudo apt-get install --no-install-recommends \
cuda-10-0 \
libcudnn7=7.6.2.24-1+cuda10.0 \
libcudnn7-dev=7.6.2.24-1+cuda10.0
$ sudo apt-get install -y --no-install-recommends libnvinfer5=5.1.5-1+cuda10.0 libnvinfer-dev=5.1.5-1+cuda10.0
```
## 3.安装TensorFlow并验证
* GPU安装: `sudo pip3 install tensorflow-gpu`
```shell
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
```
结果:
```
>>> from __future__ import absolute_import, division, print_function, unicode_literals
>>>
>>> import tensorflow as tf
>>> print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
2019-10-10 16:12:15.524570: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1
2019-10-10 16:12:15.537451: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1006] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-10-10 16:12:15.538341: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1618] Found device 0 with properties:
name: GeForce GTX 980 Ti major: 5 minor: 2 memoryClockRate(GHz): 1.2405
pciBusID: 0000:01:00.0
2019-10-10 16:12:15.538489: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.0
2019-10-10 16:12:15.539261: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10.0
2019-10-10 16:12:15.539899: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10.0
2019-10-10 16:12:15.540081: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10.0
2019-10-10 16:12:15.540886: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10.0
2019-10-10 16:12:15.541540: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10.0
2019-10-10 16:12:15.543506: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7
2019-10-10 16:12:15.543601: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1006] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-10-10 16:12:15.544469: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1006] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-10-10 16:12:15.545326: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Adding visible gpu devices: 0
Num GPUs Available: 1
```
---
信息来源:
* <https://tensorflow.google.cn/install/gpu>
* <https://tensorflow.google.cn/guide/gpu>
* <https://blog.csdn.net/qq_44774398/article/details/99832436>
* <https://blog.csdn.net/weixin_43012220/article/details/88241766>