# 绘制准确率变化曲线 plt.subplot(1, 2, 1) plt.plot(history.history['accuracy'], label='train acc') plt.plot(history.history['val_accuracy'], label='val acc') plt.legend() plt.title('Accuracy') # 绘制损失率变化曲线 plt.subplot(1, 2, 2) plt.plot(history.history['loss'], label='train loss') plt.plot(history.history['val_loss'], label='val loss') plt.legend() plt.title('Loss') plt.show()让训练集用实线表示,测试集为虚线
时间: 2023-08-07 20:04:18 浏览: 62
你可以在绘制曲线时指定实线或虚线的样式。可以像下面这样编写代码:
```
import matplotlib.pyplot as plt
# 绘制准确率变化曲线
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='train acc', linestyle='solid')
plt.plot(history.history['val_accuracy'], label='val acc', linestyle='dashed')
plt.legend()
plt.title('Accuracy')
# 绘制损失率变化曲线
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='train loss', linestyle='solid')
plt.plot(history.history['val_loss'], label='val loss', linestyle='dashed')
plt.legend()
plt.title('Loss')
plt.show()
```
这里在绘制训练集和测试集的曲线时,使用 `linestyle` 参数指定实线或虚线的样式。`linestyle='solid'` 表示实线,`linestyle='dashed'` 表示虚线。
相关问题
fig = plt.figure(figsize=(9, 5)) plt.subplot(1, 2, 1) plt.yscale('log') plt.plot(epochs, loss, linestyle='--', linewidth=3, color='orange', alpha=0.7, label='Train Loss') plt.plot(epochs, v_loss, linestyle='-.', linewidth=2, color='lime', alpha=0.8, label='Valid Loss') plt.ylim(0.3, 100) plt.xlabel('Epochs', fontsize=11) plt.ylabel('Loss', fontsize=12) plt.legend(fontsize=12) plt.subplot(1, 2, 2) plt.plot(epochs, acc, linestyle='--', linewidth=3, color='orange', alpha=0.7, label='Train Acc') plt.plot(epochs, v_acc, linestyle='-.', linewidth=2, color='lime', alpha=0.8, label='Valid Acc') plt.xlabel('Epochs', fontsize=11) plt.ylabel('Accuracy', fontsize=12) plt.legend(fontsize=12) plt.tight_layout() plt.show()这是一行输出两个图的代码,怎样实现两个图分别输出?
这段代码使用了subplot函数将两个图绘制在一个Figure中的两个子图中,其中第一个参数1表示行数,第二个参数2表示列数,第三个参数1表示在第一行第一列绘制图形,第三个参数2表示在第一行第二列绘制图形。如果想要分别输出两张图,可以将两个子图分别绘制在两个Figure中,如下所示:
```python
fig1 = plt.figure(figsize=(6, 5))
plt.yscale('log')
plt.plot(epochs, loss, linestyle='--', linewidth=3, color='orange', alpha=0.7, label='Train Loss')
plt.plot(epochs, v_loss, linestyle='-.', linewidth=2, color='lime', alpha=0.8, label='Valid Loss')
plt.ylim(0.3, 100)
plt.xlabel('Epochs', fontsize=11)
plt.ylabel('Loss', fontsize=12)
plt.legend(fontsize=12)
plt.show()
fig2 = plt.figure(figsize=(6, 5))
plt.plot(epochs, acc, linestyle='--', linewidth=3, color='orange', alpha=0.7, label='Train Acc')
plt.plot(epochs, v_acc, linestyle='-.', linewidth=2, color='lime', alpha=0.8, label='Valid Acc')
plt.xlabel('Epochs', fontsize=11)
plt.ylabel('Accuracy', fontsize=12)
plt.legend(fontsize=12)
plt.show()
```
这样就可以分别输出两张图了。注意,需要将Figure的大小调整为适当的大小,以便图像在输出时不会过于拥挤或过于稀疏。
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split # 读取训练集和测试集数据 train_data = pd.read_csv(r'C:\ADULT\Titanic\train.csv') test_data = pd.read_csv(r'C:\ADULT\Titanic\test.csv') # 统计训练集和测试集缺失值数目 print(train_data.isnull().sum()) print(test_data.isnull().sum()) # 处理 Age, Fare 和 Embarked 缺失值 most_lists = ['Age', 'Fare', 'Embarked'] for col in most_lists: train_data[col] = train_data[col].fillna(train_data[col].mode()[0]) test_data[col] = test_data[col].fillna(test_data[col].mode()[0]) # 拆分 X, Y 数据并将分类变量 one-hot 编码 y_train_data = train_data['Survived'] features = ['Pclass', 'Age', 'SibSp', 'Parch', 'Fare', 'Sex', 'Embarked'] X_train_data = pd.get_dummies(train_data[features]) X_test_data = pd.get_dummies(test_data[features]) # 合并训练集 Y 和 X 数据,并创建乘客信息分类变量 train_data_selected = pd.concat([y_train_data, X_train_data], axis=1) print(train_data_selected) cate_features = ['Pclass', 'SibSp', 'Parch', 'Sex', 'Embarked', 'Age_category', 'Fare_category'] train_data['Age_category'] = pd.cut(train_data.Fare, bins=range(0, 100, 10)).astype(str) train_data['Fare_category'] = pd.cut(train_data.Fare, bins=list(range(-20, 110, 20)) + [800]).astype(str) print(train_data) # 统计各分类变量的分布并作出可视化呈现 plt.figure(figsize=(18, 16)) plt.subplots_adjust(hspace=0.3, wspace=0.3) for i, cate_feature in enumerate(cate_features): plt.subplot(7, 2, 2 * i + 1) sns.histplot(x=cate_feature, data=train_data, stat="density") plt.xlabel(cate_feature) plt.ylabel('Density') plt.subplot(7, 2, 2 * i + 2) sns.lineplot(x=cate_feature, y='Survived', data=train_data) plt.xlabel(cate_feature) plt.ylabel('Survived') plt.show() # 绘制点状的相关系数热图 plt.figure(figsize=(12, 8)) sns.heatmap(train_data_selected.corr(), vmin=-1, vmax=1, annot=True) plt.show() sourceRow = 891 output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': predictions}) output.head() # 保存结果 output.to_csv('gender_submission.csv', index=False) print(output) train_X, test_X, train_y, test_y = train_test_split(X_train_data, y_train_data, train_size=0.8, random_state=42) print("随机森林分类结果") y_pred_train1 = train_data.predict(train_X) y_pred_test1 = train_data.predict(test_X) accuracy_train1 = accuracy_score(train_y, y_pred_train1) accuracy_test1 = accuracy_score(test_y, y_pred_test1) print("训练集——随机森林分类器准确率为:", accuracy_train1) print("测试集——随机森林分类器准确率为:", accuracy_train1)
在你的代码中,你正在尝试从 `train_data` 对象上调用一个名为 "predict" 的方法,而 `train_data` 实际上是一个 DataFrame 对象,该对象并没有 "predict" 方法。你应该使用你之前定义的随机森林分类器对象 `RandomForestClassifier` 来进行预测。请将以下代码:
```
y_pred_train1 = train_data.predict(train_X)
y_pred_test1 = train_data.predict(test_X)
```
更改为:
```
# 定义随机森林分类器对象
rfc = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
# 在训练数据上拟合分类器
rfc.fit(train_X, train_y)
# 在训练集和测试集上进行预测
y_pred_train1 = rfc.predict(train_X)
y_pred_test1 = rfc.predict(test_X)
```
这将使用你之前定义的随机森林分类器对象 `rfc` 来进行预测。同时,你需要使用 `rfc.fit(train_X, train_y)` 在训练数据上拟合分类器,然后使用 `rfc.predict(train_X)` 和 `rfc.predict(test_X)` 在训练集和测试集上进行预测。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)