题目出处:贪心学院
题目:随着海拔高度,对气温的预测
内容:
数据格式CSV:
程序代码:`import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import csv
data = pd.read_csv(‘data/height.vs.temperature.csv’) # 用 pandas 读入数据,放入data
print(data.head())
print(data.columns)
plt.figure(figsize=(8, 4)) # 建立绘画窗口,尺寸16*8
plt.scatter(data[‘height’], data[‘temperature’], c=‘black’) # 散点图,scatter
plt.xlabel(‘Height’) # 添加横轴名称
plt.ylabel(‘Temperature’) # 添加纵轴名称
plt.show() # 显示绘图
X = data[‘height’].values.reshape(-1, 1) # 将data中的height数据赋值给变量X,其中reshape(-1, 1)将数据转换成1列
y = data[‘temperature’].values.reshape(-1, 1) # 将data中temperature数据赋值给变量y,其中reshape(-1, 1)将数据转换成1列
reg = LinearRegression() # 调入线性回归函数
reg.fit(X, y) # 对X,y进行线性拟合
print(‘a = {:.5}’.format(reg.coef_[0][0])) # coef表示系数
print(‘b = {:.5}’.format(reg.intercept_[0])) # intercept表示截距
print(‘线性模型为:Y = {:.5}X + {:.5}’.format(reg.coef_[0][0],reg.intercept_[0]))
predictions = reg.predict(X)
plt.figure(figsize=(8, 4))
plt.scatter(data[‘height’], data[‘temperature’], c=‘black’)
plt.plot(data[‘height’], predictions, c=‘blue’, linewidth=2)
plt.xlabel(‘Height’)
plt.ylabel(‘Temperature’)
plt.show()
predictions = reg.predict([[8000]])
print(‘海拔8000米时,预计温度为{:.5}摄氏度’.format(predictions[0][0]))
predictions = reg.predict([[310],[1100],[3231],[4521],[5612]])
print(predictions)`
输出结果: