TensorFlow--非线性逻辑回归

本文介绍了一种利用神经网络进行非线性数据拟合的方法,通过构建一个包含一个隐藏层的简单神经网络模型,并采用梯度下降法进行参数优化,实现了对带有噪声的平方函数的有效拟合。

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

使用带一层中间层的神经网络来作为非线性模型构建

故而共有4个可调节量,分别为 weight_L1, weight_L2, biases_L1, biase_L2  可作为优化调节量

构建好模型之后,优化器用梯度下降法来做,运用梯度下降法的过程中,不断调节以上4个量

以达到使得最后代价函数最小的 weight_L1, weight_L2, biases_L1, biase_L2

神经网络的输出为,经过调节后运用较好的 weight_L1, weight_L2, biases_L1, biase_L2值

得出对y_data的非线性拟合

拟合过程为对原始的x_data输入,由 200 x 1 的矩阵 --> 200 x 10 的矩阵 --> 200 x 1 的矩阵



#-*-coding:utf-8-*-
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

#这里x_data,y_data 是一个200行1列的矩阵
x_data = np.linspace(-0.5,0.5,200)[:,np.newaxis]
noise = np.random.normal(0,0.02,x_data.shape)
y_data = np.square(x_data)+noise


#plt.scatter(x_data,y_data)
#plt.show()

#定义两个placeholder
x = tf.placeholder(tf.float32,[None,1])
y = tf.placeholder(tf.float32,[None,1])

#定义神经网络中间层 1,10 分别表示输入为一个,输出为10个,代表中间层有10个神经元
#weight_L1 为权重,biases_L1为偏置值,random_normal 为10个正态分布随机值
#biases_L1 为初始为[[0.]],与weight_L1相加后,把weight_L1的每一项都加了一个biases_L1
#x,y 就是x_data, y_data 这里 weight_L1,weight_L2,biases_L1,biase_L2 是可优化调节量
#Wx_plus_b_L1 和 L1 是200行10列的矩阵
#tf.nn.tanh() 是双曲线切线激活函数
weight_L1 = tf.Variable(tf.random_normal([1,10]))
biases_L1 = tf.Variable(tf.zeros([1,1]))
Wx_plus_b_L1 = tf.matmul(x,weight_L1)+biases_L1
L1 = tf.nn.tanh(Wx_plus_b_L1)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(biases_L1))
    print(sess.run(Wx_plus_b_L1, feed_dict={x: x_data, y: y_data}))


#定义神经网络输出层
weight_L2 = tf.Variable(tf.random_normal([10,1]))
biases_L2 = tf.Variable(tf.zeros([1,1]))
Wx_plus_b_L2 = tf.matmul(L1,weight_L2)+biases_L2
prediction = tf.nn.tanh(Wx_plus_b_L2)

#二次代价函数
loss = tf.reduce_mean(tf.square(y - prediction))
#用梯度下降法训练
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(loss)

with tf.Session() as sess:
    #变量初始化
    sess.run(tf.global_variables_initializer())
    for _ in range(2000):
        sess.run(train,feed_dict={x:x_data,y:y_data})
    #获得预测值
    prediction_value = sess.run(prediction,feed_dict={x:x_data})
    plt.scatter(x_data,y_data)
    plt.plot(x_data,prediction_value,'r-',lw=5)
    plt.show()




输出结果:








### TensorFlow.NET 和 Keras 实现非线性回归 以下是基于 TensorFlow.NET 和 Keras 的实现非线性回归的一个完整示例代码。此代码展示了如何构建一个简单的神经网络模型来解决非线性回归问题。 #### 数据准备 为了演示目的,我们将生成一些模拟数据作为输入特征 `X` 和目标变量 `Y`。这些数据遵循某种非线性关系。 ```csharp using System; using System.Linq; using NumSharp; using SciSharp.TensorFlow.Keras; using SciSharp.TensorFlow.Keras.Layers; class Program { static void Main(string[] args) { // Generate synthetic non-linear data. NDArray X = NPArange(-10, 10, 0.1); // Input features (independent variable). NDArray noise = NDRandom.Normal(0, 0.2, X.Shape); NDArray Y = np.sin(X) + noise; // Target values with added Gaussian noise. // Reshape the arrays to fit into a neural network model. X = np.reshape(X, (-1, 1)); Y = np.reshape(Y, (-1, 1)); Console.WriteLine("Data preparation completed."); BuildAndTrainModel(X, Y); } private static void BuildAndTrainModel(NDArray X, NDArray Y) { // Initialize the sequential model. var model = new Sequential(); // Add layers to the model. model.Add(new Dense(units: 64, activation: "relu", input_shape: new Shape(1))); model.Add(new Dense(units: 32, activation: "relu")); model.Add(new Dense(units: 1)); // Output layer without any activation function for regression tasks. // Compile the model specifying optimizer and loss function. model.Compile(optimizer: Optimizers.Adam(), loss: Losses.MeanSquaredError); // Train the model on generated data. model.Fit(x: X, y: Y, epochs: 500, batch_size: 32, verbose: 1); Console.WriteLine("Training complete."); // Predictions can be made as follows: // NDArray predictions = model.Predict(X_test); } } ``` 这段代码定义了一个具有两层隐藏层的前馈神经网络,并通过均方误差(MSE)优化器训练它以适应正弦波形加噪声的数据集[^4]。 #### 结果可视化 完成训练之后,可以绘制预测结果与实际值之间的对比图以便直观理解模型性能: ```python import matplotlib.pyplot as plt # Assuming 'predictions' contains output from trained model prediction step above... plt.scatter(X.flatten().ToList<double>(), Y.flatten().ToList<double>(), label="Actual Data"); plt.plot(X.flatten().ToList<double>(), predictions.flatten().ToList<double>(), color='red', linewidth=2, label="Predicted Values"); plt.legend(); plt.xlabel('Input Feature'); plt.ylabel('Target Value'); plt.title('Nonlinear Regression Results'); plt.show(); ``` 以上部分展示的是 Python 版本的结果绘图逻辑;如果需要完全在 C# 环境下操作,则可能需要用到其他库比如 OxyPlot 来替代 Matplotlib 功能[^3]。 ### 注意事项 - **环境配置**:确保已安装最新版 TensorFlow.NET 库以及其依赖项。 - **硬件加速支持**:对于更复杂的模型或者更大规模的数据集考虑启用 GPU 加速选项。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值