非线性回归Keras实现

用序贯模型实现

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

x = np.linspace(-0.5, 0.5, 200)
noise = np.random.normal(loc=0, scale=0.01, size=x.shape)
y = np.square(x) + noise

model = Sequential()
model.add(Dense(units=10, input_dim=1, activation='tanh'))
model.add(Dense(units=1, activation='tanh'))
sgd = SGD(lr=0.3) # 如果没有这一句,下面compile中的optimizer='sgd',注意要加引号
model.compile(
    loss='mse',
    optimizer=sgd
)
model.summary()

for step in range(3000):
    cost = model.train_on_batch(x,y)
    if step%500==0:
        print("cost:",cost)


y_pred = model.predict(x)

plt.scatter(x,y)
plt.plot(x, y_pred, 'r-')
plt.show()

用函数式模型实现

'''
用keras实现非线性回归
'''
import keras
import numpy as np
from keras.layers import Dense, Input
from keras.models import Model
import matplotlib.pyplot as plt
from keras.optimizers import SGD

inputs = Input(shape=(1,), dtype='float32', name="inputLayer")
dense = Dense(units=10, input_dim=1, activation='tanh')(inputs)
dense = Dense(units=1, activation='tanh')(dense)
model = Model(inputs=inputs, outputs=dense)
sgd = SGD(lr=0.3)
model.compile(
    loss='mse',
    optimizer=sgd,
    metrics=['accuracy']
)
model.summary()

# 生成输入数据
x = np.linspace(-0.5, 0.5, 200) # 在-0.5到0.5区间取值范围内生成200个数
noise = np.random.normal(loc=0, scale=0.01, size=x.shape)
y = np.square(x) + noise

model.fit(x, y, epochs=3000, verbose=0)
# 下面这种在Sequential()才有用
# for step in range(3001):
#     cost = model.train_on_batch(x, y)
#     if step%500==0:
#         print("cost:",cost)


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

w, b = model.layers[2].get_weights()
print("weights_2 = ",w, "bias_2 = ",b)

y_pred = model.predict(x)

plt.scatter(x, y)

plt.plot(x, y_pred, 'r-', lw=3)
plt.show()

效果如下图
非线性回归实现效果图

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在Python中,可以使用线性回归和非线性回归来进行数据建模和预测。引用中提到的决策树和随机森林是非线性回归的经典算法,可以使用sklearn库中的相关函数进行实现。另外,还可以使用Keras库中的神经网络模型来进行非线性回归。引用中提到的支持向量机(SVM)也可以用于非线性回归,其中支持向量机非线性回归模型(SVR)是常用的方法之一。 对于线性回归,可以使用sklearn库中的线性模型(Linear Regression)来实现。具体步骤包括导入相应的库、准备数据、创建模型、拟合数据和进行预测。以下是一个简单的线性回归示例代码: ```python import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression # 准备数据 x = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]) y = np.array([4.187, 0.964, 0.853, 0.305, 0.358, 0.338, 0.368, 0.222, 0.798, 1.515]) # 创建模型 model = LinearRegression() # 拟合数据 model.fit(x, y) # 进行预测 x_new = np.array([[11]]) y_pred = model.predict(x_new) # 打印预测结果 print("预测结果:", y_pred) ``` 对于非线性回归,可以使用决策树、随机森林或神经网络等算法来实现。具体步骤和代码可以参考引用中提到的示例,通过导入相应的库和函数,并根据数据的特点选择合适的算法和模型来进行建模和预测。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [Python非线性回归](https://download.csdn.net/download/weixin_38686080/14856924)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [python 机器学习之支持向量机非线性回归SVR模型](https://download.csdn.net/download/weixin_38622467/14914405)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值