def bestfitline(self): self.font = {'fontname': 'Arial', 'weight': 'bold', 'size': 15} self.lineindex = 4 L = len(self.Re) self.a0 = 0.0 self.a1 = 0.0 self.a2 = 0.0 self.square = 1.0 for i in xrange(self.lineindex, L+1): a, b, c = np.polyfit(self.Re[0:i], self.F[0:i], 2) Fit = a*self.Re[0:i]**2.0+b*self.Re[0:i] + c error = norm(np.abs(Fit-self.F[0:i]))/norm(self.F[0:i]) plt.plot(self.Re[0:i], self.F[0:i], 'ks', label='numerical result') plt.plot(self.Re[0:i], Fit, '-k', label='least square fit') plt.xlabel(r'$Re,\alpha=0.25$', self.font) plt.ylabel(r'$\frac{F-F_s}{\mu U}$', self.font, fontsize=16) plt.legend(frameon=False, numpoints=1, loc=9) print error, a, b, c, self.Re[i-1], i savefig("%d.eps" % i) plt.close('all') if error < self.square: self.square = error self.a0 = a self.a1 = b self.a2 = c self.lineindex = i if i == 21: break print self.square, self.a0, self.a1, self.a2, self.lineindex
def movieSimilarity_cos(self): train = self.trainData self.movieSim = {} movieRating = {} for user, movies in train.items(): for m1 in movies: for m2 in movies.keys(): if m1 == m2: continue self.movieSim.setdefault(m1, {}) self.movieSim[m1].setdefault(m2, 0) for user, movies in train.items(): for m1 in movies: for m2 in movies.keys(): if m1 == m2: continue movieRating.setdefault(m1,{}) movieRating[m1].setdefault(m2,[[],[],[]]) movieRating[m1][m2][0].append(movies[m1]) movieRating[m1][m2][1].append(movies[m2]) movieRating[m1][m2][2].append(user) for m1, related_movies in self.movieSim.items(): for m2, _ in related_movies.items(): self.movieSim[m1][m2] = \ sum(np.multiply(movieRating[m1][m2][0],movieRating[m1][m2][1])) \ / (norm(movieRating[m1][m2][0]) * norm(movieRating[m1][m2][1]))
def get_similarity(a, b): na = np.array(a) nb = np.array(b) suma = sum(na) sumb = sum(nb) if suma == 0 and sumb == 0: return 0 elif suma == 0 or sumb == 0: return 1 else: return 1 - np.vdot(na, nb) / (norm(na) * norm(nb))
def Conjugate_dir(fun, dfun, x0, Linear_Search, maxiter=200, tal=1e-10): x0 = np.atleast_1d(x0) v = -dfun(x0) for i in range(maxiter): alpha = Linear_Search(fun, dfun=dfun, x0=x0, p=-v) if (abs(v) < tal).all(): break denom = norm(np.atleast_1d(dfun(x0)), 2) x0 = x0 + alpha * v num = norm(np.atleast_1d(dfun(x0)), 2) v = -dfun(x0) - num / denom * v return x0, i
def Newton_iterate(X, Y, B, eps, max_it=10000): ''' =================== 牛顿迭代 ==================== 输入: X 样例矩阵, 每行一个样例 Y 样例类别, 向量 B 初始参数值 (w; b) eps 容许的误差限 max_it 最大迭代次数 输出: B1 收敛的参数值 (w; b) i 实际迭代次数 ============================================= ''' m = X.shape[0] # number of the samples X_hat = np.c_[X, np.ones(m)] def p(X, B): ''' p(y = 1 | X; B) ''' tmp = np.exp(np.dot(B, X)) return tmp / (1 + tmp) def plpB(X, Y, B): ''' l 对 B 的一阶偏导数 ''' lst = [ X[i,:] * (p(X[i,:].T, B) - Y[i]) for i in range(m) ] return np.sum(lst, 0) def p2lpB2(X, Y, B): ''' l 对 B 的二阶偏导数 ''' n = X.shape[1] _sum = np.zeros((n, n)) for i in range(m): tmp = p(X[i,:], B) _sum += np.outer(X[i,:], X[i,:]) * tmp * (1 - tmp) return _sum B1 = B - np.dot(np.linalg.inv(p2lpB2(X_hat, Y, B)), plpB(X_hat, Y, B)) i = 0 while norm(B1 - B) > eps: B = B1 B1 = B - np.dot(np.linalg.inv(p2lpB2(X_hat, Y, B)), plpB(X_hat, Y, B)) i += 1 if i > max_it: # 迭代不收敛 print("Not converge with ", max_it, "iterations.") print("Error norm: ", norm(B1 - B)) print("(W, b): ", B1) exit() return B1, i
def prepeq(E, f, neglect): """ a utility routine for arlseq() below that prepares the equality constraints for use""" E = atleast_2d(_asarray_validated(E, check_finite=True)) f = atleast_1d(_asarray_validated(f, check_finite=True)) EE = E.copy() ff = f.copy() m, n = EE.shape for i in range(0, m): # determine new best row and put it next if i == 0: imax = find_max_sense(EE, ff) else: rnmax = -1.0 imax = -1 for k in range(i, m): rn = norm(EE[k, :]) if imax < 0 or rn > rnmax: rnmax = rn imax = k EE[[i, imax], :] = EE[[imax, i], :] ff[[i, imax]] = ff[[imax, i]] # normalize rin = norm(EE[i, :]) if rin > 0.0: EE[i, :] /= rin ff[i] /= rin else: EE[i, :] = 0.0 # will be culled below ff[i] = 0.0 # subtract projections onto EE[i,:] for k in range(i + 1, m): d = np.dot(EE[k, :], EE[i, :]) EE[k, :] -= d * EE[i, :] ff[k] -= d * ff[i] # reject ill-conditioned rows if m > 2: g = np.zeros(m) for k in range(0, m): g[k] = abs(ff[k]) m1 = splita(m, g) mm = splitb(m1, g) if mm < m: EE = np.resize(EE, (mm, n)) ff = np.resize(ff, mm) return EE, ff
def BFGS(fun, dfun, x0, Linear_Search, maxiter=200, epsilon=1e-10, c1=0.5, c2=0.8): """ references ----------------- 李航 <统计学习方法> Stephen Boyed <convex optimization> (only refer to stop condtion:the newton decrement) """ x0 = np.atleast_1d(x0) B = np.eye(len(x0)) g = np.atleast_1d(dfun(x0)) for i in range(maxiter): if norm(g.dot(B).dot(g)) < epsilon: break p = np.linalg.solve(B, g) #p is -p in Li Hang's book alpha = Linear_Search(fun, dfun, x0, c1=c1, p=p) x = x0 x0 = x0 - alpha * p delta = x0 - x y = dfun(x0) - dfun(x) Q = -np.dot(B, np.outer(delta, np.dot(delta.T, B))) / np.dot( delta.T, np.dot(B, delta)) B = B + np.outer(y, y.T) / np.dot(y.T, delta) + Q g = dfun(x0) return x0, i
def WolfBacktrack(fun,dfun,x0,maxiter=200,eps=1e-1,c1=0.5,c2=0.7,p=None): """ find an acceptable stepsize via backtrack under wolf rule parameters ----------- fun:compute the value of objective function dfun:compute the gradient of objective function x0:the initial value of the paraments of fun w: the determined value of the fun maxiter:stop condition that the number of iteration eps: stop conditon that ||f'(x[k+1])||<eps c1:sufficient decrease Parameters c2:prevent slow Parameters """ # eta:stop condition that |f(x[k+1])-f(x[k])|<eta # tal:stop condition that |x[k+1]-x[k]|<tal x0=np.atleast_1d(x0) try: for i in range(maxiter): if norm(dfun(x0),2)<eps: #norm(np.atleast_1d(fun(x0)-fun(x0-alpha*dfun(x0))),2)<eta or break alpha=wolf_step(fun,dfun,x0=x0,c1=c1,c2=c2,p=p) x0=x0-alpha*dfun(x0) except OverflowError: print('no minimum value') return x0,i
def graph(x,span=True): ''' x是采样的图片向量 ''' num=len(x) G=nx.complete_graph(num) arr=np.ones((num,num)) weight_edge=[] for i in range(num): for j in range(num): temp=norm(x[i]-x[j]) arr[i][j]=temp weight_edge.append((i,j,temp)) #weight_edge=[(i,j,norm(x[i]-x[j])) for i in range(num) for j in range(num)] G.add_weighted_edges_from(weight_edge) if span: span_tree=nx.minimum_spanning_tree(G) span_edge=span_tree.edges() #epsilons=10e-30 else: choice_index=np.random.choice(range(len(G.edges())),size=num-1,replace=False) span_edge=np.array(G.edges())[choice_index] w_sum=0 p=[] for index in span_edge: p.append(arr[tuple(index)]) w_sum+=arr[tuple(index)] p=np.array(p)/w_sum result=-p*np.log(p) result[np.isnan(result)]=0 return result.sum()
def DFP(fun, dfun, x0, Linear_Search, maxiter=200, epsilon=1e-10, tal=1e-3, c1=0.5, c2=0.8): """ references ----------------- 李航 <统计学习方法> """ x0 = np.atleast_1d(x0) G = np.eye(len(x0)) g = np.atleast_1d(dfun(x0)) for i in range(maxiter): if norm(dfun(x0), 2) < epsilon: break p = np.dot(G, g) #p is -p in Li Hang's book alpha = Linear_Search(fun, dfun, x0, c1=c1, p=p) x = x0 x0 = x0 - alpha * p delta = x0 - x y = dfun(x0) - dfun(x) if all(np.abs(delta) < tal) or all(np.abs(y) < tal): break Q = -np.dot(G, np.outer(y.T, np.dot(y.T, G))) / np.dot( np.dot(y.T, G), y) G = G + np.outer(delta, delta.T) / np.dot(delta.T, y) + Q g = dfun(x0) return x0, i
def movieSimilarity_euclidean(self): train = self.trainData self.movieSim = {} movieRating = {} for user, movies in train.items(): for m1 in movies: for m2 in movies.keys(): if m1 == m2: continue self.movieSim.setdefault(m1, {}) self.movieSim[m1].setdefault(m2, 0) for user, movies in train.items(): for m1 in movies: for m2 in movies.keys(): if m1 == m2: continue movieRating.setdefault(m1,{}) movieRating[m1].setdefault(m2,[[],[],[]]) movieRating[m1][m2][0].append(movies[m1]) movieRating[m1][m2][1].append(movies[m2]) movieRating[m1][m2][2].append(user) for m1, related_movies in self.movieSim.items(): for m2, _ in related_movies.items(): dis = norm(np.array(movieRating[m1][m2][0]) - np.array(movieRating[m1][m2][1])) self.movieSim[m1][m2] = 1 / (1 + dis)
def test_arlsnn_with_impossible(): A = np.eye(3) b = np.ones(3) b = -b x = arlsnn(A, b)[0] assert_(norm(x) == 0.0, "Solution of arlsnn is incorrectly non-zero.") return
def test_forced_zero_solution(): A = np.array([[1.0, 1.0, 1.0], [0.0, 0.0, 0.0]]) b = np.array([0.0, 1.0]) G = np.eye(3) h = np.zeros(3) x = arlsgt(A, b, G, h)[0] assert_(norm(x) == 0.0, "Solution by arlsgt should be zero.") return
def bestfitone(self): self.lineindex = self.lineindex-2 self.b0 = 0.0 self.b1 = 0.0 self.square = 1.0 for i in xrange(self.lineindex, self.L-10): b0, b1 = np.polyfit(self.Re[i:self.L-9], self.F[i:self.L-9], 1) Fit = b0 * self.Re[i:self.L-9] + b1 # **2 + b1* self.Re[i:]+c1 error = norm(Fit-self.F[i:self.L-9])/norm(self.F[i:self.L-9]) plt.plot(self.Re[i:self.L-9], self.F[i:self.L-9], 'ks', label='numerical result') plt.plot(self.Re[i:self.L-9], Fit, 'r', label='least square') plt.xlabel(r'$Re,\alpha=0.25$', self.font) plt.ylabel(r'$\frac{F-F_s}{\mu U}$', self.font, fontsize=16) plt.legend(frameon=False, numpoints=1, loc=9) savefig("A%d.eps" % i) plt.close('all') print error, b0, b1, self.Re[i], i
def find_max_row_norm(A): """ determine max row norm of A """ m = A.shape[0] rnmax = 0.0 for i in range(0, m): rn = norm(A[i, :]) if rn > rnmax: rnmax = rn return rnmax
def test_regularization(): A = hilbert(12) xx = np.ones(12) b = A @ xx for i in range(0, 12): b[i] += 0.00001 * np.sin(float(i + i)) ans = np.array([ 0.998635, 1.013942, 0.980540, 0.986143, 1.000395, 1.011578, 1.016739, 1.015970, 1.010249, 1.000679, 0.988241, 0.973741 ]) x = arls(A, b)[0] d = norm(ans - x) assert_(d < 1.0e-5, "arls() residual too large.") x = arlsqr(A, b)[0] d = norm(ans - x) assert_(d < 1.0e-5, "arlsqr() residual too large.") return
def relativeerr(x, y): x = np.array(x) # porosity = 1.0 - x** porosity = x**2 logy = np.log(y) a, b = np.polyfit(porosity, logy, 1) fity = a*porosity+b print "the porosity %.4lf %.4lf" % (a, b) y1 = np.e**fity plt.semilogy(porosity, y1, '-rs', linewidth=2.0) plt.semilogy(porosity, y, '-kd', linewidth=2.0) plt.minorticks_off() plt.tick_params(top='off', right='off') ax = plt.gca() # ax.spines['top'].set_visible(False) # ax.spines['right'].set_visible(False) print norm(np.abs(y1-y))/norm(y) plt.show()
def test_arlsqr_underdetermined(): A = myrandom(4, 6) x = np.zeros(6) for i in range(0, 6): x[i] = float(i) b = A @ x xx = arlsqr(A, b)[0] res = norm(A @ xx - b) assert_(res < 1.0e-8, "arlsqr() residual too large.")
def test_arlsgt(): x = np.array([6.0, 5.0, 4.0, 3.0]) A = hilbert(5) A = np.delete(A, 4, 1) # delete last column b = A @ x G = np.array([0.0, 0.0, 0.0, 1.0]) h = 5 x = arlsgt(A, b, G, h)[0] res = A @ x - b assert_(norm(res) < 0.002, "Residual too large in arlsgt hilbert test.") return
def cost(self): """ Cost function with regularization :return: float """ wx = np.dot(self.x, self.w) # row-wise multiplication wx = np.clip(wx, -500, 500) # avoid overflow ret1 = -np.sum(wx * self.y) ret2 = np.sum(np.log(1 + np.exp(wx))) ret1 += norm(self.w) return ret1 + ret2
def JDA(Xs, Xt, Ys, Yt, k=100, lamda=0.1, ker='primal', gamma=1.0, data='default'): X = np.hstack((Xs, Xt)) X = np.diag(1 / np.sqrt(np.sum(X**2))) (m, n) = X.shape #源域样本量 ns = Xs.shape[1] #目标域样本量 nt = Xt.shape[1] #分类个数 C = len(np.unique(Ys)) # 生成MMD矩阵 e1 = 1 / ns * np.ones((ns, 1)) e2 = 1 / nt * np.ones((nt, 1)) e = np.vstack((e1, e2)) M = np.dot(e, e.T) * C #除了0,空,False以外都可以运行 if any(Yt) and len(Yt) == nt: for c in np.reshape(np.unique(Ys), -1, 1): e1 = np.zeros((ns, 1)) e1[Ys == c] = 1 / len(Ys[Ys == c]) e2 = np.zeros((nt, 1)) e2[Yt == c] = -1 / len(Yt[Yt == c]) e = np.hstack((e1, e2)) e = e[np.isinf(e) == 0] M = M + np.dot(e, e.T) #矩阵迹求平方根 M = M / norm(M, ord='fro') # 计算中心矩阵 H = np.eye(n) - 1 / (n) * np.ones((n, n)) # Joint Distribution Adaptation: JDA if ker == 'primal': #特征值特征向量 A = eigs(np.dot(np.dot(X, M), X.T) + lamda * np.eye(m), k=k, M=np.dot(np.dot(X, H), X.T), which='SM') Z = np.dot(A.T, X) else: pass return A, Z
def find_max_sense(E, f): """ find the row of Ex=f which his the highest ratio of f[i] to the norm of the row. """ snmax = -1.0 ibest = 0 # default m = E.shape[0] for i in range(0, m): rn = norm(E[i, :]) if rn > 0.0: s = abs(f[i]) / rn if s > snmax: snmax = s ibest = i return ibest
def loadFile2Numpy(file_name): cnt = 0 seller_idx = {} vectors = np.empty((4997933, 100)) norms = np.empty(4997933) for line in open(file_name): k,v = line.strip().split('\t') vec=np.fromstring(v, dtype=np.float32, sep=' ') seller_idx[k]=cnt vectors[cnt]=vec norms[cnt]=norm(vec) cnt = cnt + 1 print "finish to load the np vector" return seller_idx, vectors, norms
def cull(E, f, neglect): """ delete rows of Ex=f where the row norm is less than "neglect" """ EE = E.copy() ff = f.copy() m = EE.shape[0] i = 0 while i < m: if norm(EE[i, :]) < neglect: EE = np.delete(EE, i, 0) ff = np.delete(ff, i, 0) m = EE.shape[0] else: i += 1 return EE, ff
def Norm_features(data): row, col = np.shape(data) for i in range(col): flag = False for item in data[:, i]: if np.isnan(item) or np.isinf(item): flag = True if flag: data[:, i] = float("nan") else: data[:, i] = data[:, i] / norm(data[:, i]) return data
def Norm(data): row, col = np.shape(data) for i in range(col): if i == 0: continue # 第一列是类别标签,不能归一化 flag = False for item in data[:, i]: if np.isnan(item) or np.isinf(item): flag = True if flag: data[:, i] = float("nan") else: data[:, i] = data[:, i] / norm(data[:, i]) return data
def test_arlseq(): n = 14 A = np.eye(n) x = np.ones(n) b = A @ x E = hilbert(n) E[7, 7] = 3. x[7] = 5.0 f = E @ x xx = arlseq(A, b, E, f)[0] assert_(abs(xx[7] - 5.0) < 1.0e-4, "Constraint not obeyed in arlseq.") d = norm(x - xx) assert_(d < 0.01, "Residual too large in arsleq.") return
def JDA(Xs , Xt , Ys , Yt0 , k=100 , labda = 0.1 , ker = 'primal' , gamma = 1.0 , data = 'default'): print 'begin JDA' X = np.hstack((Xs , Xt)) X = np.diag(1/np.sqrt(np.sum(X**2))) (m,n) = X.shape ns = Xs.shape[1] nt = Xt.shape[1] C = len(np.unique(Ys)) # Construct MMD matrix e1 = 1/ns*np.ones((ns,1)) e2 = 1/nt*np.ones((nt,1)) e = np.vstack((e1,e2)) M = np.dot(e,e.T)*C if any(Yt0) and len(Yt0)==nt: for c in np.reshape(np.unique(Ys) ,-1 ,1): e1 = np.zeros((ns,1)) e1[Ys == c] = 1/len(Ys[Ys == c]) e2 = np.zeros((nt,1)) e2[Yt0 ==c] = -1/len(Yt0[Yt0 ==c]) e = np.hstack((e1 ,e2)) e = e[np.isinf(e) == 0] M = M+np.dot(e,e.T) M = M/norm(M ,ord = 'fro' ) # Construct centering matrix H = np.eye(n) - 1/(n)*np.ones((n,n)) #% Joint Distribution Adaptation: JDA if ker == 'primal': A = eigs(np.dot(np.dot(X,M),X.T)+labda*np.eye(m), k=k, M=np.dot(np.dot(X,H),X.T), which='SM') Z = np.dot(A.T,X) else: pass print 'JDA TERMINATED'
def test_zero_rhs(): # test solvers with zero right hand side A = np.eye(3) Z = A b = np.zeros(3) x, nr, ur, sigma, lambdah = arls(A, b) assert_(norm(x) == 0.0, "Solution of arls() is incorrectly non-zero.") x, nr, ur, sigma, lambdah = arlsqr(A, b) assert_(norm(x) == 0.0, "Solution of arlsqr() is incorrectly non-zero.") x, nr, ur, sigma, lambdah = arlsusv(A, b, Z, Z, Z) assert_(norm(x) == 0.0, "Solution of arlsusv() is incorrectly non-zero.") x, nr, ur, sigma, lambdah = arlseq(A, b, A, b) assert_(norm(x) == 0.0, "Solution of arlseq() is incorrectly non-zero.") x, nr, ur, sigma, lambdah = arlsgt(A, b, A, b) assert_(norm(x) == 0.0, "Solution of arlsgt() is incorrectly non-zero.") x, nr, ur, sigma, lambdah = arlsnn(A, b) assert_(norm(x) == 0.0, "Solution of arlsnn() is incorrectly non-zero.") return
def expm(A): """ Compute the matrix exponential using Pade approximation. .. versionadded:: 0.12.0 Parameters ---------- A : (M,M) array or sparse matrix 2D Array or Matrix (sparse or dense) to be exponentiated Returns ------- expA : (M,M) ndarray Matrix exponential of `A` References ---------- N. J. Higham, "The Scaling and Squaring Method for the Matrix Exponential Revisited", SIAM. J. Matrix Anal. & Appl. 26, 1179 (2005). """ n_squarings = 0 Aissparse = isspmatrix(A) if Aissparse: A_L1 = max(abs(A).sum(axis=0).flat) ident = speye(A.shape[0], A.shape[1], dtype=A.dtype, format=A.format) else: A = asarray(A) A_L1 = norm(A, 1) ident = eye(A.shape[0], A.shape[1], dtype=A.dtype) if A.dtype == 'float64' or A.dtype == 'complex128': if A_L1 < 1.495585217958292e-002: U, V = _pade3(A, ident) elif A_L1 < 2.539398330063230e-001: U, V = _pade5(A, ident) elif A_L1 < 9.504178996162932e-001: U, V = _pade7(A, ident) elif A_L1 < 2.097847961257068e+000: U, V = _pade9(A, ident) else: maxnorm = 5.371920351148152 n_squarings = max(0, int(ceil(log2(A_L1 / maxnorm)))) A = A / 2**n_squarings U, V = _pade13(A, ident) elif A.dtype == 'float32' or A.dtype == 'complex64': if A_L1 < 4.258730016922831e-001: U, V = _pade3(A, ident) elif A_L1 < 1.880152677804762e+000: U, V = _pade5(A, ident) else: maxnorm = 3.925724783138660 n_squarings = max(0, int(ceil(log2(A_L1 / maxnorm)))) A = A / 2**n_squarings U, V = _pade7(A, ident) else: raise ValueError("invalid type: " + str(A.dtype)) P = U + V # p_m(A) : numerator Q = -U + V # q_m(A) : denominator if Aissparse: from scipy.sparse.linalg import spsolve R = spsolve(Q, P) else: R = solve(Q, P) # squaring step to undo scaling for i in range(n_squarings): R = R.dot(R) return R
def expm(A): """Compute the matrix exponential using Pade approximation. .. versionadded:: 0.12.0 Parameters ---------- A : array or sparse matrix, shape(M,M) 2D Array or Matrix (sparse or dense) to be exponentiated Returns ------- expA : array, shape(M,M) Matrix exponential of A References ---------- N. J. Higham, "The Scaling and Squaring Method for the Matrix Exponential Revisited", SIAM. J. Matrix Anal. & Appl. 26, 1179 (2005). """ n_squarings = 0 Aissparse = isspmatrix(A) if Aissparse: A_L1 = max(abs(A).sum(axis=0).flat) ident = speye(A.shape[0], A.shape[1], dtype=A.dtype, format=A.format) else: A = asarray(A) A_L1 = norm(A,1) ident = eye(A.shape[0], A.shape[1], dtype=A.dtype) if A.dtype == 'float64' or A.dtype == 'complex128': if A_L1 < 1.495585217958292e-002: U,V = _pade3(A, ident) elif A_L1 < 2.539398330063230e-001: U,V = _pade5(A, ident) elif A_L1 < 9.504178996162932e-001: U,V = _pade7(A, ident) elif A_L1 < 2.097847961257068e+000: U,V = _pade9(A, ident) else: maxnorm = 5.371920351148152 n_squarings = max(0, int(ceil(log2(A_L1 / maxnorm)))) A = A / 2**n_squarings U,V = _pade13(A, ident) elif A.dtype == 'float32' or A.dtype == 'complex64': if A_L1 < 4.258730016922831e-001: U,V = _pade3(A, ident) elif A_L1 < 1.880152677804762e+000: U,V = _pade5(A, ident) else: maxnorm = 3.925724783138660 n_squarings = max(0, int(ceil(log2(A_L1 / maxnorm)))) A = A / 2**n_squarings U,V = _pade7(A, ident) else: raise ValueError("invalid type: "+str(A.dtype)) P = U + V # p_m(A) : numerator Q = -U + V # q_m(A) : denominator if Aissparse: from scipy.sparse.linalg import spsolve R = spsolve(Q, P) else: R = solve(Q,P) # squaring step to undo scaling for i in range(n_squarings): R = R.dot(R) return R
return x ** 2 val = quad(f, 0, 1) print val print type(val) # Ax = b A是矩阵 x b 是向量 A = array([[1, 2, 3], [4, 5, 6],[7, 8, 9]]) b = array([1, 2, 3]) x = solve(A, b) print x print dot(A, x) print Inf + 1 # 打印矩阵A的2范数 print norm(A, ord=2) def y(x): return 4*x**3 + (x - 2)**2 + x**4 fig, ax = subplots() print fig, ax x = linspace(-5, 3, 100) ax.plot(x, y(x)) # fig.show() # raw_input() x_min = optimize.fmin_bfgs(y) print x_min print y(-3)