import os import csv def detLabel(filename): #determine the label of the recording if "cello" in filename: label = 0 elif "church" in filename: label = 1 elif "clarinet" in filename: label = 2 elif "flute" in filename: label = 3 elif "guitar" in filename: label = 4 elif "harp" in filename: label = 5 elif "marimba" in filename: label = 6 elif "perldrop" in filename: label = 7 elif "piano" in filename: label = 8 elif "synlead3" in filename: label = 9 else: #violin label = 10 return label fileOrigin = "samples" dataFile = "data.csv" with open(dataFile, 'w', newline='') as csvfile: fileWriter = csv.writer(csvfile, delimiter=',') fileWriter.writerow(['filename', 'instrument']) for filename in os.listdir(fileOrigin): fileWriter.writerow([filename, detLabel(filename)])
时间: 2024-04-25 19:26:30 浏览: 9
这段代码的作用是将文件夹samples中的音频文件按照乐器种类的不同标记,并将它们的名称和标记存储在名为data.csv的CSV文件中。
首先,定义了一个名为detLabel的函数,用于根据文件名确定音频文件所属的乐器种类,并返回一个标记(从0到10)。其中,0~9分别代表cello、church、clarinet、flute、guitar、harp、marimba、perldrop、piano和synlead3,10代表violin。
然后,代码定义了两个变量fileOrigin和dataFile,分别表示存放音频文件的文件夹路径和CSV文件的路径。
接下来,使用Python内置的os模块中的listdir()函数遍历fileOrigin文件夹中的所有文件名,并将它们传递给detLabel函数,获取对应的标记。最后,将文件名和标记写入data.csv文件中,以逗号分隔。其中,第一行为文件头,包括两列:filename和instrument。
相关问题
def detSong(filename): #determine the label of the recording if "babillarde" in filename: song = 0 elif "let" in filename: song = 1 elif "sea" in filename: song = 2 elif "styrienne" in filename: song = 3 else: # tarantella song = 4 return song samplesOrigin = "samples" songsOrigin = "Recordings" numLabels = 11 numSongs = 5 numFiles = {} lengthInstr = {} lengthSong = {} hitsSong = {}、
这段代码定义了一个名为detSong的函数,用于确定音频文件的标签(乐器类别)。具体来说,函数接受一个参数filename,表示音频文件的名称,然后根据文件名中的关键字来确定标签。如果文件名中包含"babillarde",则标签为0;如果包含"let",则标签为1;如果包含"sea",则标签为2;如果包含"styrienne",则标签为3;否则标签为4。最后,函数返回确定的标签。
接下来,代码定义了一些变量:samplesOrigin表示采样数据的路径,songsOrigin表示音频文件的路径,numLabels表示标签的数量(这里是11,但是代码中没有使用),numSongs表示音频文件的数量,numFiles、lengthInstr、lengthSong和hitsSong都是空字典,用于存储后续处理过程中的一些信息。
import numpy as np def sigmoid(x): # the sigmoid function return 1/(1+np.exp(-x)) class LogisticReg(object): def __init__(self, indim=1): # initialize the parameters with all zeros # w: shape of [d+1, 1] self.w = np.zeros((indim + 1, 1)) def set_param(self, weights, bias): # helper function to set the parameters # NOTE: you need to implement this to pass the autograde. # weights: vector of shape [d, ] # bias: scaler def get_param(self): # helper function to return the parameters # NOTE: you need to implement this to pass the autograde. # returns: # weights: vector of shape [d, ] # bias: scaler def compute_loss(self, X, t): # compute the loss # X: feature matrix of shape [N, d] # t: input label of shape [N, ] # NOTE: return the average of the log-likelihood, NOT the sum. # extend the input matrix # compute the loss and return the loss X_ext = np.concatenate((X, np.ones((X.shape[0], 1))), axis=1) # compute the log-likelihood def compute_grad(self, X, t): # X: feature matrix of shape [N, d] # grad: shape of [d, 1] # NOTE: return the average gradient, NOT the sum. def update(self, grad, lr=0.001): # update the weights # by the gradient descent rule def fit(self, X, t, lr=0.001, max_iters=1000, eps=1e-7): # implement the .fit() using the gradient descent method. # args: # X: input feature matrix of shape [N, d] # t: input label of shape [N, ] # lr: learning rate # max_iters: maximum number of iterations # eps: tolerance of the loss difference # TO NOTE: # extend the input features before fitting to it. # return the weight matrix of shape [indim+1, 1] def predict_prob(self, X): # implement the .predict_prob() using the parameters learned by .fit() # X: input feature matrix of shape [N, d] # NOTE: make sure you extend the feature matrix first, # the same way as what you did in .fit() method. # returns the prediction (likelihood) of shape [N, ] def predict(self, X, threshold=0.5): # implement the .predict() using the .predict_prob() method # X: input feature matrix of shape [N, d] # returns the prediction of shape [N, ], where each element is -1 or 1. # if the probability p>threshold, we determine t=1, otherwise t=-1
以下是您提供的代码的完整实现,包括_param()和get_param()方法的实现:
```python
import numpy as np
def sigmoid(x):
# the sigmoid function
return 1 / (1 + np.exp(-x))
class LogisticReg(object):
def __init__(self, indim=1):
# initialize the parameters with all zeros
# w: shape of [d+1, 1]
self.w = np.zeros((indim + 1, 1))
def set_param(self, weights, bias):
# helper function to set the parameters
# weights: vector of shape [d, ]
# bias: scalar
self.w[:-1] = weights.reshape(-1, 1)
self.w[-1] = bias
def get_param(self):
# helper function to return the parameters
# returns:
# weights: vector of shape [d, ]
# bias: scalar
weights = self.w[:-1].reshape(-1)
bias = self.w[-1]
return weights, bias
def compute_loss(self, X, t):
# compute the loss
# X: feature matrix of shape [N, d]
# t: input label of shape [N, ]
# NOTE: return the average of the log-likelihood, NOT the sum.
# extend the input matrix
X_ext = np.concatenate((X, np.ones((X.shape[0], 1))), axis=1)
# compute the log-likelihood
z = X_ext @ self.w
y = sigmoid(z)
loss = -np.mean(t * np.log(y) + (1 - t) * np.log(1 - y))
return loss
def compute_grad(self, X, t):
# X: feature matrix of shape [N, d]
# grad: shape of [d, 1]
# NOTE: return the average gradient, NOT the sum.
X_ext = np.concatenate((X, np.ones((X.shape[0], 1))), axis=1)
z = X_ext @ self.w
y = sigmoid(z)
grad = np.mean(X_ext.T @ (y - t), axis=1)
return grad
def update(self, grad, lr=0.001):
# update the weights
# by the gradient descent rule
self.w -= lr * grad.reshape(-1, 1)
def fit(self, X, t, lr=0.001, max_iters=1000, eps=1e-7):
# implement the .fit() using the gradient descent method.
# args:
# X: input feature matrix of shape [N, d]
# t: input label of shape [N, ]
# lr: learning rate
# max_iters: maximum number of iterations
# eps: tolerance of the loss difference
# TO NOTE:
# extend the input features before fitting to it.
# return the weight matrix of shape [indim+1, 1]
X_ext = np.concatenate((X, np.ones((X.shape[0], 1))), axis=1)
prev_loss = np.inf
for i in range(max_iters):
loss = self.compute_loss(X, t)
if np.abs(loss - prev_loss) < eps:
break
grad = self.compute_grad(X, t)
self.update(grad, lr)
prev_loss = loss
return self.w
def predict_prob(self, X):
# implement the .predict_prob() using the parameters learned by .fit()
# X: input feature matrix of shape [N, d]
# NOTE: make sure you extend the feature matrix first,
# the same way as what you did in .fit() method.
# returns the prediction (likelihood) of shape [N, ]
X_ext = np.concatenate((X, np.ones((X.shape[0], 1))), axis=1)
z = X_ext @ self.w
y = sigmoid(z)
return y
def predict(self, X, threshold=0.5):
# implement the .predict() using the .predict_prob() method
# X: input feature matrix of shape [N, d]
# returns the prediction of shape [N, ], where each element is -1 or 1.
# if the probability p > threshold, we determine t = 1, otherwise t = -1
prob = self.predict_prob(X)
predictions = np.where(prob > threshold, 1, -1)
return predictions
```
这个类实现了逻辑回归的基本功能,包括参数设置、计算损失、计算梯度、更新权重、拟合数据、预测概率和预测类别等方法。您可以使用这个类来拟合二分类问题的数据,并进行预测。