刘二大人《Pytorch深度学习实践》02.线性模型

本人根据b站上刘老师的视频,简单做了一下,内容主要包括课上所讲内容的复现以及所留作业的实现。具体代码解释我都按照自己的理解放在代码后面了,如有不对的地方请多多包涵,毕竟俺也是第一次学,只是想找个地方把学到的东西找个地方存起来~


from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import numpy as np

# 1、导入数据集
exam_Dict = {
    '学习时间': [0.5, 0.75, 1.00, 1.25, 1.50, 1.75, 1.75, 2.00, 2.25, 2.50, 2.75, 3.00, 3.25, 3.50, 4.00, 4.25, 4.50, 4.75,
             5.00, 5.50],
    '分数': [10, 22, 13, 43, 20, 22, 33, 50, 62, 48, 55, 75, 62, 73, 81, 76, 64, 82, 90, 93]}
examOrderDict = OrderedDict(exam_Dict)
examDf = pd.DataFrame(examOrderDict)
examDf.head()
# 提取特征
exam_X = examDf.loc[:, '学习时间']
# 提取标签
exam_y = examDf.loc[:, '分数']
# 2、绘制散点图
# 散点图看分布情况
plt.scatter(exam_X, exam_y, color='b', label='exam data')
# 添加图标
plt.xlabel('Hours')
plt.ylabel("Scores")
# 显示图像
plt.show()
# 3、建立测试集和训练集
x_train, x_test, y_train, y_test = train_test_split(exam_X, exam_y, train_size=.8)
# 输出特征和标签
print('原式数据特征:', exam_X.shape,
      '训练集数据特征:', x_train.shape,
      "测试集数据特征:", x_test.shape)
print('原式数据标签:', exam_y.shape,
      "训练数据标签:", y_train.shape,
      '测试集数据标签:', y_test.shape)
print(type(x_train))
rDf = examDf.corr()
rDf
x_train = np.array(x_train)
x_test = np.array(x_test)
# 将训练集和测试集转化成二维数组**行1列
x_train = x_train.reshape(-1, 1)
x_test = x_test.reshape(-1, 1)
# 4,训练模型
model = LinearRegression()
model.fit(x_train, y_train)
# 最佳拟合线
a = model.intercept_
b = model.coef_
c = model.score(x_test, y_test)
print("最佳拟合线:截距为", a, ',回归系数为', b, ',模型精确程度', c)

上一篇:【机器学习】数值分析02——任意方程求根


下一篇:保存重要,未完的工作空间