zoukankan      html  css  js  c++  java
  • tensorflow2.0——波士顿房价数据与多个特征的关系(多元函数的预测)

    import tensorflow as tf
    import matplotlib.pylab as plt
    import numpy as np
    
    # 调用数据
    boston_house = tf.keras.datasets.boston_housing
    (train_x, train_y), (test_x, test_y) = boston_house.load_data(test_split=0.1)
    x1 = train_x[:, 5]                # 房间数
    x2 = train_x[:,7]                       #   另一个参数
    #   样本数据归一化
    x1 = (x1 - x1.min())/ (x1.max() - x1.min())
    x2 = (x2 - x2.min())/ (x2.max() - x2.min())
    #   维度转换
    X = np.stack((x1,x2),axis=1)                    #   转化成一个二维数组
    # print('X:',X,X.shape)
    Y = train_y.reshape(-1,1)                    #   将房价y转化为列向量
    
    #   超参数
    iter =1000              #   迭代次数
    learn_rate = 0.01      #   学习率
    #   设置模型参数初始值
    w = np.random.randn(2,1)
    W = tf.Variable(w)
    loss_list = []
    # print('W:{},W.shape:{}'.format(W,W.shape))
    for i in range(iter):
        with tf.GradientTape() as tape:
            pre_price = tf.matmul(X,W)
            loss = 0.5 * (tf.reduce_mean(pow(Y - pre_price,2)))
        loss_list.append(loss)
        dloss_dw = tape.gradient(loss,W)                        #   偏导也是一个2维向量
        # print('dloss_dw:',dloss_dw)
        W.assign_sub(learn_rate * dloss_dw)
        if i % 100 == 0:
            print('i:{},loss:{},w:{}'.format(i,loss,w))
    #   画图
    plt.rcParams["font.family"] = 'SimHei'              # 将字体改为中文
    plt.rcParams['axes.unicode_minus'] = False          # 设置了中文字体默认后,坐标的"-"号无法显示,设置这个参数就可以避免
    plt.plot(loss_list,label = '损失值')
    plt.legend()
    plt.show()

  • 相关阅读:
    中文排版指南
    HTTP返回码详解
    我的JS 类 写法
    【CodeForces】[630C]Lucky Numbers
    【CodeForces】[630C]Lucky Numbers
    【CodeForces】[630A]Again Twenty Five!
    【CodeForces】[630A]Again Twenty Five!
    【HPU】[1006]DNA
    【HPU】[1006]DNA
    【杭电】[3790]最短路径问题
  • 原文地址:https://www.cnblogs.com/cxhzy/p/13410528.html
Copyright © 2011-2022 走看看