机器学习04

# import torch
# print(torch.__version__)
# a = torch.randn(3, 3)
# print(a)
# print('gpu', torch.cuda.is_available())
# b = torch.randn(3, 3, device='cuda:0')
# print(b)
# d = torch.tensor([[-1.2687, -0.0196, -0.6722],
#                   [-1.5163, 0.1679, -0.3012],
#                   [-0.9589, 1.9353, -0.7770]])
# print(d)
# c = torch.randn(3, 2, 4, 2)
# # 3row 2col 中加入 4row 3col 数组
# print(c)
# print(c.ndimension())
# # 维度
# print(c.nelement())
# # 元素个数
# print(c.size())
import numpy as np
# as np :np为别名
import matplotlib.pyplot as plt


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_pried = forward(x)
    return (y_pried - y) ** 2
# 计算输入值得到的预测值和真实值之间的误差

# 新建两个空的列表来记录 w、mse 的值 mse为均方误差 mean square error的缩写
w_list = []
mse_list = []
# tips:python小知识点:np.arrange(起始,终止,步长) 生成一个区间的数值,步长就是起始值每次往终点值移动的长度
for w in np.arange(0.0, 4.1, 0.1):
    print('w=', w)
    l_sum = 0
    # tips: python zip函数 返回的值是:输入的两个数组对应位置组合的一个元组()
    #  a= 【1,2,3】           zip(a,b)其实就是返回 (1,4),(2,5),(3,6)
    #  b= 【4,5,6】
    for x_val, y_val in zip(x_data, y_data):
        y_pried_val = forward(x_val)
        # 得到一个预测的值
        loss_val = loss(x_val, y_val)
        # 误差进行求和
        l_sum += loss_val
        print('\t', x_val, y_val, y_pried_val, loss_val)
        print('MSE=', l_sum / 3)
        # .append 向列表中追加值
        w_list.append(w)
        mse_list.append(l_sum / 3)
plt.plot(w_list, mse_list)
plt.ylabel('loss')
plt.xlabel('w')
plt.show()

猜你喜欢

转载自blog.csdn.net/weixin_41865104/article/details/115190998