题目:利用python/matlab,读入vibrationsignal.dat,数据有8列,第一列为测量时间,第8列为振动信号,请写出振动信号与时间的回归关系。
操作步骤与提示:
import numpy as np
import numpy.fft as nf
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置matplotlib上的中文字体
plt.rcParams['axes.unicode_minus'] = False # 在matplotlib 绘图正常显示符号
times = []
vibrations = []
with open('vibrationsignal.dat', 'r') as of:
# 获取第一行表头数据
firstline = of.readline()
# 删除字符串头尾的特定字符
firstline = firstline.strip('\n')
for line in of:
# 清除前后回车符,按照空格进行分割
line = line.strip('\n').split()
# 将测量时间保存进列表
times.append(float(line[0]))
# 将振动信号保存进列表
vibrations.append(float(line[7]))
times = np.array(times).reshape(-1, 1)
vibrations = np.array(vibrations)
x_train, x_test, y_train, y_test = train_test_split(times, vibrations, test_size=0.005, random_state=1)
# 建立线性模型
lr = LinearRegression()
# 训练线性模型
lr.fit(x_train, y_train)
# 进行预测
y_predict = lr.predict(x_test)
# 通过FFT得到频谱
y_test_fft = nf.fft(y_test)
y_test_fft = np.abs(y_test_fft)
y_predict_fft = nf.fft(y_predict)
y_predict_fft = np.abs(y_predict_fft)
# 归一化处理
y_test_fft = y_test_fft / len(y_test_fft)
y_predict_fft = y_predict_fft / len(y_predict_fft)
plt.plot(range(y_test.shape[0]), y_test, 'r', label="实际曲线")
plt.plot(range(y_predict.shape[0]), y_predict, "b:", label="预测曲线")
plt.title("时间与振动信号的线性回归模型")
plt.legend()
plt.xlabel("时间")
plt.ylabel("振动信号")
# 显示图像
plt.show()
结果: