if i want to visualize loss function change, what's the code
时间: 2024-02-22 18:58:32 浏览: 64
Python Package to Visualize different aspects of a Neural Networ
You can visualize the loss function change during the training process using the `loss_curve_` attribute of the `LogisticRegression` model. Here's the modified code to plot the loss function change during training:
```
import matplotlib.pyplot as plt
import numpy as np
# Load the iris dataset
iris = load_iris()
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)
# Preprocess the data by scaling the features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Train a logistic regression model on the training set
lr = LogisticRegression(penalty='l2', C=1.0, solver='lbfgs', max_iter=1000)
lr.fit(X_train, y_train)
# Visualize loss function change during training
plt.plot(np.arange(len(lr.loss_curve_)), lr.loss_curve_)
plt.title('Loss function change during training')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.show()
# Evaluate the performance of the model on the testing set
y_pred = lr.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
```
In this code, we first train the logistic regression model using the same code as before. Then, we plot the loss function change during training using the `loss_curve_` attribute of the model. We use `np.arange(len(lr.loss_curve_))` to create an array of numbers from 0 to the length of the loss curve, which corresponds to the number of iterations during training. We then plot the loss curve against the iteration number using `plt.plot()` function from matplotlib library. Finally, we add a title, x-label, and y-label to the plot using `plt.title()`, `plt.xlabel()`, and `plt.ylabel()` functions, respectively. We use `plt.show()` function to display the plot.
阅读全文