#r "nuget:FSharp.Stats"
// Use lite if you're on Apple Silicon
//#r "nuget:DiffSharp-lite,1.0.7"
// Use CPU if you're on Windows/Linux/Intel Mac
#r "nuget: DiffSharp-cpu,1.0.7"
open DiffSharp
open DiffSharp.Compose
open DiffSharp.Model
open DiffSharp.Data
open DiffSharp.Optim
open DiffSharp.Util
open DiffSharp.Distributions
open System
open System.IO
open System.IO.Compression
open System.Text.Json
Environment.CurrentDirectory <- __SOURCE_DIRECTORY__
dsharp.seed(1)
Below is some temp fixes for rnn state saving until the next DiffSharp release comes out. DiffSharp is in active development and a fix is in process.
type ModelBase with
member m.saveState2(fileName, ?noDiff:bool) =
let noDiff = defaultArg noDiff true
let ss =
if noDiff then
let ss = m.state.copy()
ss.noDiff()
ss
else m.state
saveBinary ss fileName
member m.loadState2(filename) =
let s:ParameterDict = loadBinary filename
m.state.iter(fun (n,p) -> p.value <- s[n])
Data
We'll use a dataset containing transcripts of quarterly conference calls from NASADAQ100 companies from 2018 to 2021. Let's download that.
let gunzip (inputFile:string) (outputFile:string) =
Directory.CreateDirectory(Path.GetDirectoryName(outputFile)) |> ignore
if File.Exists(outputFile) then File.Delete(outputFile)
use inputStream = File.OpenRead(inputFile)
use outputStream = File.Create(outputFile)
use gzipStream = new GZipStream(inputStream, CompressionMode.Decompress)
gzipStream.CopyTo(outputStream)
let nq100FullUrl = "https://www.dropbox.com/s/izcsjp06lgwbauu/Nasdaq100CallFull.json.gz?dl=1"
let dataFolder = "data"
let nqFullFile = Path.Combine(dataFolder, "Nasdaq100CallFull.json")
let nq100FullFileGz = nqFullFile.Replace(".json", ".json.gz")
download nq100FullUrl nq100FullFileGz
gunzip nq100FullFileGz nqFullFile
Read the downloaded data into a list
// Types - Earnings Announcement
type CallId =
{ Ticker: string
Exchange: string
FiscalQuarter: int
Date: DateTime }
type CallFull =
{ CallId: CallId
Header: string
PreparedRemarks: string
QuestionsAndAnswers: string
Label: float }
let corpus =
File.ReadAllText(nqFullFile)
|> JsonSerializer.Deserialize<List<CallFull>>
|> List.map (fun x ->
let toTake = min 10_000 x.QuestionsAndAnswers.Length-1
x.QuestionsAndAnswers[..toTake])
|> String.concat " "
corpus.Length
corpus[..500]
Set up the NN model.
let seqLen = 64
let batchSize = 16
let hiddenSize = 512
let numLayers = 2
Convert the text into tensor datasets.
let dataset = TextDataset(corpus, seqLen)
let loader = dataset.loader(batchSize=batchSize, shuffle=true)
the total number of characters in the dataset:
dataset.numChars
the unique characters are:
dataset.chars
Actual model definition
let rnn = LSTM(dataset.numChars, hiddenSize, numLayers=numLayers, batchFirst=true)
let decoder = dsharp.view([-1; hiddenSize]) --> Linear(hiddenSize, dataset.numChars)
let languageModel = rnn --> decoder
printfn "%s" (languageModel.summary())
If we want to retrain from a saved model.
let modelFileName = "data/rnn_language_model_1.07.params"
// You cannot load a model currently in .net notebooks.
// You will need to use a script to load model state.
if false then // keep this false to use a local model.
let modelUrl = "https://www.dropbox.com/s/zzm2lrzbwwigzc8/rnn_language_model_1.07.params?dl=1"
download modelUrl modelFileName // downloads pre-trained model.
if File.Exists(modelFileName) then
printfn "Resuming training from existing model params found: %A" modelFileName
languageModel.loadState2(modelFileName)
Prediction function.
let predict (text:string) len =
rnn.reset()
let mutable prediction = text
let mutable last = text
for i in 1..len do
let lastTensor = last |> dataset.textToTensor
let nextCharProbs = lastTensor.unsqueeze(0) --> languageModel --> dsharp.slice([-1]) --> dsharp.softmax(-1)
last <- Categorical(nextCharProbs).sample() |> int |> dataset.indexToChar |> string
prediction <- prediction + last
prediction
Test a prediction.
predict "Analyst What do you expect for gross margins next quarter?" 512
The actual model training.
let optimizer = Adam(languageModel, lr=dsharp.tensor(0.001))
let losses = ResizeArray<float>()
let epochs = 10
let validInterval = 100
let start = System.DateTime.Now
for epoch = 1 to epochs do
for i, x, t in loader.epoch() do
let input = x[*,..seqLen-2]
let target = t[*,1..]
rnn.reset()
languageModel.reverseDiff()
let output = input --> languageModel
let loss = dsharp.crossEntropyLoss(output, target.view(-1))
loss.reverse()
optimizer.step()
losses.Add(float loss)
printfn "%A Epoch: %A/%A minibatch: %A/%A loss: %A" (System.DateTime.Now - start) epoch epochs (i+1) loader.length (float loss)
if i % validInterval = 0 then
printfn "\nSample from language model:\n%A\n" (predict "Analyst Yes, I guess the first question," 512)
languageModel.saveState2(modelFileName)
// free tensor memory, especially useful with GPU.
GC.Collect()
namespace DiffSharp
module Compose
from DiffSharp
namespace DiffSharp.Model
namespace DiffSharp.Data
namespace DiffSharp.Optim
namespace DiffSharp.Util
namespace DiffSharp.Distributions
namespace System
namespace System.IO
namespace System.IO.Compression
namespace System.Text
namespace System.Text.Json
type Environment =
static member Exit: exitCode: int -> unit
static member ExpandEnvironmentVariables: name: string -> string
static member FailFast: message: string -> unit + 1 overload
static member GetCommandLineArgs: unit -> string array
static member GetEnvironmentVariable: variable: string -> string + 1 overload
static member GetEnvironmentVariables: unit -> IDictionary + 1 overload
static member GetFolderPath: folder: SpecialFolder -> string + 1 overload
static member GetLogicalDrives: unit -> string array
static member SetEnvironmentVariable: variable: string * value: string -> unit + 1 overload
static member CommandLine: string
...
<summary>Provides information about, and means to manipulate, the current environment and platform. This class cannot be inherited.</summary>
<summary>Provides information about, and means to manipulate, the current environment and platform. This class cannot be inherited.</summary>
property Environment.CurrentDirectory: string with get, set
<summary>Gets or sets the fully qualified path of the current working directory.</summary>
<exception cref="T:System.ArgumentException">Attempted to set to an empty string ("").</exception>
<exception cref="T:System.ArgumentNullException">Attempted to set to <see langword="null" />.</exception>
<exception cref="T:System.IO.IOException">An I/O error occurred.</exception>
<exception cref="T:System.IO.DirectoryNotFoundException">Attempted to set a local path that cannot be found.</exception>
<exception cref="T:System.Security.SecurityException">The caller does not have the appropriate permission.</exception>
<returns>The directory path.</returns>
<summary>Gets or sets the fully qualified path of the current working directory.</summary>
<exception cref="T:System.ArgumentException">Attempted to set to an empty string ("").</exception>
<exception cref="T:System.ArgumentNullException">Attempted to set to <see langword="null" />.</exception>
<exception cref="T:System.IO.IOException">An I/O error occurred.</exception>
<exception cref="T:System.IO.DirectoryNotFoundException">Attempted to set a local path that cannot be found.</exception>
<exception cref="T:System.Security.SecurityException">The caller does not have the appropriate permission.</exception>
<returns>The directory path.</returns>
type dsharp =
static member abs: input: Tensor -> Tensor
static member acos: input: Tensor -> Tensor
static member add: a: Tensor * b: Tensor -> Tensor
static member arange: endVal: float * ?startVal: float * ?step: float * ?device: Device * ?dtype: Dtype * ?backend: Backend -> Tensor + 1 overload
static member arangeLike: input: Tensor * endVal: float * ?startVal: float * ?step: float * ?device: Device * ?dtype: Dtype * ?backend: Backend -> Tensor + 1 overload
static member argmax: input: Tensor -> int array + 1 overload
static member argmin: input: Tensor -> int array + 1 overload
static member asin: input: Tensor -> Tensor
static member atan: input: Tensor -> Tensor
static member backends: unit -> Backend list
...
<summary> Tensor operations </summary>
<summary> Tensor operations </summary>
static member dsharp.seed: ?seed: int -> unit
Multiple items
type ModelBase = new: unit -> ModelBase val mutable mode: Mode override ToString: unit -> string member addBuffer: items: Parameter seq * ?names: string seq -> unit member addModel: items: obj seq * ?names: string seq -> unit member addParameter: items: Parameter seq * ?names: string seq -> unit member checkItems: items: 'a0 seq * ?names: string seq -> 'a0 array * string array member clone: unit -> ModelBase member eval: unit -> unit member forwardDiff: derivatives: ParameterDict * ?nestingTag: uint32 -> unit ...
<summary>Represents the base class of all models.</summary>
--------------------
new: unit -> ModelBase
type ModelBase = new: unit -> ModelBase val mutable mode: Mode override ToString: unit -> string member addBuffer: items: Parameter seq * ?names: string seq -> unit member addModel: items: obj seq * ?names: string seq -> unit member addParameter: items: Parameter seq * ?names: string seq -> unit member checkItems: items: 'a0 seq * ?names: string seq -> 'a0 array * string array member clone: unit -> ModelBase member eval: unit -> unit member forwardDiff: derivatives: ParameterDict * ?nestingTag: uint32 -> unit ...
<summary>Represents the base class of all models.</summary>
--------------------
new: unit -> ModelBase
val m: ModelBase
val fileName: string
val noDiff: bool option
type bool = Boolean
val noDiff: bool
val defaultArg: arg: 'T option -> defaultValue: 'T -> 'T
val ss: ParameterDict
property ModelBase.state: ParameterDict with get, set
<summary>TBD</summary>
<summary>TBD</summary>
member ParameterDict.copy: unit -> ParameterDict
member ParameterDict.noDiff: unit -> unit
val saveBinary: object: 'T -> fileName: string -> unit
<summary> Saves the given value to the given local file using binary serialization. </summary>
<summary> Saves the given value to the given local file using binary serialization. </summary>
val filename: string
val s: ParameterDict
Multiple items
type ParameterDict = interface IEnumerable interface IEnumerable<string * Parameter> new: unit -> ParameterDict override ToString: unit -> string member add: name: 'a0 * parameter: Parameter -> unit + 2 overloads member clear: unit -> unit member copy: unit -> ParameterDict member flatten: unit -> Tensor member forwardDiff: derivatives: ParameterDict * ?nestingTag: uint32 -> unit member iter: f: (string * Parameter -> unit) -> unit ...
<summary>Represents a collection of named parameters.</summary>
--------------------
new: unit -> ParameterDict
type ParameterDict = interface IEnumerable interface IEnumerable<string * Parameter> new: unit -> ParameterDict override ToString: unit -> string member add: name: 'a0 * parameter: Parameter -> unit + 2 overloads member clear: unit -> unit member copy: unit -> ParameterDict member flatten: unit -> Tensor member forwardDiff: derivatives: ParameterDict * ?nestingTag: uint32 -> unit member iter: f: (string * Parameter -> unit) -> unit ...
<summary>Represents a collection of named parameters.</summary>
--------------------
new: unit -> ParameterDict
val loadBinary: fileName: string -> 'T
<summary> Loads the given value from the given local file using binary serialization. </summary>
<summary> Loads the given value from the given local file using binary serialization. </summary>
member ParameterDict.iter: f: (string * Parameter -> unit) -> unit
val n: string
val p: Parameter
Parameter.value: Tensor
val gunzip: inputFile: string -> outputFile: string -> unit
val inputFile: string
Multiple items
val string: value: 'T -> string
--------------------
type string = String
val string: value: 'T -> string
--------------------
type string = String
val outputFile: string
type Directory =
static member CreateDirectory: path: string -> DirectoryInfo + 1 overload
static member CreateSymbolicLink: path: string * pathToTarget: string -> FileSystemInfo
static member CreateTempSubdirectory: ?prefix: string -> DirectoryInfo
static member Delete: path: string -> unit + 1 overload
static member EnumerateDirectories: path: string -> IEnumerable<string> + 3 overloads
static member EnumerateFileSystemEntries: path: string -> IEnumerable<string> + 3 overloads
static member EnumerateFiles: path: string -> IEnumerable<string> + 3 overloads
static member Exists: path: string -> bool
static member GetCreationTime: path: string -> DateTime
static member GetCreationTimeUtc: path: string -> DateTime
...
<summary>Exposes static methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.</summary>
<summary>Exposes static methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.</summary>
Directory.CreateDirectory(path: string) : DirectoryInfo
Directory.CreateDirectory(path: string, unixCreateMode: UnixFileMode) : DirectoryInfo
Directory.CreateDirectory(path: string, unixCreateMode: UnixFileMode) : DirectoryInfo
type Path =
static member ChangeExtension: path: string * extension: string -> string
static member Combine: path1: string * path2: string -> string + 3 overloads
static member EndsInDirectorySeparator: path: ReadOnlySpan<char> -> bool + 1 overload
static member Exists: path: string -> bool
static member GetDirectoryName: path: ReadOnlySpan<char> -> ReadOnlySpan<char> + 1 overload
static member GetExtension: path: ReadOnlySpan<char> -> ReadOnlySpan<char> + 1 overload
static member GetFileName: path: ReadOnlySpan<char> -> ReadOnlySpan<char> + 1 overload
static member GetFileNameWithoutExtension: path: ReadOnlySpan<char> -> ReadOnlySpan<char> + 1 overload
static member GetFullPath: path: string -> string + 1 overload
static member GetInvalidFileNameChars: unit -> char array
...
<summary>Performs operations on <see cref="T:System.String" /> instances that contain file or directory path information. These operations are performed in a cross-platform manner.</summary>
<summary>Performs operations on <see cref="T:System.String" /> instances that contain file or directory path information. These operations are performed in a cross-platform manner.</summary>
Path.GetDirectoryName(path: string) : string
Path.GetDirectoryName(path: ReadOnlySpan<char>) : ReadOnlySpan<char>
Path.GetDirectoryName(path: ReadOnlySpan<char>) : ReadOnlySpan<char>
val ignore: value: 'T -> unit
type File =
static member AppendAllLines: path: string * contents: IEnumerable<string> -> unit + 1 overload
static member AppendAllLinesAsync: path: string * contents: IEnumerable<string> * encoding: Encoding * ?cancellationToken: CancellationToken -> Task + 1 overload
static member AppendAllText: path: string * contents: string -> unit + 1 overload
static member AppendAllTextAsync: path: string * contents: string * encoding: Encoding * ?cancellationToken: CancellationToken -> Task + 1 overload
static member AppendText: path: string -> StreamWriter
static member Copy: sourceFileName: string * destFileName: string -> unit + 1 overload
static member Create: path: string -> FileStream + 2 overloads
static member CreateSymbolicLink: path: string * pathToTarget: string -> FileSystemInfo
static member CreateText: path: string -> StreamWriter
static member Decrypt: path: string -> unit
...
<summary>Provides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of <see cref="T:System.IO.FileStream" /> objects.</summary>
<summary>Provides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of <see cref="T:System.IO.FileStream" /> objects.</summary>
File.Exists(path: string) : bool
File.Delete(path: string) : unit
val inputStream: FileStream
File.OpenRead(path: string) : FileStream
val outputStream: FileStream
File.Create(path: string) : FileStream
File.Create(path: string, bufferSize: int) : FileStream
File.Create(path: string, bufferSize: int, options: FileOptions) : FileStream
File.Create(path: string, bufferSize: int) : FileStream
File.Create(path: string, bufferSize: int, options: FileOptions) : FileStream
val gzipStream: GZipStream
Multiple items
type GZipStream = inherit Stream new: stream: Stream * compressionLevel: CompressionLevel -> unit + 3 overloads member BeginRead: buffer: byte array * offset: int * count: int * asyncCallback: AsyncCallback * asyncState: obj -> IAsyncResult member BeginWrite: buffer: byte array * offset: int * count: int * asyncCallback: AsyncCallback * asyncState: obj -> IAsyncResult member CopyTo: destination: Stream * bufferSize: int -> unit member CopyToAsync: destination: Stream * bufferSize: int * cancellationToken: CancellationToken -> Task member DisposeAsync: unit -> ValueTask member EndRead: asyncResult: IAsyncResult -> int member EndWrite: asyncResult: IAsyncResult -> unit member Flush: unit -> unit ...
<summary>Provides methods and properties used to compress and decompress streams by using the GZip data format specification.</summary>
--------------------
GZipStream(stream: Stream, compressionLevel: CompressionLevel) : GZipStream
GZipStream(stream: Stream, mode: CompressionMode) : GZipStream
GZipStream(stream: Stream, compressionLevel: CompressionLevel, leaveOpen: bool) : GZipStream
GZipStream(stream: Stream, mode: CompressionMode, leaveOpen: bool) : GZipStream
type GZipStream = inherit Stream new: stream: Stream * compressionLevel: CompressionLevel -> unit + 3 overloads member BeginRead: buffer: byte array * offset: int * count: int * asyncCallback: AsyncCallback * asyncState: obj -> IAsyncResult member BeginWrite: buffer: byte array * offset: int * count: int * asyncCallback: AsyncCallback * asyncState: obj -> IAsyncResult member CopyTo: destination: Stream * bufferSize: int -> unit member CopyToAsync: destination: Stream * bufferSize: int * cancellationToken: CancellationToken -> Task member DisposeAsync: unit -> ValueTask member EndRead: asyncResult: IAsyncResult -> int member EndWrite: asyncResult: IAsyncResult -> unit member Flush: unit -> unit ...
<summary>Provides methods and properties used to compress and decompress streams by using the GZip data format specification.</summary>
--------------------
GZipStream(stream: Stream, compressionLevel: CompressionLevel) : GZipStream
GZipStream(stream: Stream, mode: CompressionMode) : GZipStream
GZipStream(stream: Stream, compressionLevel: CompressionLevel, leaveOpen: bool) : GZipStream
GZipStream(stream: Stream, mode: CompressionMode, leaveOpen: bool) : GZipStream
[<Struct>]
type CompressionMode =
| Decompress = 0
| Compress = 1
<summary>Specifies whether to compress data to or decompress data from the underlying stream.</summary>
<summary>Specifies whether to compress data to or decompress data from the underlying stream.</summary>
field CompressionMode.Decompress: CompressionMode = 0
Stream.CopyTo(destination: Stream) : unit
GZipStream.CopyTo(destination: Stream, bufferSize: int) : unit
GZipStream.CopyTo(destination: Stream, bufferSize: int) : unit
val nq100FullUrl: string
val dataFolder: string
val nqFullFile: string
Path.Combine([<ParamArray>] paths: string array) : string
Path.Combine(path1: string, path2: string) : string
Path.Combine(path1: string, path2: string, path3: string) : string
Path.Combine(path1: string, path2: string, path3: string, path4: string) : string
Path.Combine(path1: string, path2: string) : string
Path.Combine(path1: string, path2: string, path3: string) : string
Path.Combine(path1: string, path2: string, path3: string, path4: string) : string
val nq100FullFileGz: string
String.Replace(oldValue: string, newValue: string) : string
String.Replace(oldChar: char, newChar: char) : string
String.Replace(oldValue: string, newValue: string, comparisonType: StringComparison) : string
String.Replace(oldValue: string, newValue: string, ignoreCase: bool, culture: Globalization.CultureInfo) : string
String.Replace(oldChar: char, newChar: char) : string
String.Replace(oldValue: string, newValue: string, comparisonType: StringComparison) : string
String.Replace(oldValue: string, newValue: string, ignoreCase: bool, culture: Globalization.CultureInfo) : string
val download: url: string -> localFileName: string -> unit
<summary> Synchronously downloads the given URL to the given local file. </summary>
<summary> Synchronously downloads the given URL to the given local file. </summary>
type CallId =
{
Ticker: string
Exchange: string
FiscalQuarter: int
Date: DateTime
}
Multiple items
val int: value: 'T -> int (requires member op_Explicit)
--------------------
type int = int32
--------------------
type int<'Measure> = int
val int: value: 'T -> int (requires member op_Explicit)
--------------------
type int = int32
--------------------
type int<'Measure> = int
Multiple items
[<Struct>] type DateTime = new: year: int * month: int * day: int -> unit + 16 overloads member Add: value: TimeSpan -> DateTime member AddDays: value: float -> DateTime member AddHours: value: float -> DateTime member AddMicroseconds: value: float -> DateTime member AddMilliseconds: value: float -> DateTime member AddMinutes: value: float -> DateTime member AddMonths: months: int -> DateTime member AddSeconds: value: float -> DateTime member AddTicks: value: int64 -> DateTime ...
<summary>Represents an instant in time, typically expressed as a date and time of day.</summary>
--------------------
DateTime ()
(+0 other overloads)
DateTime(ticks: int64) : DateTime
(+0 other overloads)
DateTime(ticks: int64, kind: DateTimeKind) : DateTime
(+0 other overloads)
DateTime(date: DateOnly, time: TimeOnly) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int) : DateTime
(+0 other overloads)
DateTime(date: DateOnly, time: TimeOnly, kind: DateTimeKind) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int, calendar: Globalization.Calendar) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, kind: DateTimeKind) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, calendar: Globalization.Calendar) : DateTime
(+0 other overloads)
[<Struct>] type DateTime = new: year: int * month: int * day: int -> unit + 16 overloads member Add: value: TimeSpan -> DateTime member AddDays: value: float -> DateTime member AddHours: value: float -> DateTime member AddMicroseconds: value: float -> DateTime member AddMilliseconds: value: float -> DateTime member AddMinutes: value: float -> DateTime member AddMonths: months: int -> DateTime member AddSeconds: value: float -> DateTime member AddTicks: value: int64 -> DateTime ...
<summary>Represents an instant in time, typically expressed as a date and time of day.</summary>
--------------------
DateTime ()
(+0 other overloads)
DateTime(ticks: int64) : DateTime
(+0 other overloads)
DateTime(ticks: int64, kind: DateTimeKind) : DateTime
(+0 other overloads)
DateTime(date: DateOnly, time: TimeOnly) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int) : DateTime
(+0 other overloads)
DateTime(date: DateOnly, time: TimeOnly, kind: DateTimeKind) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int, calendar: Globalization.Calendar) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, kind: DateTimeKind) : DateTime
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, calendar: Globalization.Calendar) : DateTime
(+0 other overloads)
type CallFull =
{
CallId: CallId
Header: string
PreparedRemarks: string
QuestionsAndAnswers: string
Label: float
}
Multiple items
val float: value: 'T -> float (requires member op_Explicit)
--------------------
type float = Double
--------------------
type float<'Measure> = float
val float: value: 'T -> float (requires member op_Explicit)
--------------------
type float = Double
--------------------
type float<'Measure> = float
val corpus: string
File.ReadAllText(path: string) : string
File.ReadAllText(path: string, encoding: Text.Encoding) : string
File.ReadAllText(path: string, encoding: Text.Encoding) : string
type JsonSerializer =
static member Deserialize: utf8Json: Stream * jsonTypeInfo: JsonTypeInfo -> obj + 39 overloads
static member DeserializeAsync: utf8Json: Stream * jsonTypeInfo: JsonTypeInfo * ?cancellationToken: CancellationToken -> ValueTask<obj> + 4 overloads
static member DeserializeAsyncEnumerable<'TValue> : utf8Json: Stream * ?options: JsonSerializerOptions * ?cancellationToken: CancellationToken -> IAsyncEnumerable<'TValue> + 1 overload
static member Serialize: utf8Json: Stream * value: obj * jsonTypeInfo: JsonTypeInfo -> unit + 14 overloads
static member SerializeAsync: utf8Json: Stream * value: obj * jsonTypeInfo: JsonTypeInfo * ?cancellationToken: CancellationToken -> Task + 4 overloads
static member SerializeToDocument: value: obj * jsonTypeInfo: JsonTypeInfo -> JsonDocument + 4 overloads
static member SerializeToElement: value: obj * jsonTypeInfo: JsonTypeInfo -> JsonElement + 4 overloads
static member SerializeToNode: value: obj * jsonTypeInfo: JsonTypeInfo -> JsonNode + 4 overloads
static member SerializeToUtf8Bytes: value: obj * jsonTypeInfo: JsonTypeInfo -> byte array + 4 overloads
static member IsReflectionEnabledByDefault: bool
<summary>Provides functionality to serialize objects or value types to JSON and to deserialize JSON into objects or value types.</summary>
<summary>Provides functionality to serialize objects or value types to JSON and to deserialize JSON into objects or value types.</summary>
JsonSerializer.Deserialize<'TValue>(reader: byref<Utf8JsonReader>, jsonTypeInfo: Serialization.Metadata.JsonTypeInfo<'TValue>) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(reader: byref<Utf8JsonReader>, ?options: JsonSerializerOptions) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(node: Nodes.JsonNode, jsonTypeInfo: Serialization.Metadata.JsonTypeInfo<'TValue>) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(node: Nodes.JsonNode, ?options: JsonSerializerOptions) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(element: JsonElement, jsonTypeInfo: Serialization.Metadata.JsonTypeInfo<'TValue>) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(element: JsonElement, ?options: JsonSerializerOptions) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(document: JsonDocument, jsonTypeInfo: Serialization.Metadata.JsonTypeInfo<'TValue>) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(document: JsonDocument, ?options: JsonSerializerOptions) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(json: string, jsonTypeInfo: Serialization.Metadata.JsonTypeInfo<'TValue>) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(json: string, ?options: JsonSerializerOptions) : 'TValue
(+0 other overloads)
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(reader: byref<Utf8JsonReader>, ?options: JsonSerializerOptions) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(node: Nodes.JsonNode, jsonTypeInfo: Serialization.Metadata.JsonTypeInfo<'TValue>) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(node: Nodes.JsonNode, ?options: JsonSerializerOptions) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(element: JsonElement, jsonTypeInfo: Serialization.Metadata.JsonTypeInfo<'TValue>) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(element: JsonElement, ?options: JsonSerializerOptions) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(document: JsonDocument, jsonTypeInfo: Serialization.Metadata.JsonTypeInfo<'TValue>) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(document: JsonDocument, ?options: JsonSerializerOptions) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(json: string, jsonTypeInfo: Serialization.Metadata.JsonTypeInfo<'TValue>) : 'TValue
(+0 other overloads)
JsonSerializer.Deserialize<'TValue>(json: string, ?options: JsonSerializerOptions) : 'TValue
(+0 other overloads)
Multiple items
module List from Microsoft.FSharp.Collections
--------------------
type List<'T> = | op_Nil | op_ColonColon of Head: 'T * Tail: 'T list interface IReadOnlyList<'T> interface IReadOnlyCollection<'T> interface IEnumerable interface IEnumerable<'T> member GetReverseIndex: rank: int * offset: int -> int member GetSlice: startIndex: int option * endIndex: int option -> 'T list static member Cons: head: 'T * tail: 'T list -> 'T list member Head: 'T member IsEmpty: bool member Item: index: int -> 'T with get ...
module List from Microsoft.FSharp.Collections
--------------------
type List<'T> = | op_Nil | op_ColonColon of Head: 'T * Tail: 'T list interface IReadOnlyList<'T> interface IReadOnlyCollection<'T> interface IEnumerable interface IEnumerable<'T> member GetReverseIndex: rank: int * offset: int -> int member GetSlice: startIndex: int option * endIndex: int option -> 'T list static member Cons: head: 'T * tail: 'T list -> 'T list member Head: 'T member IsEmpty: bool member Item: index: int -> 'T with get ...
val map: mapping: ('T -> 'U) -> list: 'T list -> 'U list
val x: CallFull
val toTake: int
val min: e1: 'T -> e2: 'T -> 'T (requires comparison)
CallFull.QuestionsAndAnswers: string
property String.Length: int with get
Multiple items
type String = interface IEnumerable<char> interface IEnumerable interface ICloneable interface IComparable interface IComparable<string> interface IConvertible interface IEquatable<string> interface IParsable<string> interface ISpanParsable<string> new: value: nativeptr<char> -> unit + 8 overloads ...
<summary>Represents text as a sequence of UTF-16 code units.</summary>
--------------------
String(value: nativeptr<char>) : String
String(value: char array) : String
String(value: ReadOnlySpan<char>) : String
String(value: nativeptr<sbyte>) : String
String(c: char, count: int) : String
String(value: nativeptr<char>, startIndex: int, length: int) : String
String(value: char array, startIndex: int, length: int) : String
String(value: nativeptr<sbyte>, startIndex: int, length: int) : String
String(value: nativeptr<sbyte>, startIndex: int, length: int, enc: Text.Encoding) : String
type String = interface IEnumerable<char> interface IEnumerable interface ICloneable interface IComparable interface IComparable<string> interface IConvertible interface IEquatable<string> interface IParsable<string> interface ISpanParsable<string> new: value: nativeptr<char> -> unit + 8 overloads ...
<summary>Represents text as a sequence of UTF-16 code units.</summary>
--------------------
String(value: nativeptr<char>) : String
String(value: char array) : String
String(value: ReadOnlySpan<char>) : String
String(value: nativeptr<sbyte>) : String
String(c: char, count: int) : String
String(value: nativeptr<char>, startIndex: int, length: int) : String
String(value: char array, startIndex: int, length: int) : String
String(value: nativeptr<sbyte>, startIndex: int, length: int) : String
String(value: nativeptr<sbyte>, startIndex: int, length: int, enc: Text.Encoding) : String
val concat: sep: string -> strings: string seq -> string
val seqLen: int
val batchSize: int
val hiddenSize: int
val numLayers: int
val dataset: TextDataset
Multiple items
type TextDataset = inherit Dataset new: text: string * seqLength: int * ?chars: string -> TextDataset member charToIndex: c: char -> int member indexToChar: i: int -> char override item: i: int -> Tensor * Tensor member tensorToText: tensor: Tensor -> string member textToTensor: text: string -> Tensor member chars: char array override length: int member numChars: int
--------------------
new: text: string * seqLength: int * ?chars: string -> TextDataset
type TextDataset = inherit Dataset new: text: string * seqLength: int * ?chars: string -> TextDataset member charToIndex: c: char -> int member indexToChar: i: int -> char override item: i: int -> Tensor * Tensor member tensorToText: tensor: Tensor -> string member textToTensor: text: string -> Tensor member chars: char array override length: int member numChars: int
--------------------
new: text: string * seqLength: int * ?chars: string -> TextDataset
val loader: DataLoader
member Dataset.loader: batchSize: int * ?shuffle: bool * ?dropLast: bool * ?device: Device * ?dtype: Dtype * ?backend: Backend * ?targetDevice: Device * ?targetDtype: Dtype * ?targetBackend: Backend -> DataLoader
property TextDataset.numChars: int with get
property TextDataset.chars: char array with get
val rnn: LSTM
Multiple items
type LSTM = inherit Model new: inFeatures: int * outFeatures: int * ?numLayers: int * ?bias: bool * ?batchFirst: bool * ?dropout: float * ?bidirectional: bool -> LSTM override ToString: unit -> string override forward: value: Tensor -> Tensor member reset: unit -> unit member cell: Tensor with get, set member hidden: Tensor with get, set
<summary>Long short-term memory (LSTM) recurrent neural network.</summary>
--------------------
new: inFeatures: int * outFeatures: int * ?numLayers: int * ?bias: bool * ?batchFirst: bool * ?dropout: float * ?bidirectional: bool -> LSTM
type LSTM = inherit Model new: inFeatures: int * outFeatures: int * ?numLayers: int * ?bias: bool * ?batchFirst: bool * ?dropout: float * ?bidirectional: bool -> LSTM override ToString: unit -> string override forward: value: Tensor -> Tensor member reset: unit -> unit member cell: Tensor with get, set member hidden: Tensor with get, set
<summary>Long short-term memory (LSTM) recurrent neural network.</summary>
--------------------
new: inFeatures: int * outFeatures: int * ?numLayers: int * ?bias: bool * ?batchFirst: bool * ?dropout: float * ?bidirectional: bool -> LSTM
val decoder: Model<Tensor,Tensor>
static member dsharp.view: shape: int seq -> (Tensor -> Tensor)
static member dsharp.view: shape: int -> (Tensor -> Tensor)
static member dsharp.view: input: Tensor * shape: int -> Tensor
static member dsharp.view: input: Tensor * shape: int seq -> Tensor
static member dsharp.view: shape: int -> (Tensor -> Tensor)
static member dsharp.view: input: Tensor * shape: int -> Tensor
static member dsharp.view: input: Tensor * shape: int seq -> Tensor
Multiple items
type Linear = inherit Model new: inFeatures: int * outFeatures: int * ?bias: bool -> Linear override ToString: unit -> string override forward: value: Tensor -> Tensor
<summary>A model that applies a linear transformation to the incoming data: \(y = xA^T + b\)</summary>
--------------------
new: inFeatures: int * outFeatures: int * ?bias: bool -> Linear
type Linear = inherit Model new: inFeatures: int * outFeatures: int * ?bias: bool -> Linear override ToString: unit -> string override forward: value: Tensor -> Tensor
<summary>A model that applies a linear transformation to the incoming data: \(y = xA^T + b\)</summary>
--------------------
new: inFeatures: int * outFeatures: int * ?bias: bool -> Linear
val languageModel: Model<Tensor,Tensor>
val printfn: format: Printf.TextWriterFormat<'T> -> 'T
member ModelBase.summary: unit -> string
val modelFileName: string
val modelUrl: string
member ModelBase.loadState2: filename: string -> unit
val predict: text: string -> len: int -> string
val text: string
val len: int
member LSTM.reset: unit -> unit
val mutable prediction: string
val mutable last: string
val i: int32
val lastTensor: Tensor
member TextDataset.textToTensor: text: string -> Tensor
val nextCharProbs: Tensor
member Tensor.unsqueeze: dim: int -> Tensor
static member dsharp.slice: index: int seq -> (Tensor -> Tensor)
static member dsharp.slice: input: Tensor * index: int seq -> Tensor
static member dsharp.slice: input: Tensor * index: int seq -> Tensor
static member dsharp.softmax: dim: int -> (Tensor -> Tensor)
static member dsharp.softmax: input: Tensor * dim: int -> Tensor
static member dsharp.softmax: input: Tensor * dim: int -> Tensor
Multiple items
type Categorical = inherit TensorDistribution new: ?probs: Tensor * ?logits: Tensor -> Categorical override ToString: unit -> string override logprob: value: Tensor -> Tensor override sample: unit -> Tensor override batchShape: Shape override eventShape: Shape member logits: Tensor override mean: Tensor member probs: Tensor ...
<summary>Represents a Categorial distribution.</summary>
--------------------
new: ?probs: Tensor * ?logits: Tensor -> Categorical
type Categorical = inherit TensorDistribution new: ?probs: Tensor * ?logits: Tensor -> Categorical override ToString: unit -> string override logprob: value: Tensor -> Tensor override sample: unit -> Tensor override batchShape: Shape override eventShape: Shape member logits: Tensor override mean: Tensor member probs: Tensor ...
<summary>Represents a Categorial distribution.</summary>
--------------------
new: ?probs: Tensor * ?logits: Tensor -> Categorical
member TextDataset.indexToChar: i: int -> char
val optimizer: Adam
Multiple items
type Adam = inherit Optimizer new: model: Model * ?lr: Tensor * ?beta1: Tensor * ?beta2: Tensor * ?eps: Tensor * ?weightDecay: Tensor * ?reversible: bool -> Adam override updateRule: name: string -> t: Tensor -> Tensor
<summary>TBD</summary>
--------------------
new: model: Model * ?lr: Tensor * ?beta1: Tensor * ?beta2: Tensor * ?eps: Tensor * ?weightDecay: Tensor * ?reversible: bool -> Adam
type Adam = inherit Optimizer new: model: Model * ?lr: Tensor * ?beta1: Tensor * ?beta2: Tensor * ?eps: Tensor * ?weightDecay: Tensor * ?reversible: bool -> Adam override updateRule: name: string -> t: Tensor -> Tensor
<summary>TBD</summary>
--------------------
new: model: Model * ?lr: Tensor * ?beta1: Tensor * ?beta2: Tensor * ?eps: Tensor * ?weightDecay: Tensor * ?reversible: bool -> Adam
static member dsharp.tensor: ?device: Device * ?dtype: Dtype * ?backend: Backend -> ('a -> Tensor)
static member dsharp.tensor: value: obj * ?device: Device * ?dtype: Dtype * ?backend: Backend -> Tensor
static member dsharp.tensor: value: obj * ?device: Device * ?dtype: Dtype * ?backend: Backend -> Tensor
val losses: ResizeArray<float>
type ResizeArray<'T> = Collections.Generic.List<'T>
val epochs: int
val validInterval: int
val start: DateTime
property DateTime.Now: DateTime with get
<summary>Gets a <see cref="T:System.DateTime" /> object that is set to the current date and time on this computer, expressed as the local time.</summary>
<returns>An object whose value is the current local date and time.</returns>
<summary>Gets a <see cref="T:System.DateTime" /> object that is set to the current date and time on this computer, expressed as the local time.</summary>
<returns>An object whose value is the current local date and time.</returns>
val epoch: int
val i: int
val x: Tensor
val t: Tensor
member DataLoader.epoch: ?numBatches: int -> (int * Tensor * Tensor) seq
val input: Tensor
val target: Tensor
member ModelBase.reverseDiff: ?nestingTag: uint32 -> unit
val output: Tensor
val loss: Tensor
static member dsharp.crossEntropyLoss: target: Tensor -> (Tensor -> Tensor)
static member dsharp.crossEntropyLoss: input: Tensor * target: Tensor * ?weight: Tensor * ?reduction: string -> Tensor
static member dsharp.crossEntropyLoss: input: Tensor * target: Tensor * ?weight: Tensor * ?reduction: string -> Tensor
member Tensor.view: shape: int -> Tensor
member Tensor.view: shape: int seq -> Tensor
member Tensor.view: shape: int seq -> Tensor
member Tensor.reverse: ?value: Tensor * ?zeroDerivatives: bool -> unit
member Optimizer.step: unit -> unit
Collections.Generic.List.Add(item: float) : unit
property DataLoader.length: int with get
member ModelBase.saveState2: fileName: string * ?noDiff: bool -> unit
type GC =
static member AddMemoryPressure: bytesAllocated: int64 -> unit
static member AllocateArray<'T> : length: int * ?pinned: bool -> 'T array
static member AllocateUninitializedArray<'T> : length: int * ?pinned: bool -> 'T array
static member CancelFullGCNotification: unit -> unit
static member Collect: unit -> unit + 4 overloads
static member CollectionCount: generation: int -> int
static member EndNoGCRegion: unit -> unit
static member GetAllocatedBytesForCurrentThread: unit -> int64
static member GetConfigurationVariables: unit -> IReadOnlyDictionary<string,obj>
static member GetGCMemoryInfo: unit -> GCMemoryInfo + 1 overload
...
<summary>Controls the system garbage collector, a service that automatically reclaims unused memory.</summary>
<summary>Controls the system garbage collector, a service that automatically reclaims unused memory.</summary>
GC.Collect() : unit
GC.Collect(generation: int) : unit
GC.Collect(generation: int, mode: GCCollectionMode) : unit
GC.Collect(generation: int, mode: GCCollectionMode, blocking: bool) : unit
GC.Collect(generation: int, mode: GCCollectionMode, blocking: bool, compacting: bool) : unit
GC.Collect(generation: int) : unit
GC.Collect(generation: int, mode: GCCollectionMode) : unit
GC.Collect(generation: int, mode: GCCollectionMode, blocking: bool) : unit
GC.Collect(generation: int, mode: GCCollectionMode, blocking: bool, compacting: bool) : unit