tensorflow demo 波士顿房价预测

Posted _刘文凯_

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了tensorflow demo 波士顿房价预测相关的知识,希望对你有一定的参考价值。

tensorflow 的一个基础应用,用于预测波士顿的房价

环境

python3.7
tensorflow 1.15.0

代码
import tensorflow as tf
import numpy as np
from sklearn.datasets import load_boston


def read_infile():
    data = load_boston()
    features = np.array(data.data)

    target = np.array(data.target)

    return features, target


def feature_normalize(data):
    mu = np.mean(data, axis=0)
    std = np.std(data, axis=0)

    return (data - mu)/std


def append_bias(features, target):
    n_samples = features.shape[0]
    n_features = features.shape[1]

    intercept_features = np.ones((n_samples,1))

    X = np.concatenate((features,intercept_features), axis=1)
    X = np.reshape(X, [n_samples, n_features+1])

    Y = np.reshape(target, [n_samples, 1])

    return X, Y

def trian_model(learning_rate=0.01, epochs=100):
    features, target = read_infile()

    z_features = feature_normalize(features)

    X_input, Y_input = append_bias(z_features, target)

    num_features = X_input.shape[1]

    X = tf.placeholder(tf.float32, [None, num_features])
    Y = tf.placeholder(tf.float32, [None, 1])

    w = tf.Variable(tf.random_normal((num_features, 1)), name='w')

    init = tf.global_variables_initializer()

    const_trace = []

    pred = tf.matmul(X, w)

    error = pred - Y
    cost = tf.reduce_mean(tf.square(error))

    train_op = tf.python.train.GradientDescentOptimizer(learning_rate).minimize(cost)

    with tf.Session() as sess:
        sess.run(init)
        for i in range(epochs):
            sess.run(train_op, feed_dict=X: X_input, Y: Y_input)
            const_trace.append(sess.run(cost, feed_dict=X: X_input, Y: Y_input))

        error_ = sess.run(error, X: X_input, Y: Y_input)
        pred_ = sess.run(pred, X: X_input, Y: Y_input)

    print(const_trace[-1])

    import matplotlib.pyplot as plt
    # %matplotlib inline

    # plt.plot(const_trace)

    fig, ax = plt.subplots()
    plt.scatter(Y_input, pred_)
    plt.show()

if __name__ == '__main__':
    trian_model()

以上是关于tensorflow demo 波士顿房价预测的主要内容,如果未能解决你的问题,请参考以下文章

tensorflow2.0——波士顿房价数据与房间数关系的预测

《用Python玩转数据》项目—线性回归分析入门之波士顿房价预测

线性回归预测波士顿房价

HCIA-AI_机器学习_波士顿房价预测

HCIA-AI_机器学习_波士顿房价预测

HCIA-AI_机器学习_波士顿房价预测