import pandas as pd from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsRegressor from sklearn.preprocessing import StandardScaler # 读取CSV文件 data = pd.read_csv("D:/Salary_data.csv") # 去除缺失值 data.dropna(inplace=True) # 将分类变量转换为虚拟变量 data = pd.get_dummies(data) # 将特征和目标变量分开 X = data.drop('Salary', axis=1) y = data['Salary'] # 将数据集分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 标准化特征 scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) # 创建KNN回归器 knn = KNeighborsRegressor(n_neighbors=5) # 在训练集上拟合模型 knn.fit(X_train, y_train) # 在测试集上评估模型 score = knn.score(X_test, y_test) print("R-squared score:", score) R-squared score: 0.6441725303407546 绘制可视化
时间: 2024-03-20 21:42:09 浏览: 157
好的,根据您提供的R-squared score为0.6441725303407546,您可以绘制一张散点图来可视化模型的预测结果和实际结果之间的关系。以下是示例代码:
```python
import matplotlib.pyplot as plt
# 在测试集上进行预测
y_pred = knn.predict(X_test)
# 绘制散点图
plt.scatter(y_test, y_pred)
plt.xlabel("Actual Salary")
plt.ylabel("Predicted Salary")
plt.title("KNN Regression - Actual vs. Predicted Salary")
# 绘制一条直线表示完美预测的情况
min_val = min(y_test.min(), y_pred.min())
max_val = max(y_test.max(), y_pred.max())
plt.plot([min_val, max_val], [min_val, max_val], '--', color='red')
plt.show()
```
这段代码将生成一个散点图,其中x轴表示实际薪资,y轴表示预测薪资,红色虚线表示完美预测的情况。您可以根据需要自定义图表的样式和布局。
相关问题
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix
这段代码是在 Python 中导入了一些常用的机器学习库和模块,包括 pandas、numpy、matplotlib、sklearn 等。其中:
- pandas 是 Python 中常用的数据分析库,可以用来读取和处理数据;
- numpy 是 Python 中常用的科学计算库,提供了数组、矩阵等数据结构和各种数学函数;
- matplotlib 是 Python 中常用的数据可视化库,可以用来绘制各种图表;
- sklearn 是 Python 中常用的机器学习库,提供了许多常用的机器学习算法和工具,比如数据预处理、模型选择、模型评估等。
这段代码中还导入了不同的机器学习算法,包括逻辑回归、决策树、K近邻和支持向量机等。最后还导入了一些评估指标,比如分类报告和混淆矩阵。
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt from termcolor import colored as cl import itertools from sklearn.preprocessing import StandardScaler from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier from xgboost import XGBClassifier from sklearn.neural_network import MLPClassifier from sklearn.ensemble import VotingClassifier # 定义模型评估函数 def evaluate_model(y_true, y_pred): accuracy = accuracy_score(y_true, y_pred) precision = precision_score(y_true, y_pred, pos_label='Good') recall = recall_score(y_true, y_pred, pos_label='Good') f1 = f1_score(y_true, y_pred, pos_label='Good') print("准确率:", accuracy) print("精确率:", precision) print("召回率:", recall) print("F1 分数:", f1) # 读取数据集 data = pd.read_csv('F:\数据\大学\专业课\模式识别\大作业\数据集1\data clean Terklasifikasi baru 22 juli 2015 all.csv', skiprows=16, header=None) # 检查数据集 print(data.head()) # 划分特征向量和标签 X = data.iloc[:, :-1] y = data.iloc[:, -1] # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 6. XGBoost xgb = XGBClassifier(max_depth=4) y_test = np.array(y_test, dtype=int) xgb.fit(X_train, y_train) xgb_pred = xgb.predict(X_test) print("\nXGBoost评估结果:") evaluate_model(y_test, xgb_pred)
这段代码实现了一个使用XGBoost算法进行分类的机器学习模型,并对该模型进行评估。具体步骤如下:
1. 导入需要的库:numpy、pandas、sklearn等。
2. 定义模型评估函数:evaluate_model(y_true, y_pred),该函数用于计算模型预测结果的准确率、精确率、召回率和F1分数。
3. 读取数据集:使用pandas库的read_csv()函数读取数据集。
4. 划分特征向量和标签:将数据集划分为特征向量X和标签y。
5. 划分训练集和测试集:使用sklearn库的train_test_split()函数将数据集划分为训练集和测试集。
6. 使用XGBoost算法进行分类:使用XGBClassifier类构建XGBoost分类器,并使用fit()函数将训练集拟合到该分类器中。然后,使用predict()函数对测试集进行预测,并将预测结果存储在xgb_pred中。
7. 对模型进行评估:使用evaluate_model()函数对模型进行评估,并输出准确率、精确率、召回率和F1分数等评估结果。
需要注意的是:该代码中的数据集路径可能需要修改为本地数据集路径。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20210720083447.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)