导包
import numpy as np
import os
import matplotlib.pyplot as plt
%matplotlib inline
定义保存图像的函数
#随机种子
np.random.seed(42)
#保存图像
PROJECT_ROOT_DIR ='.'
MODEL_ID ='linear_models'
def save_fig(fig_id, tight_layout = True):#定义一个保存图像的函数
path = os.path.join(PROJECT_ROOT_DIR, 'images',MODEL_ID, fig_id +'.png')#指定保存图像的路径 当前目录下的images文件夹下的model_id文件夹
print("Saving figure", fig_id) #提示函数,正在保存图片
print('Saving figure',fig_id)#提示函数
plt.savefig(path, format='png', dpi =300)#保存图片(需要指定保存路径,保存格式,清晰度)
# './images/linear_models/xx.png'
# 把讨厌的警告信息过滤掉
import warnings
warnings.filterwarnings(action = 'ignore',message='internal gelsd')
生成训练数据
import numpy as np
x = 2*np.random.rand(100,1) #生成训练数据(特征部分)
y = 4+3*x+np.random.randn(100,1)#生成训练数据(标签部分)
画图
plt.plot(x,y, 'b.')#画图
plt.xlabel('$x_1$',fontsize =18)
plt.ylabel('$y$',rotation=0, fontsize =18)
plt.axis([0,2,0,15])
save_fig('generated_data_plot')# 保存图片
结果:
Saving figure generated_data_plot
添加新特征
#添加新特征
x_b = np.c_[np.ones((100,1)),x]
x_b
结果:
array([[1. , 0.74908024],
[1. , 1.90142861],
[1. , 1.46398788],
[1. , 1.19731697],
[1. , 0.31203728],
[1. , 0.31198904],
[1. , 0.11616722],
[1. , 1.73235229],
[1. , 1.20223002],
[1. , 1.41614516],
[1. , 0.04116899],
[1. , 1.9398197 ],
[1. , 1.66488528],
[1. , 0.42467822],
[1. , 0.36364993],
[1. , 0.36680902],
[1. , 0.60848449],
[1. , 1.04951286],
[1. , 0.86389004],
[1. , 0.58245828],
[1. , 1.22370579],
[1. , 0.27898772],
[1. , 0.5842893 ],
[1. , 0.73272369],
[1. , 0.91213997],
[1. , 1.57035192],
[1. , 0.39934756],
[1. , 1.02846888],
[1. , 1.18482914],
[1. , 0.09290083],
[1. , 1.2150897 ],
[1. , 0.34104825],
[1. , 0.13010319],
[1. , 1.89777107],
[1. , 1.93126407],
[1. , 1.6167947 ],
[1. , 0.60922754],
[1. , 0.19534423],
[1. , 1.36846605],
[1. , 0.88030499],
[1. , 0.24407647],
[1. , 0.99035382],
[1. , 0.06877704],
[1. , 1.8186408 ],
[1. , 0.51755996],
[1. , 1.32504457],
[1. , 0.62342215],
[1. , 1.04013604],
[1. , 1.09342056],
[1. , 0.36970891],
[1. , 1.93916926],
[1. , 1.55026565],
[1. , 1.87899788],
[1. , 1.7896547 ],
[1. , 1.19579996],
[1. , 1.84374847],
[1. , 0.176985 ],
[1. , 0.39196572],
[1. , 0.09045458],
[1. , 0.65066066],
[1. , 0.77735458],
[1. , 0.54269806],
[1. , 1.65747502],
[1. , 0.71350665],
[1. , 0.56186902],
[1. , 1.08539217],
[1. , 0.28184845],
[1. , 1.60439396],
[1. , 0.14910129],
[1. , 1.97377387],
[1. , 1.54448954],
[1. , 0.39743136],
[1. , 0.01104423],
[1. , 1.63092286],
[1. , 1.41371469],
[1. , 1.45801434],
[1. , 1.54254069],
[1. , 0.1480893 ],
[1. , 0.71693146],
[1. , 0.23173812],
[1. , 1.72620685],
[1. , 1.24659625],
[1. , 0.66179605],
[1. , 0.1271167 ],
[1. , 0.62196464],
[1. , 0.65036664],
[1. , 1.45921236],
[1. , 1.27511494],
[1. , 1.77442549],
[1. , 0.94442985],
[1. , 0.23918849],
[1. , 1.42648957],
[1. , 1.5215701 ],
[1. , 1.1225544 ],
[1. , 1.54193436],
[1. , 0.98759119],
[1. , 1.04546566],
[1. , 0.85508204],
[1. , 0.05083825],
[1. , 0.21578285]])
创建测试数据
#创建测试数据
x_new =np.array([[0],[2]])