代码如下:
import numpy as np
from sklearn.model_selection import train_test_split
from numpy.linalg import inv
import matplotlib.pyplot as plt
# 1. 读数据、预处理数据(aqi2.csv读取出来)
# 这里的delimiter="," 代表的是用逗号分隔,skiprows=1代表的是前面第一行的数据不用带入。
data = np.loadtxt(r"D:\Pycharm\code\MY_machine_learning\mydata\aqi2.csv", delimiter=",", skiprows=1, dtype=np.float32)
# print(data)
index = np.ones((data.shape[0], 1))
data = np.hstack((data, index))
# print(data)
# 2. 特征与标签
y = data[:, 0]
x = data[:, 1:]
# 3. 数据集分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)
weight = np.dot(np.dot(inv(np.dot(X_train.T, X_train)), X_train.T), y_train)
print(weight)
# 4. 预测值y_predict
y_predict = np.dot(X_test, weight)
print('-----------------------------------------')
print('打印真实值:\n', y_test)
print('打印预测值:\n', y_predict)
# 5. 画图分析预测与真实值偏离程度
plt.scatter(range(len(y_test)), y_test, c='red') # 真实值散点图
plt.plot(range(len(y_test)), y_predict, c='green') # 预测值拟合直线图
plt.show()
运行结果如下:
附aqi2.csv网盘提取
提取码:uuyp