我将为您生成一段用于数据分析的Python代码,该代码约100-150行,格式清晰易懂,包含数据预处理、探索性分析和简单建模的完整流程。
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.preprocessing import StandardScaler
import warnings
warnings.filterwarnings('ignore')
class DataAnalyzer:
"""数据分析类,封装完整的数据分析流程"""
def __init__(self, data_path=None):
"""
初始化数据分析器
Args:
data_path: 数据文件路径,如果为None则生成模拟数据
"""
self.data = None
self.X_train = None
self.X_test = None
self.y_train = None
self.y_test = None
self.model = None
self.load_data(data_path)
def load_data(self, data_path):
"""加载或生成数据"""
if data_path:
# 从文件加载数据
self.data = pd.read_csv(data_path)
print(f"数据加载成功,形状: {self.data.shape}")
else:
# 生成模拟数据用于演示
np.random.seed(42)
n_samples = 1000
# 生成特征数据
age = np.random.normal(45, 15, n_samples)
income = np.random.normal(50000, 20000, n_samples)
education = np.random.randint(1, 5, n_samples)
health_score = np.random.normal(7, 2, n_samples)
# 生成目标变量(模拟老人自养意愿得分)
target = (0.3 * age + 0.4 * income/10000 + 0.2 * education +
0.1 * health_score + np.random.normal(0, 1, n_samples))
self.data = pd.DataFrame({
'age': age,
'income': income,
'education': education,
'health_score': health_score,
'self_care_willingness': target
})
print("模拟数据生成完成")
# 显示数据基本信息
self.display_basic_info()
def display_basic_info(self):
"""显示数据基本信息"""
print("\n" + "="*50)
print("数据基本信息")
print("="*50)
print(f"数据形状: {self.data.shape}")
print(f"\n前5行数据:")
print(self.data.head())
print(f"\n数据描述性统计:")
print(self.data.describe())
print(f"\n缺失值统计:")
print(self.data.isnull().sum())
def preprocess_data(self):
"""数据预处理"""
print("\n" + "="*50)
print("数据预处理")
print("="*50)
# 处理缺失值
if self.data.isnull().sum().sum() > 0:
self.data = self.data.fillna(self.data.mean())
print("缺失值已用均值填充")
# 检测并处理异常值
self.detect_outliers()
# 数据标准化
scaler = StandardScaler()
numeric_cols = ['age', 'income', 'health_score']
self.data[numeric_cols] = scaler.fit_transform(self.data[numeric_cols])
print("数值型特征已标准化")
def detect_outliers(self):
"""检测异常值"""
print("\n异常值检测:")
for col in self.data.select_dtypes(include=[np.number]).columns:
Q1 = self.data[col].quantile(0.25)
Q3 = self.data[col].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
outliers = self.data[(self.data[col] < lower_bound) |
(self.data[col] > upper_bound)]
if len(outliers) > 0:
print(f"{col}: 发现 {len(outliers)} 个异常值")
def exploratory_analysis(self):
"""探索性数据分析"""
print("\n" + "="*50)
print("探索性数据分析")
print("="*50)
# 设置绘图风格
plt.style.use('seaborn-v0_8')
fig, axes = plt.subplots(2, 2, figsize=(15, 12))
# 1. 目标变量分布
axes[0,0].hist(self.data['self_care_willingness'], bins=30, alpha=0.7, color='skyblue')
axes[0,0].set_title('目标变量分布 - 自养意愿')
axes[0,0].set_xlabel('自养意愿得分')
axes[0,0].set_ylabel('频数')
# 2. 年龄与自养意愿的关系
axes[0,1].scatter(self.data['age'], self.data['self_care_willingness'], alpha=0.6)
axes[0,1].set_title('年龄 vs 自养意愿')
axes[0,1].set_xlabel('年龄')
axes[0,1].set_ylabel('自养意愿')
# 3. 收入与自养意愿的关系
axes[1,0].scatter(self.data['income'], self.data['self_care_willingness'], alpha=0.6, color='green')
axes[1,0].set_title('收入 vs 自养意愿')
axes[1,0].set_xlabel('收入')
axes[1,0].set_ylabel('自养意愿')
# 4. 相关性热力图
corr_matrix = self.data.corr()
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', ax=axes[1,1])
axes[1,1].set_title('变量相关性热力图')
plt.tight_layout()
plt.savefig('exploratory_analysis.png', dpi=300, bbox_inches='tight')
plt.show()
# 打印关键相关性
print("\n关键相关性分析:")
target_corr = corr_matrix['self_care_willingness'].sort_values(ascending=False)
for feature, corr in target_corr.items():
if feature != 'self_care_willingness':
print(f"{feature}: {corr:.3f}")
def build_model(self):
"""构建预测模型"""
print("\n" + "="*50)
print("模型构建")
print("="*50)
# 准备特征和目标变量
X = self.data[['age', 'income', 'education', 'health_score']]
y = self.data['self_care_willingness']
# 划分训练集和测试集
self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# 创建并训练模型
self.model = LinearRegression()
self.model.fit(self.X_train, self.y_train)
print("线性回归模型训练完成")
print(f"特征系数: {dict(zip(X.columns, self.model.coef_))}")
print(f"截距: {self.model.intercept_:.3f}")
def evaluate_model(self):
"""模型评估"""
print("\n" + "="*50)
print("模型评估")
print("="*50)
# 预测
y_pred = self.model.predict(self.X_test)
# 计算评估指标
mse = mean_squared_error(self.y_test, y_pred)
r2 = r2_score(self.y_test, y_pred)
print(f"均方误差 (MSE): {mse:.3f}")
print(f"决定系数 (R²): {r2:.3f}")
# 可视化预测结果
plt.figure(figsize=(10, 6))
plt.scatter(self.y_test, y_pred, alpha=0.6)
plt.plot([self.y_test.min(), self.y_test.max()],
[self.y_test.min(), self.y_test.max()], 'r--', lw=2)
plt.xlabel('实际值')
plt.ylabel('预测值')
plt.title('预测值 vs 实际值')
plt.savefig('prediction_results.png', dpi=300, bbox_inches='tight')
plt.show()
def run_full_analysis(self):
"""运行完整分析流程"""
self.preprocess_data()
self.exploratory_analysis()
self.build_model()
self.evaluate_model()
print("\n" + "="*50)
print("分析完成!")
print("="*50)
# 主程序执行
if __name__ == "__main__":
# 创建分析器实例(使用模拟数据)
analyzer = DataAnalyzer()
# 运行完整分析流程
analyzer.run_full_analysis()
# 保存处理后的数据
analyzer.data.to_csv('processed_analysis_data.csv', index=False)
print("处理后的数据已保存为 'processed_analysis_data.csv'")
```
## 代码功能说明
这段代码提供了一个完整的数据分析框架,主要包含以下功能模块:
### 1. 数据加载与探索
* **自动生成模拟数据**:基于老年人自养意愿研究主题生成合理的数据
* **数据基本信息展示**:包括数据形状、描述性统计和缺失值检测
### 2. 数据预处理
* **缺失值处理**:使用均值填充缺失值
* **异常值检测**:基于IQR方法识别异常数据点
* **数据标准化**:对数值型特征进行标准化处理
### 3. 探索性数据分析
* **分布可视化**:目标变量分布直方图
* **关系分析**:散点图展示特征与目标变量的关系
* **相关性分析**:热力图展示变量间相关性
### 4. 建模与评估
* **线性回归模型**:建立多变量线性回归模型
* **模型评估**:使用MSE和R²指标评估模型性能
* **结果可视化**:预测值与实际值的对比散点图
## 使用说明
1. **直接运行**:代码会自动生成模拟数据并执行完整分析流程
2. **使用真实数据**:修改 `DataAnalyzer('your_data.csv')` 来加载您的数据文件
3. **输出结果**:代码会生成分析图表并保存处理后的数据
这段代码结构清晰,注释详细,便于理解和修改,适合作为数据分析项目的基础模板。