仅向遵守特定条件的数组点添加随机值

时间:2019-02-25 16:57:35

标签: python

我有这段代码已经完成了我打算做的事情,只是因为我正在使用for循环,这与优化有些冲突,据我所知,这通常是个坏主意。

Nx=100
Ny=100
A=np.random.normal(0,scale=2,size=(Nx,Ny))
for x in range(0,Nx):
    for y in range(0,Ny):
        if (A[x,y]*A[x,y] < 1): 
            A[x,y]+=np.random.normal(0)*(1-A[x,y]**2)

问题是我不知道如何用python编写没有for循环就可以执行相同操作的代码。

我没有找到答案,因为我只找到了集中于服从特定语句的数组所有术语的问题/答案。 就我而言,我有兴趣对遵循我的陈述的数组中每个位置添加不同的随机数。

2 个答案:

答案 0 :(得分:2)

如果您可以生成一个以随机数开头的列表,可以按如下所示对代码进行矢量化处理

btnGenerate_DataComments_Click()

以下是用于较小测试用例的可行示例

Nx = 100
Ny = 100
A = np.random.normal(0, scale=2, size=(Nx, Ny))

# Create conditional mask
mask = A**2 < 1

# generate random numbers
randoms = np.random.normal(0, size=A[mask].shape)

# Modify the values where mask condition is fulfilled.
A[mask] += randoms * (1 - A[mask]**2)

答案 1 :(得分:2)

您可以像这样从Python使用import pandas as pd feedback_data = pd.read_csv('output_svm.csv') print(feedback_data) data target 0 facilitates good student teacher communication. positive 1 lectures are very lengthy. negative 2 the teacher is very good at interaction. positive 3 good at clearing the concepts. positive 4 good at clearing the concepts. positive 5 good at teaching. positive 6 does not shows test copies. negative 7 good subjective knowledge. positive 8 good communication skills. positive 9 good teaching methods. positive 10 posseses very good and thorough knowledge of t... positive feedback_data_test = pd.read_csv('classified_feedbacks_test.csv') print(feedback_data_test) data target 0 good teaching. NaN 1 punctuality. NaN 2 provides good practical examples. NaN 3 weak subject knowledge. NaN 4 excellent teacher. NaN 5 no strength. NaN 6 very poor communication skills. NaN 7 not able to clear the concepts. NaN 8 punctual. NaN 9 lack of proper guidance. NaN 10 fantastic speaker. NaN from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(binary = True) ct = CountVectorizer(binary= True) cv.fit(feedback_data['data'].values) ct.fit(feedback_data_test['data'].values) X = feedback_data['data'].apply(lambda X : cv.transform([X])).values X = list([list(x.toarray()[0]) for x in X]) X_test = feedback_data_test['data'].apply(lambda X_test : ct.transform([X_test])).values X_test = list([list(x.toarray()[0]) for x in X_test]) from sklearn import svm from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split target = [1 if i<72 else 0 for i in range(144)] X_train, X_val, y_train, y_val = train_test_split(X, target, train_size = 0.50) clf = svm.SVC(kernel = 'linear', gamma = 0.001, C = 0.05) clf.fit(X, target) #The below line gives error print("Accuracy = %s" %accuracy_score(target,clf.predict([X_test])) )

np.where

这是数组的优势。我们可以高效,快速地应用算术计算。