前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用tensorflow搭建线性回归模型

使用tensorflow搭建线性回归模型

作者头像
带萝卜
发布2020-10-26 14:30:51
9240
发布2020-10-26 14:30:51
举报

上一阶段的数据分析学习因为工作原因耽误了,今天忙里偷个闲,重新开始了。 @猴子 求个第二关门票。

先分享一下最近学到的东西吧……

以前买过一本《tensorflow实战谷歌深度学习框架》,看了一半就留在家里吃灰了,最近重新翻开发现这本书已经跟不上现在的版本了,所以从网上找了一点代码学习。

tensorflow不止能用于深度学习,也能用来实现传统机器学习算法。比如实现线性回归。

tensorflow的线性回归代码当然不如scikit learn的简洁,在scikit learn中只需要几行代码:

from sklearn.linear_model import LinearRegression
clf = LinearRegression()
clf.fit(x,y)

而在tensorflow中很多功能需要自己实现。看起来麻烦,其实是提供了更加个性化的解决方案,比如可以自定义误差函数,达到个性化的模型效果。

而像梯度下降优化器这种写起来麻烦的功能,tensorflow已经实现好了。

要说tensorflow有什么优势的话,那就是如果你数据特别特别大的话,用tensorflow能分布计算吧。

下面是用tensorflow实现线性回归的完整代码。

import matplotlib.pyplot as plt 
import tensorflow as tf 
import numpy as np 

from sklearn.datasets import load_boston

#读取数据
def read_boston_data():
    boston = load_boston()
    x = np.array(boston.data)
    y = np.array(boston.target)

    return x,y

#转化为正态分布
def feature_normalize(dataset):
    mu = np.mean(dataset,axis = 0)
    sigma = np.std(dataset,axis=0)

    return (dataset-mu)/sigma

#添加一个常数项,用于训练偏差
def append_bias_reshape(x,y):
    n_training_samples = x.shape[0]#训练样本数量
    n_dim = x.shape[1]#特征数量
    f = np.reshape(np.c_[np.ones(n_training_samples),x],[n_training_samples,n_dim+1])
    l = np.reshape(y,[n_training_samples,1])
    
    return f,l

if __name__ == '__main__':
    
    #处理数据
    
    x,y = read_boston_data()
    norm_features = feature_normalize(x)
    f,l = append_bias_reshape(norm_features,y)
    n_dim = f.shape[1]

    rnd_indices = np.random.rand(len(f)) < 0.80#生成一个随机的布尔数组

    x_train = f[rnd_indices]
    y_train = l[rnd_indices]
    x_test = f[~rnd_indices]
    y_test = l[~rnd_indices]


    #tensorflow模型

    learning_rate = 0.01#步长
    training_epochs = 6000#训练次数
    cost_history = []#记录训练误差
    test_history = []#记录测试误差

    X = tf.placeholder(tf.float32,[None,n_dim])
    Y = tf.placeholder(tf.float32,[None,1])
    W = tf.Variable(tf.ones([n_dim,1]))

    init = tf.initialize_all_variables()

    y_ = tf.matmul(X,W)
    cost = tf.reduce_mean(tf.abs(y_-Y))#选择了绝对平均误差作为衡量指标
    training_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

    sess = tf.Session()
    sess.run(init)

    for epoch in range(training_epochs):
        sess.run(training_step,feed_dict={X:x_train,Y:y_train})#训练模型
        c = sess.run(cost,feed_dict={X:x_train,Y:y_train})#计算误差
        print(c)
        t = sess.run(cost,feed_dict={X:x_test,Y:y_test})#计算测试误差
        print(t)
        cost_history.append(c)
        test_history.append(t)

    plt.plot(range(len(test_history)),test_history,color = 'green')
    plt.plot(range(len(cost_history)),cost_history,color = 'red')
    
    plt.axis([0,training_epochs,0,np.max(cost_history)])
    plt.show()

训练误差(红色)与测试误差(绿色)

效果还算不错,比自己写的梯度下降靠谱多了……

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档