0%

一直都对这两个函数的一些概念理不清楚,今天就整理一下,结合吴恩达老师和李沐给出的Tensorflow的coding过程,一并整理厘清概念和这两者的区别。

Sigmoid

Sigmoid通常用于逻辑回归Logistic Regression的二分类中,output出一个概率值(比如:预测一张图片是一只猫的概率)。它的公式为: \[ \frac{1}{1+e^{-z}} \] 图示为:

特点:y的值是介于[0,1]之间的,而x是负无穷到正无穷的。x=0时,y=0.5。

LR的网络结构为:

在将Sigmoid用于LR任务中时,模型的输入是一个特征向量X,这时的loss function使用:

这里不会使用MSE,原因是:

loss function是在单个训练样本中定义的,它衡量的是算法在单个训练样本中表现如何,为了衡量算法在全部训练样本上的表现,需要定义代价函数(cost function),在LR中代价函数即为对m个样本的损失函数求和再平均:

虽然有这么多计算步骤,但是在tensorflow中,我们并不需要自己计算sigmoid后的值a,然后将a和y放到J函数中计算中整体的cost,只需要一个函数就可以帮助我们实现。

tf.nn.sigmoid_cross_entropy_with_logits(logits=z,labels=y)

注意:上述的z是before the final sigmoid activation的值,也就是还没有传入Sigmoid前,只是经过线性计算后的值。

Softmax

softmax函数是对sigmoid的推广,用于处理多分类的问题。公式:

它的输入是一个向量,输出也是一个向量。不同于Sigmoid的输入(实数),输出(介于0,1之间的概率值)。Sigmoid的输出是一个向量,其中 向量中的每一个元素的范围都在(0,1)之间,它能将一个含任意实数的K维向量压缩到另一个K维向量中。

它在线性模型中的应用方式为:对接最后一层,输出一个向量。

它的loss function是:

其中q为输出向量y的维度。

那么它的cost function J应该是将整个训练集的损失总和: 通常叫做cross-entropy loss交叉熵损失函数

在tensorflow中该过程只需要一个函数来实现:

tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = labels))

  • 其中logits也是传入softmax激活函数之前的结果,也就是经过线性计算之后的Z
  • logits和labels也必须是相同的shape (num of examples, num_classes)

用tensorflow的完整实现即为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def compute_cost(Z3, Y):
"""
Arguments:
Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples)
Y -- "true" labels vector placeholder, same shape as Z3

Returns:
cost - Tensor of the cost function
"""
# to fit the tensorflow requirement for tf.nn.softmax_cross_entropy_with_logits(...,...)
logits = tf.transpose(Z3)
labels = tf.transpose(Y)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = labels))

return cost

optimizer = tf.train.GradientDescentOptimizer(learning_rate = learning_rate).minimize(cost)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# Do the training loop
for epoch in range(num_epochs):

epoch_cost = 0. # Defines a cost related to an epoch
num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set
seed = seed + 1
minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed)

for minibatch in minibatches:

# Select a minibatch
(minibatch_X, minibatch_Y) = minibatch

# IMPORTANT: The line that runs the graph on a minibatch.
# Run the session to execute the "optimizer" and the "cost", the feedict should contain a minibatch for (X,Y).
_ , minibatch_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y})

epoch_cost += minibatch_cost / num_minibatches

# Print the cost every epoch
if print_cost == True and epoch % 100 == 0:
print ("Cost after epoch %i: %f" % (epoch, epoch_cost))
if print_cost == True and epoch % 5 == 0:
costs.append(epoch_cost)

以上的实现是将里面的计算步骤都展示出来的实现,也就是我们得到Z之后再进一步的得到loss。在李沐的教程中,用tensorflow实现softmax回归使用了更高级的API来实现。

tensorflow keras模块对softmax更简洁的实现

softmax回归的输出层是一个全连接层。因此,为了实现我们的模型,我们只需在Sequential中添加一个带有10个输出的全连接层。同样,在这里,Sequential并不是必要的,但我们可能会形成这种习惯。因为在实现深度模型时,Sequential将无处不在。我们仍然以均值0和标准差0.01随机初始化权重。

1
2
3
4
net = tf.keras.models.Sequential()
net.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
weight_initializer = tf.keras.initializers.RandomNormal(mean=0.0, stddev=0.01)
net.add(tf.keras.layers.Dense(10, kernel_initializer=weight_initializer))

以上实现的输入是28*28大小的灰度图片,分类类别数为10。

在这里,我们使用学习率为0.1的小批量随机梯度下降作为优化算法

1
2
3
4
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
trainer = tf.keras.optimizers.SGD(learning_rate=.1)
num_epochs = 10
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)

mysql 查看当前使用的配置文件my.cnf的方法

my.cnf是mysql启动时加载的配置文件,一般会放在mysql的安装目录中,用户也可以放在其他目录加载。

安装mysql后,系统中会有多个my.cnf文件,有些是用于测试的。

使用locate my.cnf命令可以列出所有的my.cnf文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
命令
locate my.cnf

输出
/usr/local/Cellar/mysql/5.6.24/my.cnf
/usr/local/Cellar/mysql/5.6.24/mysql-test/include/default_my.cnf
/usr/local/Cellar/mysql/5.6.24/mysql-test/suite/federated/my.cnf
/usr/local/Cellar/mysql/5.6.24/mysql-test/suite/ndb/my.cnf
/usr/local/Cellar/mysql/5.6.24/mysql-test/suite/ndb_big/my.cnf
/usr/local/Cellar/mysql/5.6.24/mysql-test/suite/ndb_binlog/my.cnf
/usr/local/Cellar/mysql/5.6.24/mysql-test/suite/ndb_rpl/my.cnf
/usr/local/Cellar/mysql/5.6.24/mysql-test/suite/ndb_team/my.cnf
/usr/local/Cellar/mysql/5.6.24/mysql-test/suite/rpl/extension/bhs/my.cnf
/usr/local/Cellar/mysql/5.6.24/mysql-test/suite/rpl/my.cnf
/usr/local/Cellar/mysql/5.6.24/mysql-test/suite/rpl_ndb/my.cnf

当我们需要修改配置文件时,需要找到mysql启动时是加载了哪个my.cnf文件。

查看是否使用了指定目录的my.cnf

启动mysql后,我们查看mysql的进程,看看是否有设置使用指定目录的my.cnf文件,如果有则表示mysql启动时是加载了这个配置文件。

1
2
3
4
5
6
命令
ps aux|grep mysql|grep 'my.cnf'

输出
fdipzone 25174 0.0 0.0 3087244 600 ?? S 4:12下午 0:01.14 /usr/local/Cellar/mysql/5.6.24/bin/mysqld --defaults-file=/usr/local/Cellar/mysql/5.6.24/my.cnf --basedir=/usr/local/Cellar/mysql/5.6.24 --datadir=/usr/local/var/mysql --plugin-dir=/usr/local/Cellar/mysql/5.6.24/lib/plugin --bind-address=127.0.0.1 --log-error=/usr/local/var/mysql/TerrydeMacBook-Air.local.err --pid-file=/usr/local/var/mysql/TerrydeMacBook-Air.local.pid
fdipzone 25064 0.0 0.0 2452824 4 ?? S 4:12下午 0:00.03 /bin/sh /usr/local/opt/mysql/bin/mysqld_safe --defaults-file=/usr/local/Cellar/mysql/5.6.24/my.cnf --bind-address=127.0.0.1 --datadir=/usr/local/var/mysql

可以看到/usr/local/Cellar/mysql/5.6.24/my.cnf就是mysql启动加载的配置文件。

如果上面的命令没有输出,表示没有设置使用指定目录的my.cnf。

查看mysql默认读取my.cnf的目录

如果没有设置使用指定目录的my.cnf,mysql启动时会读取安装目录根目录及默认目录下的my.cnf文件。

查看mysql启动时读取配置文件的默认目录。

1
2
3
4
5
6
命令
mysql --help|grep 'my.cnf'

输出
order of preference, my.cnf, $MYSQL_TCP_PORT,
/etc/my.cnf /etc/mysql/my.cnf /usr/local/etc/my.cnf ~/.my.cnf

/etc/my.cnf, /etc/mysql/my.cnf, /usr/local/etc/my.cnf, ~/.my.cnf 这些就是mysql默认会搜寻my.cnf的目录,顺序排前的优先。

启动时没有使用配置文件

如果没有设置使用指定目录my.cnf文件及默认读取目录没有my.cnf文件,表示mysql启动时并没有加载配置文件,而是使用默认配置。

需要修改配置,可以在mysql默认读取的目录中,创建一个my.cnf文件(例如:/etc/my.cnf),把需要修改的配置内容写入,重启mysql后即可生效。

mysql使用group by查询报错SELECT list is not in GROUP BY clause and contains nonaggregated column...解决方案

MySQL5.7.5后only_full_group_by成为sql_mode的默认选项之一,这可能导致一些sql语句失效。 比如在使用group by进行分组查询报错

查看自己的sql_mode配置

1
在sql命令行中输入select @@sql_mode;这时我们能够看到自己的sql_mode配置,其中如果有ONLY_FULL_GROUP_BY,那它就是group by查询报错的罪魁祸首了

解决办法

命令行打开mysql.cnf,默认路径为/etc/mysql/conf.d/mysql.cnf,如果找不到可以使用whereis进行查询

1
sql_mode = STRICT_TRANS_TABLES, NO_ZERO_IN_DATE, NO_ZERO_DATE, ERROR_FOR_DIVISION_BY_ZERO,      NO_AUTO_CREATE_USER, NO_ENGINE_SUBSTITUTION

保存退出重启mysql

1
sudo service mysqld restart #对于linux是mysql

Anaconda 安装包可以到 https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/ 下载。

TUNA 还提供了 Anaconda 仓库与第三方源(conda-forge、msys2、pytorch等,查看完整列表)的镜像,各系统都可以通过修改用户目录下的 .condarc 文件。Windows 用户无法直接创建名为 .condarc 的文件,可先执行 conda config --set show_channel_urls yes 生成该文件之后再修改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
channels:
- defaults
show_channel_urls: true
channel_alias: https://mirrors.tuna.tsinghua.edu.cn/anaconda
default_channels:
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/pro
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2
custom_channels:
conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
msys2: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
bioconda: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
menpo: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
simpleitk: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud

一般表示 conda 应用程序的配置文件,在用户的家目录(windows:C:\users\username\,linux:/home/username/)。但对于.condarc配置文件,是一种可选的(optional)运行期配置文件,其默认情况下是不存在的,但当用户第一次运行 conda config命令时,将会在用户的家目录创建该文件。

换国内源

  • 查看现在的源地址:conda config --show-sources
  • 设置搜索时显示通道地址 conda config --set show_channel_urls yes
  • 添加镜像源 conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free

虚拟环境

常用命令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
conda list 查看安装了那些包

conda env list或者conda info -e 查看当前存在哪些虚拟环境

conda update conda 更新当前conda

conda create -n env_name python=3.6 创建虚拟环境

activate env_name 激活某虚拟环境

python --version 检查当前python版本

conda install -n env_name [package] 安装某个包至某一个虚拟环境下

deactivate 关闭当前虚拟环境

conda remove -n env_name --all 删除某虚拟环境

conda remove package_name 删除某个包
pip unistall package_name

conda env export > requirements.yaml 将当前环境下安装的包保存为yaml文件
conda env update -f=/path/requirements.yaml

(如果不要conda,用pip的时候导出的是txt文件)
pip freeze > requirements.txt
pip install -r /path/requirements.txt