質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

2回答

1876閲覧

minimize関数を使いたい(jupyter)

united

総合スコア0

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/08/07 07:05

編集2021/08/07 07:16

前提・実現したいこと

minimize関数を使いたい(jupyter)
どこが悪いのでしょうか?
よろしくお願いいたします。

発生している問題・エラーメッセージ

<ipython-input-2-c4d8c494bf74> in model(x, w) 3 4 def model(x,w): ----> 5 y = w[0]*x + w[1] 6 return y 7 can't multiply sequence by non-int of type 'numpy.float64'

該当のソースコード

python

1import numpy as np 2from scipy.optimize import minimize 3 4X=[1,2,3,4,5] 5T=[7,9,11,13,15] 6 7def model(x,w): 8 y = w[0]*x + w[1] 9 return y 10 11def mse_model(w,x,t): 12 y = model(x,w) 13 mse = np.mean((y-t)**2) 14 return mse 15 16def fit_model(w_init,x,t): 17 res1 = minimize(mse_model,w_init,args=(x,t),method="powell") 18 return res1.x 19 20W_init = [4,10] 21W = fit_model(W_init,X,T) 22print(W)

試したこと

補足情報(FW/ツールのバージョンなど)

return res1.x の .xを付ける理由も分からないです。もしご存じの方いたら教えてください。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

分からないときは、ドキュメント文字列を読みましょう。

python

1from scipy.optimize import minimize 2print(minimize.__doc__)

英語で表示されるので、英語が不得意ならGoogle翻訳などで翻訳して読んでください。
長いので全ては載せることができませんが、以下のようなものが表示されます。

python

1>>> print(minimize.__doc__) 2Minimization of scalar function of one or more variables. 3 4 Parameters 5 ---------- 6 fun : callable 7 The objective function to be minimized. 8 9 ``fun(x, *args) -> float`` 10 11 where ``x`` is an 1-D array with shape (n,) and ``args`` 12 is a tuple of the fixed parameters needed to completely 13 specify the function. 14 x0 : ndarray, shape (n,) 15 Initial guess. Array of real elements of size (n,), 16 where 'n' is the number of independent variables. 17 args : tuple, optional 18 Extra arguments passed to the objective function and its 19 derivatives (`fun`, `jac` and `hess` functions). 20 method : str or callable, optional 21 Type of solver. Should be one of 22 23 - 'Nelder-Mead' :ref:`(see here) <optimize.minimize-neldermead>` 24 - 'Powell' :ref:`(see here) <optimize.minimize-powell>` 25 - 'CG' :ref:`(see here) <optimize.minimize-cg>` 26 - 'BFGS' :ref:`(see here) <optimize.minimize-bfgs>` 27 - 'Newton-CG' :ref:`(see here) <optimize.minimize-newtoncg>` 28 - 'L-BFGS-B' :ref:`(see here) <optimize.minimize-lbfgsb>` 29 - 'TNC' :ref:`(see here) <optimize.minimize-tnc>` 30 - 'COBYLA' :ref:`(see here) <optimize.minimize-cobyla>` 31 - 'SLSQP' :ref:`(see here) <optimize.minimize-slsqp>` 32 - 'trust-constr':ref:`(see here) <optimize.minimize-trustconstr>` 33 - 'dogleg' :ref:`(see here) <optimize.minimize-dogleg>` 34 - 'trust-ncg' :ref:`(see here) <optimize.minimize-trustncg>` 35 - 'trust-exact' :ref:`(see here) <optimize.minimize-trustexact>` 36 - 'trust-krylov' :ref:`(see here) <optimize.minimize-trustkrylov>` 37 - custom - a callable object (added in version 0.14.0), 38 see below for description. 39 40 If not given, chosen to be one of ``BFGS``, ``L-BFGS-B``, ``SLSQP``, 41 depending if the problem has constraints or bounds. 42 jac : {callable, '2-point', '3-point', 'cs', bool}, optional 43 Method for computing the gradient vector. Only for CG, BFGS, 44 Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg, trust-krylov, 45 trust-exact and trust-constr. 46 If it is a callable, it should be a function that returns the gradient 47 vector: 48 49 ``jac(x, *args) -> array_like, shape (n,)`` 50 51 where ``x`` is an array with shape (n,) and ``args`` is a tuple with 52 the fixed parameters. If `jac` is a Boolean and is True, `fun` is 53 assumed to return and objective and gradient as an ``(f, g)`` tuple. 54 Methods 'Newton-CG', 'trust-ncg', 'dogleg', 'trust-exact', and 55 'trust-krylov' require that either a callable be supplied, or that 56 `fun` return the objective and gradient. 57 If None or False, the gradient will be estimated using 2-point finite 58 difference estimation with an absolute step size. 59 Alternatively, the keywords {'2-point', '3-point', 'cs'} can be used 60 to select a finite difference scheme for numerical estimation of the 61 gradient with a relative step size. These finite difference schemes 62 obey any specified `bounds`. 63 hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy}, optional 64 Method for computing the Hessian matrix. Only for Newton-CG, dogleg, 65 trust-ncg, trust-krylov, trust-exact and trust-constr. If it is 66 callable, it should return the Hessian matrix: 67 68 ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)`` 69 70 where x is a (n,) ndarray and `args` is a tuple with the fixed 71 parameters. LinearOperator and sparse matrix returns are 72 allowed only for 'trust-constr' method. Alternatively, the keywords 73 {'2-point', '3-point', 'cs'} select a finite difference scheme 74 for numerical estimation. Or, objects implementing 75 `HessianUpdateStrategy` interface can be used to approximate 76 the Hessian. Available quasi-Newton methods implementing 77 this interface are: 78 79 - `BFGS`; 80 - `SR1`. 81 82 Whenever the gradient is estimated via finite-differences, 83 the Hessian cannot be estimated with options 84 {'2-point', '3-point', 'cs'} and needs to be 85 estimated using one of the quasi-Newton strategies. 86 Finite-difference options {'2-point', '3-point', 'cs'} and 87 `HessianUpdateStrategy` are available only for 'trust-constr' method. 88 hessp : callable, optional 89 Hessian of objective function times an arbitrary vector p. Only for 90 Newton-CG, trust-ncg, trust-krylov, trust-constr. 91 Only one of `hessp` or `hess` needs to be given. If `hess` is 92 provided, then `hessp` will be ignored. `hessp` must compute the 93 Hessian times an arbitrary vector: 94 95 ``hessp(x, p, *args) -> ndarray shape (n,)`` 96 97 where x is a (n,) ndarray, p is an arbitrary vector with 98 dimension (n,) and `args` is a tuple with the fixed 99 parameters. 100 bounds : sequence or `Bounds`, optional 101 Bounds on variables for L-BFGS-B, TNC, SLSQP, Powell, and 102 trust-constr methods. There are two ways to specify the bounds: 103 104 1. Instance of `Bounds` class. 105 2. Sequence of ``(min, max)`` pairs for each element in `x`. None 106 is used to specify no bound. 107 108 constraints : {Constraint, dict} or List of {Constraint, dict}, optional 109 Constraints definition (only for COBYLA, SLSQP and trust-constr). 110 111 Constraints for 'trust-constr' are defined as a single object or a 112 list of objects specifying constraints to the optimization problem. 113 Available constraints are: 114 115 - `LinearConstraint` 116 - `NonlinearConstraint` 117 118 Constraints for COBYLA, SLSQP are defined as a list of dictionaries. 119 Each dictionary with fields: 120 121 type : str 122 Constraint type: 'eq' for equality, 'ineq' for inequality. 123 fun : callable 124 The function defining the constraint. 125 jac : callable, optional 126 The Jacobian of `fun` (only for SLSQP). 127 args : sequence, optional 128 Extra arguments to be passed to the function and Jacobian. 129 130 Equality constraint means that the constraint function result is to 131 be zero whereas inequality means that it is to be non-negative. 132 Note that COBYLA only supports inequality constraints. 133 tol : float, optional 134 Tolerance for termination. For detailed control, use solver-specific 135 options. 136 options : dict, optional 137 A dictionary of solver options. All methods accept the following 138 generic options: 139 140 maxiter : int 141 Maximum number of iterations to perform. Depending on the 142 method each iteration may use several function evaluations. 143 disp : bool 144 Set to True to print convergence messages. 145 146 For method-specific options, see :func:`show_options()`. 147 callback : callable, optional 148 Called after each iteration. For 'trust-constr' it is a callable with 149 the signature: 150 151 ``callback(xk, OptimizeResult state) -> bool`` 152 153 where ``xk`` is the current parameter vector. and ``state`` 154 is an `OptimizeResult` object, with the same fields 155 as the ones from the return. If callback returns True 156 the algorithm execution is terminated. 157 For all the other methods, the signature is: 158 159 ``callback(xk)`` 160 161 where ``xk`` is the current parameter vector. 162 163 Returns 164 ------- 165 res : OptimizeResult 166 The optimization result represented as a ``OptimizeResult`` object. 167 Important attributes are: ``x`` the solution array, ``success`` a 168 Boolean flag indicating if the optimizer exited successfully and 169 ``message`` which describes the cause of the termination. See 170 `OptimizeResult` for a description of other attributes. 171 172 See also 173 -------- 174 minimize_scalar : Interface to minimization algorithms for scalar 175 univariate functions 176 show_options : Additional options accepted by the solvers 177 178 Notes 179 ----- 180 This section describes the available solvers that can be selected by the 181 'method' parameter. The default method is *BFGS*. 182 183 References 184 ---------- 185 .. [1] Nelder, J A, and R Mead. 1965. A Simplex Method for Function 186 187 Examples 188 -------- 189 Let us consider the problem of minimizing the Rosenbrock function. This 190

投稿2021/08/07 07:27

ppaul

総合スコア24666

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

自己解決

X=[1,2,3,4,5]
T=[7,9,11,13,15]

X=np.array([1,2,3,4,5])
T=np.array([7,9,11,13,15])

にしたら解決しました

投稿2021/08/07 07:19

united

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問