keras 线性回归 预测

本文通过使用Keras实现线性回归模型,演示了如何从数据准备到模型训练及预测的全过程。文中详细介绍了利用Python及其相关库进行数据生成、模型搭建、训练以及最终结果的可视化展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/env python
# -*- coding:UTF-8 -*-
import numpy as np
np.random.seed(1337)  # for reproducibility
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt 
# 可视化模块

X = np.linspace(-1, 1, 200)
np.random.shuffle(X)    # randomize the data
Y = 0.9 * X + 2 + np.random.normal(0, 0.05, (200, ))
# plot data
#plt.scatter(X, Y)
#plt.show()
 
X_train, Y_train = X[:160], Y[:160]     # train 前 160 data points
X_test, Y_test = X[160:], Y[160:]       # test 后 40 data points
#plt.plot(X_train, Y_train,'.')
#plt.show()

model = Sequential()
l1 = Dense(output_dim = 1,input_dim = 1)
model.add(l1)

model.compile(loss = 'mse',optimizer = 'sgd')
model.fit(X_train,Y_train,epochs= 3000)

print(l1.get_weights())
Xe = np.linspace(1, 2, 20)
Ye = model.predict(Xe)

plt.plot(X_train, Y_train,'.',Xe,Ye,'.')
plt.show()


 

 

运行结果

Epoch 3000/3000
160/160 [==============================] - 0s 30us/step - loss: 0.0026
[array([[0.8913625]], dtype=float32), array([2.0040555], dtype=float32)]
训练得到的权重和偏置和理论值0.9  2 很接近了。

下图中橙色点是预测部分,蓝色点是训练数据。

代码托管在github

https://github.com/sofiathefirst/AIcode

### 使用 TensorFlow.NET 和 Keras 实现非线性回归预测 以下是基于 TensorFlow.NET 和 Keras 的非线性回归预测的一个完整代码示例。此代码展示了如何构建一个简单的神经网络模型来进行非线性回归任务。 #### 数据准备 为了实现非线性回归,通常会生成一些具有复杂关系的数据点作为输入和目标值。以下是一个简单的正弦波数据集的生成方法: ```csharp using System; using NumSharp; using static Tensorflow.Binding; class Program { static void Main(string[] args) { // Step 1: Generate data for non-linear regression. NDArray X_train = np.linspace(-np.pi, np.pi, 100).reshape(100, 1); NDArray y_train = (X_train * np.sin(X_train)) + np.random.normal(0, 0.1, size: new Shape(100, 1)); Console.WriteLine("Data generated successfully."); } } ``` 以上代码生成了一个带有噪声的正弦波数据集[^4]。 --- #### 构建模型 接下来定义一个多层感知机(MLP),它能够捕捉到复杂的非线性模式。这里使用 `Sequential` API 来堆叠多个全连接层。 ```csharp // Step 2: Define the model architecture. var model = new Sequential(); model.Add(new Dense(units: 32, activation: "relu", input_shape: new Shape(1))); model.Add(new Dense(units: 64, activation: "relu")); model.Add(new Dense(units: 1)); // Output layer without activation function. Console.WriteLine("Model defined successfully."); ``` 该模型由两个隐藏层组成,分别有 32 和 64 个神经元,并采用 ReLU 激活函数。最后一层只有一个神经元,适合于回归任务[^5]。 --- #### 编译模型 编译阶段指定优化器、损失函数以及评估指标。 ```csharp // Step 3: Compile the model. model.Compile( optimizer: Optimizers.Adam(), loss: Losses.MeanSquaredError(), metrics: new string[] { Metrics.MeanAbsoluteError }); Console.WriteLine("Model compiled successfully."); ``` 此处选择了均方误差(MSE)作为损失函数,这是处理连续数值输出的标准选择之一[^6]。 --- #### 训练模型 利用之前生成的数据对模型进行训练。 ```csharp // Step 4: Train the model on synthetic dataset. var history = model.Fit( x: X_train, y: y_train, epochs: 100, batch_size: 8); Console.WriteLine("Training completed."); ``` 这段代码设置了批量大小为 8 并迭代 100 轮次完成整个训练过程[^7]。 --- #### 测试与可视化 最后可以测试模型性能并将结果绘制成图表以便观察拟合效果。 ```csharp // Step 5: Predict and visualize results. NDArray predictions = model.Predict(X_train); plt.plot((double[])X_train.reshape(-1), (double[])y_train.reshape(-1), label: "True Values"); plt.plot((double[])X_train.reshape(-1), (double[])predictions.reshape(-1), label: "Predictions"); plt.legend(); plt.show(); Console.WriteLine("Visualization displayed."); ``` 通过 Matplotlib 展示真实值与预测值之间的对比图象有助于直观理解模型的表现情况[^8]。 --- ### 总结 上述流程涵盖了从数据预处理到最终展示的一整套解决方案,适用于解决一般的非线性回归问题。值得注意的是,在实际应用过程中可能还需要进一步调整超参数或者尝试其他类型的架构设计以获得更优的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值