Lang's Blog

Keep writing, Keep loving

环境: Tensorflow2.4.1
报错: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model.
产生原因: 采用了tf下的Keras 自定义损函数
分析:
损失函数部分代码:

1
2
3
4
5
6
def vae_loss(x, x_decoded_mean):
xent_loss = original_dim * losses.binary_crossentropy(x, x_decoded_mean)
print(type(xent_loss))
kl_loss = -0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
print(type(kl_loss))
return xent_loss + kl_loss

这是变分自编码的自定义损失函数,从中可以发现分别得到两种张量:

1
2
xent_loss --> tensorflow.python.framework.ops.Tensor
kl_loss --> tensorflow.python.keras.engine.keras_tensor.KerasTensor

自定义函数的输入是KerasTensor,但是默认的loss函数输出的是Tensor,KerasTensor和Tensor是完全不同的类,kera_tensor源码中可以发现Keras可以将Tensor转成KerasTensor,但是没发现将KerasTensor转成Tensor的部分。。。
所以。。。我们可以说:

1
Tensor+KerasTensor = KerasTensor

但是keras自定义损失函数输入的是KerasTensor,默认输出的是Tensor,而这里会导致输出KerasTensor,所以就报错了。

解决方案: 我采用的解决方案如下:

1
2
3
# 一般情况下采用该代码能够解决问题,可以发现函数返回结果已经转化成tensorflow.python.framework.ops.Tensor类了
from tensorflow.python.framework.ops import disable_eager_execution
disable_eager_execution()

所以keras还是避免使用吧,还是用的不太灵活的亚子,我还是老老实实学明白tensorflow怎么用吧~

tensorflow运行时会输出一大串的日志信息
眼花缭乱,用以下方法可以去除错误之外的日志信息(屏蔽通知信息和警告信息)

1
2
3
4
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import tensorflow as tf

切记:日志等级设置代码要放在导入tensorflow之前!

版本 Python 版本 编译器 构建工具 cuDNN CUDA
tensorflow_gpu-2.4.0 3.6-3.8 MSVC 2019 Bazel 3.1.0 8.0 11.0
tensorflow_gpu-2.3.0 3.5-3.8 MSVC 2019 Bazel 3.1.0 7.6 10.1
tensorflow_gpu-2.2.0 3.5-3.8 MSVC 2019 Bazel 2.0.0 7.6 10.1
tensorflow_gpu-2.1.0 3.5-3.7 MSVC 2019 Bazel 0.27.1-0.29.1 7.6 10.1
tensorflow_gpu-2.0.0 3.5-3.7 MSVC 2017 Bazel 0.26.1 7.4 10
tensorflow_gpu-1.15.0 3.5-3.7 MSVC 2017 Bazel 0.26.1 7.4 10
tensorflow_gpu-1.14.0 3.5-3.7 MSVC 2017 Bazel 0.24.1-0.25.2 7.4 10
tensorflow_gpu-1.13.0 3.5-3.7 MSVC 2015 update 3 Bazel 0.19.0-0.21.0 7.4 10
tensorflow_gpu-1.12.0 3.5-3.6 MSVC 2015 update 3 Bazel 0.15.0 7.2 9.0
tensorflow_gpu-1.11.0 3.5-3.6 MSVC 2015 update 3 Bazel 0.15.0 7 9
tensorflow_gpu-1.10.0 3.5-3.6 MSVC 2015 update 3 Cmake v3.6.3 7 9
tensorflow_gpu-1.9.0 3.5-3.6 MSVC 2015 update 3 Cmake v3.6.3 7 9
tensorflow_gpu-1.8.0 3.5-3.6 MSVC 2015 update 3 Cmake v3.6.3 7 9
tensorflow_gpu-1.7.0 3.5-3.6 MSVC 2015 update 3 Cmake v3.6.3 7 9
tensorflow_gpu-1.6.0 3.5-3.6 MSVC 2015 update 3 Cmake v3.6.3 7 9
tensorflow_gpu-1.5.0 3.5-3.6 MSVC 2015 update 3 Cmake v3.6.3 7 9
tensorflow_gpu-1.4.0 3.5-3.6 MSVC 2015 update 3 Cmake v3.6.3 6 8
tensorflow_gpu-1.3.0 3.5-3.6 MSVC 2015 update 3 Cmake v3.6.3 6 8
tensorflow_gpu-1.2.0 3.5-3.6 MSVC 2015 update 3 Cmake v3.6.3 5.1 8
tensorflow_gpu-1.1.0 3.5 MSVC 2015 update 3 Cmake v3.6.3 5.1 8
tensorflow_gpu-1.0.0 3.5 MSVC 2015 update 3 Cmake v3.6.3 5.1 8

tensorflow-gpu单离线包下载地址 清华镜像
tensorflow-gpu单离线包下载地址 豆瓣镜像
N卡驱动下载地址
CUDA下载地址
cuDNN下载地址(需登录N卡官网)
安装11版本的CUDA可能存在缺失的dll合集(bug) 访问码:2vmn

KNN简介:

k-Nearest Neighbor:kNN 即k近邻算法
分类问题:对新的样本,根据其k个最近邻的训练样本的类别,通过多数表决等方式进行预测。
回归问题:对新的样本,根据其k个最近邻的训练样本标签值的均值作为预测值。
优缺点:

  • k近邻模型具有非常高的容量,这使得它在训练样本数量较大时能获得较高的精度
  • 计算成本很高
  • 在训练集较小时,泛化能力很差,非常容易陷入过拟合
  • 无法判断特征的重要性

数据集采用阿里巴巴天池项目中的“渔船轨迹数据
本数据集为h5数据,运行代码目录结构如下
img

代码如下:

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
45
46
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
import pickle

data = pd.read_hdf("data/hy_round1_train_20200102.h5")
print(data.shape)
print(data.columns)
# 校验是否存在NaN
# print(np.all(pd.notnull(data)))

# 载入数据集
data = np.array(data)
# 量化标签
# print(np.where(data[:,-1] == "刺网"))
data[np.where(data[:,-1] == "刺网"),-1] = 0
data[np.where(data[:,-1] == "围网"),-1] = 1
data[np.where(data[:,-1] == "拖网"),-1] = 2
x_train, x_test, y_train, y_test = train_test_split(data[:,:-2],data[:,-1],test_size=0.25,random_state=42)
# 标准化(归一化存在离群点影响弊端)
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.fit_transform(x_test)
y_train = y_train.astype("int")
y_test = y_test.astype("int")
print(y_train)

# 模型训练
estimator = KNeighborsClassifier(n_neighbors=5)
estimator.fit(x_train,y_train)

# 保存模型
f = open("model/hy_knn_model.pickle","wb")
pickle.dump(estimator, f)

# 模型评估
# 预测值
y_predict = estimator.predict(x_test)
print("模型预测结果:\n", y_predict)
print("真实值对比结果:\n", y_test == y_predict)

# 准确率
score = estimator.score(x_test,y_test)
print("模型准确率:",score)

问题描述:

windows环境,python3,正确使用matplotlib绘图后存在的中文显示异常问题

解决方案:

1.找到当前python环境下如下文件

1
lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc

2.采用notepad++(文本编辑器)打开matplotlibrc

ctrl+f 搜索 font.family

根据定位寻找到”font.family“和”font.sans-serif“字段

取消注释或直接改成如下形式:

1
2
font.family: sans-serif
font.sans-serif: SimHei,Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif

如果存在负号显示异常则可以在添加一行
axes.unicode_minus:False
保存文件,重新加载python环境

img

本章记录:Redis6.0.6安装于Ubuntu中遇到的坑

注:使用前记得apt-get update一下

报错1:

1
2
python@python:/usr/local/redis$ sudo make
sudo: make: command not found

==解决方案:==

sudo apt-get install make

报错2:

1
2
3
4
5
6
7
8
9
10
11
make[3]: cc: Command not found
make[3]: *** [Makefile:201: net.o] Error 127
make[3]: Leaving directory '/usr/local/redis/deps/hiredis'
make[2]: *** [Makefile:50: hiredis] Error 2
make[2]: Leaving directory '/usr/local/redis/deps'
make[1]: [Makefile:264: persist-settings] Error 2 (ignored)
CC adlist.o
/bin/sh: 1: cc: not found
make[1]: *** [Makefile:315: adlist.o] Error 127
make[1]: Leaving directory '/usr/local/redis/src'
make: *** [Makefile:6: all] Error 2

解决方案:

sudo apt-get install gcc

报错3:

1
2
3
4
5
cc: error: ../deps/hiredis/libhiredis.a: No such file or directory
cc: error: ../deps/lua/src/liblua.a: No such file or directory
make[1]: *** [Makefile:283: redis-server] Error 1
make[1]: Leaving directory '/usr/local/redis/src'
make: *** [Makefile:6: all] Error 2

解决方案:

1
2
3
4
cd deps/
make lua hiredis linenoise
cd ..
sudo make

报错4:

You need tcl 8.5 or newer in order to run the Redis test

解决方案:

tcl8.6.1-src.tar.gz

1
2
3
4
5
tar zxvf tcl8.6.1-src.tar.gz
cd tcl8.6.1/unix/
./configure
make
sudo make install

1.备份源

ctrl+alt+t打开终端

sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak

2.打开源文件

用gedit打开源文件,ctrl+a全选删除,并粘贴更换源(任选一个)

sudo gedit /etc/apt/sources.list

bfsu源

18.04 LTS(bionic) 换源

1
2
3
4
deb https://mirrors.bfsu.edu.cn/ubuntu/ bionic main restricted universe multiverse
deb https://mirrors.bfsu.edu.cn/ubuntu/ bionic-updates main restricted universe multiverse
deb https://mirrors.bfsu.edu.cn/ubuntu/ bionic-backports main restricted universe multiverse
deb https://mirrors.bfsu.edu.cn/ubuntu/ bionic-security main restricted universe multiverse
清华源

20.04 LTS(focal) 换源

1
2
3
4
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-updates main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-backports main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-security main restricted universe multiverse

3.更新源

sudo apt-get update

LeetCode链表问题:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 两个已知链表对象ListNode l1, ListNode l2
输出:7 -> 0 -> 8
原因:342 + 465 = 807

1
2
3
graph LR
1((2)) --> 2((4)) --> 3((3))
4((5))--> 5((6)) --> 6((4))

1
2
graph LR
7((7)) --> 8((0)) --> 9((7))

备注:一开始是真没看懂题目。。。后来发现是反向存储的链表结构,又发现不知道ListNode这个类,,万事开头难,看着大家的方案题解,也琢磨了一份,并给出了详细的注释,算是留个笔记吧,继续努力!

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
45
46
47
48
49
50
51
52
53
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//记录结果,用于最后返回
ListNode root = new ListNode();
//存储过程中的游标
ListNode cursor = root;
//保存进位
int carry = 0;

//计算共同长度的部分
while(l1 != null && l2 != null){
int sumVal = l1.val + l2.val + carry;
cursor.next = new ListNode(sumVal % 10);
//计算进位
carry = sumVal / 10;

//下一节点
l1 = l1.next;
l2 = l2.next;
cursor = cursor.next;
}

//根据剩余长度构建存储节点
ListNode overplus = null;
overplus = l1 != null ? l1 : l2;

while(overplus != null){
int sumVal = overplus.val + carry;
cursor.next = new ListNode(sumVal % 10);
//计算进位
carry = sumVal / 10;

//下一节点
overplus = overplus.next;
cursor = cursor.next;
}

//判断是否有进位残留
if(carry != 0){
cursor.next = new ListNode(carry);
}

return root.next;
}
}

问题描述

我在实验室的电脑上的VS2017上编写好了相关代码,为了能够在自己电脑上也能同步编写,我配置好了github进行版本控制,采用推送和拉取进行项目同步,但是在我笔记本上拉取后程序却报出了未定义识别符的错误。

img

问题抽象

1.VS的集成编程环境

2.非本机构建的C++项目

3.程序本身没有问题,但拉取克隆到本机后出现了“未定义识别符”错误

解决方案

其实通过上面的问题抽象我已经能够推断问题原因了,出在了非本机项目的问题上,说明是环境不同所致,所以解决方案如下:

右键解决方案 >> 属性 >> 常规 >> Windows SDK 版本

换到本机安装的对应版本即可!

img

img

收工!

编程环境

python 3.6.8

tensorflow 1.12.3 离线包

matplotlib 3.1.2

numpy 1.17.4

数据集说明

我所采用的数据集,是我自己构建的一个网络流量数据集,借鉴了Wei Wang等人端到端的思想,

但是处理成的数据集却不同于他们的MNIST型数据集,而是采用的npy进行存储。

由于只是用于测试模型搭建,该数据集仅包含了一部分数据(Chat流量),

原数据来源于加拿大网络安全研究所的公开数据集(ISCX2016)

模型代码

训练模型部分:训练模型部分:

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from tensorflow import keras
from tensorflow.python.keras.layers import Dense, Dropout, Activation, Flatten, Conv1D, MaxPool1D
import matplotlib.pyplot as plt
import numpy as np
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# 数据集路径
dataset_path = 'dataset.npy'
# 接入softmax的全连接层维数
dense_num = 6
# 保存的模型文件路径
model_file = 'model/cnn_6traffic_model.h5'

# 数据集存储结构
# [training_images, training_labels, validation_images, validation_labels, testing_images, testing_labels]
data = np.load(dataset_path, allow_pickle=True)

x_train, y_train, x_test, y_test = np.array(data[0]), np.array(data[1]), np.array(data[2]), np.array(data[3])
print(x_train.shape, y_train.shape)

# 一维化
X_train = x_train.reshape(-1, 784, 1)
# print(X_train)
# X_train = X_train.astype('float32')
X_test = x_test.reshape(-1, 784, 1)
# X_test = X_test.astype('float32')


# 将像素值做归一化,也就是从0~255的取值压缩到0~1之间
# X_train /= 255
# X_test /= 255

# 构建模型
model = keras.models.Sequential()

# 卷积层1 + relu
# 25 卷积核的数量 即输出的维度
# 3 每个过滤器的长度
model.add(Conv1D(32, 3, activation='relu', input_shape=(784, 1), padding="same"))
# 池化层1
model.add(MaxPool1D(pool_size=3, strides=3))

# 卷积层2 + relu
model.add(Conv1D(64, 3, strides=1, activation='relu', padding='same'))
# 池化层2
model.add(MaxPool1D(pool_size=3, strides=3))

# 神经元随机失活
model.add(Dropout(0.25))
# 拉成一维数据
model.add(Flatten())
# 全连接层1
model.add(Dense(1024))
# 激活层
model.add(Activation('relu'))

# 随机失活
model.add(Dropout(0.4))
# 全连接层2
model.add(Dense(dense_num))
# Softmax评分
model.add(Activation('softmax'))

# 查看定义的模型
model.summary()

# 自定义优化器参数
# rmsprop = keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)

# lr表示学习速率
# decay是学习速率的衰减系数(每个epoch衰减一次)
# momentum表示动量项
# Nesterov的值是False或者True,表示使不使用Nesterov momentum
sgd = keras.optimizers.SGD(lr=0.01, decay=1e-4, momentum=0.9, nesterov=True)

model.compile(optimizer='sgd', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# 训练
history = model.fit(X_train, y_train, epochs=10, batch_size=1000,
verbose=1, validation_data=[X_test, y_test])

model.save(model_file)
print(history.params)

注:神经网络初涉,有啥问题请直接指出,谢谢!有流量识别领域的小伙伴欢迎打扰!相互交流!

说明:鉴于很多人问我数据集的问题,但写这个文章时所用的仅有“Chat”的流量的数据集我已经删除了,所以我在这里提供了包含有我已处理好的六类网络流量的npy数据集,有需要的自取天翼云盘地址(访问码:hp8m),鉴于之前的数据集是二分类的,但我提供的数据集的六个标签,所以代码中需要做出相应修改,我已将修改后的代码附上了。

0%