PermissionError: [Errno 13] Permission denied:を解決したい。
PermissionError: [Errno 13] Permission denied:を解決したい。
教師なし学習を行わせる際に作成したコードを実行したところ実行させた中にある指定ファイルの権限がないと言われ進めません。
解決方法を教えていただきたいです。
個人的なファイルになっているためファイル名をA,B,Cで置き換えています。エラーの出ているファイルはCと置き換えてあファイルになっています。
使用環境
windows10
jupyter notebook
python 3.10.6
発生している問題・エラー
PermissionError Traceback (most recent call last)
Cell In[8], line 122
118 plot_scatter3d(pca_df)
121 if __name__ == "__main__":
--> 122 main()
Cell In[8], line 100, in main()
97 CSV_PATH = 'C.csv'
99 try:
--> 100 pca_df = pd.read_csv(CSV_PATH)
101 except FileNotFoundError:
102 npy_image_list = load_image(LOAD_PATH)
File ~\anaconda3\Lib\site-packages\pandas\io\parsers\readers.py:1026, in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, date_format, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options, dtype_backend)
1013 kwds_defaults = _refine_defaults_read(
1014 dialect,
1015 delimiter,
(...)
1022 dtype_backend=dtype_backend,
1023 )
1024 kwds.update(kwds_defaults)
-> 1026 return _read(filepath_or_buffer, kwds)
File ~\anaconda3\Lib\site-packages\pandas\io\parsers\readers.py:620, in _read(filepath_or_buffer, kwds)
617 _validate_names(kwds.get("names", None))
619 # Create the parser.
--> 620 parser = TextFileReader(filepath_or_buffer, **kwds)
622 if chunksize or iterator:
623 return parser
File ~\anaconda3\Lib\site-packages\pandas\io\parsers\readers.py:1620, in TextFileReader.__init__(self, f, engine, **kwds)
1617 self.options["has_index_names"] = kwds["has_index_names"]
1619 self.handles: IOHandles | None = None
-> 1620 self._engine = self._make_engine(f, self.engine)
File ~\anaconda3\Lib\site-packages\pandas\io\parsers\readers.py:1880, in TextFileReader._make_engine(self, f, engine)
1878 if "b" not in mode:
1879 mode += "b"
-> 1880 self.handles = get_handle(
1881 f,
1882 mode,
1883 encoding=self.options.get("encoding", None),
1884 compression=self.options.get("compression", None),
1885 memory_map=self.options.get("memory_map", False),
1886 is_text=is_text,
1887 errors=self.options.get("encoding_errors", "strict"),
1888 storage_options=self.options.get("storage_options", None),
1889 )
1890 assert self.handles is not None
1891 f = self.handles.handle
File ~\anaconda3\Lib\site-packages\pandas\io\common.py:873, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)
868 elif isinstance(handle, str):
869 # Check whether the filename is to be opened in binary mode.
870 # Binary mode does not support 'encoding' and 'newline'.
871 if ioargs.encoding and "b" not in ioargs.mode:
872 # Encoding
--> 873 handle = open(
874 handle,
875 ioargs.mode,
876 encoding=ioargs.encoding,
877 errors=errors,
878 newline="",
879 )
880 else:
881 # Binary mode
882 handle = open(handle, ioargs.mode)
PermissionError: [Errno 13] Permission denied: 'C.csv'
該当するソースコード
import glob as gb
import shutil
import cv2
import os
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D
# 画像の読み込み
def load_image(path):
image_list = []
npy_image_list = []
image_path_list = gb.glob(f"{path}/*") # 画像の保存先次第で変更
for i, image in enumerate(image_path_list):
image_path = image.replace(chr(92), '/') # Windows特有の問題を修正
if i % 100 == 0:
print(i)
img_npy = cv2.imread(image_path, cv2.IMREAD_COLOR)
img_npy = cv2.cvtColor(img_npy, cv2.COLOR_BGR2RGB)
img_npy = cv2.resize(img_npy, (64, 64))
img_npy = img_npy.flatten()
npy_image_list.append(img_npy / 255)
return npy_image_list
def build_kmeans(df, cluster_num):
kmeans = KMeans(n_clusters=cluster_num, random_state=2021)
kmeans.fit(df)
return kmeans
def build_pca(df):
pca = PCA()
pca.fit(df)
return pca
def plot_contribution_rate(pca):
fig = plt.figure()
plt.gca().get_xaxis().set_major_locator(ticker.MaxNLocator(integer=True))
plt.plot([0] + list(np.cumsum(pca.explained_variance_ratio_)), "-o")
plt.xlabel("Number of principal components")
plt.ylabel("Cumulative contribution rate")
plt.grid()
plt.show()
def plot_scatter2d(df):
fig = plt.figure()
sns.scatterplot(data=df, x='PC1', y='PC2', hue='label', palette='bright', legend='full')
plt.show()
def plot_scatter3d(df):
fig = plt.figure()
ax = Axes3D(fig)
ax.set_xlabel("PC1")
ax.set_ylabel("PC2")
ax.set_zlabel("PC3")
for label in df['label'].values:
ax.plot(df.loc[df['label'] == label, 'PC1'],
df.loc[df['label'] == label, 'PC2'],
df.loc[df['label'] == label, 'PC3'],
alpha=0.8, marker=".", linestyle='None')
plt.show()
def make_cluster_dir(load_path, save_path, kmeans):
shutil.rmtree(save_path, ignore_errors=True)
os.makedirs(save_path, exist_ok=True)
for i in range(kmeans.n_clusters):
cluster_dir = os.path.join(save_path, f"cluster{i}")
os.makedirs(cluster_dir, exist_ok=True)
image_path_list = gb.glob(os.path.join(load_path, '*'))
for label, path in zip(kmeans.labels_, image_path_list):
shutil.copyfile(path, os.path.join(save_path, f'cluster{label}', os.path.basename(path)))
print('クラスタごとにファイル作成完了')
def main():
LOAD_PATH = 'A'
SAVE_PATH = 'B'
CSV_PATH = 'C.csv'
try:
pca_df = pd.read_csv(CSV_PATH)
except FileNotFoundError:
npy_image_list = load_image(LOAD_PATH)
df = pd.DataFrame(npy_image_list)
print(df.shape)
pca = build_pca(df)
pca_df = pd.DataFrame(pca.transform(df), columns=[f"PC{x + 1}" for x in range(len(df.columns))])
plot_contribution_rate(pca)
pca_df.to_csv(CSV_PATH, index=False)
train_df = pca_df.iloc[:, :1200]
cluster_num = int(input('cluster_num > '))
kmeans = build_kmeans(train_df, cluster_num)
make_cluster_dir(LOAD_PATH, SAVE_PATH, kmeans)
pca_df['label'] = kmeans.labels_
plot_scatter2d(pca_df)
plot_scatter3d(pca_df)
if __name__ == "__main__":
main()
自分で試したこと
エラーの出ているファイルの読み取り専用のチェックを外すことは試みましたが解決しませんでした。
0