上面代码报错E:/python3.9-workspace/python-learn/softmax regression.py:47: MatplotlibDeprecationWarning: Support for FigureCanvases without a required_interactive_framework attribute was deprecated in Matplotlib 3.6 and will be removed two minor releases later. plt.scatter(X_test[y_pred == i, 0], X_test[y_pred == i, 1], color=colors[i], marker=markers[i], E:/python3.9-workspace/python-learn/softmax regression.py:50: MatplotlibDeprecationWarning: Support for FigureCanvases without a required_interactive_framework attribute was deprecated in Matplotlib 3.6 and will be removed two minor releases later. plt.show()
时间: 2024-03-14 08:47:48 浏览: 81
这是由于 Matplotlib 3.6 版本开始,FigureCanvas 对象需要一个 `required_interactive_framework` 属性,而在旧版本中没有该属性,因此会出现警告。这不会影响代码的运行,但建议更新到新版本的 Matplotlib 库。
如果想要避免这个警告,可以在代码中加入以下语句:
```python
import warnings
warnings.filterwarnings("ignore", message="Support for FigureCanvases without a required_interactive_framework attribute was deprecated")
```
这样就可以忽略这个警告了。完整代码如下:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import warnings
warnings.filterwarnings("ignore", message="Support for FigureCanvases without a required_interactive_framework attribute was deprecated")
iris = load_iris()
X = pd.DataFrame(data=iris.data, columns=iris.feature_names)
y = pd.DataFrame(data=iris.target, columns=['target'])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
class SoftmaxRegression:
def __init__(self, n_classes, n_features):
self.n_classes = n_classes
self.n_features = n_features
self.weights = np.zeros((n_features, n_classes))
def softmax(self, z):
return np.exp(z) / np.sum(np.exp(z), axis=1, keepdims=True)
def predict(self, X):
logits = np.dot(X, self.weights)
return np.argmax(self.softmax(logits), axis=1)
def fit(self, X, y, learning_rate=0.1, epochs=1000):
for i in range(epochs):
logits = np.dot(X, self.weights)
y_pred = self.softmax(logits)
loss = -np.mean(np.sum(y * np.log(y_pred), axis=1))
gradient = np.dot(X.T, (y_pred - y))
self.weights -= learning_rate * gradient
if i % 100 == 0:
print(f'Epoch {i}, Loss: {loss:.4f}')
model = SoftmaxRegression(n_classes=3, n_features=4)
model.fit(X_train, pd.get_dummies(y_train['target']).values, learning_rate=0.1, epochs=1000)
y_pred = model.predict(X_test)
colors = ['red', 'green', 'blue']
markers = ['o', 's', 'x']
for i in range(3):
plt.scatter(X_test[y_pred == i, 0], X_test[y_pred == i, 1], color=colors[i], marker=markers[i],
label=iris.target_names[i])
plt.legend()
plt.show()
```
这样就不会再出现警告了。
阅读全文