def __init__(self, harmonic: int, detector: str, *args: Any, **kwargs: Any): # Base class super().__init__(*args, **kwargs) # Configuration self.harmonic = harmonic self.main_detector_name = detector # Properties for determining the event plane resolution # Here we take all other detectors that aren't the main detector self.other_detector_names = [ name for name in self.task_config.get("detectors") if name != self.main_detector_name ] self.output_ranges = self.task_config.get("output_ranges", None) # Validation if self.output_ranges is None: # Default should be to process each centrality range. self.output_ranges = [ params.SelectedRange(min, max) for min, max in zip( np.linspace(0, 100, 11)[:-1], np.linsapce(0, 100, 11)[1:]) ] # Objects that will be created during the calculation self.main_detector: Detector self.other_detectors: List[Detector] self.resolution: histogram.Histogram1D self.selected_resolutions: Dict[params.SelectedRange, Tuple[float, float]] = {}
def lut(val=-1): """ Create an empty look up table(LUT) :param val: If default value is what the lut is initially filled with if val == 0 the array is all zeros. if val > 0 the array is set to default value. Clipped to 255. if val < 0 the array is set to the range [0,255] if val is a tuple of two values: we set stretch the range of 0 to 255 to match the range provided. :return: a LUT. """ lut = None if isinstance(val, list) or isinstance(val, tuple): start = np.clip(val[0], 0, 255) stop = np.clip(val[1], 0, 255) lut = np.around(np.linsapce(start, stop, 256), 0) lut = np.array(lut, dtype='uint8') lut = lut.tolist() elif val == 0: lut = np.zeros([1, 256]).tolist()[0] elif val > 0: val = np.clip(val, 1, 255) lut = np.ones([1, 256]) * val lut = np.array(lut, dtype='uint8') lut = lut.tolist() elif val < 0: lut = np.linspace(0, 256, 256) lut = np.array(lut, dtype='uint8') lut = lut.tolist() return lut
def plot_poly_fit(): plot_data() x=np.linsapce(-60,60,100) xx = x.reshape(100,1) XX = np.insert(xx,0,1,axis=1) xx = poly_feature(xx,power) xx = feature_normalize(xx,train_mean,train_std) plt.plot(x,xx@theta_fit,'r--')
def traj(start,end,const): num_steps = 10 y = np.linspace(start, end, num_steps) x = np.linsapce(const,const,num_steps) def gait_trajectory(y, height): z = np.zeros(num_steps) for i in range(len(y)): z[i] = math.sqrt((height)**2 - (y[i])**2) return z fig = plt.figure() ax = fig.gca(projection='3d') z = gait_trajectory(y, 2)
def optimize(self, f, x0=None, df=None, f_df=None): if self.num_sample is None: x = [np.arange(b[0], b[1], self.epsilon) for b in self.bounds] if self.epsilon is None: x = [np.linsapce(b[0], b[1], self.num_sample) for b in self.bounds] X = np.meshgrid(*x) X = np.array(X).reshape(len(self.bounds), -1).T f_X = self.cost(X) * f(X) final_locs = np.argpartition(f_X.reshape(1, len(f_X))[0], self.save_k)[0:self.save_k] return np.atleast_2d(X[final_locs]), np.atleast_2d(f_X[final_locs])
def transverse_slice(acc_pos, slice_length, beam, height, nb=10, nh=10): """ Returns 3D coordinates of a transverse slice at slice_height. The slice height is relative to the ship origin but the returned positions are relative to the accelerometer. To convert back into ship coordinates use [X] """ x = np.linspace(slice_length, slice_length, 1) y = np.linsapce(-beam / 2, beam / 2, nb) z = np.linspace(0, height, nh) x -= acc_pos[0] y -= acc_pos[1] z -= acc_pos[2] XX, YY, ZZ = np.meshgrid(x, y, z) return XX, YY, ZZ
def prob2 """ 首先录入数据 录入数据并不是矩阵 转换成矩阵 """ columns = data.shape[1] X = data.iloc[:, :columns - 1] y = data.iloc[:, columns - 1:columns] # 创立一个一维向量 与自变量的取值个数相同 w = pd.Series(np.ones(X.shape[0])) X.insert(0,'Ones', w) X = np.matrix(X.values) y = np.matrix(y.values) # 创立参数列向量 theta = np.matrix(np.array([0, 0])) theta, cost, all_theta = gradient_descent(X, y, theta) x = np.linsapce(data.population.min(),data.population.max(),100) #在最大值和最小值之间均匀的取100个值 f = theta[0,0] + (theta[0,1]*x)#g[0,0]相当于十个100维的列向量 f是最后一次迭代后出来的theta函数 fig,ax = plt.subplots(figsize=(12,8)) #figure使用add_subplot,pyplot使用的是subplot生成一个 figure #figure里面再包含多个axes,axes本质上数组 #pyplot由两个函数fugure(figsize=指定画板大小) #和subplot(nrows=,ncols,figsize=(大小)) #fig =plt.figure(figsize=(12,8)) ax.plot(x,f,'r',label='prediction') #真正画图的数据 ax.scatter(data.population,data.profit,marker='x',label='training data') #画散点图 原始数据 ax.set_title('predicted profit vs population size') ax.set_xlabel('population') ax.set_ylabel('profit') ax.legend(loc=2) plt.show() #画预测出的函数与population之间的关系 def pro3: """画出1000次迭代后的tcost值""" fig,ax = plt.subplot(figsize=(12,8)) ax.plot(np.arrange(1000),cost,'blue',label='error') #真正画图的数据 ax.set_title('Error vs. Triaining Epoch') ax.set_xlabel('Iterations') ax.set_ylabel('Cost') plt.show() def pro4: path1 = os.path.join(r'C:\Users\TenSh\Desktop\MachineLearningEx\ex1\ex1', 'ex1data2.txt') #os.path.join(os.getcwd(),'data')就是获取当前目录,并组合成新目录 data1 = pd.read_csv(path1, names=['size', 'bedrooms', 'price']) #均值归一化 data1 = (data1 - data1.mean())/data.std() # 简洁的语句实现了标准化变换,类似地可以实现任何想要的变换。 # data.mean(axis=0) 输出矩阵为一行,求每列的平均值,同理data.mean(axis=1) 输出矩阵为一列,求每行的平均值 # data.std(axis=0) 输出矩阵为一列,求每列的标准差,同理data.std(axis=1) 输出矩阵为一列,求每行的标准差 # 标准差也成为标准偏差,表示数据的离散程度,和标准差大小成反比 col1 = pd.Series(np.ones(data1.shape[0])) #对象 不是数组 也不是矩阵? data1.insert(o,'ones',col1) cols = data1.shape[1] X1 = np.matrix(data1.iloc[:,0:cols - 1].values) #x1 = np.matrix(data2.iloc[:,:]) y1 = np.matrix(data1.iloc[:,cols-1:cols].values) theta1 = np.matrix([0,0,0]) #构建 自变量 因变量(预测数据) 矩阵 #构建函数矩阵 #得出预测数据 画图 theta1,cost1,all_theta1 = gradient_descent(X1,y1,theta1) fig1,ax1 = plt.subplots(figsize=(12,8)) ax1.plot(np.arange(1000),cost1,'r',label='multierror') ax.set_title('multi varible linear regression') plt.show() def main(): """
'''linspace start, stop, numの3つです。 startは数列の開始点を指定する stopは数列の終了点を指定する numは数列の要素の数を指定する ''' x_1 = np.linspace(0, 1, 100) y_1 = x_1 x_2 = np.linspace(0, 1, 100) y_2 = x_2 ** 2 x_3 = np.linspace(0, 1, 100) y_3 = x_3 ** 3 x_4 = np.linspace(0, 1, 100) y_4 = x_4 ** 4 fig = plt.figure() ax_1 = fig.add_subplot(221) #? 2 x 2 so 4 charts first chart ax_2 = fig.add_subplot(222) ax_3 = fig.add_subplot(223) ax_4 = fig.add_subplot(224) ax_1.plot(x_1, y_1) ax_2.plot(x_2, y_2) ax_3.plot(x_3, y_3) ax_4.plot(x_4, y_4) plt.show() print(np.linsapce(0 ,30, 11))
gammas = [0.01, 0.03, 0.05, 0.07, 0.09, 0.12, 0.15] r = -0.1 np.random.seed(0) x = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]] y = [0] * 20 + [1] * 20 for gamma in gammas: my_estimator = svm.SVR(kernel = 'sigmoid', gamma = gamma, coef0 = r) my_estimator.fit(x, y) # w = my_estimator.coef_[0] # a = -w[0] / w[1] x_lim = np.linspace(-5, 5) y_lim = np.linsapce(-5, 5) # b = my_estimator.support_vectors_[0] # y_lower = a * x_lim + (b[1] - a * b[0]) b = my_estimator.support_vectors_[-1] y_upper = a * x_lim + (b[1] - a * b[0]) plt.plot(x_lim, y_lim, 'k-*-') plt.plot(x_lim, y_lower, 'bo') plt.plot(x_lim, y_upper, 'r-') plt.scatter(my_estimator.support_vectors_[:, 0], my_estimator.support_vectors_[:, 1], s = 80, facecolors = 'none') plt.scatter(x[:, 0], x[:, 1], c = y, cmap = plt.cm.Paired)
b.date b.data c = dtype([[1,2],[3,4]],dtype=complex) c = np.array([[1,2],[3,4]],dtype=complex) c np.zeros((3,4)) np.zeros([3,4]) np.ones((2,5),dtype=np.int16) np.empty((3,4)) np.arange(0,4,0.5) np.pi pi pi.evalf() pi.evalf(18) pi.evalf(100) np.linsapce(0,2,9) np.linspace(0,2,9) np.linspace(0,2*np.pi,100) x = np.linspace(0,2*np.pi,100) f = np.sin(x) a = np.arange(6) b = np.arange(12).reshape(4,3) b print(b) b = np.arange(12).reshape(2,3,2) b print(np.arange(10000)) a b c = np.linspace(1,6,6) c
def __init__(self, name, Ns, n_class, params = None): self.name = name self.Ns = Ns self.n_class = n_class if (params is None): self.params = {} else: self.params = params #For each type of aggregator, set default parameters or check if the provided one are correct. if (name == 'naive'): if ("cond_pdf" in self.params): if (self.params["cond_pdf"].shape[1] != self.n_class): raise ValueError('Incorrect array size. Conditional probabilities is 3D array with shape (Ns,n_class,n_class)') else: self.params["cond_pdf"]=None if ("prior" in self.params): if (self.params["prior"].shape != (self.n_class,)): raise ValueError('Incorrect array size. Prior probabilities is 1D array with shape (n_class,)') else: self.params["prior"]=None elif (name == 'spocc'): if ("tnorm" in self.params): if (self.params["tnorm"] not in ['Aczel-Alsina','convex']): raise ValueError('Unknown tnorm type.') else: self.params["tnorm"]='convex' if ("cond_pdf" in self.params): if (self.params["cond_pdf"].shape[1] != self.n_class): raise ValueError('Incorrect array size. Conditional probabilities is 3D array with shape (Ns,n_class,n_class)') else: self.params["cond_pdf"]=None if ("cond_possib" in self.params): if (self.params["cond_possib"].shape[1] != self.n_class): raise ValueError('Incorrect array size. Conditional possibilities is 3D array with shape (Ns,n_class,n_class)') else: self.params["cond_possib"]=None if ("hyper" in self.params): if not(isinstance(self.params["hyper"], Number)): raise ValueError('Invalid type for parameter hyper which must be a number') else: if (self.params["hyper"]<0): raise ValueError('Invalid value for parameter hyper which must be positive.') else: self.params["hyper"] = 0.0 if ("hyper_range" in self.params): if (self.params["hyper_range"].ndim !=1): raise ValueError('Invalid array dimension. hyper_range must be a 1D array') else: self.params["hyper_range"] = np.logspace(-2,1,101) elif (name == 'adaspocc'): self.params["alpha"]=None self.params["dendro"]=None if ("clf_scores" in self.params): if (self.params["clf_scores"].shape != (self.Ns,)): raise ValueError('Incorrect shape for parameter clf_scores which must have shape (Ns,).') else: self.params["clf_scores"] = None if ("tnorm" in self.params): if (self.params["tnorm"] not in ['convex','Aczel-Alsina']): raise ValueError('Unknown tnorm type.') else: self.params["tnorm"]='convex' if ("cond_pdf" in self.params): if (self.params["cond_pdf"].shape[1] != self.n_class): raise ValueError('Incorrect array size. Conditional probabilities is 3D array with shape (Ns or more,n_class,n_class)') else: self.params["cond_pdf"]=None if ("cond_possib" in self.params): if (self.params["cond_possib"].shape[1] != self.n_class): raise ValueError('Incorrect array size. Conditional possibilities is 3D array with shape (Ns or more,n_class,n_class)') else: self.params["cond_possib"]=None if ("r" in self.params): if not(isinstance(self.params["r"], Number)): raise ValueError('Invalid type for parameter r which must be a number') else: if (self.params["r"]<0): raise ValueError('Invalid value for parameter r which must be positive.') else: self.params["r"] = 10.0 if ("hyper" in self.params): if not(isinstance(self.params["hyper"], Number)): raise ValueError('Invalid type for parameter hyper which must be a number') else: if (self.params["hyper"]<0): raise ValueError('Invalid value for parameter hyper which must be positive.') else: self.params["hyper"] = 0.0 if ("hyper_range" in self.params): if (self.params["hyper_range"].ndim !=1): raise ValueError('Invalid array dimension. hyper_range must be a 1D array') else: self.params["hyper_range"] = np.logspace(-2,1,101) if ("alpha_range" in self.params): if (self.params["alpha_range"].ndim !=1): raise ValueError('Invalid array dimension. alpha_range must be a 1D array') else: self.params["alpha_range"] = np.linsapce(0,1,101) elif (name == 'stacked_logreg'): if ("hyper" in self.params): if not(isinstance(self.params["hyper"], Number)): raise ValueError('Invalid type for parameter hyper which must be a number') else: if (self.params["hyper"]<0) : raise ValueError('Invalid value for parameter hyper which must be positive.') else: self.params["hyper"] = 1.0 if ("clf_meta" in self.params): if not(isinstance(self.params["clf_meta"], LogisticRegression)): raise ValueError('Invalid type of object. clf_meta must be an instance of LogisticRegression from sklearn.') else: self.params["clf_meta"] = LogisticRegression(penalty='l2', C=self.params["hyper"]) if ("regul_range" in self.params): if (self.params["regul_range"].ndim !=1): raise ValueError('Invalid array dimension. regul_range must be a 1D array') else: self.params["regul_range"] = np.logspace(-2,2,101) elif (name == 'weighted_vote'): if ("clf_scores" in self.params): if (self.params["clf_scores"].shape != (self.Ns,)): raise ValueError('Incorrect shape for parameter clf_scores which must have shape (Ns,).') else: self.params["clf_scores"] = None if ("r" in self.params): if not(isinstance(self.params["r"], Number)): raise ValueError('Invalid type for parameter r which must be a number') else: if (self.params["r"]<0): raise ValueError('Invalid value for parameter r which must be positive.') else: self.params["r"] = 10.0 if ("r_range" in self.params): if (self.params["r_range"].ndim !=1): raise ValueError('Invalid array dimension. r_range must be a 1D array') else: self.params["r_range"] = np.logspace(-1,2,201) if("expo" in self.params): if (type(self.params["expo"])!=bool): raise ValueError('Parameter expo must be a bool.') else: self.params["expo"]=True elif (name == 'selection'): if ("clf_scores" in self.params): if (self.params["clf_scores"].shape != (self.Ns,)): raise ValueError('Incorrect shape for parameter clf_scores which must have shape (Ns,).') else: self.params["clf_scores"] = None if ("select" in self.params): if (type(self.params["select"]) is not int): raise ValueError('Invalid type for parameter select which must be an integer.') else: self.params["select"] = None elif (name == 'bayes'): size = (self.n_class,) for i in range(Ns): size += (self.n_class,) self.params["cond_probas"] = np.zeros(size) else: raise ValueError('Unknown type of Aggregator.')
import mplcursors import Modelo_fast.graficos_matplotly as gm import numpy as np lista_arquivos_base = [ "modelo1(42x42)[tipo_1].txt", # 0 "modelo2(42x42)[tipo_1].txt", # 1 "modelo4(42x42)[tipo_1].txt", # 2 "modelo5(42x42)[tipo_1].txt", # 3 "modelo6(42x42)[tipo_1].txt" ] # 4 arquivo_usado = lista_arquivos_base[1] pesos_dif_orientacao = np.linspace(0, 1, 100) pesos_distancia = np.linsapce(0, 1, 100) numero_simulacao = 0 qnt_time_steps_teste = 30 matriz_entropias = [] lista_cores = [] lista_labels = [] for peso_orientacao in pesos_dif_orientacao: for peso_distancia in pesos_distancia: numero_simulacao += 1 peso_atual = (peso_orientacao, peso_distancia) df_resultados = simulacao_com_arquivo(arquivo_usado,