您当前的位置: 首页 >  网络

川川菜鸟

暂无认证

  • 3浏览

    0关注

    969博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

tensorflow神经网络线性回归

川川菜鸟 发布时间:2021-11-18 20:43:26 ,浏览量:3

tensorflow神经网络
# import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

import matplotlib.pyplot as plt
import numpy as np
 
a = 2  # 权重
b = 1.5  # 偏置
 
# 设置随机种子
np.random.seed(5)
 
# 生成100个点,区间为-1到1
x_data = np.linspace(-1, 1, 100)
 
# y = x_data * a + b + 噪声
y_data = a * x_data + b + np.random.randn(*x_data.shape) * 0.2
 
# 画出散点图
plt.scatter(x_data, y_data)
 
# 想要学习到的线性函数  y = x_data * a + b
# plt.plot(x_data, x_data * a + b,color='red', linewidth=3)
plt.show()
 
# 定义训练数据的占位符 x为特征  y为标签
x = tf.placeholder('float', name='x')
y = tf.placeholder('float', name='y')
 
 
# 定义模型函数
def model(x, w, b):
    return tf.multiply(x, w) + b
 
 
# 构建线性函数的斜率w
w = tf.Variable(0.5, name='w')
b = tf.Variable(0.0, name='b')
 
# 前向计算 y = w * x + b
pred = model(x, w, b)
 
# 使用均方差损失函数
loss_function = tf.reduce_mean(tf.square(y - pred))
 
# 使用梯度下降优化器
optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss_function)
 
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)  # 初始化所有变量
    for step in range(5):
        for xs, ys in zip(x_data, y_data):
            # 运行计算图
            _, loss = sess.run([optimizer, loss_function], \
                               feed_dict={x: xs, y: ys})
        print('w:', sess.run(w), ' b:', sess.run(b))
 
    plt.scatter(x_data, y_data)
    plt.plot(x_data, x_data * sess.run(w) + sess.run(b), \
             color='red', linewidth=3)
    plt.show()
 
    x_test = 5
    y = x_test * 2 + 1.5
    y_out = x_test * sess.run(w) + sess.run(b)
    print('真实结果:', y)
    print('预测结果', y_out)

运行: 在这里插入图片描述 在这里插入图片描述

Sklearn线性回归
#使用matplotlib绘制图像,使用numpy准备数据集
import  matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model

#准备自变量x,生成数据集,3到6的区间均分间隔30份数
x = np.linspace(3,6.40)

#准备因变量y,这一个关于x的假设函数
y = 3 * x + 2

#由于fit 需要传入二维矩阵数据,因此需要处理x,y的数据格式,将每个样本信息单独作为矩阵的一行
x=[[i] for i in x]
y=[[i] for i in y]
# 构建线性回归模型
model=linear_model.LinearRegression()
# 训练模型,"喂入"数据
model.fit(x,y)
# 准备测试数据 x_,这里准备了三组,如下:
x_=[[4],[5],[6]]
# 打印预测结果
y_=model.predict(x_)
print(y_)

#查看w和b的
print("w值为:",model.coef_)
print("b截距值为:",model.intercept_)

#数据集绘制,散点图,图像满足函假设函数图像
plt.scatter(x,y)
plt.show()

运行: 在这里插入图片描述

关注
打赏
1665165634
查看更多评论
立即登录/注册

微信扫码登录

0.1133s