b站视频教程推荐:《PyTorch深度学习实践》02.线性模型_哔哩哔哩_bilibili
1、本科期间算法分类(1)穷举法(2)贪心(3)分治(4)动态规划
机器学习和之前算法的区别在于:机器学习利用数据进行推理,之前的算法是设计好算法后代入数据
2、深度学习过程:
(1)准备数据集
(2)选择模型或设计模型(神经网络、决策树、朴素贝叶斯)
(3)训练(KNN模型不用训练)
(4)推理(拿到新的数据推理出结果)
3、模型选择时可以先考虑线性模型y=x*w,w权重如何确定,需要根据训练的结果选择损失最小时的权重
4、评估模型和真实数据集之间的误差:loss
5、MSE:Mean Square Error平均平方误差
6、线性模型代码
import matplotlib.pyplot as plt
import numpy as np
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
def forward(x):
return x * w
def loss(x , y):
y_pred = forward(x)
return (y_pred - y) * (y_pred - y)
#权重列表
w_list = []
mse_list = []
#间隔为0.1,从0.0到4.1,穷举法求权重
for w in np.arange(0.0, 4.1, 0.1):
print('w=', w)
l_sum = 0
for x_val, y_val in zip(x_data, y_data):
y_pred_val = forward(x_val)
loss_val = loss(x_val, y_val)
l_sum += loss_val
print('\t', x_val, y_val, y_pred_val, loss_val)
print('MSE=', l_sum/3)
w_list.append(w)
mse_list.append(l_sum/3)
plt.plot(w_list, mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()
7、线性模型课后作业,画3D图
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
def forward(x):
return x * w + b
def loss(x , y):
y_pred = forward(x)
return (y_pred - y) * (y_pred - y)
W = np.arange(0.0, 4.1, 0.1)
B = np.arange(-2.0, 2.1, 0.1)
[w, b] = np.meshgrid(W,B)
l_sum = 0
for x_val, y_val in zip(x_data, y_data):
y_pred_val = forward(x_val)
loss_val = loss(x_val, y_val)
l_sum += loss_val
print('\t', x_val, y_val, y_pred_val, loss_val)
print('MSE=', l_sum/3)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.plot_surface(w, b, l_sum/3, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
ax.set_xlabel('w')
ax.set_ylabel('b')
ax.set_zlabel('Loss')
plt.show()
作业结果图: