前言
镇楼:茴字有13种写法其实才是深入学习的有效方式
之前的例子我们已经可以训练任何一元函数的数据了,再继续深入其他数据之前,我们来试一下任意手绘曲线数据来检验成果。
提示:以下是本篇文章正文内容,下面案例可供参考
一、手绘曲线数据的获取
找遍csdn竟然没有找到几个简单可用的曲线读取案例,我们来尝试自己做一个:
读取曲线的步骤
1, 画图
打开系统自带的画板(mspaint),手画一条曲线,另存为png格式,如下图,我们特意加了一些黄色的杂线。特别要注意,曲线不要有重叠,比如8字型,就是一个 x 不能推出2个y值。
如果是从其他地方拍照得到的曲线,需要手工处理掉不需要的部分,保存为png格式。
2, 图像处理
将图像进行二值化处理,即只有黑白色的图片,代码如下:
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 26 16:09:43 2021
@author: huwp001
Dependencies:
matplotlib
numpy
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as img
# 彩色图转灰度图的函数, 0是黑色,1是白色,seg 是分隔值(0~1),只保留小于seg的颜色
def rgb2gray(rgb, seg):
# 3维的rgb颜色 转 1维的黑白颜色
gray = np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
# 只保留小于 seg的 颜色。
gray = np.minimum(gray, seg)
gray[gray<seg]=0
gray = 1 - gray
gray[gray>seg]=1
gray[gray<=seg]=0
# 这里得到的只有 0和1
return gray
# 读取图像并按颜色深度过滤,得到黑白二值图, 0 黑,1 白
da = rgb2gray(img.imread('d:/1.png'), 0.5)
# 打印过滤处理后的图像
plt.imshow(da, cmap='Greys_r')
运行效果如下,可见那些黄色的部分都过滤掉了。
3,修正数据
去掉图片上下左右的空白部分,具体方法:
- 从上往下循环,直到该行有值1出现后停止循环,前面的行都删掉
- 从下往上循环,直到该行有值1出现后停止循环,已经出现的全部为0的行都删掉
- 从左往后循环所有的列,列有1的时候停止,已经出现的全部为0的列都删掉
- 从右往左循环所有的列,列有1的时候停止,已经出现的全部为0的列都删掉
源码后面一起贴,运行效果如下:
4,获取曲线
计算方法:逐列循环,计算坐标,如果某列有多个 1,对所有1 的下标取平均值。
5,完整源码
整个流程的完整源码如下:
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 15:09:51 2021
@author: huwp001
Dependencies:
matplotlib
numpy
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as img
# 彩色图转灰度图的函数, 0是黑色,1是白色,seg 是分隔值(0~1),只保留小于seg的颜色
def rgb2gray(rgb, seg):
# 3维的rgb颜色 转 1维的黑白颜色
gray = np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
# 只保留小于 seg的 颜色。
gray = np.minimum(gray, seg)
gray[gray<seg]=0
gray = 1 - gray
gray[gray>seg]=1
gray[gray<=seg]=0
# 这里得到的只有 0和1
return gray
# 去除上下部分的空白
def removeUpDownWhite(da):
p0=0
for row in da:
if np.max(row)>0:
break
p0 = p0 +1
# 截取从pa行开始到末尾
da2 = da[p0-1:-1]
# 倒叙
da3 = np.flipud(da2)
p1=0
for row in da3:
if np.max(row)>0:
break
p1 = p1 +1
# 截取 前 da2.shape[0]-p1 行
da4 = da2[0:(da2.shape[0] - p1)]
return da4
# 去除左右部分的空白
def removeLeftRightWhite(da):
d1 = np.sum(da, axis=0) #按列求和
p0=0
for o in d1:
if o>0:
break
p0 = p0 +1
# 倒叙
da3 = np.flipud(d1)
p1=0
for o in da3:
if o>0:
break
p1 = p1 +1
# 截取 前 da2.shape[0]-p1 行
da4 = da[:,p0:(d1.shape[0] - p1)]
return da4
# 转换矩形为 曲线的值
def convert(da):
x = np.empty(0)
y = np.empty(0)
for j in range(da.shape[1]):
a = da[:, j:j+1].flatten()
idxs = np.empty(0)
for i in range(a.size):
if a[i]>0 :
idxs = np.append(idxs, a.size - i)
x = np.append(x, j)
y = np.append(y, 0 if idxs.size==0 else np.mean(idxs))
return np.concatenate((x[:, np.newaxis], y[:, np.newaxis]), axis=1)
# 读取图像并按颜色深度过滤,得到黑白二值图, 0 黑,1 白
da = rgb2gray(img.imread('d:/1.png'), 0.5)
# 打印过滤处理后的图像
#plt.imshow(da, cmap='Greys_r')
da1 = removeUpDownWhite(da)
da2 = removeLeftRightWhite(da1)
# 打印去掉上下左右空白的原始曲线
#plt.imshow(da2, cmap='Greys_r')
# 转换为 二维数组
arr = convert(da2)
# 打印曲线数据
plt.scatter(arr[:, 0:1], arr[:, 1:2])
运行结果如下,跟原图比还不错:
二、机器学习
1,增加噪点
拿到的手绘曲线非常平滑,我们给他增加一点噪点,代码如下:
arr = np.genfromtxt('d:/1.csv', delimiter=',')
xraw = arr[:, 0:1]
yraw = arr[:, 1:2]
noise = np.random.normal(0, 0.1, size=xraw.shape)
# 归一化
x = (xraw - xraw.min()) / (xraw.max() - xraw.min())
y = (yraw - yraw.min()) / (yraw.max() - yraw.min())
y = y + noise
2,模型调整
模型的层数稍微修改一下,代码如下:
#构建模型
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(10, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.relu),
tf.keras.layers.Dense(1)
])
3,源码
完整的训练代码如下:
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 14:06:24 2021
@author: huwp001
Dependencies:
tensorflow: 2.0
matplotlib
numpy
从csv读取曲线数据,增加噪点,进行训练
"""
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# data
arr = np.genfromtxt('d:/1.csv', delimiter=',')
xraw = arr[:, 0:1]
yraw = arr[:, 1:2]
noise = np.random.normal(0, 0.1, size=xraw.shape)
# 归一化, 注意这个归一化会影响线条走势
x = (xraw - xraw.min()) / (xraw.max() - xraw.min())
y = (yraw - yraw.min()) / (yraw.max() - yraw.min())
y = y + noise
#plt.scatter(x, y)
x = tf.constant(x, dtype=tf.float32)
y = tf.constant(y, dtype=tf.float32)
# 最多训练次数
max_num_epoch = 20000
# 当前训练次数
index_epoch = 0
# 在训练的时候输出进度图
class PrintDot(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs):
global index_epoch, max_num_epoch
if (epoch+1) % 10 == 0 or epoch==max_num_epoch-1:
print(epoch, logs['loss'])
y_pred = model.predict(x)
plt.cla()
plt.scatter(x, y)
plt.plot(x, y_pred, 'r-', lw=5)
plt.pause(0.1)
index_epoch = epoch
def on_train_end(self, logs=None):
print(index_epoch, logs)
# patience 值用来检查改进 epochs 的数量
# 大约意思是 如果 每次训练 loss的变动 小于 0.0001 ,则为学习没有进展
# 如果连续100次没有进展,结束训练
early_stop = tf.keras.callbacks.EarlyStopping(monitor='loss', min_delta=0.0001, patience=100)
#构建模型
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(10, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.relu),
tf.keras.layers.Dense(1)
])
# 编译模型,设置了损失函数,优化器,评估工具
model.compile(
optimizer=tf.keras.optimizers.SGD(learning_rate=5e-2),
loss=tf.losses.MeanSquaredError(),
metrics=['mae', 'mse']
)
# 训练模型
# validation_split 表示边训练,边验证的比例。 Fraction of the training data to be used as validation data
history = model.fit(x, y, epochs=max_num_epoch,
# validation_split=0.2,
callbacks=[early_stop, PrintDot()],
use_multiprocessing=True,
verbose=0)
hist = pd.DataFrame(history.history)
hist['epoch'] = history.epoch
hist.tail()
def plot_history(history):
hist = pd.DataFrame(history.history)
hist['epoch'] = history.epoch
plt.figure()
plt.xlabel('Epoch')
plt.ylabel('Mean Abs Error [MPG]')
plt.plot(hist['epoch'], hist['mae'],
label='mae Train Error')
if 'val_mae' in hist.columns:
plt.plot(hist['epoch'], hist['val_mae'],
label = 'mae Val Error')
plt.legend()
plt.xlabel('Epoch')
plt.ylabel('Mean Square Error [$MPG^2$]')
plt.plot(hist['epoch'], hist['mse'],
label='mse Train Error')
if 'val_mse' in hist.columns:
plt.plot(hist['epoch'], hist['val_mse'],
label = 'mse Val Error')
#plt.ylim([0,20])
plt.legend()
plt.show()
plot_history(history)
4,运行
结果如下图,跟原始手绘图基本吻合。但是有明显的图像压缩,是因为原始数据我们做了归一化,所以图像看起来跟 手绘图比是 压缩了。
另外,如果我不添加噪点, 就使用原始数据直接训练,注释如下代码:
# y = y + noise
运行结果如图,完美拟合:
3.其他
tensorflow 开发环境 前往
总结
本章内容实现了完整的读取任意手绘曲线并进行机器学习,那么,平面数据的学习就截止了,后续进行预测分类方面的研究。