import pandas as pd import warnings import sklearn.datasets import sklearn.linear_model import matplotlib import matplotlib.font_manager as fm import matplotlib.pyplot as plt import numpy as np import seaborn as sns data = pd.read_excel(r'C:\Users\Lenovo\Desktop\data.xlsx') print(data.info()) fig = plt.figure(figsize=(10, 8)) sns.heatmap(data.corr(), cmap="YlGnBu", annot=True) plt.title('相关性分析热力图') plt.rcParams['axes.unicode_minus'] = False plt.rcParams['font.sans-serif'] = 'SimHei' plt.show() y = data['y'] X = data.drop(['y'], axis=1) print('************************输出新的特征集数据***************************') print(X.head()) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) def relu(x): output=np.maximum(0, X) return output def relu_back_propagation(derror_wrt_output,X): derror_wrt_dinputs = np.array(derror_wrt_output, copy=True) derror_wrt_dinputs[x <= 0] = 0 return derror_wrt_dinputs def activated(activation_choose,X): if activation_choose == 'relu': return relu(X) def activated_back_propagation(activation_choose, derror_wrt_output, output): if activation_choose == 'relu': return relu_back_propagation(derror_wrt_output, output)
时间: 2023-10-21 09:55:38 浏览: 157
这段代码看起来是用于数据分析和机器学习的,以下是代码的主要功能:
1. 导入必要的包和数据文件(data.xlsx);
2. 读取数据文件并输出数据信息(data.info());
3. 绘制数据的相关性热力图(sns.heatmap());
4. 将特征集和标签分别赋值给X和y;
5. 利用train_test_split()函数将数据集划分为训练集和测试集;
6. 定义了一个名为relu()的函数,这个函数实现了ReLU激活函数的功能;
7. 定义了一个名为relu_back_propagation()的函数,这个函数实现了ReLU激活函数的反向传播功能;
8. 定义了一个名为activated()的函数,这个函数根据传入的激活函数名称,对输入的数据进行激活操作(在这里,激活函数是ReLU);
9. 定义了一个名为activated_back_propagation()的函数,这个函数根据传入的激活函数名称、误差信号和输出值,对误差信号进行反向传播操作(在这里,激活函数是ReLU)。
相关问题
import pandas as pd import warnings import sklearn.datasets import sklearn.linear_model import matplotlib import matplotlib.font_manager as fm import matplotlib.pyplot as plt import numpy as np import seaborn as sns data = pd.read_excel(r'C:\Users\Lenovo\Desktop\data.xlsx') fig = plt.figure(figsize=(10, 8)) sns.heatmap(data.corr(), cmap="YlGnBu", annot=True) plt.title('相关性分析热力图') plt.rcParams['axes.unicode_minus'] = False plt.rcParams['font.sans-serif'] = 'SimHei' plt.show() y = data['y'] X = data.drop(['y'], axis=1) print('************************输出新的特征集数据***************************') print(x.head()) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) data = np.random.rand(42, 42) data_flattened = data.flatten(data)
这段代码中存在一些错误:
1. 第一行代码应该换行,因为 Python 默认不支持在同一行中导入多个模块。
2. 导入模块的语句应该放在文件的开头,而不是在代码中间。
3. `print(x.head())` 应该改为 `print(X.head())`,因为特征集的变量名是大写的 X。
4. `data_flattened = data.flatten(data)` 应该改为 `data_flattened = data.flatten()`,因为 `numpy.ndarray.flatten()` 方法不接受参数。
下面是修改后的代码:
```
import pandas as pd
import warnings
import sklearn.datasets
import sklearn.linear_model
import matplotlib
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.model_selection import train_test_split
data = pd.read_excel(r'C:\Users\Lenovo\Desktop\data.xlsx')
fig = plt.figure(figsize=(10, 8))
sns.heatmap(data.corr(), cmap="YlGnBu", annot=True)
plt.title('相关性分析热力图')
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.show()
y = data['y']
X = data.drop(['y'], axis=1)
print('************************输出新的特征集数据***************************')
print(X.head())
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
data = np.random.rand(42, 42)
data_flattened = data.flatten()
```
上面代码报错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()
这是由于 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()
```
这样就不会再出现警告了。
阅读全文