C# 中 numsharp的用法 numpy

using System;
using System.Collections.Generic;
using NumSharp;
//using NumpyDotNet;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] arr = new int[2, 3] { { 5, 6, 7 }, { 8, 7, 6 } };
            NDArray ndarr = np.array(arr);
            Console.WriteLine(ndarr.ToString());
            Console.WriteLine("------------------------");
            //int[,] arr1 = np.arange(0, 9).reshape(3, 3);
            NDArray arr1 = np.array(new int[,] { { 1, 2, 3 }, { 4, 5, 6 } });
            var arr2 = np.matmul(arr1.T, arr1);
            Console.WriteLine(arr2.ToString());
            Console.WriteLine("------------------------");
            var arr3 = arr2[":,1:3"];
            
            Console.WriteLine(arr3.ToString());
            Console.WriteLine("***************");
            foreach (var item in arr3)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("***************");
            IEnumerable<int> iter = arr3.AsIterator<int>();

            foreach (var item in iter)
            {
                Console.WriteLine(item);
            }
            
            Console.ReadKey();
            
        }
    }
}

结果:

[[5, 6, 7],
[8, 7, 6]]
------------------------
[[17, 22, 27],
[22, 29, 36],
[27, 36, 45]]
------------------------
[[22, 27],
[29, 36],
[36, 45]]
***************
22
27
29
36
36
45
***************
22
27
29
36
36
45

官方例程:

using NumSharp;

var nd = np.full(5, 12); //[5, 5, 5 .. 5]
nd = np.zeros(12); //[0, 0, 0 .. 0]
nd = np.arange(12); //[0, 1, 2 .. 11]

// create a matrix
nd = np.zeros((3, 4)); //[0, 0, 0 .. 0]
nd = np.arange(12).reshape(3, 4);

// access data by index
var data = nd[1, 1];

// create a tensor
nd = np.arange(12);

// reshaping
data = nd.reshape(2, -1); //returning ndarray shaped (2, 6)

Shape shape = (2, 3, 2);
data = nd.reshape(shape); //Tuple implicitly casted to Shape
    //or:
nd =   nd.reshape(2, 3, 2);

// slicing tensor
data = nd[":, 0, :"]; //returning ndarray shaped (2, 1, 2)
data = nd[Slice.All, 0, Slice.All]; //equivalent to the line above.

// nd is currently shaped (2, 3, 2)
// get the 2nd vector in the 1st dimension
data = nd[1]; //returning ndarray shaped (3, 2)

// get the 3rd vector in the (axis 1, axis 2) dimension
data = nd[1, 2]; //returning ndarray shaped (2, )

// get flat representation of nd
data = nd.flat; //or nd.flatten() for a copy

// interate ndarray
foreach (object val in nd)
{
    // val can be either boxed value-type or a NDArray.
}

var iter = nd.AsIterator<int>(); //a different T can be used to automatically perform cast behind the scenes.
while (iter.HasNext())
{
    //read
    int val = iter.MoveNext();

    //write
    iter.MoveNextReference() = 123; //set value to the next val
    //note that setting is not supported when calling AsIterator<T>() where T is not the dtype of the ndarray.
}

与二维数组的互相转化

// See https://aka.ms/new-console-template for more information

using NumSharp;



//测试numsharp
int[,] ints = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };

NDArray dArray1 = np.array(ints);

foreach (var item in dArray1)
{
    Console.WriteLine($"{item}");
}


//dArray1.ToArray();
int a = dArray1.size;
int[] b = dArray1.shape;
Console.WriteLine($"{dArray1[0][1]},{a},{b[0]},{b[1]}");

int[,] ints1 = new int[dArray1.shape[0],dArray1.shape[1]];

for (int i = 0; i < ints1.GetLength(0); i++)
{
    for (int j = 0; j < ints1.GetLength(1); j++)
    {
        ints1[i,j] = dArray1[i][j];
    }
}

for (int i = 0; i < ints1.GetLength(0); i++)
{
    for (int j = 0; j < ints1.GetLength(1); j++)
    {
        Console.WriteLine($"写入的值为:{ints1[i, j]}");
    }
}

//结果:
/*
 1
2
3
4
5
6
2,6,2,3
写入的值为:1
写入的值为:2
写入的值为:3
写入的值为:4
写入的值为:5
写入的值为:6
 */

矩阵求逆 MathNet.Numerics:

  <ItemGroup>
    <PackageReference Include="MathNet.Numerics" Version="5.0.0" />
    <PackageReference Include="NumSharp" Version="0.30.0" />
  </ItemGroup>
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using NumSharp;
using NumSharp.Generic;

int[][] mat1 =
[
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

double[][] m1 =
[
    [1, 2, 3],
    [0, 5, 6],
    [0, 0, 9]
];

double[][] mat5 =
[
    [1.1d, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

int[][] mat2 =
[
    [1, 2, 3, 4],
    [4, 5, 6, 8],
    [7, 8, 9, 10]
];

NDArray? arr1 = np.array(mat1,np.float32);

var arr2 = np.matmul(mat1, mat2);
int a = 1;

Console.WriteLine(arr2.ToString());
Console.WriteLine("=================");
Console.WriteLine(arr2[$":,{a}"].ToString());
Console.WriteLine("=================");
//取所有行, 第0列到第2列, 不包括第二列
Console.WriteLine(arr2[$":,{a - 1}:{a + 1}"].ToString());




Console.WriteLine("-----------");

NDArray mat3 = arr2[$":,{a - 1}:{a + 1}"];

Console.WriteLine(mat3.ToString());


var mat1_1 = NDArrayTo2DDouble(m1);

Matrix<double> mat1_2 = DenseMatrix.OfArray(mat1_1);


var mat1_3 = mat1_2.Inverse();

Console.WriteLine(mat1_3);

Console.WriteLine(mat1_3* mat1_2);

var mat1_4 = mat1_3.ToArray();

Console.WriteLine(np.matmul(np.array(mat1_4), m1).ToString());




static double[,] NDArrayTo2DDouble(NDArray ndArray)
{

    if (ndArray.Shape.NDim != 2)
    {
        return default;
    }

    // 创建一个与 ndArray 形状相同的二维 int 数组  
    double[,] ints = new double[ndArray.shape[0], ndArray.shape[1]];

    // 复制 ndArray 的内容到 ints  
    for (int i = 0; i < ints.GetLength(0); i++)
    {
        for (int j = 0; j < ints.GetLength(1); j++)
        {
            // 注意:这里直接使用 ndArray[i, j] 访问元素,因为 NumSharp 支持这种索引方式  
            ints[i, j] = ndArray[i, j];
        }
    }

    return ints;
}

static int[,] NDArrayTo2DInt(NDArray ndArray)
{


    // 创建一个与 ndArray 形状相同的二维 int 数组  
    int[,] ints = new int[ndArray.shape[0], ndArray.shape[1]];

    // 复制 ndArray 的内容到 ints  
    for (int i = 0; i < ints.GetLength(0); i++)
    {
        for (int j = 0; j < ints.GetLength(1); j++)
        {
            // 注意:这里直接使用 ndArray[i, j] 访问元素,因为 NumSharp 支持这种索引方式  
            ints[i, j] = ndArray[i, j];
        }
    }

    return ints;
}
NumPy是在python处理数据的最基本和最强大的包。 如果您打算从事数据分析或机器学习项目,那么对numpy的充分理解几乎是必须的。 其他用于数据分析的软件包(如pandas)是建立在numpy之上,用于构建机器学习应用的scikit-learn软件包也在numpy上运行。 但对于.NET开发人员来说,却没有这样的强大工具库。 虽然有像Deedle和Math.NET这样的开源库,但它们不是很容易使用,也不能借用很多现有的python代码。 NumSharpNumerical .NET)可以说是C#的线性代数库。 它是用C#编写的,符合.netstandard 2.0库标准。 它的目标是让.NET开发人员使用NumPy的语法编写机器学习代码,从而最大限度地借鉴现有大量在python代码的转译成本。 NumSharp使用最新的Span技术安全高效地访问内存,优化每个模拟API的性能,确保最底层的NDArray达到最佳性能状态。NumSharp对于在数组上执行数学和逻辑运算非常有用。 它为.NET的n阵列和矩阵的操作提供了大量有用的功能。 让我们给出一个代码片段来说明如何使用NumSharp。 // 初始化一个NumSharp实例,类名故意叫NumPy var np = new NumPy(); // 产生一个数字0到9的向量 np.arange(10) // 产生一个3维张量 np.arange(12).reshape(2, 3, 2); // 产生10个0到9的随机数,并转换成5*5的矩阵 np.random.randint(low: 0, high: 10, size: new Shape(5, 5)); 上面的代码是不是看起来否非常接近python代码?简直就是如出一辙。NumSharp的目的就是让你可以轻松的复制粘贴Python代码。 如何安装: PM> Install-Package NumSharp   NumSharp 已被如下项目使用: Pandas.NET Bigtree.MachineLearning CherubNLP BotSharp 标签:numpy
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值