第1步:导入数据分析库pandas,数据可视化库matplotlib

%matplotlib inline是Ipython的魔法函数,其作用是使matplotlib绘制的图像嵌入在juptyer notebook的单元格里

  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. %matplotlib inline

第2步:导入数据集,查看数据集

代码:

  1. dataset = pd.read_csv('./studentscores.csv')
  2. dataset.head(10) # 展示前10行

输出:

  1. Hours Scores
  2. 0 2.5 21
  3. 1 5.1 47
  4. 2 3.2 27
  5. 3 8.5 75
  6. 4 3.5 30
  7. 5 1.5 20
  8. 6 9.2 88
  9. 7 5.5 60
  10. 8 8.3 81
  11. 9 2.7 25

代码:

  1. dataset.shape # 查看形状

输出:

  1. (25, 2) # 25行2列

代码:

  1. dataset.columns # 查看表头

输出:

  1. Index(['Hours', 'Scores'], dtype='object')

代码:

  1. dataset.info() # 查看数据的具体信息

输出:

  1. <class 'pandas.core.frame.DataFrame'>
  2. RangeIndex: 25 entries, 0 to 24
  3. Data columns (total 2 columns):
  4. # Column Non-Null Count Dtype
  5. --- ------ -------------- -----
  6. 0 Hours 25 non-null float64
  7. 1 Scores 25 non-null int64
  8. dtypes: float64(1), int64(1)
  9. memory usage: 528.0 bytes

代码:

  1. dataset.describe() # 查看基本统计特征

输出:

  1. Hours Scores
  2. count 25.000000 25.000000
  3. mean 5.012000 51.480000
  4. std 2.525094 25.286887
  5. min 1.100000 17.000000
  6. 25% 2.700000 30.000000
  7. 50% 4.800000 47.000000
  8. 75% 7.400000 75.000000
  9. max 9.200000 95.000000

第3步:提取特征

提取特征:学习时间, 提取标签:学习成绩

  1. feature_columns = ['Hours']
  2. label_column = ['Scores']
  3. features = dataset[feature_columns]
  4. label = dataset[label_column]
  5. X = features.values # 特征数据
  6. Y = label.values # 标签数据

第四步:建立模型

拆分数据,四分之三的数据作为训练集,四分之一的数据作为测试集

  1. from sklearn.model_selection import train_test_split
  2. X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 1/4, random_state = 0)

用训练集的数据进行训练

  1. from sklearn.linear_model import LinearRegression
  2. regressor = LinearRegression()
  3. regressor = regressor.fit(X_train, Y_train)

对测试集进行预测

  1. Y_pred = regressor.predict(X_test)

可视化

  1. # 散点图:红色点表示训练集的点
  2. plt.scatter(X_train, Y_train, color = 'red')
  3. # 线图:蓝色线表示由训练集训练出的线性回归模型
  4. plt.plot(X_train, regressor.predict(X_train), color ='blue')
  5. plt.show()

image.png

  1. # 散点图:红色点表示测试集的点
  2. plt.scatter(X_test , Y_test, color = 'red')
  3. # 线图:蓝色线表示对测试集进行预测的结果
  4. plt.plot(X_test, regressor.predict(X_test), color ='blue')
  5. plt.show()