线性回归Keras实现

该博客介绍了如何使用Keras库,分别通过序贯模型和函数式模型来实现线性回归。文中提供了详细的实现步骤,并附有实现效果的展示。
摘要由CSDN通过智能技术生成

用序贯模型实现

'''
用keras实现线性回归
'''
import keras
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense

# 使用numpy生成100个随机点
x_data = np.random.rand(100)
noise = np.random.normal(loc=0, scale=0.01, size=x_data.shape) # 生成标准正态分布
y_data = x_data*0.1 + 0.2 + noise

# 把这些点在坐标轴中打印出来
plt.scatter(x_data, y_data)
plt.xlabel("x")
plt.ylabel("y")
plt.title("random")
plt.show()

# 构建一个顺序模型
model = Sequential()
# 模型中添加一个全连接层
model.add(Dense(units=1, input_dim=1)) # activation = 'relu'
#sgd随机梯度下降,mse均方误差
model.compile(
    optimizer='sgd', 
    loss='mse',
    metrics=['accuracy']
    )

model.summary()

# 训练3001个批次
for step in range(3001):
    # 每一个批次
    cost = model.train_on_batch(x_data, y_data)
    if step%500==0:
        print("cost:",cost)

# 打印权值和偏置值
w, b = model.layers[0].get_weights()
print("w:",w," b:",b)

#x_data输入网络中,得到预测值y_pred
y_pred = model.predict(x_data)

# 显示随机点
plt.scatter(x_data, y_data)

# 显示预测结果
plt.plot(x_data, y_pred, 'r-', lw=3)
plt.show()

用函数试模型实现

'''
用keras实现线性回归
不用Sequential
'''
import keras
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Model
from keras.layers.core import Dense
from keras.layers import Input

# 搭建模型
inputs = Input(shape=(1,), dtype='float32', name='inputlayer')
dense = Dense(units=1, input_dim=1, activation='linear')(inputs)
model = Model(inputs=inputs, outputs=dense)
model.compile(
    loss='mse',
    optimizer='sgd',
    metrics=['accuracy']
)
model.summary()

x = np.random.rand(100) # 随机生成100个点
noise = np.random.normal(loc=0, scale=0.01, size=x.shape) # 生成标准正态分布
y = x*0.1 + 0.2 + noise

model.fit(x, y, epochs=3000, verbose=0) # batch_size=64
y_pred = model.predict(x)

# cost = model.evaluate(x_test, y_yesy, batch_size=40)
# print("cost on test:", cost)

w,b = model.layers[1].get_weights()
print("w = ", w, "bias = ", b)


# 显示随机点
plt.scatter(x, y)

# 显示预测结果
plt.plot(x, y_pred, 'r-', lw=2)
plt.show()

效果图如下
线性回归效果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值