我在编写如下代码的时候,读取csv里的数据总显示数据读不到,可我csv里有100多个数据。有没有大佬帮忙看看我应该怎么改写代码或者改变csv原始数据集中的格式呢。
1. CSV文件中的内容如下
2. 代码如下
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import r2_score, mean_squared_error
import matplotlib.pyplot as plt
# 1. 数据准备
data = pd.read_csv('1.csv')
X = data.iloc[:, 1:91] # 特征变量(面积、规模和进水浓度值)
y = data.iloc[:, 88:] # 目标变量(出水浓度值)
# 2. 数据划分
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 3. 特征工程(可以根据需要进行进一步的处理)
# 4. 模型选择和训练
model = DecisionTreeRegressor()
model.fit(X_train, y_train)
# 5. 模型评估
y_train_pred = model.predict(X_train)
train_r2 = r2_score(y_train, y_train_pred)
train_rmse = np.sqrt(mean_squared_error(y_train, y_train_pred))
y_test_pred = model.predict(X_test)
test_r2 = r2_score(y_test, y_test_pred)
test_rmse = np.sqrt(mean_squared_error(y_test, y_test_pred))
print("训练集拟合优度(R²):", train_r2)
print("训练集均方根误差(RMSE):", train_rmse)
print("测试集拟合优度(R²):", test_r2)
print("测试集均方根误差(RMSE):", test_rmse)
# 6. 可视化
# 假设你想可视化第一个指标的预测结果和真实值
index = 0
plt.scatter(y_test.iloc[:, index], y_test_pred[:, index])
plt.plot([min(y_test.iloc[:, index]), max(y_test.iloc[:, index])], [min(y_test.iloc[:, index]), max(y_test.iloc[:, index])], 'r')
plt.xlabel('真实值')
plt.ylabel('预测值')
plt.title('指标{}:预测值 vs 真实值'.format(index + 1))
plt.show()
# 7. 预测未来值
# 假设你想预测第一个指标在未来一年的出水浓度
future_input = X_test.iloc[0, :].values.reshape(1, -1) # 使用测试集中的一个样本作为输入
future_prediction = model.predict(future_input)
print("未来一年的出水浓度预测:", future_prediction)