この記事では、主に TensorFlow を使用してラッソ回帰アルゴリズムとリッジ回帰アルゴリズムを実装する例を紹介します。回帰アルゴリズムの出力結果。最も一般的に使用される 2 つの正則化方法は、ラッソ回帰とリッジ回帰です。
ラッソ回帰アルゴリズムとリッジ回帰アルゴリズムは、従来の線形回帰アルゴリズムと非常によく似ていますが、1 つの違いは、傾き (または正味傾き) を制限するために式に正規項が追加されることです。これを行う主な理由は、従属変数に対する特徴の影響を制限するためです。これは、傾き A に依存する損失関数を追加することで実現されます。
なげなわ回帰アルゴリズムの場合、損失関数に項目 (傾き A の指定された倍数) を追加します。 TensorFlow の論理演算を使用しますが、これらの演算に関連付けられた勾配を使用せず、代わりに、連続ステップ関数とも呼ばれる、カットオフ ポイントでジャンプして拡張するステップ関数の連続推定を使用します。なげなわ回帰アルゴリズムの使用方法については、すぐに説明します。
リッジ回帰アルゴリズムの場合、傾斜係数の L2 正則化である L2 ノルムを追加します。
# LASSO and Ridge Regression # lasso回归和岭回归 # # This function shows how to use TensorFlow to solve LASSO or # Ridge regression for # y = Ax + b # # We will use the iris data, specifically: # y = Sepal Length # x = Petal Width # import required libraries import matplotlib.pyplot as plt import sys import numpy as np import tensorflow as tf from sklearn import datasets from tensorflow.python.framework import ops # Specify 'Ridge' or 'LASSO' regression_type = 'LASSO' # clear out old graph ops.reset_default_graph() # Create graph sess = tf.Session() ### # Load iris data ### # iris.data = [(Sepal Length, Sepal Width, Petal Length, Petal Width)] iris = datasets.load_iris() x_vals = np.array([x[3] for x in iris.data]) y_vals = np.array([y[0] for y in iris.data]) ### # Model Parameters ### # Declare batch size batch_size = 50 # Initialize placeholders x_data = tf.placeholder(shape=[None, 1], dtype=tf.float32) y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32) # make results reproducible seed = 13 np.random.seed(seed) tf.set_random_seed(seed) # Create variables for linear regression A = tf.Variable(tf.random_normal(shape=[1,1])) b = tf.Variable(tf.random_normal(shape=[1,1])) # Declare model operations model_output = tf.add(tf.matmul(x_data, A), b) ### # Loss Functions ### # Select appropriate loss function based on regression type if regression_type == 'LASSO': # Declare Lasso loss function # 增加损失函数,其为改良过的连续阶跃函数,lasso回归的截止点设为0.9。 # 这意味着限制斜率系数不超过0.9 # Lasso Loss = L2_Loss + heavyside_step, # Where heavyside_step ~ 0 if A < constant, otherwise ~ 99 lasso_param = tf.constant(0.9) heavyside_step = tf.truep(1., tf.add(1., tf.exp(tf.multiply(-50., tf.subtract(A, lasso_param))))) regularization_param = tf.multiply(heavyside_step, 99.) loss = tf.add(tf.reduce_mean(tf.square(y_target - model_output)), regularization_param) elif regression_type == 'Ridge': # Declare the Ridge loss function # Ridge loss = L2_loss + L2 norm of slope ridge_param = tf.constant(1.) ridge_loss = tf.reduce_mean(tf.square(A)) loss = tf.expand_dims(tf.add(tf.reduce_mean(tf.square(y_target - model_output)), tf.multiply(ridge_param, ridge_loss)), 0) else: print('Invalid regression_type parameter value',file=sys.stderr) ### # Optimizer ### # Declare optimizer my_opt = tf.train.GradientDescentOptimizer(0.001) train_step = my_opt.minimize(loss) ### # Run regression ### # Initialize variables init = tf.global_variables_initializer() sess.run(init) # Training loop loss_vec = [] for i in range(1500): rand_index = np.random.choice(len(x_vals), size=batch_size) rand_x = np.transpose([x_vals[rand_index]]) rand_y = np.transpose([y_vals[rand_index]]) sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y}) temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y}) loss_vec.append(temp_loss[0]) if (i+1)%300==0: print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)) + ' b = ' + str(sess.run(b))) print('Loss = ' + str(temp_loss)) print('\n') ### # Extract regression results ### # Get the optimal coefficients [slope] = sess.run(A) [y_intercept] = sess.run(b) # Get best fit line best_fit = [] for i in x_vals: best_fit.append(slope*i+y_intercept) ### # Plot results ### # Plot regression line against data points plt.plot(x_vals, y_vals, 'o', label='Data Points') plt.plot(x_vals, best_fit, 'r-', label='Best fit line', linewidth=3) plt.legend(loc='upper left') plt.title('Sepal Length vs Pedal Width') plt.xlabel('Pedal Width') plt.ylabel('Sepal Length') plt.show() # Plot loss over time plt.plot(loss_vec, 'k-') plt.title(regression_type + ' Loss per Generation') plt.xlabel('Generation') plt.ylabel('Loss') plt.show()
出力結果:
ステップ #300 A = [[ 0.77170753]] b = [[ 1.82499862]]損失 = [[ 10.26473045]]ステップ #600 A = [[ 0. 7 5908542]] b = [[ 3.2220633]]
損失 = [[ 3.06292033]]
ステップ #900 A = [[ 0.74843585]] b = [[ 3.9975822]]
損失 = [[ 1.23220456]]
ステップ #1200 A = [[ 0.737 52165] ] b = [[ 4.42974091]]
損失 = [[ 0.57872057]]
ステップ #1500 A = [[ 0.72942668]] b = [[ 4.67253113]]
損失 = [[ 0.40874988]]
ラッソ回帰アルゴリズムは、標準の線形回帰推定に基づいて連続ステップ関数を追加することによって実装されます。ステップ関数の傾きにより、ステップ サイズが大きすぎると最終的に収束しなくなるため、ステップ サイズに注意する必要があります。
関連する推奨事項:
以上がTensorFlow を使用したラッソ回帰アルゴリズムとリッジ回帰アルゴリズムの実装例の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

Arraysinpython、特にvianumpy、arecrucialinscientificComputing fortheirefficienty andversitility.1)彼らは、fornumericaloperations、data analysis、andmachinelearning.2)numpy'simplementation incensuresfasteroperationsthanpasteroperations.3)arayableminablecickick

Pyenv、Venv、およびAnacondaを使用して、さまざまなPythonバージョンを管理できます。 1)Pyenvを使用して、複数のPythonバージョンを管理します。Pyenvをインストールし、グローバルバージョンとローカルバージョンを設定します。 2)VENVを使用して仮想環境を作成して、プロジェクトの依存関係を分離します。 3)Anacondaを使用して、データサイエンスプロジェクトでPythonバージョンを管理します。 4)システムレベルのタスク用にシステムPythonを保持します。これらのツールと戦略を通じて、Pythonのさまざまなバージョンを効果的に管理して、プロジェクトのスムーズな実行を確保できます。

numpyarrayshaveveraladvantages-averstandardpythonarrays:1)thealmuchfasterduetocベースのインプレンテーション、2)アレモレメモリ効率、特にlargedatasets、および3)それらは、拡散化された、構造化された形成術科療法、

パフォーマンスに対する配列の均一性の影響は二重です。1)均一性により、コンパイラはメモリアクセスを最適化し、パフォーマンスを改善できます。 2)しかし、タイプの多様性を制限し、それが非効率につながる可能性があります。要するに、適切なデータ構造を選択することが重要です。

craftexecutablepythonscripts、次のようになります

numpyarraysarasarebetterfornumeroperations andmulti-dimensionaldata、whilethearraymoduleissuitable forbasic、1)numpyexcelsinperformance and forlargedatasentassandcomplexoperations.2)thearraymuremememory-effictientivearientfa

NumPyArraySareBetterforHeavyNumericalComputing、whilethearrayarayismoreSuitableformemory-constrainedprojectswithsimpledatatypes.1)numpyarraysofferarays andatiledance andpeperancedatasandatassandcomplexoperations.2)thearraymoduleisuleiseightweightandmemememe-ef

ctypesallowsinging andmanipulatingc-stylearraysinpython.1)usectypestointerfacewithclibrariesforperformance.2)createc-stylearraysfornumericalcomputations.3)passarraystocfunctions foreffientientoperations.how、how、becuutiousmorymanagemation、performanceo


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

Safe Exam Browser
Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

MantisBT
Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター

ホットトピック









