gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
generate linear regression with deep learning using tensorflow
- User
generate linear regression with deep learning using tensorflow
- Assistant
Certainly! Below is an example of how to implement a simple linear regression model using deep learning with TensorFlow. We'll create some synthetic data and then train a very simple model to fit this data.
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # Generate synthetic data # y = 3.5 * x + 2.0 + noise np.random.seed(42) X = np.linspace(0, 10, 100) noise = np.random.normal(0, 1, X.shape) y = 3.5 * X + 2.0 + noise # Reshape data for the model X = X.reshape(-1, 1) y = y.reshape(-1, 1) # Build the linear regression model using Keras API model = tf.keras.Sequential([ tf.keras.layers.Dense(1, input_shape=(1,)) ]) # Compile the model model.compile(optimizer='adam', loss='mse') # Train the model history = model.fit(X, y, epochs=100, verbose=0) # Print the learned weights and bias weights, bias = model.layers[0].get_weights() print(f'Learned weight: {weights[0][0]:.4f}') print(f'Learned bias: {bias[0]:.4f}') # Make predictions predictions = model.predict(X) # Plot original data and the regression line plt.scatter(X, y, label='Data') plt.plot(X, predictions, color='red', label='Fitted line') plt.legend() plt.show()