73 lines
2.8 KiB
Python
73 lines
2.8 KiB
Python
# 导入必要库
|
||
import pandas as pd
|
||
import matplotlib.pyplot as plt
|
||
from sklearn.linear_model import LinearRegression
|
||
import numpy as np
|
||
|
||
# 设置中文字体(避免中文乱码)
|
||
plt.rcParams['font.sans-serif'] = ['WenQuanYi Zen Hei']
|
||
plt.rcParams['axes.unicode_minus'] = False
|
||
|
||
# 1. 读取数据
|
||
df = pd.read_csv('/mnt/code_20251204.csv')
|
||
# 验证数据结构
|
||
print("数据前5行:")
|
||
print(df.head())
|
||
print("\n数据列名:", df.columns.tolist())
|
||
|
||
# 2. 数据预处理(定义自变量X和因变量y)
|
||
X = df['时间(秒)'].values.reshape(-1, 1) # 时间转为二维数组(模型要求)
|
||
y = df['V2(mV)'].values # V2电压值
|
||
|
||
# 3. 构建线性回归模型
|
||
model = LinearRegression()
|
||
model.fit(X, y)
|
||
# 计算回归参数
|
||
slope = model.coef_[0] # 斜率(每秒电压变化量)
|
||
intercept = model.intercept_ # 截距(初始电压预测值)
|
||
r_squared = model.score(X, y) # 决定系数R²(拟合优度)
|
||
# 生成回归预测值
|
||
y_pred = model.predict(X)
|
||
|
||
# 4. 绘制图表
|
||
fig, ax = plt.subplots(figsize=(12, 8))
|
||
|
||
# 绘制原始数据折线
|
||
ax.plot(df['时间(秒)'], y, color='#1f77b4', linewidth=2.5,
|
||
marker='o', markersize=8, label='V2原始电压')
|
||
# 绘制线性回归趋势线
|
||
ax.plot(df['时间(秒)'], y_pred, color='#d62728', linewidth=2,
|
||
linestyle='--', label=f'线性回归趋势 (R²={r_squared:.4f})')
|
||
|
||
# 添加数据点数值标签
|
||
for i, (x, y_val) in enumerate(zip(df['时间(秒)'], y)):
|
||
ax.annotate(f'{y_val:.2f}', (x, y_val),
|
||
textcoords="offset points", xytext=(0,10),
|
||
ha='center', fontsize=9, color='#1f77b4')
|
||
|
||
# 设置图表样式
|
||
ax.set_title('V2电压随时间变化曲线(含线性回归)', fontsize=16, fontweight='bold', pad=20)
|
||
ax.set_xlabel('时间(秒)', fontsize=12, fontweight='bold')
|
||
ax.set_ylabel('V2电压(mV)', fontsize=12, fontweight='bold')
|
||
ax.set_xlim(-10, 280) # 横轴范围微调,避免数据贴边
|
||
ax.set_ylim(1.8, 2.4) # 纵轴范围微调,突出变化趋势
|
||
ax.grid(True, alpha=0.3, linestyle='-', linewidth=0.5) # 添加网格线
|
||
ax.legend(fontsize=11, loc='upper right') # 图例位置
|
||
|
||
# 标注回归方程
|
||
equation = f'y = {slope:.6f}x + {intercept:.4f}'
|
||
ax.text(0.02, 0.02, equation, transform=ax.transAxes,
|
||
fontsize=11, bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8),
|
||
verticalalignment='bottom')
|
||
|
||
# 保存图表
|
||
plt.tight_layout()
|
||
plt.savefig('/mnt/v2_time_regression_redo.png', dpi=300, bbox_inches='tight')
|
||
plt.close()
|
||
|
||
# 输出回归模型关键参数
|
||
print(f"\n线性回归模型参数:")
|
||
print(f"回归方程:V2电压 = {slope:.6f} × 时间(秒) + {intercept:.4f}")
|
||
print(f"每秒电压变化量(斜率):{slope:.6f} mV/秒")
|
||
print(f"初始电压预测值(截距):{intercept:.4f} mV")
|
||
print(f"拟合优度(R²):{r_squared:.4f}") |