PermissionError: [Errno 13] Permission denied: 'submission.csv'
时间: 2024-10-23 14:07:41 浏览: 70
出现 `PermissionError: [Errno 13] Permission denied: 'submission.csv'` 错误的原因通常是由于没有足够的权限在指定路径下创建或写入文件。以下是一些可能的解决方案:
1. **检查文件路径**:
- 确保 `output_path` 路径是正确的,并且该目录存在。
- 如果路径中包含多个层级,请确保所有中间目录都已创建。
2. **运行程序的权限**:
- 确保你有足够的权限在目标目录下创建文件。你可以尝试以管理员身份运行你的代码(例如,在Windows上右键点击命令提示符并选择“以管理员身份运行”)。
3. **文件是否被其他程序占用**:
- 确认 `submission.csv` 文件是否已经被其他程序打开或锁定。如果是,请关闭相关程序后再试。
4. **更改输出路径**:
- 尝试将 `output_path` 更改为一个你有写权限的目录,例如当前工作目录:
```python
output_path = "./submission.csv"
```
5. **检查磁盘空间**:
- 确保目标磁盘有足够的空间来创建新文件。
以下是修改后的代码示例,将输出路径更改为当前工作目录:
```python
import os
import json
import numpy as np
import pandas as pd
from PIL import Image
import tensorflow as tf
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam
from sklearn.metrics import f1_score, accuracy_score
def load_data(data_dir, label_path):
with open(label_path, 'r') as f:
labels_list = json.load(f)
labels = {item['文件名']: item['标签'] for item in labels_list if '文件名' in item and '标签' in item}
images = []
targets = []
for file_name, label in labels.items():
img_path = os.path.join(data_dir, file_name)
if not os.path.exists(img_path):
print(f"Warning: Image file {img_path} does not exist.")
continue
img = Image.open(img_path).resize((128, 128))
img_array = np.array(img) / 255.0
images.append(img_array)
targets.append(label)
if len(images) == 0:
raise ValueError("No valid images found. Please check the data directory and label path.")
return np.array(images), np.array(targets)
data_dir = "C:\\Users\\24067\\Desktop\\peach_split\\train"
label_path = "C:\\Users\\24067\\Desktop\\train_label.json"
try:
images, labels = load_data(data_dir, label_path)
except ValueError as e:
print(e)
exit()
label_map = {'特级': 3, '一级': 2, '二级': 1, '三级': 0}
labels = np.array([label_map[label] for label in labels])
X_train, X_val, y_train, y_val = train_test_split(images, labels, test_size=0.2, random_state=42)
def create_model(input_shape=(128, 128, 3)):
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=input_shape),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Conv2D(128, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(4, activation='softmax')
])
return model
model = create_model()
model.compile(optimizer=Adam(learning_rate=0.001), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
datagen = ImageDataGenerator(
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True,
vertical_flip=True
)
history = model.fit(datagen.flow(X_train, y_train, batch_size=32), epochs=1, validation_data=(X_val, y_val))
def evaluate_model(model, X, y):
predictions = model.predict(X)
predicted_labels = np.argmax(predictions, axis=1)
accuracy = accuracy_score(y, predicted_labels)
f1 = f1_score(y, predicted_labels, average='weighted')
print(f'Accuracy: {accuracy:.4f}')
print(f'F1 Score: {f1:.4f}')
return accuracy, f1
evaluate_model(model, X_val, y_val)
def predict_and_save(test_data_dir, test_label_path, output_path):
test_images = []
test_file_names = []
with open(test_label_path, 'r') as f:
test_labels_list = json.load(f)
test_labels = {item['文件名']: item['标签'] for item in test_labels_list if '文件名' in item and '标签' in item}
for file_name in test_labels.keys():
img_path = os.path.join(test_data_dir, file_name)
if not os.path.exists(img_path):
print(f"Warning: Test image file {img_path} does not exist.")
continue
img = Image.open(img_path).resize((128, 128))
img_array = np.array(img) / 255.0
test_images.append(img_array)
test_file_names.append(file_name)
test_images = np.array(test_images)
predictions = model.predict(test_images)
predicted_labels = np.argmax(predictions, axis=1)
label_map_inv = {v: k for k, v in label_map.items()}
predicted_labels = [label_map_inv[label] for label in predicted_labels]
submission_df = pd.DataFrame({'file_name': test_file_names, 'label': predicted_labels})
submission_df.to_csv(output_path, index=False)
test_data_dir = "C:\\Users\\24067\\Desktop\\peach_split\\val"
test_label_path = "C:\\Users\\24067\\Desktop\\val_label.json"
output_path = "./submission.csv" # 修改输出路径
predict_and_save(test_data_dir, test_label_path, output_path)
```
希望这些步骤能帮助你解决权限问题。如果问题仍然存在,请提供更多详细信息以便进一步诊断。
阅读全文